Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
9a33fd4
agent: prevent a switch queue left on the server by synchronous deletion
evgeny-simplex Nov 21, 2026
f620a6b
agent: prevent waits for the notification command queue in a switch
evgeny-simplex Nov 21, 2026
de119c4
agent: prevent an error event when an asynchronous switch is aborted
evgeny-simplex Nov 21, 2026
b4e3329
tests: time out the switch with a full notification command queue
evgeny-simplex Nov 21, 2026
f8890ac
plans: lock holders never wait for notification command queue space
evgeny-simplex Nov 21, 2026
36d3207
clients: simplify command sending; request time in system seconds
evgeny-simplex Nov 23, 2026
4c2ee39
clients: fail commands of a disconnected client without queueing them
evgeny-simplex Nov 23, 2026
953dac4
clients: revert command sending to f8890ac3
evgeny-simplex Nov 23, 2026
f0bdba6
clients: send a block only while connected, with one dispatch on msgQ
evgeny-simplex Nov 23, 2026
c9ae815
clients: request creation time in system seconds
evgeny-simplex Nov 23, 2026
c55ef71
clients: write a message received in a response to msgQ in its order …
evgeny-simplex Nov 23, 2026
2eb02bb
clients: check the entity of a response once
evgeny-simplex Nov 23, 2026
9c6121e
agent: simplify acknowledgement, new queue recording and command post…
evgeny-simplex Nov 23, 2026
3398bac
tests: remove duplicate switch tests, share full queue helpers
evgeny-simplex Nov 23, 2026
4a42ac9
plans: correct the agent no-blocking plan to the code
evgeny-simplex Nov 23, 2026
2989063
tests: import the full notification queue helper
evgeny-simplex Nov 23, 2026
9b08382
clients: keep requests for late responses until disconnection
evgeny-simplex Nov 24, 2026
6826cf6
agent: plan requests without contested connection locks
evgeny-simplex Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
232 changes: 176 additions & 56 deletions plans/2026-11-21-agent-no-blocking.md

Large diffs are not rendered by default.

64 changes: 33 additions & 31 deletions src/Simplex/Messaging/Agent.hs
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 =
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 =
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -2965,6 +2963,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
Expand All @@ -2974,7 +2973,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
Expand All @@ -2990,17 +2989,19 @@ 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)
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 =
Expand Down Expand Up @@ -3093,7 +3094,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]
Expand All @@ -3107,7 +3107,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' #-}
Expand Down Expand Up @@ -3212,7 +3211,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'
Expand Down Expand Up @@ -4305,7 +4307,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
Expand Down
1 change: 0 additions & 1 deletion src/Simplex/Messaging/Agent/Client.hs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading