Skip to content

agent: prevent switch leftovers and waits for the notification queue - #2095

Open
evgeny-simplex wants to merge 45 commits into
simplex-chat:masterfrom
evgeny-simplex:ep/agent-no-blocking-answers
Open

evgeny-simplex wants to merge 45 commits into
simplex-chat:masterfrom
evgeny-simplex:ep/agent-no-blocking-answers

Conversation

@evgeny-simplex

@evgeny-simplex evgeny-simplex commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • a switch queue is no longer left on the server by a synchronous deletion (Q1 A);
  • a switch no longer waits for space in the notification command queue (Q2 A);
  • aborting an asynchronous switch while its new queue is created no longer produces an error event;
  • test: the switch completes within a time limit while the notification command queue is full;
  • plan: lock holders never wait for notification command queue space.

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).

# Conflicts:
#	.github/workflows/build.yml
#	scripts/ci/README.md
…ing-rework

# Conflicts:
#	tests/XFTPServerTests.hs
Comment thread src/Simplex/Messaging/Client.hs Resolved

@evgeny-simplex evgeny-simplex left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comments next to each change: why, where it is used, which test covers it. "Rule 1–4" refers to the plan:

## Rules
1. A server request is never made under a connection lock; in builds with `conn_lock_checks`, used by the tests with the PostgreSQL agent store, such a request fails.
2. The second locked step reads the connection again; when its state changed, the step is dropped, postponed during ratchet synchronization, or undone.
3. A queue created on a server is recorded under the connection lock or deleted from the server; connection deletion takes the same locks.
4. API threads and lock holders never wait for space in subQ or msgQ; lock holders never wait for space in ntfSubQ.

Comment thread src/Simplex/Messaging/Client.hs Resolved
Comment thread src/Simplex/Messaging/Client.hs Resolved
smpClientStub g sessionId thVersion thAuth = do
let ts = UTCTime (read "2024-03-31") 0
connected <- newTVarIO False
connected <- newTVarIO True

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True, as commands fail in sendBlock while False (L1398); on base, never read. The stub is only used in BatchingTests.hs#L271.

Comment thread src/Simplex/Messaging/Client.hs Resolved
Comment thread src/Simplex/Messaging/Client.hs Resolved
Comment thread src/Simplex/Messaging/Client.hs Resolved
Comment thread src/Simplex/Messaging/Client.hs Resolved
Comment thread src/Simplex/Messaging/Client.hs Resolved
Comment thread src/Simplex/Messaging/Client.hs Resolved
Comment thread src/Simplex/Messaging/Client.hs Resolved

@evgeny-simplex evgeny-simplex left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same flags as L302, so that the -O0 cache of master and stable pushes matches pull request builds.

Comment thread simplexmq.cabal
Comment on lines +97 to +101
flag conn_lock_checks
description: Fail agent server requests made inside a connection lock, for tests.
manual: True
default: False

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only for tests, off by default: the check and its test are compiled with it.

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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Written without waiting for subQ space: called in the API thread of xftpDeleteSndFilesRemote (rule 4); no test.

waitForWork,
hasWorkToDo,
hasWorkToDo',
noWorkToDo,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lock check in the calling thread, see L1168-L1170.

Comment on lines +2181 to +2184
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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rule 3: DEL of a NewRcvQueue whose record failed, as deleteQueue takes a stored RcvQueue. Only used in recordNewQueue; test: L4476-L4489.

Comment on lines +1750 to +1760
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_)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only used in postponeCommand: ICQSecure and ICQSndSecure are not counted, to avoid a postponement loop; test: L4648-L4685.

Comment on lines +2775 to +2780
where
forUpdateClause =
" AND deleted_at_wait_delivery IS NULL"
#if defined(dbPostgres)
<> " FOR UPDATE"
#endif

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 evgeny-simplex left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Continued: comments next to each change.

@@ -1,4 +1,5 @@
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Written without waiting for subQ space (rule 4): called in the API thread of deleteUser'; test: testDeleteUserStatsErrorFullQueue.

Comment on lines +365 to +368
#if defined(conn_lock_checks)
violations <- readTVarIO $ connLockViolations c
unless (null violations) $ E.throwIO $ INTERNAL $ "server requests in connection locks " <> show violations
#endif

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MSGNTF of ackMessage' is written without waiting (rule 4); on base, the thread waited for subQ space; test: testAckMessageFullQueue.

Comment on lines +2392 to +2393
withServer $ \srv -> tryAtomicCommand . void $
requestAndCommit c connId "ICQSecure" (switchingQueues srv) (\(_, _, _, rq, _) -> secureQueue c NRMBackground rq senderKey) $

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

KEY between two locked reads (rule 2), postponed during ratchet synchronization: on base, QUSE failed after KEY; test: testSwitchBothDirectionsRatchetSync.

Comment on lines +2418 to +2419
withServer $ \srv -> tryCommand . void $
requestAndCommit c connId "ICQSndSecure" (securingQueues srv) secureNewQueue $ \_ (cData, rqs, sqs, sq', oldSq) -> do

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SKEY and confirmation between locked reads, postponed during ratchet synchronization: on base, QEND failed after the database update; test: testFastSwitchRatchetSyncWhileSecuring.

Comment on lines +2451 to +2452
withServer $ \srv -> tryAtomicCommand . void $
requestAndCommit c connId "ICQDelete" (removedQueue srv) deleteRemovedQueue $ \deleted (cData@ConnData {enableNtfs}, rq', rqs, sqs) -> do

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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])

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Written without waiting for ntfSubQ space under the lock (rule 4); on base, the lock holder waited; test: testSwitchFullNtfQueue.

Comment on lines -2475 to -2477
tryWithLock name = tryCommand . withConnLock c connId name
tryAtomicWithLock name = tryAtomicCommand . withConnLock c connId name
tryMoveableWithLock name = tryMoveableCommand . withConnLock c connId name

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed: requests of all former callers are made outside the lock (rule 1), e.g. SWCH, ICQDelete.

@evgeny-simplex evgeny-simplex left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Continued: comments next to each change.

Comment on lines +2484 to +2485
recordAck :: SMP.MsgId -> Maybe (RcvQueue, Bool) -> AM (Maybe ATransmission)
recordAck srvMsgId = maybe (pure Nothing) $ \(rq, drained) -> recordQueueAck c rq srvMsgId drained

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The queue is re-read under the lock in recordQueueAck; on base, its status before ACK was used.

Comment on lines +2490 to +2491
withConnLock c connId "secure" . withStore' c $ \db ->
getRcvQueue db connId server rcvId >>= mapM_ (\rq'@RcvQueue {status} -> when (status == Confirmed) $ setRcvQueueStatus db rq' Secured)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Secured is written only from Confirmed, as Active can be set during the unlocked KEY (L3831); no dedicated test.

Comment on lines +2500 to +2501
duplexConn :: AM (Maybe (ConnData, NonEmpty RcvQueue, NonEmpty SndQueue))
duplexConn =

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Connection parts are returned instead of a continuation, for the validation steps of requestAndCommit.

Comment on lines +2525 to +2531
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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +2898 to +2902
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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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])

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Written without waiting under the processSMP lock; on base, the lock holder waited for ntfSubQ space; test: testSwitchFullNtfQueue.

Comment on lines +4506 to +4509
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"

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only the database write is under the lock; the keys are generated locally (newSndQueue).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant