Repository navigation
agent: prevent switch leftovers and waits for the notification queue - #2095
evgeny-simplex wants to merge 45 commits into
Conversation
# Conflicts: # .github/workflows/build.yml # scripts/ci/README.md
…ing-rework # Conflicts: # tests/XFTPServerTests.hs
evgeny-simplex
left a comment
There was a problem hiding this comment.
Comments next to each change: why, where it is used, which test covers it. "Rule 1–4" refers to the plan:
simplexmq/plans/2026-11-21-agent-no-blocking.md
Lines 10 to 15 in f8890ac
| smpClientStub g sessionId thVersion thAuth = do | ||
| let ts = UTCTime (read "2024-03-31") 0 | ||
| connected <- newTVarIO False | ||
| connected <- newTVarIO True |
There was a problem hiding this comment.
True, as commands fail in sendBlock while False (L1398); on base, never read. The stub is only used in BatchingTests.hs#L271.
evgeny-simplex
left a comment
There was a problem hiding this comment.
Continued: comments next to each change.
| scripts/ci/prune-old-builds.sh dist-client-postgres | ||
| cabal update | ||
| cabal build --builddir=dist-client-postgres --jobs=$(nproc) --enable-tests -fserver_postgres -fclient_postgres -fslow_servers ${{ env.ghc_options }} simplexmq-test | ||
| cabal build --builddir=dist-client-postgres --jobs=$(nproc) --enable-tests -fserver_postgres -fclient_postgres -fslow_servers -fconn_lock_checks ${{ env.ghc_options }} simplexmq-test |
There was a problem hiding this comment.
PostgreSQL agent store tests are built with conn_lock_checks, also in the reduced build (L554).
| scripts/ci/prune-old-builds.sh dist-newstyle dist-postgres dist-client-postgres | ||
| if [ "${{ matrix.client_postgres }}" = true ]; then | ||
| cabal build --builddir=dist-client-postgres --jobs=$(nproc) --enable-tests -fserver_postgres -fclient_postgres -fslow_servers --ghc-options=-O0 simplexmq-test | ||
| cabal build --builddir=dist-client-postgres --jobs=$(nproc) --enable-tests -fserver_postgres -fclient_postgres -fslow_servers -fconn_lock_checks --ghc-options=-O0 simplexmq-test |
There was a problem hiding this comment.
Same flags as L302, so that the -O0 cache of master and stable pushes matches pull request builds.
| flag conn_lock_checks | ||
| description: Fail agent server requests made inside a connection lock, for tests. | ||
| manual: True | ||
| default: False | ||
|
|
| deleteSndFilesRemote :: AgentClient -> UserId -> [(SndFileId, ValidFileDescription 'FSender)] -> AM' () | ||
| deleteSndFilesRemote c userId sndFileIdsDescrs = do | ||
| deleteSndFilesInternal c (map fst sndFileIdsDescrs) `E.catchAny` (notify c "" . SFERR . INTERNAL . show) | ||
| deleteSndFilesInternal c (map fst sndFileIdsDescrs) `E.catchAny` (notifySub' c "" . SFERR . INTERNAL . show) |
There was a problem hiding this comment.
Written without waiting for subQ space: called in the API thread of xftpDeleteSndFilesRemote (rule 4); no test.
| waitForWork, | ||
| hasWorkToDo, | ||
| hasWorkToDo', | ||
| noWorkToDo, |
There was a problem hiding this comment.
Only used in postponeCommand: the work flag is cleared, so that the worker waits while all pending commands are postponed.
| subscribeQueues :: AgentClient -> Bool -> [RcvQueueSub] -> AM' [(RcvQueueSub, Either AgentErrorType (Maybe ServiceId))] | ||
| subscribeQueues _ _ [] = pure [] | ||
| subscribeQueues c withEvents qs = do | ||
| subscribeQueues c withEvents qs = checkBatchOutsideConnLock c qs $ do |
There was a problem hiding this comment.
Lock check in the calling thread, see L1168-L1170.
| -- it includes arguments in the results instead. | ||
| sendTSessionBatches :: forall q r. ByteString -> (q -> TransportSessionMode -> SMPTransportSession) -> (SMPClient -> NonEmpty q -> IO (BatchResponses q SMPClientError r)) -> AgentClient -> NetworkRequestMode -> [q] -> AM' [(q, Either AgentErrorType r)] | ||
| sendTSessionBatches statCmd mkSession action c nm qs = do | ||
| sendTSessionBatches statCmd mkSession action c nm qs = checkBatchOutsideConnLock c qs $ do |
There was a problem hiding this comment.
Lock check in the calling thread, see L1168-L1170.
| deleteNewQueue :: AgentClient -> NetworkRequestMode -> SMPTransportSession -> NewRcvQueue -> AM () | ||
| deleteNewQueue c nm tSess RcvQueue {rcvId, rcvPrivateKey} = | ||
| withLogClient c nm tSess (unEntityId rcvId) "DEL" $ \smp -> | ||
| deleteSMPQueue (connectedClient smp) nm rcvPrivateKey rcvId |
There was a problem hiding this comment.
Rule 3: DEL of a NewRcvQueue whose record failed, as deleteQueue takes a stored RcvQueue. Only used in recordNewQueue; test: L4476-L4489.
| hasNonQSecureCommand :: DB.Connection -> ConnId -> SMPServer -> IO Bool | ||
| hasNonQSecureCommand db connId (SMPServer host port _) = | ||
| maybeFirstRow' False fromOnlyBI $ | ||
| DB.query | ||
| db | ||
| [sql| | ||
| SELECT 1 FROM commands | ||
| WHERE conn_id = ? AND host = ? AND port = ? AND failed = 0 AND command_tag NOT IN (?,?) | ||
| LIMIT 1 | ||
| |] | ||
| (connId, host, port, AInternalCommandTag ICQSecure_, AInternalCommandTag ICQSndSecure_) |
There was a problem hiding this comment.
Only used in postponeCommand: ICQSecure and ICQSndSecure are not counted, to avoid a postponement loop; test: L4648-L4685.
| where | ||
| forUpdateClause = | ||
| " AND deleted_at_wait_delivery IS NULL" | ||
| #if defined(dbPostgres) | ||
| <> " FOR UPDATE" | ||
| #endif |
There was a problem hiding this comment.
Connections whose deletion waits for delivery are excluded: on base, a new switch queue could be deleted without DEL. Used by getConnForUpdate, e.g. L554; test: L4491-L4507.
evgeny-simplex
left a comment
There was a problem hiding this comment.
Continued: comments next to each change.
| @@ -1,4 +1,5 @@ | |||
| {-# LANGUAGE BangPatterns #-} | |||
| {-# LANGUAGE CPP #-} | |||
There was a problem hiding this comment.
Required by #if defined(conn_lock_checks) at L365.
| import Data.Time.Clock | ||
| import Data.Time.Clock.System (systemToUTCTime) | ||
| import Data.Traversable (mapAccumL) | ||
| import Data.Unique (Unique, newUnique) |
There was a problem hiding this comment.
For the switch identifier: newRcvSwitch, endRcvSwitch, startSwitch.
| let stats = AgentPersistedServerStats {smpServersStats = sss, xftpServersStats = xss, ntfServersStats = OptionalMap nss} | ||
| tryAllErrors' (withStore' c (`updateServersStats` stats)) >>= \case | ||
| Left e -> atomically $ writeTBQueue subQ ("", "", AEvt SAEConn $ ERR $ INTERNAL $ show e) | ||
| Left e -> notifySub' c "" $ ERR $ INTERNAL $ show e |
There was a problem hiding this comment.
Written without waiting for subQ space (rule 4): called in the API thread of deleteUser'; test: testDeleteUserStatsErrorFullQueue.
| #if defined(conn_lock_checks) | ||
| violations <- readTVarIO $ connLockViolations c | ||
| unless (null violations) $ E.throwIO $ INTERNAL $ "server requests in connection locks " <> show violations | ||
| #endif |
There was a problem hiding this comment.
Only in tests (conn_lock_checks): an exception is thrown at disposal after a server request under a connection lock. Used in withAgent; test: testServerRequestInConnLock.
|
|
||
| ackMessage :: AgentClient -> ConnId -> AgentMsgId -> Maybe MsgReceiptInfo -> AE () | ||
| ackMessage c = withAgentEnv c .:. ackMessage' c Nothing | ||
| ackMessage c connId msgId rcptInfo_ = withAgentEnv c $ ackMessage' c Nothing connId msgId rcptInfo_ >>= mapM_ (liftIO . nonBlockingWriteTBQueue (subQ c)) |
There was a problem hiding this comment.
MSGNTF of ackMessage' is written without waiting (rule 4); on base, the thread waited for subQ space; test: testAckMessageFullQueue.
| withServer $ \srv -> tryAtomicCommand . void $ | ||
| requestAndCommit c connId "ICQSecure" (switchingQueues srv) (\(_, _, _, rq, _) -> secureQueue c NRMBackground rq senderKey) $ |
There was a problem hiding this comment.
KEY between two locked reads (rule 2), postponed during ratchet synchronization: on base, QUSE failed after KEY; test: testSwitchBothDirectionsRatchetSync.
| withServer $ \srv -> tryCommand . void $ | ||
| requestAndCommit c connId "ICQSndSecure" (securingQueues srv) secureNewQueue $ \_ (cData, rqs, sqs, sq', oldSq) -> do |
There was a problem hiding this comment.
SKEY and confirmation between locked reads, postponed during ratchet synchronization: on base, QEND failed after the database update; test: testFastSwitchRatchetSyncWhileSecuring.
| withServer $ \srv -> tryAtomicCommand . void $ | ||
| requestAndCommit c connId "ICQDelete" (removedQueue srv) deleteRemovedQueue $ \deleted (cData@ConnData {enableNtfs}, rq', rqs, sqs) -> do |
There was a problem hiding this comment.
DEL between two locked reads; a permanent DEL error is reported after SWITCH, as on base; test: testSwitchConnection.
| withStore' c $ \db -> deleteConnRcvQueue db rq' >> deleteCommand db cmdId | ||
| when enableNtfs $ do | ||
| ns <- asks ntfSupervisor | ||
| liftIO . whenM (hasInstantNotifications ns) $ nonBlockingWriteTBQueue (ntfSubQ ns) (NSCCreate, [connId]) |
There was a problem hiding this comment.
Written without waiting for ntfSubQ space under the lock (rule 4); on base, the lock holder waited; test: testSwitchFullNtfQueue.
| tryWithLock name = tryCommand . withConnLock c connId name | ||
| tryAtomicWithLock name = tryAtomicCommand . withConnLock c connId name | ||
| tryMoveableWithLock name = tryMoveableCommand . withConnLock c connId name |
evgeny-simplex
left a comment
There was a problem hiding this comment.
Continued: comments next to each change.
| recordAck :: SMP.MsgId -> Maybe (RcvQueue, Bool) -> AM (Maybe ATransmission) | ||
| recordAck srvMsgId = maybe (pure Nothing) $ \(rq, drained) -> recordQueueAck c rq srvMsgId drained |
There was a problem hiding this comment.
The queue is re-read under the lock in recordQueueAck; on base, its status before ACK was used.
| withConnLock c connId "secure" . withStore' c $ \db -> | ||
| getRcvQueue db connId server rcvId >>= mapM_ (\rq'@RcvQueue {status} -> when (status == Confirmed) $ setRcvQueueStatus db rq' Secured) |
There was a problem hiding this comment.
Secured is written only from Confirmed, as Active can be set during the unlocked KEY (L3831); no dedicated test.
| duplexConn :: AM (Maybe (ConnData, NonEmpty RcvQueue, NonEmpty SndQueue)) | ||
| duplexConn = |
There was a problem hiding this comment.
Connection parts are returned instead of a continuation, for the validation steps of requestAndCommit.
| postponeCommand srv = do | ||
| liftIO $ noWorkToDo doWork | ||
| otherCmds <- withStore c $ \db -> runExceptT $ do | ||
| liftIO $ deleteCommand db cmdId | ||
| pending <- liftIO $ hasNonQSecureCommand db connId srv | ||
| pending <$ ExceptT (createCommand db corrId connId server_ command) | ||
| when otherCmds . atomically $ hasWorkToDo' doWork |
There was a problem hiding this comment.
ICQSecure and ICQSndSecure are postponed during ratchet synchronization: on base, they failed after KEY or SKEY. Used at 2413 and 2443; test: sync while securing.
| requestAndCommit :: AgentClient -> ConnId -> Text -> AM (Maybe s) -> (s -> AM r) -> (r -> s -> AM a) -> AM (Maybe a) | ||
| requestAndCommit c connId name validate request commit = | ||
| withConnLock c connId name validate $>>= \s -> do | ||
| r <- request s | ||
| withConnLock c connId name $ validate $>>= fmap Just . commit r |
There was a problem hiding this comment.
Rule 2 helper: the request is made between two locked validations, the second followed by the commit. Used by ICQSecure, ackMessage', ICDuplexSecure, ICQSndSecure and ICQDelete.
| cStats <- connectionStats c conn'' | ||
| notify $ RSYNC RSOk Nothing cStats | ||
| withStore' c $ \db -> setConnRatchetSync db connId RSOk | ||
| resumeConnCmds c True [connId] |
There was a problem hiding this comment.
Switch commands postponed during synchronization are resumed, with an existing worker woken; test: sync while securing.
| cStats <- connectionStats c conn'' | ||
| notify $ RSYNC rss' (Just e) cStats | ||
| withStore' c $ \db -> setConnRatchetSync db connId rss' | ||
| when (rss' == RSAllowed) $ resumeConnCmds c True [connId] |
There was a problem hiding this comment.
Same as 3875, when RSAllowed is set; no test expects an RSAllowed event.
| when enableNtfs $ do | ||
| ns <- asks ntfSupervisor | ||
| liftIO $ sendNtfSubCommand ns (NSCCreate, [connId]) | ||
| liftIO . whenM (hasInstantNotifications ns) $ nonBlockingWriteTBQueue (ntfSubQ ns) (NSCCreate, [connId]) |
There was a problem hiding this comment.
Written without waiting under the processSMP lock; on base, the lock holder waited for ntfSubQ space; test: testSwitchFullNtfQueue.
| withConnLock c connId "connectReplyQueues" $ | ||
| withStore c (`getConn` connId) >>= \case | ||
| SomeConn _ (DuplexConnection cData' _ (sq :| _)) -> enqueueConfirmation c cmdId cData' sq ownConnInfo Nothing | ||
| _ -> throwE $ INTERNAL "connectReplyQueues: incorrect connection type" |
There was a problem hiding this comment.
SKEY is sent unlocked; the confirmation is enqueued under the lock after a fresh read (rule 2). Used in ICAllowSecure; test: runAgentClientTestPQ.
| upgradeConn = do | ||
| (sq, _) <- lift $ newSndQueue userId connId qInfo' Nothing | ||
| withStore c $ \db -> upgradeRcvConnToDuplex db connId sq | ||
| withConnLock c connId "connectReplyQueues" . withStore c $ \db -> upgradeRcvConnToDuplex db connId sq |
There was a problem hiding this comment.
Only the database write is under the lock; the keys are generated locally (newSndQueue).
Stacked on #2079: until it merges, this diff also shows #2079's commit. Its own changes are the 5 commits after cd3f7a7: evgeny-simplex/simplexmq@cd3f7a7...f8890ac (+103 −22; Agent.hs 36 lines, tests 81, plan 8).
The answers Q1 A and Q2 A on #2079, and one fix found with them:
Tests on the fork at f8890ac: 2052 examples, and 1955 with the PostgreSQL agent store, 0 failures (https://github.com/evgeny-simplex/simplexmq/actions/runs/44959018981).