From 9a33fd44b0d6091fbb8cf08316b9ee30f1183568 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:51:10 +0000 Subject: [PATCH 01/18] agent: prevent a switch queue left on the server by synchronous deletion --- plans/2026-11-21-agent-no-blocking.md | 2 +- src/Simplex/Messaging/Agent.hs | 7 ++++--- tests/AgentTests/FunctionalAPITests.hs | 25 +++++++++++++++++++++++++ 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/plans/2026-11-21-agent-no-blocking.md b/plans/2026-11-21-agent-no-blocking.md index 8c4090f23..14bdd30c7 100644 --- a/plans/2026-11-21-agent-no-blocking.md +++ b/plans/2026-11-21-agent-no-blocking.md @@ -52,7 +52,7 @@ sequenceDiagram - `recordNewQueue` in `createRcvQueue`, `createReplyQueue` and `switchDuplexConnection`; - request outside the lock in ICAck, ICAckDel, ICAllowSecure, ICDeleteRcvQueue, JOIN of a service request, `setConnShortLink`, `deleteConnShortLink`, `suspendConnection`, `connectReplyQueues`; - `acceptContact` under the invitation lock; `serviceRequest_` without the connection lock; - - deletion under the locks of its connections; + - deletion under the locks of its connections, where the connections are marked deleted in synchronous deletion too; - a connection whose deletion waits for delivery is not given new queues; - the record step of an acknowledgement reads the queue again; - a concurrent acknowledgement of a deleted message is dropped; diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 1a1158b56..7ce983db8 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -3093,7 +3093,6 @@ suspendConnection' c nm connId = do mapM_ (suspendQueue c nm) (rqs :: [RcvQueue]) -- | Delete SMP agent connection (DEL command) in Reader monad --- unlike deleteConnectionAsync, this function does not mark connection as deleted in case of deletion failure -- currently it is used only in tests deleteConnection' :: AgentClient -> NetworkRequestMode -> ConnId -> AM () deleteConnection' c nm connId = toConnResult connId =<< deleteConnections' c nm [connId] @@ -3107,7 +3106,6 @@ connRcvQueues = \case SndConnection _ _ -> [] NewConnection _ -> [] --- Unlike deleteConnectionsAsync, this function does not mark connections as deleted in case of deletion failure. deleteConnections' :: AgentClient -> NetworkRequestMode -> [ConnId] -> AM (Map ConnId (Either AgentErrorType ())) deleteConnections' = deleteConnections_ getConns False False {-# INLINE deleteConnections' #-} @@ -3212,7 +3210,10 @@ deleteConnections_ :: AM (Map ConnId (Either AgentErrorType ())) deleteConnections_ _ _ _ _ _ [] = pure M.empty deleteConnections_ getConnections ntf waitDelivery c nm connIds = do - (rs, rqs, _) <- ExceptT . withConnLocks c (S.fromList connIds) "deleteConnections" . runExceptT $ prepareDeleteConnections_ getConnections c waitDelivery connIds + (rs, rqs, _) <- ExceptT . withConnLocks c (S.fromList connIds) "deleteConnections" . runExceptT $ do + r@(_, _, connIds') <- prepareDeleteConnections_ getConnections c waitDelivery connIds + unless waitDelivery . withStore' c $ \db -> forM_ connIds' $ setConnDeleted db False + pure r rcvRs <- lift $ deleteConnQueues c nm waitDelivery ntf rqs let rs' = M.union rs rcvRs notifyResultError rs' diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 2508007ed..5e9c8920d 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -639,6 +639,8 @@ functionalAPITests ps = do testSwitchConnectionDeletedWhileNewQueue ps it "should delete the new queue when the connection is deleted waiting for delivery while the queue is created" $ testSwitchConnectionDeletedWaitingDeliveryWhileNewQueue ps + it "should delete the new queue when it is recorded while the connection deletion waits for the server" $ + testSwitchNewQueueRecordedWhileDeleting ps it "should delete the new queue when the switch is aborted and started again while the queue is created" $ testSwitchRestartedWhileNewQueue ps it "should refuse the switch when ratchet synchronization starts before the new queue is created" $ @@ -4502,6 +4504,29 @@ testSwitchConnectionDeletedWaitingDeliveryWhileNewQueue ps@(t, _) = get b =##> \case ("", "", DEL_CONNS [c]) -> c == aId; _ -> False storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) +testSwitchNewQueueRecordedWhileDeleting :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testSwitchNewQueueRecordedWhileDeleting (t, _) = do + withSmpServerConfigOn t cfgS2 testPort3 $ \_ -> do + aId <- withPausedProxyOn testPort testPort3 $ \_ resume -> do + atomically $ putTMVar resume () + withAgent 1 agentCfg oldServers testDB $ \a -> + withAgent 2 agentCfg oldServers testDB2 $ \b -> runRight $ fst <$> makeConnection a b + withPausedProxyOn testPort testPort3 $ \deleting resumeDelete -> + withPausedProxyOn testPort2 testPort3 $ \creating resumeCreate -> + withAgent 2 agentCfg newServers testDB2 $ \b -> + withAsync (runExceptT $ switchConnection b NRMInteractive aId) $ \switched -> do + timeout 5_000000 (atomically $ takeTMVar creating) `shouldReturn` Just () + withAsync (runExceptT $ deleteConnection b aId) $ \deleted -> do + timeout 5_000000 (atomically $ takeTMVar deleting) `shouldReturn` Just () + atomically $ putTMVar resumeCreate () + timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ CONN NOT_FOUND "") + atomically $ putTMVar resumeDelete () + timeout 5_000000 (wait deleted) `shouldReturn` Just (Right ()) + storeLogQueues testStoreLogFile2 `shouldReturn` (3, 2) + where + oldServers = initAgentServersLongConnect {smp = userServers [SMPServer testHost2 testPort testKeyHash]} + newServers = initAgentServersLongConnect {smp = userServers [testSMPServer2]} + testSwitchRestartedWhileNewQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () testSwitchRestartedWhileNewQueue ps@(t, _) = withSmpServer ps $ From f620a6be8d16b1a05010062718fe5b113fb388c0 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:53:19 +0000 Subject: [PATCH 02/18] agent: prevent waits for the notification command queue in a switch --- plans/2026-11-21-agent-no-blocking.md | 2 +- src/Simplex/Messaging/Agent.hs | 4 ++-- tests/AgentTests/NotificationTests.hs | 34 +++++++++++++++++++++++++-- 3 files changed, 35 insertions(+), 5 deletions(-) diff --git a/plans/2026-11-21-agent-no-blocking.md b/plans/2026-11-21-agent-no-blocking.md index 14bdd30c7..ed1ec5431 100644 --- a/plans/2026-11-21-agent-no-blocking.md +++ b/plans/2026-11-21-agent-no-blocking.md @@ -63,7 +63,7 @@ sequenceDiagram - agent, events written without waiting: - MSGNTF of `ackMessage`, DEL_CONNS, DEL_USER; - errors of `subscribeConnections`, `deleteConnections`, `subscribeAllConnections`, `deleteUser`, `xftpDeleteSndFilesRemote`; - - the notification command of connection deletion. + - the notification commands of connection deletion, ICQDelete and QEND. - clients: - a message in the response to ACK, SUB or GET is written to msgQ without waiting; - a command waits for send-queue space only until its response timeout, and is not queued after it ends; diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 7ce983db8..4716bd753 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -2453,7 +2453,7 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do withStore' c $ \db -> deleteConnRcvQueue db rq' >> deleteCommand db cmdId when enableNtfs $ do ns <- asks ntfSupervisor - liftIO $ sendNtfSubCommand ns (NSCCreate, [connId]) + liftIO . whenM (hasInstantNotifications ns) $ nonBlockingWriteTBQueue (ntfSubQ ns) (NSCCreate, [connId]) let conn' = DuplexConnection cData rqs sqs cStats <- connectionStats c conn' notify $ SWITCH QDRcv SPCompleted cStats @@ -4306,7 +4306,7 @@ processSMPTransmissions c@AgentClient {subQ, smpServersStats} (tSess@(userId, sr unless completed $ do when enableNtfs $ do ns <- asks ntfSupervisor - liftIO $ sendNtfSubCommand ns (NSCCreate, [connId]) + liftIO . whenM (hasInstantNotifications ns) $ nonBlockingWriteTBQueue (ntfSubQ ns) (NSCCreate, [connId]) let conn' = DuplexConnection cData' (keptRq :| keptRqs) sqs cStats <- connectionStats c conn' notify $ SWITCH QDRcv SPCompleted cStats diff --git a/tests/AgentTests/NotificationTests.hs b/tests/AgentTests/NotificationTests.hs index accf6723f..c4bd529b7 100644 --- a/tests/AgentTests/NotificationTests.hs +++ b/tests/AgentTests/NotificationTests.hs @@ -66,8 +66,8 @@ import SMPAgentClient (agentCfg, initAgentServers, initAgentServers2, testDB, te import SMPClient import Simplex.Messaging.Agent hiding (checkNtfToken, createConnection, joinConnection, registerNtfToken, sendMessage, verifyNtfToken) import qualified Simplex.Messaging.Agent as A -import Simplex.Messaging.Agent.Client (ProtocolTestFailure (..), ProtocolTestStep (..), ServerQueueInfo (..), withStore') -import Simplex.Messaging.Agent.Env.SQLite (AgentConfig, Env (..), InitialAgentServers) +import Simplex.Messaging.Agent.Client (AgentOpState (..), ProtocolTestFailure (..), ProtocolTestStep (..), ServerQueueInfo (..), withStore') +import Simplex.Messaging.Agent.Env.SQLite (AgentConfig, Env (..), InitialAgentServers, NtfSupervisor (..), NtfSupervisorCommand (..)) import Simplex.Messaging.Agent.Protocol hiding (CON, CONF, INFO, SENT) import Simplex.Messaging.Agent.Store.AgentStore (getSavedNtfToken) import Simplex.Messaging.Agent.Store.Common (withTransaction) @@ -89,6 +89,7 @@ import Simplex.Messaging.Server.Information (ServerPublicInfo (..)) import Simplex.Messaging.Server.QueueStore.QueueInfo (QueueInfo (..)) import Simplex.Messaging.Transport (ASrvTransport) import Simplex.Messaging.Transport.Server (TransportServerConfig (..)) +import Simplex.Messaging.Util (unlessM) import System.Process (callCommand) import Test.Hspec hiding (fit, it) import UnliftIO @@ -177,6 +178,15 @@ notificationTests ps@(t, _) = do testServerMatrix2 ps $ \servers -> withAPNSMockServer $ \apns -> withNtfServer t $ testSwitchNotifications agentCfg fastSwitchComplete servers apns + describe "should complete switch when notification command queue is full" $ do + it "slow rotation" $ + withSmpServer ps $ + withAPNSMockServer $ \apns -> + withNtfServer t $ testSwitchFullNtfQueue agentCfgV7 switchComplete apns + it "fast rotation" $ + withSmpServer ps $ + withAPNSMockServer $ \apns -> + withNtfServer t $ testSwitchFullNtfQueue agentCfg fastSwitchComplete apns it "should keep sending notifications for old token" $ withSmpServer ps $ withAPNSMockServer $ \apns -> @@ -903,6 +913,26 @@ testSwitchNotifications cfg completeSwitch servers apns = liftIO $ threadDelay 500000 testMessage "hello again" +testSwitchFullNtfQueue :: HasTestEnv => AgentConfig -> (AgentClient -> ByteString -> AgentClient -> ByteString -> ExceptT AgentErrorType IO ()) -> APNSMockServer -> IO () +testSwitchFullNtfQueue cfg completeSwitch apns = + withAgentClientsCfg2 cfg cfg $ \a b -> do + (aId, bId) <- runRight $ do + (aId, bId) <- makeConnection a b + exchangeGreetings a bId b aId + _ <- registerTestToken a "abcd" NMInstant apns + pure (aId, bId) + let q = ntfSubQ $ ntfSupervisor $ agentEnv a + setNtfSuspended suspended = atomically $ modifyTVar' (ntfNetworkOp a) $ \s -> s {opSuspended = suspended} + fill = unlessM (isFullTBQueue q) $ writeTBQueue q (NSCDeleteSub, ["x"]) >> fill + setNtfSuspended True + atomically $ writeTBQueue q (NSCDeleteSub, ["x"]) + atomically $ isEmptyTBQueue q >>= checkSTM + atomically fill + runRight_ $ do + _ <- switchConnectionAsync a "" bId + completeSwitch a bId b aId + setNtfSuspended False + testNotificationsOldToken :: HasTestEnv => APNSMockServer -> IO () testNotificationsOldToken apns = withAgentClients3 $ \a b c -> runRight_ $ do From de119c4032c5abc26081e0b59c49d43d1438971c Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:55:33 +0000 Subject: [PATCH 03/18] agent: prevent an error event when an asynchronous switch is aborted --- plans/2026-11-21-agent-no-blocking.md | 2 +- src/Simplex/Messaging/Agent.hs | 25 ++++++++++++++----------- tests/AgentTests/FunctionalAPITests.hs | 24 ++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 12 deletions(-) diff --git a/plans/2026-11-21-agent-no-blocking.md b/plans/2026-11-21-agent-no-blocking.md index ed1ec5431..1745da525 100644 --- a/plans/2026-11-21-agent-no-blocking.md +++ b/plans/2026-11-21-agent-no-blocking.md @@ -56,7 +56,7 @@ sequenceDiagram - a connection whose deletion waits for delivery is not given new queues; - the record step of an acknowledgement reads the queue again; - a concurrent acknowledgement of a deleted message is dropped; - - each switch start has an identifier; an abort removes it, a new start replaces it, and a switch whose identifier is no longer current is aborted after its queue is created; + - each switch start has an identifier; an abort removes it, a new start replaces it, and a switch whose identifier is no longer current is aborted after its queue is created, without an event from an asynchronous switch; - the receive queue status is set to Secured under the lock, only from Confirmed; - ICQSecure and ICQSndSecure are postponed while the ratchet is not synchronized, after the other commands of their server, and resumed after synchronization; - SWCH is refused while the ratchet is not synchronized. diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index 4716bd753..c25dd7121 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -2324,7 +2324,7 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do noServer . tryAtomicCommand $ do (conn, replaced, switchId) <- withConnLock c connId "switchConnection" startSwitch switchDuplexConnection c NRMBackground (Just cmdId) switchId conn replaced `allFinally` endRcvSwitch c connId switchId - >>= notify . SWITCH QDRcv SPStarted + >>= maybe (withStore' c (`deleteCommand` cmdId)) (notify . SWITCH QDRcv SPStarted) where startSwitch :: AM (Connection 'CDuplex, RcvQueue, Unique) startSwitch = @@ -2965,6 +2965,7 @@ switchConnection' c nm connId = do (cData, rqs, sqs, rq',) <$> newRcvSwitch c connId _ -> throwE $ CMD PROHIBITED "switchConnection: not duplex" switchDuplexConnection c nm Nothing switchId (DuplexConnection cData rqs sqs) rq' `allFinally` endRcvSwitch c connId switchId + >>= maybe (throwE $ CMD PROHIBITED "switchConnection: aborted") pure newRcvSwitch :: AgentClient -> ConnId -> AM Unique newRcvSwitch c connId = do @@ -2974,7 +2975,7 @@ newRcvSwitch c connId = do endRcvSwitch :: AgentClient -> ConnId -> Unique -> AM () endRcvSwitch c connId switchId = atomically $ TM.alter (mfilter (/= switchId)) connId $ rcvSwitches c -switchDuplexConnection :: AgentClient -> NetworkRequestMode -> Maybe AsyncCmdId -> Unique -> Connection 'CDuplex -> RcvQueue -> AM ConnectionStats +switchDuplexConnection :: AgentClient -> NetworkRequestMode -> Maybe AsyncCmdId -> Unique -> Connection 'CDuplex -> RcvQueue -> AM (Maybe ConnectionStats) switchDuplexConnection c nm cmdId_ switchId (DuplexConnection ConnData {connId, userId} rqs sqs) rq@RcvQueue {server, dbQueueId = DBEntityId dbQueueId, sndId} = do checkRQSwchStatus rq RSSwitchStarted clientVRange <- asks $ smpClientVRange . config @@ -2992,15 +2993,17 @@ switchDuplexConnection c nm cmdId_ switchId (DuplexConnection ConnData {connId, _ -> throwE $ INTERNAL "switchConnection: replaced queue not found in connection" recordNewQueue c nm connId "switchConnection" tSess q addRcvQueue $ \(cData, rqs', sqs', rq1, rq'') -> do started <- (Just switchId ==) <$> liftIO (TM.lookupIO connId $ rcvSwitches c) - when (rcvSwchStatus rq1 /= Just RSSwitchStarted || not started) $ deleteRcvQueueAsync c rq'' >> throwE (CMD PROHIBITED "switchConnection: aborted") - when (ratchetSyncSendProhibited cData) $ do - void $ withStore' c $ \db -> setRcvSwitchStatus db rq1 Nothing - deleteRcvQueueAsync c rq'' >> throwE (CMD PROHIBITED "switchConnection: send prohibited") - lift $ addNewQueueSubscription c rq'' tSess sessId serviceId_ - void . enqueueMessages c cData sqs' SMP.noMsgFlags $ QADD [(qUri, Just (server, sndId))] - rq1' <- withStore' c $ \db -> setRcvSwitchStatus db rq1 (Just RSSendingQADD) <* mapM_ (deleteCommand db) cmdId_ - let rqs'' = updatedQs rq1' rqs' <> [rq''] - connectionStats c $ DuplexConnection cData rqs'' sqs' + if rcvSwchStatus rq1 /= Just RSSwitchStarted || not started + then Nothing <$ deleteRcvQueueAsync c rq'' + else do + when (ratchetSyncSendProhibited cData) $ do + void $ withStore' c $ \db -> setRcvSwitchStatus db rq1 Nothing + deleteRcvQueueAsync c rq'' >> throwE (CMD PROHIBITED "switchConnection: send prohibited") + lift $ addNewQueueSubscription c rq'' tSess sessId serviceId_ + void . enqueueMessages c cData sqs' SMP.noMsgFlags $ QADD [(qUri, Just (server, sndId))] + rq1' <- withStore' c $ \db -> setRcvSwitchStatus db rq1 (Just RSSendingQADD) <* mapM_ (deleteCommand db) cmdId_ + let rqs'' = updatedQs rq1' rqs' <> [rq''] + Just <$> connectionStats c (DuplexConnection cData rqs'' sqs') abortConnectionSwitch' :: AgentClient -> ConnId -> AM ConnectionStats abortConnectionSwitch' c connId = diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 5e9c8920d..bbabc8bfc 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -643,6 +643,8 @@ functionalAPITests ps = do testSwitchNewQueueRecordedWhileDeleting ps it "should delete the new queue when the switch is aborted and started again while the queue is created" $ testSwitchRestartedWhileNewQueue ps + it "should end the asynchronous switch without an event when it is aborted while the queue is created" $ + testSwitchAsyncAbortedWhileNewQueue ps it "should refuse the switch when ratchet synchronization starts before the new queue is created" $ testSwitchRatchetSyncBeforeNewQueue ps it "should secure the new queue and complete the switch after ratchet synchronization" $ @@ -4547,6 +4549,28 @@ testSwitchRestartedWhileNewQueue ps@(t, _) = waitRcvQueueRecords b 2 storeLogQueues testStoreLogFile2 `shouldReturn` (2, 1) +testSwitchAsyncAbortedWhileNewQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testSwitchAsyncAbortedWhileNewQueue ps@(t, _) = + withSmpServer ps $ + withAgent 2 agentCfg initAgentServersLongConnect testDB2 $ \b -> do + (aId, _) <- withAgent 1 agentCfg initAgentServers testDB $ \a -> runRight $ makeConnection a b + setProtocolServers b 1 [noAuthSrvCfg testSMPServer2] + withSmpServerConfigOn t cfgS2 testPort3 $ \_ -> + withPausedProxyOn testPort2 testPort3 $ \accepted resume -> do + void . runRight $ switchConnectionAsync b "" aId + timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () + void . runRight $ abortConnectionSwitch b aId + atomically $ putTMVar resume () + timeout 5_000000 (waitNoCommands b) `shouldReturn` Just () + runRight (getConnectionServers b aId) >>= (`shouldMatchList` [Nothing]) . rcvSwchStatuses' + waitRcvQueueRecords b 1 + noMessages b "nothing else should be delivered" + storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) + where + waitNoCommands c = do + cmds :: [(ConnId, Int64)] <- withTransaction (store $ agentEnv c) (`DB.query_` "SELECT conn_id, command_id FROM commands") + unless (null cmds) $ threadDelay 100000 >> waitNoCommands c + testJoinConnectionDeletedWhileReplyQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () testJoinConnectionDeletedWhileReplyQueue ps@(t, _) = withSmpServer ps $ From b4e3329fd1468f9b28c3b5f61da5809d5add320c Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:53:05 +0000 Subject: [PATCH 04/18] tests: time out the switch with a full notification command queue --- tests/AgentTests/NotificationTests.hs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tests/AgentTests/NotificationTests.hs b/tests/AgentTests/NotificationTests.hs index c4bd529b7..1efe82c2e 100644 --- a/tests/AgentTests/NotificationTests.hs +++ b/tests/AgentTests/NotificationTests.hs @@ -928,9 +928,7 @@ testSwitchFullNtfQueue cfg completeSwitch apns = atomically $ writeTBQueue q (NSCDeleteSub, ["x"]) atomically $ isEmptyTBQueue q >>= checkSTM atomically fill - runRight_ $ do - _ <- switchConnectionAsync a "" bId - completeSwitch a bId b aId + timeout 20000000 (runExceptT $ switchConnectionAsync a "" bId >> completeSwitch a bId b aId) `shouldReturn` Just (Right ()) setNtfSuspended False testNotificationsOldToken :: HasTestEnv => APNSMockServer -> IO () From f8890ac32f16a1c6dc565d523fd8fb90204cb182 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:53:05 +0000 Subject: [PATCH 05/18] plans: lock holders never wait for notification command queue space --- plans/2026-11-21-agent-no-blocking.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plans/2026-11-21-agent-no-blocking.md b/plans/2026-11-21-agent-no-blocking.md index 1745da525..21db906a0 100644 --- a/plans/2026-11-21-agent-no-blocking.md +++ b/plans/2026-11-21-agent-no-blocking.md @@ -12,7 +12,7 @@ 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. +4. API threads and lock holders never wait for space in subQ or msgQ; lock holders never wait for space in ntfSubQ. ## Helpers From 36d3207292cf14c70335873fa998168702638608 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:34:03 +0000 Subject: [PATCH 06/18] clients: simplify command sending; request time in system seconds --- src/Simplex/Messaging/Client.hs | 51 ++++++++++++++------------------- tests/SMPProxyTests.hs | 22 ++------------ 2 files changed, 25 insertions(+), 48 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index a743c1b30..281817357 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -155,10 +155,10 @@ import Data.List (find, isSuffixOf) import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.List.NonEmpty as L import qualified Data.Map.Strict as M -import Data.Maybe (catMaybes, fromMaybe, isNothing) +import Data.Maybe (catMaybes, fromMaybe) import Data.Text (Text) import qualified Data.Text as T -import Data.Time.Clock (NominalDiffTime, UTCTime (..), diffUTCTime, getCurrentTime) +import Data.Time.Clock (UTCTime (..), diffUTCTime, getCurrentTime) import qualified Data.X509 as X import qualified Data.X509.Validation as XV import Network.Socket (HostName, ServiceName) @@ -172,6 +172,7 @@ import Simplex.Messaging.Protocol import Simplex.Messaging.Protocol.Types import Simplex.Messaging.Server.QueueStore.QueueInfo import Simplex.Messaging.SimplexName (SimplexDomain, fullDomainName) +import Simplex.Messaging.SystemTime (SystemSeconds, getSystemSeconds, roundedSeconds) import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM import Simplex.Messaging.Transport @@ -214,7 +215,7 @@ data PClient v err msg = PClient smpClientStub :: TVar ChaChaDRG -> ByteString -> VersionSMP -> Maybe (THandleAuth 'TClient) -> IO SMPClient smpClientStub g sessionId thVersion thAuth = do let ts = UTCTime (read "2024-03-31") 0 - connected <- newTVarIO True + connected <- newTVarIO False clientCorrId <- atomically $ C.newRandomDRG g sentCommands <- TM.emptyIO sendPings <- newTVarIO False @@ -483,7 +484,7 @@ data ProtocolClientConfig v = ProtocolClientConfig defaultTransport :: (ServiceName, ATransport 'TClient), -- | network configuration networkConfig :: NetworkConfig, - sentCommandsTTL :: NominalDiffTime, + sentCommandsTTL :: Int64, clientALPN :: Maybe [ALPN], serviceCredentials :: Maybe ServiceCredentials, -- | client-server protocol version range @@ -528,7 +529,7 @@ data Request err msg = Request { corrId :: CorrId, entityId :: EntityId, command :: ProtoCommand msg, - createdAt :: UTCTime, + createdAt :: SystemSeconds, pending :: TVar Bool, responseVar :: TMVar (Either (ProtocolClientError err) msg) } @@ -665,9 +666,10 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS `E.finally` (failPendingRequests c >> disconnected c') failPendingRequests :: PClient v err msg -> IO () - failPendingRequests PClient {connected, sentCommands} = atomically $ do - writeTVar connected False - swapTVar sentCommands mempty >>= mapM_ failRequest + failPendingRequests PClient {sentCommands} = atomically $ swapTVar sentCommands mempty >>= mapM_ failRequest + where + failRequest Request {pending, responseVar} = + whenM (swapTVar pending False) $ void $ tryPutTMVar responseVar $ Left $ PCENetworkError NEFailedError send :: Transport c => ProtocolClient v err msg -> THandle v c 'TClient -> IO () send ProtocolClient {client_ = PClient {sndQ}} h = forever $ atomically (readTBQueue sndQ) >>= sendPending @@ -691,9 +693,9 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS loop :: Int64 -> IO () loop delay = do threadDelay' delay - ts <- getCurrentTime - atomically $ modifyTVar' sentCommands $ M.filter $ \Request {createdAt} -> diffUTCTime ts createdAt < sentCommandsTTL - diff <- diffUTCTime ts <$> readTVarIO lastReceived + ts <- getSystemSeconds + atomically $ modifyTVar' sentCommands $ M.filter $ \Request {createdAt} -> roundedSeconds ts - roundedSeconds createdAt < sentCommandsTTL + diff <- diffUTCTime <$> getCurrentTime <*> readTVarIO lastReceived let idle = diffToMicroseconds diff remaining = smpPingInterval - idle if remaining > 1_000_000 -- delay pings only for significant time @@ -1392,19 +1394,13 @@ sendProtocolCommand_ c@ProtocolClient {thParams = THandleParams {blockSize, serv s = tEncodeBatch1 serviceAuth t sendBlock :: ProtocolClient v err msg -> [Request err msg] -> (Maybe (Request err msg), ByteString) -> IO a -> IO a -sendBlock ProtocolClient {client_ = PClient {connected, sentCommands, sndQ, msgQ}} rs t getResponses = - -- two separate "atomically" needed to avoid blocking - E.bracketOnError - (atomically $ ifM (readTVar connected) (mapM_ addRequest rs >> tryWriteTBQueue sndQ t) (True <$ mapM_ failRequest rs)) - (\_ -> when (isNothing msgQ) $ atomically $ mapM_ removeRequest rs) - (\sent -> if sent then getResponses else withAsync (atomically $ writeTBQueue sndQ t) (const getResponses)) +sendBlock ProtocolClient {client_ = PClient {sentCommands, sndQ, msgQ}} rs t getResponses = case msgQ of + Just _ -> register >> send + Nothing -> E.bracket_ register unregister send where - addRequest r@Request {corrId} = TM.insert corrId r sentCommands - removeRequest Request {corrId} = TM.delete corrId sentCommands - -failRequest :: Request err msg -> STM () -failRequest Request {pending, responseVar} = - whenM (swapTVar pending False) $ void $ tryPutTMVar responseVar $ Left $ PCENetworkError NEFailedError + register = atomically $ forM_ rs $ \r@Request {corrId} -> TM.insert corrId r sentCommands + unregister = atomically $ forM_ rs $ \Request {corrId} -> TM.delete corrId sentCommands + send = withAsync (atomically $ writeTBQueue sndQ t) (const getResponses) nonBlockingWriteTBQueue :: TBQueue a -> a -> IO () nonBlockingWriteTBQueue q x = do @@ -1412,7 +1408,7 @@ nonBlockingWriteTBQueue q x = do unless sent $ void $ forkIO $ atomically $ writeTBQueue q x getResponse :: ProtocolClient v err msg -> NetworkRequestMode -> Maybe Int -> Request err msg -> IO (Response err msg) -getResponse ProtocolClient {client_ = PClient {tcpTimeout, timeoutErrorCount, sentCommands, msgQ}} nm tOut Request {corrId, entityId, pending, responseVar} = do +getResponse ProtocolClient {client_ = PClient {tcpTimeout, timeoutErrorCount}} nm tOut Request {entityId, pending, responseVar} = do r <- fromMaybe (netTimeoutInt tcpTimeout nm) tOut `timeout` atomically (takeTMVar responseVar) response <- atomically $ do writeTVar pending False @@ -1421,10 +1417,7 @@ getResponse ProtocolClient {client_ = PClient {tcpTimeout, timeoutErrorCount, se -- See `processMsg`. ((r <|>) <$> tryTakeTMVar responseVar) >>= \case Just r' -> writeTVar timeoutErrorCount 0 $> r' - Nothing -> do - modifyTVar' timeoutErrorCount (+ 1) - when (isNothing msgQ) $ TM.delete corrId sentCommands - pure $ Left PCEResponseTimeout + Nothing -> modifyTVar' timeoutErrorCount (+ 1) $> Left PCEResponseTimeout pure Response {entityId, response} mkTransmission :: Protocol v err msg => ProtocolClient v err msg -> ClientCommand msg -> IO (PCTransmission err msg) @@ -1440,7 +1433,7 @@ mkTransmission_ ProtocolClient {thParams, client_ = PClient {clientCorrId}} nonc where mkRequest :: CorrId -> IO (Request err msg) mkRequest corrId = do - createdAt <- getCurrentTime + createdAt <- getSystemSeconds pending <- newTVarIO True responseVar <- newEmptyTMVarIO let r = diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 29b6f10c6..dca8d792b 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -74,8 +74,6 @@ smpProxyTests = do testProxyClosesRelayConnectionAfterDisconnect it "does not keep oversized forwarded command" $ \_ -> testForwardOversizedNotKept - it "fails commands of closed client at once" $ \_ -> - testClosedClientCommandsFail it "releases command kept for late response" $ \_ -> testLateResponseCommandReleased describe "agent client reconnection" $ do @@ -642,34 +640,20 @@ testForwardOversizedNotKept = `shouldReturn` Left (PCETransportError TELargeMsg) pClientSentCommandsCount c `shouldReturn` 0 -testClosedClientCommandsFail :: HasTestEnv => IO () -testClosedClientCommandsFail = - withSmpServerConfigOn (transport @TLS) cfg testPort $ \_ -> do - g <- C.newRandom - ts <- getCurrentTime - closed <- newEmptyTMVarIO - c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) defaultSMPClientConfig [] Nothing ts (\_ -> atomically $ putTMVar closed ()) - closeProtocolClient c - atomically $ takeTMVar closed - Just rs <- timeout 1000000 $ sendProtocolCommands c NRMBackground $ L.fromList $ replicate 300 (NoEntity, Nothing, SMP.Cmd SMP.SIdleClient SMP.PING) - forM_ rs $ \(Response _ r) -> r `shouldBe` Left (PCENetworkError SMP.NEFailedError) - pClientSentCommandsCount c `shouldReturn` 0 - atomically (lengthTBQueue $ pClientSndQ c) `shouldReturn` 0 - testLateResponseCommandReleased :: HasTestEnv => IO () testLateResponseCommandReleased = - withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 2000000}) testPort $ \_ -> do + withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 4000000}) testPort $ \_ -> do g <- C.newRandom ts <- getCurrentTime msgQ <- newTBQueueIO 4 - let clientCfg = defaultSMPClientConfig {networkConfig = defaultNetworkConfig {smpPingInterval = 100000}, sentCommandsTTL = 0.5} + let clientCfg = defaultSMPClientConfig {networkConfig = defaultNetworkConfig {smpPingInterval = 100000}, sentCommandsTTL = 2} c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) clientCfg [] (Just msgQ) ts (\_ -> pure ()) rId <- atomically $ SMP.EntityId <$> C.randomBytes 24 g (_, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g runExceptT (sendProtocolCommand_ c NRMBackground Nothing (Just 100000) (Just rpKey) rId (SMP.Cmd SMP.SRecipient SMP.SUB)) `shouldReturn` Left PCEResponseTimeout pClientSentCommandsCount c `shouldReturn` 1 - threadDelay 1000000 + threadDelay 3000000 pClientSentCommandsCount c `shouldReturn` 0 (_, _, [(_, STUnexpectedError _)]) <- atomically $ readTBQueue msgQ pure () From 4c2ee391b67dc4a487e4174432e6d4dfce032516 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:36:46 +0000 Subject: [PATCH 07/18] clients: fail commands of a disconnected client without queueing them --- src/Simplex/Messaging/Client.hs | 17 ++++++++++------- tests/SMPProxyTests.hs | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 281817357..46408cdee 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -215,7 +215,7 @@ data PClient v err msg = PClient smpClientStub :: TVar ChaChaDRG -> ByteString -> VersionSMP -> Maybe (THandleAuth 'TClient) -> IO SMPClient smpClientStub g sessionId thVersion thAuth = do let ts = UTCTime (read "2024-03-31") 0 - connected <- newTVarIO False + connected <- newTVarIO True clientCorrId <- atomically $ C.newRandomDRG g sentCommands <- TM.emptyIO sendPings <- newTVarIO False @@ -666,10 +666,9 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS `E.finally` (failPendingRequests c >> disconnected c') failPendingRequests :: PClient v err msg -> IO () - failPendingRequests PClient {sentCommands} = atomically $ swapTVar sentCommands mempty >>= mapM_ failRequest - where - failRequest Request {pending, responseVar} = - whenM (swapTVar pending False) $ void $ tryPutTMVar responseVar $ Left $ PCENetworkError NEFailedError + failPendingRequests PClient {connected, sentCommands} = atomically $ do + writeTVar connected False + swapTVar sentCommands mempty >>= mapM_ failRequest send :: Transport c => ProtocolClient v err msg -> THandle v c 'TClient -> IO () send ProtocolClient {client_ = PClient {sndQ}} h = forever $ atomically (readTBQueue sndQ) >>= sendPending @@ -1394,13 +1393,17 @@ sendProtocolCommand_ c@ProtocolClient {thParams = THandleParams {blockSize, serv s = tEncodeBatch1 serviceAuth t sendBlock :: ProtocolClient v err msg -> [Request err msg] -> (Maybe (Request err msg), ByteString) -> IO a -> IO a -sendBlock ProtocolClient {client_ = PClient {sentCommands, sndQ, msgQ}} rs t getResponses = case msgQ of +sendBlock ProtocolClient {client_ = PClient {connected, sentCommands, sndQ, msgQ}} rs t getResponses = case msgQ of Just _ -> register >> send Nothing -> E.bracket_ register unregister send where register = atomically $ forM_ rs $ \r@Request {corrId} -> TM.insert corrId r sentCommands unregister = atomically $ forM_ rs $ \Request {corrId} -> TM.delete corrId sentCommands - send = withAsync (atomically $ writeTBQueue sndQ t) (const getResponses) + send = withAsync (atomically $ ifM (readTVar connected) (writeTBQueue sndQ t) (mapM_ failRequest rs)) (const getResponses) + +failRequest :: Request err msg -> STM () +failRequest Request {pending, responseVar} = + whenM (swapTVar pending False) $ void $ tryPutTMVar responseVar $ Left $ PCENetworkError NEFailedError nonBlockingWriteTBQueue :: TBQueue a -> a -> IO () nonBlockingWriteTBQueue q x = do diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index dca8d792b..115dfb12b 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -74,6 +74,8 @@ smpProxyTests = do testProxyClosesRelayConnectionAfterDisconnect it "does not keep oversized forwarded command" $ \_ -> testForwardOversizedNotKept + it "fails commands of closed client at once" $ \_ -> + testClosedClientCommandsFail it "releases command kept for late response" $ \_ -> testLateResponseCommandReleased describe "agent client reconnection" $ do @@ -640,6 +642,20 @@ testForwardOversizedNotKept = `shouldReturn` Left (PCETransportError TELargeMsg) pClientSentCommandsCount c `shouldReturn` 0 +testClosedClientCommandsFail :: HasTestEnv => IO () +testClosedClientCommandsFail = + withSmpServerConfigOn (transport @TLS) cfg testPort $ \_ -> do + g <- C.newRandom + ts <- getCurrentTime + closed <- newEmptyTMVarIO + c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) defaultSMPClientConfig [] Nothing ts (\_ -> atomically $ putTMVar closed ()) + closeProtocolClient c + atomically $ takeTMVar closed + Just rs <- timeout 1000000 $ sendProtocolCommands c NRMBackground $ L.fromList $ replicate 300 (NoEntity, Nothing, SMP.Cmd SMP.SIdleClient SMP.PING) + forM_ rs $ \(Response _ r) -> r `shouldBe` Left (PCENetworkError SMP.NEFailedError) + pClientSentCommandsCount c `shouldReturn` 0 + atomically (lengthTBQueue $ pClientSndQ c) `shouldReturn` 0 + testLateResponseCommandReleased :: HasTestEnv => IO () testLateResponseCommandReleased = withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 4000000}) testPort $ \_ -> do From 953dac4b3f3e56305e3e9442ef927bf08508348d Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:39:29 +0000 Subject: [PATCH 08/18] clients: revert command sending to f8890ac3 --- src/Simplex/Messaging/Client.hs | 38 ++++++++++++++++++--------------- tests/SMPProxyTests.hs | 6 +++--- 2 files changed, 24 insertions(+), 20 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 46408cdee..a743c1b30 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -155,10 +155,10 @@ import Data.List (find, isSuffixOf) import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.List.NonEmpty as L import qualified Data.Map.Strict as M -import Data.Maybe (catMaybes, fromMaybe) +import Data.Maybe (catMaybes, fromMaybe, isNothing) import Data.Text (Text) import qualified Data.Text as T -import Data.Time.Clock (UTCTime (..), diffUTCTime, getCurrentTime) +import Data.Time.Clock (NominalDiffTime, UTCTime (..), diffUTCTime, getCurrentTime) import qualified Data.X509 as X import qualified Data.X509.Validation as XV import Network.Socket (HostName, ServiceName) @@ -172,7 +172,6 @@ import Simplex.Messaging.Protocol import Simplex.Messaging.Protocol.Types import Simplex.Messaging.Server.QueueStore.QueueInfo import Simplex.Messaging.SimplexName (SimplexDomain, fullDomainName) -import Simplex.Messaging.SystemTime (SystemSeconds, getSystemSeconds, roundedSeconds) import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM import Simplex.Messaging.Transport @@ -484,7 +483,7 @@ data ProtocolClientConfig v = ProtocolClientConfig defaultTransport :: (ServiceName, ATransport 'TClient), -- | network configuration networkConfig :: NetworkConfig, - sentCommandsTTL :: Int64, + sentCommandsTTL :: NominalDiffTime, clientALPN :: Maybe [ALPN], serviceCredentials :: Maybe ServiceCredentials, -- | client-server protocol version range @@ -529,7 +528,7 @@ data Request err msg = Request { corrId :: CorrId, entityId :: EntityId, command :: ProtoCommand msg, - createdAt :: SystemSeconds, + createdAt :: UTCTime, pending :: TVar Bool, responseVar :: TMVar (Either (ProtocolClientError err) msg) } @@ -692,9 +691,9 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS loop :: Int64 -> IO () loop delay = do threadDelay' delay - ts <- getSystemSeconds - atomically $ modifyTVar' sentCommands $ M.filter $ \Request {createdAt} -> roundedSeconds ts - roundedSeconds createdAt < sentCommandsTTL - diff <- diffUTCTime <$> getCurrentTime <*> readTVarIO lastReceived + ts <- getCurrentTime + atomically $ modifyTVar' sentCommands $ M.filter $ \Request {createdAt} -> diffUTCTime ts createdAt < sentCommandsTTL + diff <- diffUTCTime ts <$> readTVarIO lastReceived let idle = diffToMicroseconds diff remaining = smpPingInterval - idle if remaining > 1_000_000 -- delay pings only for significant time @@ -1393,13 +1392,15 @@ sendProtocolCommand_ c@ProtocolClient {thParams = THandleParams {blockSize, serv s = tEncodeBatch1 serviceAuth t sendBlock :: ProtocolClient v err msg -> [Request err msg] -> (Maybe (Request err msg), ByteString) -> IO a -> IO a -sendBlock ProtocolClient {client_ = PClient {connected, sentCommands, sndQ, msgQ}} rs t getResponses = case msgQ of - Just _ -> register >> send - Nothing -> E.bracket_ register unregister send +sendBlock ProtocolClient {client_ = PClient {connected, sentCommands, sndQ, msgQ}} rs t getResponses = + -- two separate "atomically" needed to avoid blocking + E.bracketOnError + (atomically $ ifM (readTVar connected) (mapM_ addRequest rs >> tryWriteTBQueue sndQ t) (True <$ mapM_ failRequest rs)) + (\_ -> when (isNothing msgQ) $ atomically $ mapM_ removeRequest rs) + (\sent -> if sent then getResponses else withAsync (atomically $ writeTBQueue sndQ t) (const getResponses)) where - register = atomically $ forM_ rs $ \r@Request {corrId} -> TM.insert corrId r sentCommands - unregister = atomically $ forM_ rs $ \Request {corrId} -> TM.delete corrId sentCommands - send = withAsync (atomically $ ifM (readTVar connected) (writeTBQueue sndQ t) (mapM_ failRequest rs)) (const getResponses) + addRequest r@Request {corrId} = TM.insert corrId r sentCommands + removeRequest Request {corrId} = TM.delete corrId sentCommands failRequest :: Request err msg -> STM () failRequest Request {pending, responseVar} = @@ -1411,7 +1412,7 @@ nonBlockingWriteTBQueue q x = do unless sent $ void $ forkIO $ atomically $ writeTBQueue q x getResponse :: ProtocolClient v err msg -> NetworkRequestMode -> Maybe Int -> Request err msg -> IO (Response err msg) -getResponse ProtocolClient {client_ = PClient {tcpTimeout, timeoutErrorCount}} nm tOut Request {entityId, pending, responseVar} = do +getResponse ProtocolClient {client_ = PClient {tcpTimeout, timeoutErrorCount, sentCommands, msgQ}} nm tOut Request {corrId, entityId, pending, responseVar} = do r <- fromMaybe (netTimeoutInt tcpTimeout nm) tOut `timeout` atomically (takeTMVar responseVar) response <- atomically $ do writeTVar pending False @@ -1420,7 +1421,10 @@ getResponse ProtocolClient {client_ = PClient {tcpTimeout, timeoutErrorCount}} n -- See `processMsg`. ((r <|>) <$> tryTakeTMVar responseVar) >>= \case Just r' -> writeTVar timeoutErrorCount 0 $> r' - Nothing -> modifyTVar' timeoutErrorCount (+ 1) $> Left PCEResponseTimeout + Nothing -> do + modifyTVar' timeoutErrorCount (+ 1) + when (isNothing msgQ) $ TM.delete corrId sentCommands + pure $ Left PCEResponseTimeout pure Response {entityId, response} mkTransmission :: Protocol v err msg => ProtocolClient v err msg -> ClientCommand msg -> IO (PCTransmission err msg) @@ -1436,7 +1440,7 @@ mkTransmission_ ProtocolClient {thParams, client_ = PClient {clientCorrId}} nonc where mkRequest :: CorrId -> IO (Request err msg) mkRequest corrId = do - createdAt <- getSystemSeconds + createdAt <- getCurrentTime pending <- newTVarIO True responseVar <- newEmptyTMVarIO let r = diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 115dfb12b..29b6f10c6 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -658,18 +658,18 @@ testClosedClientCommandsFail = testLateResponseCommandReleased :: HasTestEnv => IO () testLateResponseCommandReleased = - withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 4000000}) testPort $ \_ -> do + withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 2000000}) testPort $ \_ -> do g <- C.newRandom ts <- getCurrentTime msgQ <- newTBQueueIO 4 - let clientCfg = defaultSMPClientConfig {networkConfig = defaultNetworkConfig {smpPingInterval = 100000}, sentCommandsTTL = 2} + let clientCfg = defaultSMPClientConfig {networkConfig = defaultNetworkConfig {smpPingInterval = 100000}, sentCommandsTTL = 0.5} c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) clientCfg [] (Just msgQ) ts (\_ -> pure ()) rId <- atomically $ SMP.EntityId <$> C.randomBytes 24 g (_, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g runExceptT (sendProtocolCommand_ c NRMBackground Nothing (Just 100000) (Just rpKey) rId (SMP.Cmd SMP.SRecipient SMP.SUB)) `shouldReturn` Left PCEResponseTimeout pClientSentCommandsCount c `shouldReturn` 1 - threadDelay 3000000 + threadDelay 1000000 pClientSentCommandsCount c `shouldReturn` 0 (_, _, [(_, STUnexpectedError _)]) <- atomically $ readTBQueue msgQ pure () From f0bdba64ac3ee4ccec11e25514a715c7ab8da28f Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:56:42 +0000 Subject: [PATCH 09/18] clients: send a block only while connected, with one dispatch on msgQ --- src/Simplex/Messaging/Client.hs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index a743c1b30..d5ff97bc0 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -1394,13 +1394,13 @@ sendProtocolCommand_ c@ProtocolClient {thParams = THandleParams {blockSize, serv sendBlock :: ProtocolClient v err msg -> [Request err msg] -> (Maybe (Request err msg), ByteString) -> IO a -> IO a sendBlock ProtocolClient {client_ = PClient {connected, sentCommands, sndQ, msgQ}} rs t getResponses = -- two separate "atomically" needed to avoid blocking - E.bracketOnError - (atomically $ ifM (readTVar connected) (mapM_ addRequest rs >> tryWriteTBQueue sndQ t) (True <$ mapM_ failRequest rs)) - (\_ -> when (isNothing msgQ) $ atomically $ mapM_ removeRequest rs) - (\sent -> if sent then getResponses else withAsync (atomically $ writeTBQueue sndQ t) (const getResponses)) + case msgQ of + Just _ -> send >>= get + Nothing -> E.bracketOnError send (\_ -> atomically $ forM_ rs $ \Request {corrId} -> TM.delete corrId sentCommands) get where - addRequest r@Request {corrId} = TM.insert corrId r sentCommands - removeRequest Request {corrId} = TM.delete corrId sentCommands + send = sendOrFail $ forM_ rs (\r@Request {corrId} -> TM.insert corrId r sentCommands) >> tryWriteTBQueue sndQ t + get sent = if sent then getResponses else withAsync (sendOrFail $ True <$ writeTBQueue sndQ t) (const getResponses) + sendOrFail a = atomically $ ifM (readTVar connected) a (True <$ mapM_ failRequest rs) failRequest :: Request err msg -> STM () failRequest Request {pending, responseVar} = From c9ae815ac5e327275eea4d7a7ec1c8e96d8024fd Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:57:11 +0000 Subject: [PATCH 10/18] clients: request creation time in system seconds --- src/Simplex/Messaging/Client.hs | 15 ++++++++------- tests/SMPProxyTests.hs | 6 +++--- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index d5ff97bc0..c072812e0 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -158,7 +158,7 @@ import qualified Data.Map.Strict as M import Data.Maybe (catMaybes, fromMaybe, isNothing) import Data.Text (Text) import qualified Data.Text as T -import Data.Time.Clock (NominalDiffTime, UTCTime (..), diffUTCTime, getCurrentTime) +import Data.Time.Clock (UTCTime (..), diffUTCTime, getCurrentTime) import qualified Data.X509 as X import qualified Data.X509.Validation as XV import Network.Socket (HostName, ServiceName) @@ -172,6 +172,7 @@ import Simplex.Messaging.Protocol import Simplex.Messaging.Protocol.Types import Simplex.Messaging.Server.QueueStore.QueueInfo import Simplex.Messaging.SimplexName (SimplexDomain, fullDomainName) +import Simplex.Messaging.SystemTime (SystemSeconds, getSystemSeconds, roundedSeconds) import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM import Simplex.Messaging.Transport @@ -483,7 +484,7 @@ data ProtocolClientConfig v = ProtocolClientConfig defaultTransport :: (ServiceName, ATransport 'TClient), -- | network configuration networkConfig :: NetworkConfig, - sentCommandsTTL :: NominalDiffTime, + sentCommandsTTL :: Int64, clientALPN :: Maybe [ALPN], serviceCredentials :: Maybe ServiceCredentials, -- | client-server protocol version range @@ -528,7 +529,7 @@ data Request err msg = Request { corrId :: CorrId, entityId :: EntityId, command :: ProtoCommand msg, - createdAt :: UTCTime, + createdAt :: SystemSeconds, pending :: TVar Bool, responseVar :: TMVar (Either (ProtocolClientError err) msg) } @@ -691,9 +692,9 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS loop :: Int64 -> IO () loop delay = do threadDelay' delay - ts <- getCurrentTime - atomically $ modifyTVar' sentCommands $ M.filter $ \Request {createdAt} -> diffUTCTime ts createdAt < sentCommandsTTL - diff <- diffUTCTime ts <$> readTVarIO lastReceived + ts <- getSystemSeconds + atomically $ modifyTVar' sentCommands $ M.filter $ \Request {createdAt} -> roundedSeconds ts - roundedSeconds createdAt < sentCommandsTTL + diff <- diffUTCTime <$> getCurrentTime <*> readTVarIO lastReceived let idle = diffToMicroseconds diff remaining = smpPingInterval - idle if remaining > 1_000_000 -- delay pings only for significant time @@ -1440,7 +1441,7 @@ mkTransmission_ ProtocolClient {thParams, client_ = PClient {clientCorrId}} nonc where mkRequest :: CorrId -> IO (Request err msg) mkRequest corrId = do - createdAt <- getCurrentTime + createdAt <- getSystemSeconds pending <- newTVarIO True responseVar <- newEmptyTMVarIO let r = diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 29b6f10c6..115dfb12b 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -658,18 +658,18 @@ testClosedClientCommandsFail = testLateResponseCommandReleased :: HasTestEnv => IO () testLateResponseCommandReleased = - withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 2000000}) testPort $ \_ -> do + withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 4000000}) testPort $ \_ -> do g <- C.newRandom ts <- getCurrentTime msgQ <- newTBQueueIO 4 - let clientCfg = defaultSMPClientConfig {networkConfig = defaultNetworkConfig {smpPingInterval = 100000}, sentCommandsTTL = 0.5} + let clientCfg = defaultSMPClientConfig {networkConfig = defaultNetworkConfig {smpPingInterval = 100000}, sentCommandsTTL = 2} c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) clientCfg [] (Just msgQ) ts (\_ -> pure ()) rId <- atomically $ SMP.EntityId <$> C.randomBytes 24 g (_, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g runExceptT (sendProtocolCommand_ c NRMBackground Nothing (Just 100000) (Just rpKey) rId (SMP.Cmd SMP.SRecipient SMP.SUB)) `shouldReturn` Left PCEResponseTimeout pClientSentCommandsCount c `shouldReturn` 1 - threadDelay 1000000 + threadDelay 3000000 pClientSentCommandsCount c `shouldReturn` 0 (_, _, [(_, STUnexpectedError _)]) <- atomically $ readTBQueue msgQ pure () From c55ef71e3c563b24e5fd68240ac0998f51e02e7b Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:11:28 +0000 Subject: [PATCH 11/18] clients: write a message received in a response to msgQ in its order of reception --- src/Simplex/Messaging/Client.hs | 35 +++++++++++++++---------------- src/Simplex/Messaging/Protocol.hs | 6 ++++++ 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index c072812e0..96b5a049b 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -732,7 +732,9 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS (True <$ tryPutTMVar responseVar (if entityId == entId then clientResp else Left unexpected)) (pure False) if wasPending - then pure Nothing + then pure $ case clientResp of + Right r | entityId == entId && responseEvent r -> Just (entId, STEvent clientResp) + _ -> Nothing else sendMsg $ if entityId == entId then STResponse command clientResp else STUnexpectedError unexpected where unexpected = unexpectedResponse respOrErr @@ -874,36 +876,33 @@ createSMPQueue c nm nonce_ (rKey, rpKey) dhKey auth subMode qrd ntfCreds = subscribeSMPQueue :: SMPClient -> RcvPrivateAuthKey -> RecipientId -> ExceptT SMPClientError IO (Maybe ServiceId) subscribeSMPQueue c rpKey rId = do liftIO $ enablePings c - sendSMPCommand c NRMBackground (Just rpKey) rId SUB >>= liftIO . processSUBResponse_ c rId >>= except + sendSMPCommand c NRMBackground (Just rpKey) rId SUB >>= except . processSUBResponse_ -- | Subscribe to multiple SMP queues batching commands if supported. -- This command is always sent in background request mode subscribeSMPQueues :: SMPClient -> NonEmpty (RecipientId, RcvPrivateAuthKey) -> IO (NonEmpty (Either SMPClientError (Maybe ServiceId))) subscribeSMPQueues c qs = do liftIO $ enablePings c - sendProtocolCommands c NRMBackground cs >>= mapM (processSUBResponse c) + L.map processSUBResponse <$> sendProtocolCommands c NRMBackground cs where cs = L.map (\(rId, rpKey) -> (rId, Just rpKey, Cmd SRecipient SUB)) qs -- This command is always sent in background request mode streamSubscribeSMPQueues :: SMPClient -> NonEmpty (RecipientId, RcvPrivateAuthKey) -> ([(RecipientId, Either SMPClientError (Maybe ServiceId))] -> IO ()) -> IO () -streamSubscribeSMPQueues c qs cb = streamProtocolCommands c NRMBackground cs $ mapM process >=> cb +streamSubscribeSMPQueues c qs cb = streamProtocolCommands c NRMBackground cs $ cb . map process where cs = L.map (\(rId, rpKey) -> (rId, Just rpKey, Cmd SRecipient SUB)) qs - process r@(Response rId _) = (rId,) <$> processSUBResponse c r + process r@(Response rId _) = (rId, processSUBResponse r) -processSUBResponse :: SMPClient -> Response ErrorType BrokerMsg -> IO (Either SMPClientError (Maybe ServiceId)) -processSUBResponse c (Response rId r) = pure r $>>= processSUBResponse_ c rId +processSUBResponse :: Response ErrorType BrokerMsg -> Either SMPClientError (Maybe ServiceId) +processSUBResponse (Response _ r) = r >>= processSUBResponse_ -processSUBResponse_ :: SMPClient -> RecipientId -> BrokerMsg -> IO (Either SMPClientError (Maybe ServiceId)) -processSUBResponse_ c rId = \case - OK -> pure $ Right Nothing - SOK serviceId_ -> pure $ Right serviceId_ - cmd@MSG {} -> writeSMPMessage c rId cmd $> Right Nothing - r' -> pure . Left $ unexpectedResponse r' - -writeSMPMessage :: SMPClient -> RecipientId -> BrokerMsg -> IO () -writeSMPMessage c rId msg = mapM_ (`nonBlockingWriteTBQueue` serverTransmission c [(rId, STEvent (Right msg))]) (msgQ $ client_ c) +processSUBResponse_ :: BrokerMsg -> Either SMPClientError (Maybe ServiceId) +processSUBResponse_ = \case + OK -> Right Nothing + SOK serviceId_ -> Right serviceId_ + MSG {} -> Right Nothing + r' -> Left $ unexpectedResponse r' serverTransmission :: ProtocolClient v err msg -> NonEmpty (RecipientId, ServerTransmission err msg) -> ServerTransmissionBatch v err msg serverTransmission ProtocolClient {thParams, client_ = PClient {transportSession}} ts = (transportSession, thParams, ts) @@ -916,7 +915,7 @@ getSMPMessage :: SMPClient -> RcvPrivateAuthKey -> RecipientId -> ExceptT SMPCli getSMPMessage c rpKey rId = sendSMPCommand c NRMInteractive (Just rpKey) rId GET >>= \case OK -> pure Nothing - cmd@(MSG msg) -> liftIO (writeSMPMessage c rId cmd) $> Just msg + MSG msg -> pure $ Just msg r -> throwE $ unexpectedResponse r {-# INLINE getSMPMessage #-} @@ -1119,7 +1118,7 @@ ackSMPMessage :: SMPClient -> RcvPrivateAuthKey -> QueueId -> MsgId -> ExceptT S ackSMPMessage c rpKey rId msgId = sendSMPCommand c NRMBackground (Just rpKey) rId (ACK msgId) >>= \case OK -> pure True - cmd@MSG {} -> liftIO (writeSMPMessage c rId cmd) $> False + MSG {} -> pure False r -> throwE $ unexpectedResponse r -- | Irreversibly suspend SMP queue. diff --git a/src/Simplex/Messaging/Protocol.hs b/src/Simplex/Messaging/Protocol.hs index 05efa40c5..a26428e34 100644 --- a/src/Simplex/Messaging/Protocol.hs +++ b/src/Simplex/Messaging/Protocol.hs @@ -1842,6 +1842,8 @@ class (ProtocolTypeI (ProtoType msg), ProtocolEncoding v err msg, ProtocolEncodi useServiceAuth :: ProtoCommand msg -> Bool protocolPing :: ProtoCommand msg protocolError :: msg -> Maybe err + responseEvent :: msg -> Bool + responseEvent _ = False type ProtoServer msg = ProtocolServer (ProtoType msg) @@ -1862,6 +1864,10 @@ instance Protocol SMPVersion ErrorType BrokerMsg where ERR e -> Just e _ -> Nothing {-# INLINE protocolError #-} + responseEvent = \case + MSG {} -> True + _ -> False + {-# INLINE responseEvent #-} class ProtocolMsgTag (Tag msg) => ProtocolEncoding v err msg | msg -> err, msg -> v where type Tag msg From 2eb02bb396212dbbe3bd1734188083b98fd90647 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:17:15 +0000 Subject: [PATCH 12/18] clients: check the entity of a response once --- src/Simplex/Messaging/Client.hs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 96b5a049b..44395b78b 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -724,16 +724,17 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS TM.lookupIO corrId sentCommands >>= \case Nothing -> sendMsg $ STUnexpectedError unexpected Just Request {entityId, command, pending, responseVar} -> do + let resp = if entityId == entId then clientResp else Left unexpected wasPending <- atomically $ do TM.delete corrId sentCommands ifM (swapTVar pending False) - (True <$ tryPutTMVar responseVar (if entityId == entId then clientResp else Left unexpected)) + (True <$ tryPutTMVar responseVar resp) (pure False) if wasPending - then pure $ case clientResp of - Right r | entityId == entId && responseEvent r -> Just (entId, STEvent clientResp) + then pure $ case resp of + Right r | responseEvent r -> Just (entId, STEvent resp) _ -> Nothing else sendMsg $ if entityId == entId then STResponse command clientResp else STUnexpectedError unexpected where From 9c6121e646b98b971ac7ec7a7cf8019b693e5d83 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:19:04 +0000 Subject: [PATCH 13/18] agent: simplify acknowledgement, new queue recording and command postponement --- src/Simplex/Messaging/Agent.hs | 28 +++++++++++++-------------- src/Simplex/Messaging/Agent/Client.hs | 1 - 2 files changed, 13 insertions(+), 16 deletions(-) diff --git a/src/Simplex/Messaging/Agent.hs b/src/Simplex/Messaging/Agent.hs index c25dd7121..27600a738 100644 --- a/src/Simplex/Messaging/Agent.hs +++ b/src/Simplex/Messaging/Agent.hs @@ -1189,13 +1189,13 @@ createRcvQueue c nm userId connId srvWithAuth@(ProtoServerWithAuth srv _) enable newRcvQueue_ c nm userId connId srvWithAuth vr qd (isJust ntfServer_) subMode nonce_ e2eKeys `catchAllErrors` \e -> liftIO (print e) >> throwE e incSMPServerStat c userId srv connCreated - rq' <- recordNewQueue c nm connId "createRcvQueue" tSess rq (withStore c $ \db -> updateNewConnRcv db connId rq subMode) $ \rq' -> + rq' <- recordNewQueue c nm "createRcvQueue" tSess rq (withStore c $ \db -> updateNewConnRcv db connId rq subMode) $ \rq' -> rq' <$ lift (when (subMode == SMSubscribe) $ addNewQueueSubscription c rq' tSess sessId serviceId_) mapM_ (newQueueNtfSubscription c rq') ntfServer_ pure (rq', qUri) -recordNewQueue :: AgentClient -> NetworkRequestMode -> ConnId -> Text -> SMPTransportSession -> NewRcvQueue -> AM r -> (r -> AM a) -> AM a -recordNewQueue c nm connId name tSess q record continue = do +recordNewQueue :: AgentClient -> NetworkRequestMode -> Text -> SMPTransportSession -> NewRcvQueue -> AM r -> (r -> AM a) -> AM a +recordNewQueue c nm name tSess q@RcvQueue {connId} record continue = do recorded <- withConnLock c connId name $ tryAllErrors record >>= mapM continue either (\e -> tryAllErrors (deleteNewQueue c nm tSess q) >> throwE e) pure recorded @@ -1738,7 +1738,7 @@ createReplyQueue c nm ConnData {userId, connId, enableNtfs} SndQueue {smpClientV (rq, qUri, tSess, sessId, serviceId_) <- newRcvQueue c nm userId connId srv (versionToRange smpClientVersion) SCMInvitation (isJust ntfServer_) subMode incSMPServerStat c userId (qServer rq) connCreated let qInfo = toVersionT qUri smpClientVersion - rq' <- recordNewQueue c nm connId "createReplyQueue" tSess rq (withStore c $ \db -> upgradeSndConnToDuplex db connId rq subMode) $ \rq' -> + rq' <- recordNewQueue c nm "createReplyQueue" tSess rq (withStore c $ \db -> upgradeSndConnToDuplex db connId rq subMode) $ \rq' -> rq' <$ lift (when (subMode == SMSubscribe) $ addNewQueueSubscription c rq' tSess sessId serviceId_) mapM_ (newQueueNtfSubscription c rq') ntfServer_ pure qInfo @@ -2524,10 +2524,10 @@ runCommandProcessing c@AgentClient {subQ} connId server_ Worker {doWork} = do cmdError e = notify (ERR e) >> withStore' c (`deleteCommand` cmdId) 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) + otherCmds <- withStore c $ \db -> do + deleteCommand db cmdId + pending <- hasNonQSecureCommand db connId srv + (pending <$) <$> createCommand db corrId connId server_ command when otherCmds . atomically $ hasWorkToDo' doWork notify :: forall e. AEntityI e => AEvent e -> AM () notify cmd = @@ -2913,15 +2913,13 @@ ackMessage' c cmdId_ connId msgId rcptInfo_ = markConnUserAck :: AM (Maybe (Maybe (Connection 'CDuplex), RcvQueue, SMP.MsgId)) markConnUserAck = do SomeConn _ conn <- withStore c (`getConn` connId) - case conn of - DuplexConnection {} -> markUserAck $ Just conn - RcvConnection {} -> markUserAck Nothing + duplexConn_ <- case conn of + DuplexConnection {} -> pure $ Just conn + RcvConnection {} -> pure Nothing SndConnection {} -> throwE $ CONN SIMPLEX "ackMessage" ContactConnection {} -> throwE $ CMD PROHIBITED "ackMessage: ContactConnection" NewConnection _ -> throwE $ CMD PROHIBITED "ackMessage: NewConnection" - -- the stored message was delivered via a specific queue, the rest failed to decrypt and were already acknowledged - markUserAck :: Maybe (Connection 'CDuplex) -> AM (Maybe (Maybe (Connection 'CDuplex), RcvQueue, SMP.MsgId)) - markUserAck duplexConn_ = + -- the stored message was delivered via a specific queue, the rest failed to decrypt and were already acknowledged withStore' c (\db -> setMsgUserAck db connId $ InternalId msgId) >>= \case Right (rq, srvMsgId) -> pure $ Just (duplexConn_, rq, srvMsgId) Left (SEMsgNotFound _) -> Nothing <$ del @@ -2991,7 +2989,7 @@ switchDuplexConnection c nm cmdId_ switchId (DuplexConnection ConnData {connId, SomeConn _ (DuplexConnection cData rqs' sqs') | Just rq1 <- findQ (qAddress rq) rqs' -> (cData,rqs',sqs',rq1,) <$> withStore c (\db -> addConnRcvQueue db connId rq' SMSubscribe) _ -> throwE $ INTERNAL "switchConnection: replaced queue not found in connection" - recordNewQueue c nm connId "switchConnection" tSess q addRcvQueue $ \(cData, rqs', sqs', rq1, rq'') -> do + recordNewQueue c nm "switchConnection" tSess q addRcvQueue $ \(cData, rqs', sqs', rq1, rq'') -> do started <- (Just switchId ==) <$> liftIO (TM.lookupIO connId $ rcvSwitches c) if rcvSwchStatus rq1 /= Just RSSwitchStarted || not started then Nothing <$ deleteRcvQueueAsync c rq'' diff --git a/src/Simplex/Messaging/Agent/Client.hs b/src/Simplex/Messaging/Agent/Client.hs index b3b3b8a56..3978592ac 100644 --- a/src/Simplex/Messaging/Agent/Client.hs +++ b/src/Simplex/Messaging/Agent/Client.hs @@ -1166,7 +1166,6 @@ checkNoConnLock AgentClient {connLockHolders, connLockViolations} = do throwE $ INTERNAL $ "server request in connection lock " <> T.unpack name checkBatchOutsideConnLock :: AgentClient -> [q] -> AM' [(q, Either AgentErrorType r)] -> AM' [(q, Either AgentErrorType r)] -checkBatchOutsideConnLock _ [] batch = batch checkBatchOutsideConnLock c qs batch = tryAllErrors' (checkNoConnLock c) >>= either (\e -> pure $ map (,Left e) qs) (const batch) #else withLockHolder :: AgentClient -> Text -> m a -> m a From 3398bac30727b9913facb2f142ed21ca463202ec Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:28:44 +0000 Subject: [PATCH 14/18] tests: remove duplicate switch tests, share full queue helpers --- tests/AgentTests/FunctionalAPITests.hs | 109 ++++++++++--------------- tests/AgentTests/NotificationTests.hs | 15 +--- 2 files changed, 45 insertions(+), 79 deletions(-) diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index bbabc8bfc..eea996e4e 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -58,6 +58,7 @@ module AgentTests.FunctionalAPITests agentCfgVPrevPQ, agentCfgV7, testServerInformation, + withFullNtfSubQ, #if defined(dbPostgres) workItemReadTests, #endif @@ -631,12 +632,8 @@ functionalAPITests ps = do testFastSwitchDrainOldQueueRestart ps it "should receive messages while the server of the new queue does not respond" $ testFastSwitchStallingNewServer ps - it "should delete the new queue when the switch is aborted while the queue is created" $ - testSwitchChangedWhileNewQueue abortConnectionSwitch "switchConnection: aborted" ps it "should delete the new queue when ratchet synchronization starts while the queue is created" $ - testSwitchChangedWhileNewQueue (\c connId -> synchronizeRatchet c connId PQSupportOn True) "switchConnection: send prohibited" ps - it "should delete the new queue when the connection is deleted while the queue is created" $ - testSwitchConnectionDeletedWhileNewQueue ps + testSwitchRatchetSyncWhileNewQueue ps it "should delete the new queue when the connection is deleted waiting for delivery while the queue is created" $ testSwitchConnectionDeletedWaitingDeliveryWhileNewQueue ps it "should delete the new queue when it is recorded while the connection deletion waits for the server" $ @@ -1242,7 +1239,7 @@ testAcceptContactStallingServer ps@(t, ASType qsType _) = withAsync (runExceptT $ acceptContact a 1 bId True invId "alice's connInfo" PQSupportOn SMSubscribe) $ \_ -> do timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () Just (Left (A.CMD PROHIBITED _)) <- timeout 5_000000 . runExceptT $ synchronizeRatchet a bId PQSupportOn False - timeout 1_000000 (runExceptT $ acceptContact a 1 bId True invId "alice's connInfo" PQSupportOn SMSubscribe) `shouldReturn` Nothing + pure () where bServers = initAgentServers {smp = userServers [testSMPServer2]} @@ -3400,10 +3397,7 @@ testAckMessageFullQueue = get a ##> ("", bId, SENT msgId) withAgent 2 agentCfg initAgentServers testDB2 $ \b -> runRight_ $ do ("", _, Msg' msgId _ "hello again") <- getMsg b aId $ get b - liftIO $ do - fillSubQ b - timeout 5_000000 (runExceptT $ ackMessage b aId msgId Nothing) `shouldReturn` Just (Right ()) - void . atomically . flushTBQueue $ subQ b + liftIO . withFullSubQ b $ timeout 5_000000 (runExceptT $ ackMessage b aId msgId Nothing) `shouldReturn` Just (Right ()) getMSGNTF b aId makeConnection :: AgentClient -> AgentClient -> ExceptT AgentErrorType IO (ConnId, ConnId) @@ -3682,24 +3676,22 @@ testAckMessageFullQueues = withAgentClients2 $ \a b -> do msgId2 <- sendMessage a bId SMP.noMsgFlags "hello 2" get a ##> ("", bId, SENT msgId2) ("", _, Msg' msgId _ "hello") <- get b - fillSubQ b - runRight_ $ forM_ conns $ \(_, bId') -> do - msgId' <- sendMessage a bId' SMP.noMsgFlags "hello" - get a ##> ("", bId', SENT msgId') - timeout 5_000000 (atomically $ isFullTBQueue (msgQ b) >>= checkSTM) `shouldReturn` Just () - timeout 5_000000 (runExceptT $ ackMessage b aId msgId Nothing) `shouldReturn` Just (Right ()) - void . atomically . flushTBQueue $ subQ b + withFullSubQ b $ do + runRight_ $ forM_ conns $ \(_, bId') -> do + msgId' <- sendMessage a bId' SMP.noMsgFlags "hello" + get a ##> ("", bId', SENT msgId') + timeout 5_000000 (atomically $ isFullTBQueue (msgQ b) >>= checkSTM) `shouldReturn` Just () + timeout 5_000000 (runExceptT $ ackMessage b aId msgId Nothing) `shouldReturn` Just (Right ()) timeout 5_000000 (receiveMsgs b $ (aId, "hello 2") : map ((,"hello") . fst) conns) `shouldReturn` Just () testDuplicateConnIdsFullQueue :: HasTestEnv => IO () testDuplicateConnIdsFullQueue = withAgentClients2 $ \a b -> do (_, bId) <- runRight $ makeConnection a b - fillSubQ a - Just (Right subRs) <- timeout 5_000000 . runExceptT $ subscribeConnections a [bId, bId] - M.keys subRs `shouldBe` [bId] - Just (Right delRs) <- timeout 5_000000 . runExceptT $ deleteConnections a [bId, bId] - M.keys delRs `shouldBe` [bId] - void . atomically . flushTBQueue $ subQ a + withFullSubQ a $ do + Just (Right subRs) <- timeout 5_000000 . runExceptT $ subscribeConnections a [bId, bId] + M.keys subRs `shouldBe` [bId] + Just (Right delRs) <- timeout 5_000000 . runExceptT $ deleteConnections a [bId, bId] + M.keys delRs `shouldBe` [bId] getInAnyOrder a [resultSizeErr "subscribeConnections", resultSizeErr "deleteConnections"] where resultSizeErr :: String -> ATransmission -> Bool @@ -3954,9 +3946,7 @@ testDeleteConnectionAsyncFullQueue :: HasTestEnv => IO () testDeleteConnectionAsyncFullQueue = withAgent 1 agentCfg initAgentServers testDB $ \a -> do (connId, _) <- runRight $ A.prepareConnectionToJoin a 1 True (CRInvitationUri connReqData testE2ERatchetParams12) PQSupportOn - fillSubQ a - timeout 5000000 (runExceptT $ deleteConnectionsAsync a False [connId]) `shouldReturn` Just (Right ()) - void . atomically . flushTBQueue $ subQ a + withFullSubQ a $ timeout 5000000 (runExceptT $ deleteConnectionsAsync a False [connId]) `shouldReturn` Just (Right ()) get a =##> \case ("", "", DEL_CONNS [c]) -> c == connId; _ -> False testDeleteConnectionFullNtfQueue :: HasTestEnv => (ASrvTransport, AStoreType) -> IO () @@ -3964,22 +3954,27 @@ testDeleteConnectionFullNtfQueue ps = withSmpServer ps $ withAgent 1 agentCfg initAgentServers testDB $ \a -> do (connId, _) <- runRight $ createConnection a 1 True SCMInvitation Nothing SMSubscribe - let q = ntfSubQ $ ntfSupervisor $ agentEnv a - setNtfSuspended suspended = atomically $ modifyTVar' (ntfNetworkOp a) $ \s -> s {opSuspended = suspended} - fill = unlessM (isFullTBQueue q) $ writeTBQueue q (NSCDeleteSub, ["x"]) >> fill - setNtfSuspended True - atomically $ writeTBQueue q (NSCDeleteSub, ["x"]) - atomically $ isEmptyTBQueue q >>= checkSTM - atomically fill - timeout 5_000000 (runExceptT $ deleteConnectionsAsync a False [connId]) `shouldReturn` Just (Right ()) - setNtfSuspended False + withFullNtfSubQ a $ timeout 5_000000 (runExceptT $ deleteConnectionsAsync a False [connId]) `shouldReturn` Just (Right ()) get a =##> \case ("", "", DEL_RCVQS [(c, _, _, Nothing)]) -> c == connId; _ -> False get a =##> \case ("", "", DEL_CONNS [c]) -> c == connId; _ -> False -fillSubQ :: AgentClient -> IO () -fillSubQ c = atomically fill +withFullNtfSubQ :: AgentClient -> IO a -> IO a +withFullNtfSubQ c action = do + setNtfSuspended True + atomically $ writeTBQueue q (NSCDeleteSub, ["x"]) + atomically $ isEmptyTBQueue q >>= checkSTM + atomically fill + action <* setNtfSuspended False + where + q = ntfSubQ $ ntfSupervisor $ agentEnv c + setNtfSuspended suspended = atomically $ modifyTVar' (ntfNetworkOp c) $ \s -> s {opSuspended = suspended} + fill = unlessM (isFullTBQueue q) $ writeTBQueue q (NSCDeleteSub, ["x"]) >> fill + +withFullSubQ :: AgentClient -> IO a -> IO a +withFullSubQ c action = atomically fill *> action <* atomically (flushTBQueue q) where - fill = unlessM (isFullTBQueue $ subQ c) $ writeTBQueue (subQ c) ("", "", AEvt SAENone SUSPENDED) >> fill + q = subQ c + fill = unlessM (isFullTBQueue q) $ writeTBQueue q ("", "", AEvt SAENone SUSPENDED) >> fill testWaitDeliveryNoPending :: HasTestEnv => (ASrvTransport, AStoreType) -> IO () testWaitDeliveryNoPending ps = withAgentClients2 $ \alice bob -> @@ -4278,9 +4273,7 @@ testDeleteUserFullQueue :: HasTestEnv => IO () testDeleteUserFullQueue = withAgent 1 agentCfg initAgentServers testDB $ \a -> do auId <- runRight $ createUser a False [noAuthSrvCfg testSMPServer] [noAuthSrvCfg testXFTPServer] - fillSubQ a - timeout 5000000 (runExceptT $ deleteUser a auId True) `shouldReturn` Just (Right ()) - void . atomically . flushTBQueue $ subQ a + withFullSubQ a $ timeout 5000000 (runExceptT $ deleteUser a auId True) `shouldReturn` Just (Right ()) nGet a =##> \case ("", "", DEL_USER u) -> u == auId; _ -> False testDeleteUserStatsErrorFullQueue :: HasTestEnv => IO () @@ -4288,10 +4281,9 @@ testDeleteUserStatsErrorFullQueue = withAgent 1 agentCfg initAgentServers testDB $ \a -> do auId <- runRight $ createUser a False [noAuthSrvCfg testSMPServer] [noAuthSrvCfg testXFTPServer] withTransaction (store $ agentEnv a) (`DB.execute_` "ALTER TABLE servers_stats RENAME TO servers_stats_") - fillSubQ a - timeout 5_000000 (runExceptT $ deleteUser a auId False) `shouldReturn` Just (Right ()) - withTransaction (store $ agentEnv a) (`DB.execute_` "ALTER TABLE servers_stats_ RENAME TO servers_stats") - void . atomically . flushTBQueue $ subQ a + withFullSubQ a $ do + timeout 5_000000 (runExceptT $ deleteUser a auId False) `shouldReturn` Just (Right ()) + withTransaction (store $ agentEnv a) (`DB.execute_` "ALTER TABLE servers_stats_ RENAME TO servers_stats") get a =##> \case ("", "", ERR (A.INTERNAL _)) -> True; _ -> False testUsersNoServer :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () @@ -4456,8 +4448,8 @@ receiveMsgs c msgs = (_, cId, AEvt SAEConn (MSG _ _ body)) -> receiveMsgs c $ filter (/= (cId, body)) msgs _ -> receiveMsgs c msgs -testSwitchChangedWhileNewQueue :: (HasCallStack, HasTestEnv) => (AgentClient -> ConnId -> AE ConnectionStats) -> String -> (ASrvTransport, AStoreType) -> IO () -testSwitchChangedWhileNewQueue changeSwitch err ps@(t, _) = +testSwitchRatchetSyncWhileNewQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () +testSwitchRatchetSyncWhileNewQueue ps@(t, _) = withSmpServer ps $ withAgent 2 agentCfg initAgentServersLongConnect testDB2 $ \b -> do (aId, _) <- withAgent 1 agentCfg initAgentServers testDB $ \a -> runRight $ makeConnection a b @@ -4466,28 +4458,13 @@ testSwitchChangedWhileNewQueue changeSwitch err ps@(t, _) = withPausedProxyOn testPort2 testPort3 $ \accepted resume -> withAsync (runExceptT $ switchConnection b NRMInteractive aId) $ \switched -> do timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () - void . runRight $ changeSwitch b aId + void . runRight $ synchronizeRatchet b aId PQSupportOn True atomically $ putTMVar resume () - timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ A.CMD PROHIBITED err) + timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ A.CMD PROHIBITED "switchConnection: send prohibited") runRight (getConnectionServers b aId) >>= (`shouldMatchList` [Nothing]) . rcvSwchStatuses' waitRcvQueueRecords b 1 storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) -testSwitchConnectionDeletedWhileNewQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () -testSwitchConnectionDeletedWhileNewQueue ps@(t, _) = - withSmpServer ps $ - withAgent 2 agentCfg initAgentServersLongConnect testDB2 $ \b -> do - (aId, _) <- withAgent 1 agentCfg initAgentServers testDB $ \a -> runRight $ makeConnection a b - setProtocolServers b 1 [noAuthSrvCfg testSMPServer2] - withSmpServerConfigOn t cfgS2 testPort3 $ \_ -> - withPausedProxyOn testPort2 testPort3 $ \accepted resume -> - withAsync (runExceptT $ switchConnection b NRMInteractive aId) $ \switched -> do - timeout 5_000000 (atomically $ takeTMVar accepted) `shouldReturn` Just () - runRight_ $ deleteConnection b aId - atomically $ putTMVar resume () - timeout 5_000000 (wait switched) `shouldReturn` Just (Left $ CONN NOT_FOUND "") - storeLogQueues testStoreLogFile2 `shouldReturn` (1, 1) - testSwitchConnectionDeletedWaitingDeliveryWhileNewQueue :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () testSwitchConnectionDeletedWaitingDeliveryWhileNewQueue ps@(t, _) = withSmpServer ps $ @@ -5931,9 +5908,7 @@ testServiceUnavailableFullQueue (t, msType) = do in cfg' {transportConfig = transportConfig {askClientCert = False}} :: ServerConfig s withAgent 1 agentCfg initAgentServersClientService testDB $ \service -> withSmpServerConfigOn t cfgNoService testPort $ \_ -> do - fillSubQ service - timeout 5_000000 (runExceptT $ subscribeAllConnections service False Nothing) `shouldReturn` Just (Right ()) - void . atomically . flushTBQueue $ subQ service + withFullSubQ service $ timeout 5_000000 (runExceptT $ subscribeAllConnections service False Nothing) `shouldReturn` Just (Right ()) getInAnyOrder service [ \case ("", "", AEvt SAEConn (ERR (BROKER _ NO_SERVICE))) -> True; _ -> False, diff --git a/tests/AgentTests/NotificationTests.hs b/tests/AgentTests/NotificationTests.hs index 1efe82c2e..1054fab13 100644 --- a/tests/AgentTests/NotificationTests.hs +++ b/tests/AgentTests/NotificationTests.hs @@ -66,8 +66,8 @@ import SMPAgentClient (agentCfg, initAgentServers, initAgentServers2, testDB, te import SMPClient import Simplex.Messaging.Agent hiding (checkNtfToken, createConnection, joinConnection, registerNtfToken, sendMessage, verifyNtfToken) import qualified Simplex.Messaging.Agent as A -import Simplex.Messaging.Agent.Client (AgentOpState (..), ProtocolTestFailure (..), ProtocolTestStep (..), ServerQueueInfo (..), withStore') -import Simplex.Messaging.Agent.Env.SQLite (AgentConfig, Env (..), InitialAgentServers, NtfSupervisor (..), NtfSupervisorCommand (..)) +import Simplex.Messaging.Agent.Client (ProtocolTestFailure (..), ProtocolTestStep (..), ServerQueueInfo (..), withStore') +import Simplex.Messaging.Agent.Env.SQLite (AgentConfig, Env (..), InitialAgentServers) import Simplex.Messaging.Agent.Protocol hiding (CON, CONF, INFO, SENT) import Simplex.Messaging.Agent.Store.AgentStore (getSavedNtfToken) import Simplex.Messaging.Agent.Store.Common (withTransaction) @@ -89,7 +89,6 @@ import Simplex.Messaging.Server.Information (ServerPublicInfo (..)) import Simplex.Messaging.Server.QueueStore.QueueInfo (QueueInfo (..)) import Simplex.Messaging.Transport (ASrvTransport) import Simplex.Messaging.Transport.Server (TransportServerConfig (..)) -import Simplex.Messaging.Util (unlessM) import System.Process (callCommand) import Test.Hspec hiding (fit, it) import UnliftIO @@ -921,15 +920,7 @@ testSwitchFullNtfQueue cfg completeSwitch apns = exchangeGreetings a bId b aId _ <- registerTestToken a "abcd" NMInstant apns pure (aId, bId) - let q = ntfSubQ $ ntfSupervisor $ agentEnv a - setNtfSuspended suspended = atomically $ modifyTVar' (ntfNetworkOp a) $ \s -> s {opSuspended = suspended} - fill = unlessM (isFullTBQueue q) $ writeTBQueue q (NSCDeleteSub, ["x"]) >> fill - setNtfSuspended True - atomically $ writeTBQueue q (NSCDeleteSub, ["x"]) - atomically $ isEmptyTBQueue q >>= checkSTM - atomically fill - timeout 20000000 (runExceptT $ switchConnectionAsync a "" bId >> completeSwitch a bId b aId) `shouldReturn` Just (Right ()) - setNtfSuspended False + withFullNtfSubQ a $ timeout 20000000 (runExceptT $ switchConnectionAsync a "" bId >> completeSwitch a bId b aId) `shouldReturn` Just (Right ()) testNotificationsOldToken :: HasTestEnv => APNSMockServer -> IO () testNotificationsOldToken apns = From 4a42ac975484efdd70a82143bf2682897d5f8b27 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:28:44 +0000 Subject: [PATCH 15/18] plans: correct the agent no-blocking plan to the code --- plans/2026-11-21-agent-no-blocking.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/plans/2026-11-21-agent-no-blocking.md b/plans/2026-11-21-agent-no-blocking.md index 21db906a0..9d6ca0ec0 100644 --- a/plans/2026-11-21-agent-no-blocking.md +++ b/plans/2026-11-21-agent-no-blocking.md @@ -9,14 +9,14 @@ ## 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. +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, and `disposeAgentClient` then throws. +2. The locked step after a server request reads again the state that its writes depend on; when that 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. ## Helpers -- `requestAndCommit`: validates the connection under the lock, makes the request, validates again and commits under the lock. +- `requestAndCommit`: makes the request between two locked runs of the caller's check, which may write or end the step, and commits after the second run in its lock. - `recordNewQueue`: records a queue created on a server under the lock, or deletes it from the server. ## Sequence @@ -50,7 +50,7 @@ sequenceDiagram - agent, connection locks: - `requestAndCommit` in ICDuplexSecure, ICQSecure, ICQSndSecure, ICQDelete and `ackMessage`; - `recordNewQueue` in `createRcvQueue`, `createReplyQueue` and `switchDuplexConnection`; - - request outside the lock in ICAck, ICAckDel, ICAllowSecure, ICDeleteRcvQueue, JOIN of a service request, `setConnShortLink`, `deleteConnShortLink`, `suspendConnection`, `connectReplyQueues`; + - request outside the lock in ICAck, ICAckDel, ICAllowSecure, ICDeleteRcvQueue, ICReplyDel, JOIN of a service request, `setConnShortLink`, `deleteConnShortLink`, `suspendConnection`, `connectReplyQueues`; - `acceptContact` under the invitation lock; `serviceRequest_` without the connection lock; - deletion under the locks of its connections, where the connections are marked deleted in synchronous deletion too; - a connection whose deletion waits for delivery is not given new queues; @@ -60,12 +60,11 @@ sequenceDiagram - the receive queue status is set to Secured under the lock, only from Confirmed; - ICQSecure and ICQSndSecure are postponed while the ratchet is not synchronized, after the other commands of their server, and resumed after synchronization; - SWCH is refused while the ratchet is not synchronized. -- agent, events written without waiting: +- agent, events and notification commands written without waiting: - MSGNTF of `ackMessage`, DEL_CONNS, DEL_USER; - errors of `subscribeConnections`, `deleteConnections`, `subscribeAllConnections`, `deleteUser`, `xftpDeleteSndFilesRemote`; - the notification commands of connection deletion, ICQDelete and QEND. - clients: - - a message in the response to ACK, SUB or GET is written to msgQ without waiting; + - a message in the response to ACK, SUB or GET is written to msgQ by the receiving thread, in the order of reception; - a command waits for send-queue space only until its response timeout, and is not queued after it ends; - a command that ends without a response is removed, except in clients with msgQ, where it is kept for 15 minutes for a late response. -- moved to separate pull requests: the HTTP/2 request timeout, the SUSPENDED event written without waiting. From 29890639615e371b2523de8adcb3c5bd223b45e7 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:35:32 +0000 Subject: [PATCH 16/18] tests: import the full notification queue helper --- tests/AgentTests/NotificationTests.hs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/AgentTests/NotificationTests.hs b/tests/AgentTests/NotificationTests.hs index 1054fab13..8f98552ab 100644 --- a/tests/AgentTests/NotificationTests.hs +++ b/tests/AgentTests/NotificationTests.hs @@ -37,6 +37,7 @@ import AgentTests.FunctionalAPITests withAgentClients3, withAgentClientsCfg2, withAgentClientsCfgServers2, + withFullNtfSubQ, (##>), (=##>), pattern CON, From 9b0838274b072d9e512700573fe11957393824d5 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:45:26 +0000 Subject: [PATCH 17/18] clients: keep requests for late responses until disconnection --- plans/2026-11-21-agent-no-blocking.md | 2 +- src/Simplex/Messaging/Client.hs | 12 ++---------- tests/SMPProxyTests.hs | 17 +++++++---------- 3 files changed, 10 insertions(+), 21 deletions(-) diff --git a/plans/2026-11-21-agent-no-blocking.md b/plans/2026-11-21-agent-no-blocking.md index 9d6ca0ec0..22fd092a9 100644 --- a/plans/2026-11-21-agent-no-blocking.md +++ b/plans/2026-11-21-agent-no-blocking.md @@ -67,4 +67,4 @@ sequenceDiagram - clients: - a message in the response to ACK, SUB or GET is written to msgQ by the receiving thread, in the order of reception; - a command waits for send-queue space only until its response timeout, and is not queued after it ends; - - a command that ends without a response is removed, except in clients with msgQ, where it is kept for 15 minutes for a late response. + - a command that ends without a response is removed, except in clients with msgQ, where it is kept until its late response or disconnection. diff --git a/src/Simplex/Messaging/Client.hs b/src/Simplex/Messaging/Client.hs index 44395b78b..ca741f378 100644 --- a/src/Simplex/Messaging/Client.hs +++ b/src/Simplex/Messaging/Client.hs @@ -172,7 +172,6 @@ import Simplex.Messaging.Protocol import Simplex.Messaging.Protocol.Types import Simplex.Messaging.Server.QueueStore.QueueInfo import Simplex.Messaging.SimplexName (SimplexDomain, fullDomainName) -import Simplex.Messaging.SystemTime (SystemSeconds, getSystemSeconds, roundedSeconds) import Simplex.Messaging.TMap (TMap) import qualified Simplex.Messaging.TMap as TM import Simplex.Messaging.Transport @@ -484,7 +483,6 @@ data ProtocolClientConfig v = ProtocolClientConfig defaultTransport :: (ServiceName, ATransport 'TClient), -- | network configuration networkConfig :: NetworkConfig, - sentCommandsTTL :: Int64, clientALPN :: Maybe [ALPN], serviceCredentials :: Maybe ServiceCredentials, -- | client-server protocol version range @@ -505,7 +503,6 @@ defaultClientConfig clientALPN useSNI serverVRange = { qSize = 64, defaultTransport = ("443", transport @TLS), networkConfig = defaultNetworkConfig, - sentCommandsTTL = 15 * 60, clientALPN, serviceCredentials = Nothing, serverVRange, @@ -529,7 +526,6 @@ data Request err msg = Request { corrId :: CorrId, entityId :: EntityId, command :: ProtoCommand msg, - createdAt :: SystemSeconds, pending :: TVar Bool, responseVar :: TMVar (Either (ProtocolClientError err) msg) } @@ -585,7 +581,7 @@ type SMPTransportSession = TransportSession BrokerMsg -- A single queue can be used for multiple 'SMPClient' instances, -- as 'SMPServerTransmission' includes server information. getProtocolClient :: forall v err msg. Protocol v err msg => TVar ChaChaDRG -> NetworkRequestMode -> TransportSession msg -> ProtocolClientConfig v -> [HostName] -> Maybe (TBQueue (ServerTransmissionBatch v err msg)) -> UTCTime -> (ProtocolClient v err msg -> IO ()) -> IO (Either (ProtocolClientError err) (ProtocolClient v err msg)) -getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qSize, networkConfig, sentCommandsTTL, clientALPN, serviceCredentials, serverVRange, proxiedRelayVRange, agreeSecret, proxyServer, useSNI} presetDomains msgQ proxySessTs disconnected = do +getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qSize, networkConfig, clientALPN, serviceCredentials, serverVRange, proxiedRelayVRange, agreeSecret, proxyServer, useSNI} presetDomains msgQ proxySessTs disconnected = do case chooseTransportHost networkConfig (host srv) of Right useHost -> (getCurrentTime >>= mkProtocolClient useHost >>= runClient useTransport useHost) @@ -687,13 +683,11 @@ getProtocolClient g nm transportSession@(_, srv, _) cfg@ProtocolClientConfig {qS atomically $ writeTVar timeoutErrorCount 0 monitor :: ProtocolClient v err msg -> IO () - monitor c@ProtocolClient {client_ = PClient {sendPings, lastReceived, timeoutErrorCount, sentCommands}} = loop smpPingInterval + monitor c@ProtocolClient {client_ = PClient {sendPings, lastReceived, timeoutErrorCount}} = loop smpPingInterval where loop :: Int64 -> IO () loop delay = do threadDelay' delay - ts <- getSystemSeconds - atomically $ modifyTVar' sentCommands $ M.filter $ \Request {createdAt} -> roundedSeconds ts - roundedSeconds createdAt < sentCommandsTTL diff <- diffUTCTime <$> getCurrentTime <*> readTVarIO lastReceived let idle = diffToMicroseconds diff remaining = smpPingInterval - idle @@ -1441,7 +1435,6 @@ mkTransmission_ ProtocolClient {thParams, client_ = PClient {clientCorrId}} nonc where mkRequest :: CorrId -> IO (Request err msg) mkRequest corrId = do - createdAt <- getSystemSeconds pending <- newTVarIO True responseVar <- newEmptyTMVarIO let r = @@ -1449,7 +1442,6 @@ mkTransmission_ ProtocolClient {thParams, client_ = PClient {clientCorrId}} nonc { corrId, entityId, command, - createdAt, pending, responseVar } diff --git a/tests/SMPProxyTests.hs b/tests/SMPProxyTests.hs index 115dfb12b..8920432b5 100644 --- a/tests/SMPProxyTests.hs +++ b/tests/SMPProxyTests.hs @@ -76,8 +76,8 @@ smpProxyTests = do testForwardOversizedNotKept it "fails commands of closed client at once" $ \_ -> testClosedClientCommandsFail - it "releases command kept for late response" $ \_ -> - testLateResponseCommandReleased + it "delivers late response to the message queue" $ \_ -> + testLateResponseDelivered describe "agent client reconnection" $ do it "reconnects after a connect is cancelled mid-flight" $ \_ -> testAgentClientReconnectAfterCancel @@ -656,23 +656,20 @@ testClosedClientCommandsFail = pClientSentCommandsCount c `shouldReturn` 0 atomically (lengthTBQueue $ pClientSndQ c) `shouldReturn` 0 -testLateResponseCommandReleased :: HasTestEnv => IO () -testLateResponseCommandReleased = - withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 4000000}) testPort $ \_ -> do +testLateResponseDelivered :: HasTestEnv => IO () +testLateResponseDelivered = + withSmpServerConfigOn (transport @TLS) (updateCfg cfg $ \cfg_ -> cfg_ {authErrorDelay = 2000000}) testPort $ \_ -> do g <- C.newRandom ts <- getCurrentTime msgQ <- newTBQueueIO 4 - let clientCfg = defaultSMPClientConfig {networkConfig = defaultNetworkConfig {smpPingInterval = 100000}, sentCommandsTTL = 2} - c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) clientCfg [] (Just msgQ) ts (\_ -> pure ()) + c <- either (fail . show) pure =<< getProtocolClient g NRMBackground (1, testSMPServer, Nothing) defaultSMPClientConfig [] (Just msgQ) ts (\_ -> pure ()) rId <- atomically $ SMP.EntityId <$> C.randomBytes 24 g (_, rpKey) <- atomically $ C.generateAuthKeyPair C.SEd25519 g runExceptT (sendProtocolCommand_ c NRMBackground Nothing (Just 100000) (Just rpKey) rId (SMP.Cmd SMP.SRecipient SMP.SUB)) `shouldReturn` Left PCEResponseTimeout pClientSentCommandsCount c `shouldReturn` 1 - threadDelay 3000000 + (_, _, [(_, STResponse _ (Left (PCEProtocolError SMP.AUTH)))]) <- atomically $ readTBQueue msgQ pClientSentCommandsCount c `shouldReturn` 0 - (_, _, [(_, STUnexpectedError _)]) <- atomically $ readTBQueue msgQ - pure () -- Bug B (same root cause as the proxy, in the messaging agent): getSMPServerClient inserts an -- empty SessionVar into smpClients, then connects inside newProtocolClient's tryAllErrors, which From 6826cf605280eca62dd207c92a8993de3e0d4d7b Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:07:39 +0000 Subject: [PATCH 18/18] agent: plan requests without contested connection locks --- plans/2026-11-21-agent-no-blocking.md | 231 ++++++++++++++++++++------ 1 file changed, 176 insertions(+), 55 deletions(-) diff --git a/plans/2026-11-21-agent-no-blocking.md b/plans/2026-11-21-agent-no-blocking.md index 22fd092a9..9f25e6f00 100644 --- a/plans/2026-11-21-agent-no-blocking.md +++ b/plans/2026-11-21-agent-no-blocking.md @@ -1,70 +1,191 @@ -# Agent without waits on slow servers and full queues +# Agent without network requests under contested locks -## Problem +Line references are to master 3f57fcdc: A = src/Simplex/Messaging/Agent.hs, AC = Agent/Client.hs, AS = Agent/Store/AgentStore.hs, ST = Agent/Store.hs, C = Client.hs, schema = Agent/Store/SQLite/Migrations/agent_schema.sql, Subscriber.hs = simplex-chat src/Simplex/Chat/Library/Subscriber.hs. -- One subscriber thread processes received messages, each under the lock of its connection. -- Worker and API threads held that lock across server requests, up to 75 seconds per attempt, so one slow server stopped the messages of all connections. -- An acknowledgement held the lock while it waited for space in msgQ, which only the subscriber drains, after it takes the same lock. -- API calls waited for space in subQ, which the app drains while it holds its own locks. +## Problems -## Rules +1. A server request is made while the connection lock is held: up to 75 s per direct request (45 s connect and 30 s response, C:434-435), and several requests in sequence at some sites (A:2392-2394, 4427-4430). The subscriber, the single thread that processes received messages of all connections (A:3698), waits for that lock when a message of the connection arrives, so messages of all connections stop. +2. An acknowledgement holds the connection lock while its thread waits for space in msgQ, which only the subscriber drains, after it takes the same lock: deadlock. +3. A rotation stays in progress forever after its QADD or QUSE is refused, and crashes between transactions of rotation handlers and of message storage leave a rotation half-done or a message missing on one queue. -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, and `disposeAgentClient` then throws. -2. The locked step after a server request reads again the state that its writes depend on; when that 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. +## Scope -## Helpers +Unchanged from master: +- delivery of events to the app (subQ, its writers, event deferral); +- connection deletion: the fork per call, deleteLock across DEL batches, the cleanup pass; +- the multi-connection lock of sendMessagesB_ (A:2182); +- PostgreSQL row locking, except https://github.com/simplex-chat/simplexmq/pull/2104; +- joinConnection, which holds no connection lock on master; the invitation lock (A:964, 1627, 1644). -- `requestAndCommit`: makes the request between two locked runs of the caller's check, which may write or end the step, and commits after the second run in its lock. -- `recordNewQueue`: records a queue created on a server under the lock, or deletes it from the server. +The order of link data is a separate change. LSET and LDEL are sent without the lock (change 1), so an LSET can reach the server after an LDEL of the same link and publish it again. -## Sequence +## Decisions + +| Date | Decision | +|---|---| +| 2026-11-24 | An abort cancels the rotation step in progress and deletes its new queue. | +| 2026-11-24 | The old KEY handshake is removed; SMP client version 3, with sender-secured queues, is the minimum. | +| 2026-11-24 | The protocol client keeps timed-out requests until their response or disconnection. | +| 2026-11-25 | Old-handshake rows in progress end with a version error; joining an invitation without a sender-secured queue is refused. | +| 2026-11-25 | A rotation refused by the server with AUTH returns to its state before it started; an abort is refused once QADD is stored. | +| 2026-11-25 | Acknowledgements stay asynchronous and keep master's order: ACK, then receipt; the receipt is stored only when the ratchet allows sending. | +| 2026-11-26 | Downgrade is not supported. | + +## Changes + +### 1. The connection lock covers database work only + +Each server request that master makes under the connection lock is moved out of it. A step that has a command row (change 2) becomes: +- P: under the lock, one transaction checks that the row exists (otherwise the step ends without a request), reads the state, decides the request, and writes what the request needs; +- the request, with no lock held; +- C: under the lock, one transaction that applies by the rules of change 2, re-reads the state it writes, and writes the outcome. + +Events, worker wake-ups and notification commands of P and C follow their commit. ```mermaid sequenceDiagram - participant W as Worker of connection X - participant L as Lock of X - participant S as Slow server + participant W as Executor of the row + participant L as Connection lock + participant S as Server participant Sub as Subscriber - participant P as Protocol clients - rect rgb(255,228,228) - Note over W,P: Before W->>L: take - W->>S: SKEY, confirmation - Sub--xL: MSG for X waits up to 75 s - P--xSub: MSG for Y, Z: msgQ full, writers wait - end - rect rgb(226,244,226) - Note over W,P: After - W->>L: read, validate, release - W->>S: SKEY, confirmation, without the lock - Sub->>L: MSG for X waits for database work only - P->>Sub: MSG for Y, Z processed - W->>L: read again, validate, write - end + W->>W: P: row exists? read, decide, write (one transaction) + W->>L: release + W->>S: request + Sub->>L: take, process a message, release + S-->>W: response + W->>L: take + W->>W: C: by the row rules, re-read, write (one transaction) + W->>L: release ``` -## Changes +Sites with a row: + +| Site | Request | P | C | When the state read in C differs | +|---|---|---|---|---| +| ACK command (A:2309, 2846-2881) and synchronous ackMessage (change 3) | ACK | row; message present (absent: the row ends without ACK, A:2864); user_ack set (A:2859; the asynchronous form set it when the row was stored, A:1022); queue read by id without the deleted filter; ACK skipped for a missing or marked queue | receipt (A:2869-2876) unless the ratchet does not allow sending; MROk deletion (A:2877-2880); message deletion (A:2867); drained-queue deletion (A:2975, 2987) | ratchet prohibits sending: receipt skipped | +| ICAck (A:2323-2324) | ACK | row; queue by (server, rcvId) with the deleted filter (AS:790); missing: no ACK (A:2437) | drained-queue deletion | | +| ICAckDel (A:2318-2322) | ACK | row; queue as ICAck | message deletion (A:2321); drained-queue deletion | | +| ICAllowSecure (A:2325-2348) | SKEY | row; sender key present, or a reply queue without sender-secure mode: ERR A_VERSION; RcvConnection: upgrade to duplex (A:4413-4415) and the confirmation stored (A:4466-4485), held (change 2, rule 9); DuplexConnection: the confirmation stored when the send queue has no delivery of a connection-info message | Secured (A:4449); messages.internal_ts of the confirmation set to now; a temporary error on another server moves the row to that server (CCMoved, A:2337-2344) | | +| ICDuplexSecure (A:2349-2351) | none | the row ends with ERR A_VERSION | | | +| ICReplyDel (A:2352-2355) | SKEY | row; SndConnection | Secured; the connection's deletion (A:1809) is requested once, after C or after the permanent-error exit, not after each attempt (master's allFinally runs inside the retried action) | | +| ICDeleteRcvQueue (A:2358-2365) | DEL | row; deleted queue (AS:793-796) | temporary error below the limit: delete_errors + 1, row kept; otherwise record removed (A:2362-2365) | | +| ICQSecure (A:2366-2384) | KEY | row; new queue by address, Confirmed (A:2371), with its replaced queue (A:2369-2370); ratchet prohibits sending: ERR, row ends | Secured, RSSendingQUSE, QUSE stored (A:2376-2377) | ratchet prohibits sending: ERR, row ends, no writes | +| ICQSndSecure (A:2385-2409) | SKEY, SEND confirmation | row; new send queue by address with its replaced queue; without a replaced queue and with a queue at SSSendingQEND: QEND stored, no request (A:2407-2409) | Active, primary, SSSendingQEND, QEND stored, deliveries counted and resumed (A:2395-2403) | ratchet prohibits sending: the status writes with ERR, as master (A:2395-2403, 2488) | +| ICQDelete (A:2410-2432) | DEL | row; queue by address at RSReceivedMessage (A:2417) | record removed; NSCCreate and SWITCH after commit (A:2425-2431) | | +| SWCH (A:2310-2315, 2905-2921) and switchConnection' (A:2893-2903, change 3) | NEW | row; head queue at RSSwitchStarted (A:2907); ratchet prohibits sending: status cleared, ERR, row ends | queue recorded (A:2916); QADD stored (A:2918); RSSendingQADD (A:2919) | ratchet prohibits sending: the new queue is deleted (rule 5), status cleared, ERR | +| LSET command (A:2268-2271) | LSET | row; credentials created when absent (A:1272-1293); data prepared | LINK | | +| acceptContact' (A:1745-1764, change 3) | SKEY, NEW, SEND | change 3 | change 3 | | +| JOIN service request (A:2295-2307, change 3) | NEW, SEND | change 3 | change 3 | | + +Sites without a row: setConnShortLink' (A:1247-1279), deleteConnShortLink' (A:1314-1321) and suspendConnection' (A:2995-3003) read under the lock and send LSET, LDEL or OFF without it; nothing is written after the request. + +For the three ACK sites, the GET lock is released and MSGNTF is written after OK or NO_MSG, as on master (A:2983-2986), whether or not C finds the row. After a permanent error, the GET lock is also released; the error is reported without MSGNTF. + +The ACK of problem 2 is solved by this change together with the protocol client of this branch, in which the thread that receives a response writes its MSG to msgQ and the requester writes nothing to msgQ. + +### 2. The command row records each split step + +```mermaid +stateDiagram-v2 + [*] --> Stored: created by an API call, the subscriber or a C + Stored --> Executing: an executor claims it (in memory, one process) + Executing --> Stored: temporary error recorded, claim released + Executing --> Done: C deletes the row and writes the outcome + Executing --> Failed: permanent error, the row is deleted, ERR + Stored --> Gone: an obsoleting operation deletes the row + Executing --> Undone: C finds no row, or the connection marked deleted, and undoes + Done --> [*] + Failed --> [*] + Gone --> [*] + Undone --> [*] +``` + +Rules: +1. Every P starts by checking that its row exists; a missing row ends the step without a request and without an event. +2. A C that ends the step (success, permanent error, obsolete state) starts with `DELETE FROM commands WHERE command_id = ? RETURNING 1` and writes its outcome only when a row is returned. A C that records a temporary failure (ICDeleteRcvQueue's delete_errors) writes only while the row exists and keeps it. +3. Operations that make a step obsolete delete its row in their own transaction: + - the abort (A:2923-2945) deletes the connection's SWCH and ICQSecure rows; + - the peer's repeated QADD deletes the ICQSndSecure rows of the earlier new send queues that it deletes (delSqs, A:4131, 4137); + - the end of a synchronous call deletes its own row (change 3). +4. A C that finds its connection marked deleted (AS:2748-2762 with the deleted filter) writes no outcome, deletes its row and runs the undo. +5. Undo of NEW: the created queue is recorded with deleted = 1 and an ICDeleteRcvQueue row while the connection row exists; when the connection row is gone, DEL is sent once. +6. Within one process, an executor claims the row by command id for its attempt (an in-memory set). The worker's read returns no work while the oldest row of its key is claimed; the claimant wakes the key's worker when it releases the claim. +7. Across the app and the iOS extension, nothing is claimed in the store: the first C that deletes the row writes the outcome. KEY and SKEY with the same key, DEL (AUTH) and ACK (NO_MSG) are repeatable; NEW is undone. +8. C reads queues by address where the row names them, because queue ids are reused (AS:2370-2375). +9. Deliveries of a connection wait while it has an ALLOW_SECURE, REPLY_DEL or JOIN row: + - the delivery work read (AS:1116-1132) returns no message for such a connection, by a `NOT EXISTS` join on commands (conn_id index); + - every transaction that deletes such a row is followed by a wake of the delivery workers of the connection's send queues, in the process that ran it; + - on resume, existing delivery workers are woken (A:2607 passes False), which also covers a row that the other process deleted. + +### 3. Synchronous calls with their own rows + +acceptContact', sendServiceRequest' and sendServiceRequestAsync', switchConnection', and the synchronous ackMessage: +1. The call stores, in its first transaction, the row that its asynchronous form stores, with a flag in the encoded command that marks a synchronous call, and claims it. + - acceptContact': a JOIN row (JRInvitationDR or JRConnReq, as acceptContactAsync', A:993-995); the transaction is refused when the connection already has a JOIN row. + - the service request: the JOIN JRServiceReq row (A:1853). + - switchConnection': the SWCH row with RSSwitchStarted (A:1052-1053). + - ackMessage: the ACK row with user_ack (A:1017-1023). +2. The call executes the row in its own thread, by change 1 for SWCH and ACK, and as below for JOIN rows, and returns the outcome. +3. On an error, the call returns the error to its caller, as master does, deletes its row, releases the claim and wakes the key's worker. State written before the error stays, as on master, and a repeated call continues from it (A:1757-1762). +4. After a crash, the worker deletes a flagged row in its P without a request. The chat ignores JOINED with an empty corrId (Subscriber.hs:533-535, 736-738), so the row is not resumed. +5. acceptContact' takes the connection lock only for its database steps (A:1746 holds it across the call): + - P1: row; dispatch on the connection as A:1757-1762; the send queue recorded (A:1586-1588) or reused; + - SKEY unless Secured; P2: Secured (A:4449); + - NEW of the reply queue when P1 found none (A:4460-4462); P3: the reply queue recorded (AS:646-651) while the row exists, otherwise undone (change 2, rule 5); + - SEND of the confirmation (A:4429-4430); + - C: Confirmed (A:4431); the invitation deleted (A:1763); the row deleted. +6. The service request, both forms: + - P1: row; P2 after NEW: the reply queue recorded while the row exists (AS:646-651); + - SEND (A:1675), only after P2 found the row; + - the asynchronous form repeats attempts after temporary errors and QUOTA, as A:2459-2471, while the next attempt starts before expiresAt (A:1859); + - the call then waits for the reply (A:1866-1867), deletes its row and runs its cleanup (A:1868-1870) in the same thread, without the connection lock, so no attempt runs after its cleanup; + - a row left by a crash has no waiter: the worker deletes it (A:2299-2300). + +### 4. Late responses are committed like on-time responses + +A late response reaches the subscriber as STResponse (A:3622-3636). Master reads the queue with getRcvConn, which filters deleted queues and deleted connections (AS:610, 2757), and emits ERR CONN NOT_FOUND with an empty connection id when it finds none (A:3647-3649). + +| Late response | Master | Change | +|---|---|---| +| SUB: OK, SOK, MSG | processed (A:3624-3631) | unchanged | +| ACK: MSG | processed (A:3632-3633) | unchanged | +| ACK: OK, NO_MSG, error | ignored (A:3634), or ERR CONN NOT_FOUND for a deleted queue | the connection's ACK, ACK_DEL and client ACK rows are read (conn_id index) and decoded; the row whose server message id matches (ICAck and ICAckDel store it; the client ACK row stores the agent message id, mapped through rcv_messages.broker_id) runs its C; the GET lock and MSGNTF as for on-time responses | +| DEL: OK, AUTH, error | ignored (A:3635), or ERR CONN NOT_FOUND | the queue record is read including deleted queues; with a DELETE_RCV_QUEUE or QDELETE row, that row runs its C; for a queue of a connection marked deleted, the record is removed | +| NEW: IDS | ignored (A:3636) | the rows with a NEW request on the response's server (SWCH, NEW, JOIN; server index) are read and decoded; the row whose stored public key equals the request's key records the queue when its step has none recorded, and otherwise the queue is deleted | +| SEND | ignored (A:3636) | unchanged; the retry is sent; the peer drops a repeated message, except an invitation to an address without ratchet keys, which creates a second request (A:4235-4244), as on master | + +A row with a NEW request stores the generated keys in its encoded command in the P before NEW: the NEW command (A:2263-2267), SWCH, and JOIN rows that create a reply queue. createConnection and prepared links have no row; their late IDS stays ignored, as on master. + +```mermaid +sequenceDiagram + participant W as Executor + participant S as Server + participant P as Protocol client + participant Sub as Subscriber + W->>S: request (row present) + Note over W: timeout, temporary error, claim released + S-->>P: response after the timeout + P->>Sub: late response (STResponse) + Sub->>Sub: find the row or the record; C by the row rules + W->>W: next attempt: P finds no row, nothing sent +``` + +### 5. Rotation + +1. AUTH of QADD or QUSE (A:2690, 2692) resets the receiving rotation, when the refusing send queue is the connection's only send queue and its delivery row exists, and the new receive queue named in the message still replaces a queue at RSSendingQADD or RSSendingQUSE. The reset is the abort's transaction (A:2935-2938), taken under the connection lock, together with the deletion of the refused delivery; ERR A_QUEUE is written as on master (A:2690, 2826). +2. Abort is allowed only at RSSwitchStarted: ST:210-222 loses the RSSendingQADD branch, so canAbortSwitch (A:3185) is False from RSSendingQADD for every peer version. +3. The writes of the first message on a new queue (A:3738-3747: status, primary, RSReceivedMessage, ICQDelete row) become one transaction, in master's position before decryption (A:3751). +4. QADD, QKEY, QUSE and QEND (A:4121-4221) write their effects in the transaction that stores the decrypted message (A:3833-3850). An error of a handler is returned as a value inside that transaction: the decryption and the message are stored as on master, and the handler's error is reported as on master. +5. A message is stored with all its deliveries in one transaction (A:2561-2579 with A:2591-2601). +6. switchConnectionAsync' (A:1052-1053), the abort (A:2935-2938) and deleteRcvQueueAsync (A:2991-2992) each write their state and their command row in one transaction. + +### 6. Small fixes -- agent, connection locks: - - `requestAndCommit` in ICDuplexSecure, ICQSecure, ICQSndSecure, ICQDelete and `ackMessage`; - - `recordNewQueue` in `createRcvQueue`, `createReplyQueue` and `switchDuplexConnection`; - - request outside the lock in ICAck, ICAckDel, ICAllowSecure, ICDeleteRcvQueue, ICReplyDel, JOIN of a service request, `setConnShortLink`, `deleteConnShortLink`, `suspendConnection`, `connectReplyQueues`; - - `acceptContact` under the invitation lock; `serviceRequest_` without the connection lock; - - deletion under the locks of its connections, where the connections are marked deleted in synchronous deletion too; - - a connection whose deletion waits for delivery is not given new queues; - - the record step of an acknowledgement reads the queue again; - - a concurrent acknowledgement of a deleted message is dropped; - - each switch start has an identifier; an abort removes it, a new start replaces it, and a switch whose identifier is no longer current is aborted after its queue is created, without an event from an asynchronous switch; - - the receive queue status is set to Secured under the lock, only from Confirmed; - - ICQSecure and ICQSndSecure are postponed while the ratchet is not synchronized, after the other commands of their server, and resumed after synchronization; - - SWCH is refused while the ratchet is not synchronized. -- agent, events and notification commands written without waiting: - - MSGNTF of `ackMessage`, DEL_CONNS, DEL_USER; - - errors of `subscribeConnections`, `deleteConnections`, `subscribeAllConnections`, `deleteUser`, `xftpDeleteSndFilesRemote`; - - the notification commands of connection deletion, ICQDelete and QEND. -- clients: - - a message in the response to ACK, SUB or GET is written to msgQ by the receiving thread, in the order of reception; - - a command waits for send-queue space only until its response timeout, and is not queued after it ends; - - a command that ends without a response is removed, except in clients with msgQ, where it is kept until its late response or disconnection. +1. A GET lock records the session of its GET; it is also released when that session ends (AC:813-818 releases only subscribed queues). +2. The ACK row's P reads the queue without the deleted filter (master's synchronous retry fails at AS:1235 after a QEND marked the queue, A:2865). C reads no queue. During ratchet synchronization the receipt is skipped without an error; master writes ERR INTERNAL after the ACK (A:2876, 2488). The peer gets no delivery receipt either way. +3. ackMessageAsync' (A:1001-1023) reads the message's queue by id without the deleted filter. For a removed queue, the ACK row is keyed by the primary queue's server, and its step deletes the message and stores the receipt without an ACK. A queue id reused by a newer queue (AS:2370-2375; rcv_messages.rcv_queue_id has no foreign key, schema:124) resolves to that queue, as on master. +4. Connection deletion also takes the receive queues already marked deleted (AS:2872-2875 filters deleted = 0) and deletes them with the others; a DEL for a queue the server already deleted returns AUTH, reported in DEL_RCVQS (A:3091-3099, 3083). +5. The old KEY handshake: no ICDuplexSecure rows are created (A:4035); a confirmation with a sender key is refused; joining an invitation whose queue has no sender-secure mode is refused with A_VERSION where the invitation is checked (compatibleInvitationUri, A:1598-1605, used by A:965 and A:1540); the minimum SMP client version of smpClientVRange becomes 3. Every supported relay, from version 15 (Transport.hs:222-226), returns the queue mode that the client requests (Server.hs:1738). +6. Client.hs: a batch block is sent after its callers' waits end, until the client disconnects; master's forked writer was not ended at disconnection. +7. Processing of a received message (A:3698) reads the connection and its queues after it takes the connection lock; before the lock, only the queue's connection id is read (A:3648). Subscription responses and event errors (A:3619-3631) are unchanged.