From ec5deda6f368c734d918608ba3398c1d510938c6 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:02:39 +0000 Subject: [PATCH 1/3] tests: delete a connection while the delivery of its message is deleted --- tests/AgentTests.hs | 3 +- tests/AgentTests/FunctionalAPITests.hs | 57 +++++++++++++++++++++++++- 2 files changed, 57 insertions(+), 3 deletions(-) diff --git a/tests/AgentTests.hs b/tests/AgentTests.hs index cb14f5fff..cc892cd7c 100644 --- a/tests/AgentTests.hs +++ b/tests/AgentTests.hs @@ -20,7 +20,7 @@ import Simplex.Messaging.Transport (ASrvTransport) import Test.Hspec hiding (fit, it) #if defined(dbPostgres) -import AgentTests.FunctionalAPITests (workItemReadTests) +import AgentTests.FunctionalAPITests (connectionDeletionTests, workItemReadTests) #else import AgentTests.SQLiteTests (storeTests) #endif @@ -38,6 +38,7 @@ agentCoreTests = do describe "resolve names" resolveNameTests #if defined(dbPostgres) describe "Work item reads" workItemReadTests + describe "Connection deletion" connectionDeletionTests #endif agentTests :: (ASrvTransport, AStoreType) -> Spec diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 5f6b0d835..9ed9782fc 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -60,6 +60,7 @@ module AgentTests.FunctionalAPITests testServerInformation, #if defined(dbPostgres) workItemReadTests, + connectionDeletionTests, #endif ) where @@ -140,9 +141,10 @@ import Database.PostgreSQL.Simple (Only (..), Query) import Fixtures import Simplex.Messaging.Agent.Client (withStoreIsolation', withWork, withWorkItems) import Simplex.Messaging.Agent.Env.SQLite (AM) -import Simplex.Messaging.Agent.Store (AgentCommand (AClientCommand), RcvQueue, RcvQueueSub (..), ServiceAssoc) -import Simplex.Messaging.Agent.Store.AgentStore (createCommand, createNtfSubscription, createServer, createSndFile, deleteClientService, getNextNtfSubNTFActions, getNextNtfSubSMPActions, getNextSndFileToPrepare, getPendingServerCommand, getSubscriptionService, getUserServerRcvQueueSubs, removeRcvServiceAssocs, setRcvServiceAssocs, startPreparedSndFile) +import Simplex.Messaging.Agent.Store (AgentCommand (AClientCommand), InternalId (..), RcvQueue, RcvQueueSub (..), ServiceAssoc) +import Simplex.Messaging.Agent.Store.AgentStore (createCommand, createNtfSubscription, createServer, createSndFile, deleteClientService, deleteConn, deleteSndMsgDelivery, getNextNtfSubNTFActions, getNextNtfSubSMPActions, getNextSndFileToPrepare, getPendingServerCommand, getSubscriptionService, getUserServerRcvQueueSubs, removeRcvServiceAssocs, setRcvServiceAssocs, startPreparedSndFile) import Simplex.Messaging.Agent.Store.Common (IsolationLevel (..)) +import Simplex.Messaging.Agent.Store.Entity (DBEntityId' (..)) import Simplex.Messaging.Notifications.Types (NtfAgentSubStatus (NASNew), NtfSubAction (NSANtf, NSASMP), NtfSubNTFAction (NSACreate), NtfSubSMPAction (NSASmpKey), newNtfSubscription) #endif #if defined(dbServerPostgres) @@ -5173,6 +5175,57 @@ waitForLock st holder waitingQuery = timeout 5000000 waitLoop `shouldReturn` Jus withTransaction st $ \db -> DB.query db "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE ? = ANY (pg_blocking_pids(pid)) AND position(? IN query) > 0)" (holder, waitingQuery) unless waiting $ threadDelay 10000 >> waitLoop + +waitForBlocked :: DBStore -> String -> IO () +waitForBlocked st waitingQuery = timeout 5000000 waitLoop `shouldReturn` Just () + where + waitLoop = do + [Only waiting] <- + withTransaction st $ \db -> + DB.query db "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0 AND position(? IN query) > 0)" (Only waitingQuery) + unless waiting $ threadDelay 10000 >> waitLoop + +connectionDeletionTests :: Spec +connectionDeletionTests = + it "should delete a connection while the delivery of its sent message is deleted" $ + withAgent 1 agentCfg initAgentServers testDB $ \a -> do + let st = store $ agentEnv a + connId = "conn1" + g <- C.newRandom + sndPrivateKey <- atomically $ C.generatePrivateAuthKey C.SEd25519 g + (dhPubKey, dhPrivKey) <- atomically $ C.generateKeyPair g + let sq = + SndQueue + { userId = 1, + connId, + server = testSMPServer, + sndId = SMP.EntityId "1", + queueMode = Nothing, + sndPrivateKey, + e2ePubKey = Nothing, + e2eDhSecret = C.dh' dhPubKey dhPrivKey, + status = Active, + dbQueueId = DBEntityId 1, + primary = True, + dbReplaceQueueId = Nothing, + sndSwchStatus = Nothing, + smpClientVersion = Version 1 + } + withTransaction st $ \db -> do + DB.execute db "INSERT INTO connections (user_id, conn_id, conn_mode) VALUES (1,?,?)" (connId, SCMInvitation) + DB.execute db "INSERT INTO messages (conn_id, internal_id, internal_ts, internal_snd_id, msg_type) VALUES (?,1,now(),1,'')" (Only connId) + DB.execute db "INSERT INTO snd_messages (conn_id, internal_snd_id, internal_id, internal_hash) VALUES (?,1,1,'')" (Only connId) + DB.execute db "INSERT INTO snd_message_deliveries (conn_id, snd_queue_id, internal_id) VALUES (?,1,1)" (Only connId) + (delivery, deletion) <- withTransaction st $ \db -> do + _ :: [Only Int] <- DB.query_ db "SELECT 1 FROM snd_messages FOR UPDATE" + [Only holder] <- DB.query_ db "SELECT pg_backend_pid()" + delivery <- async $ withTransaction st $ \db' -> deleteSndMsgDelivery db' connId sq (InternalId 1) False + waitForLock st holder "FROM snd_messages" + deletion <- async $ withTransaction st $ \db' -> deleteConn db' Nothing connId + waitForBlocked st "DELETE FROM connections" + pure (delivery, deletion) + wait delivery `shouldReturn` () + wait deletion `shouldReturn` Just connId #endif testClientServiceConnection :: (HasCallStack, HasTestEnv) => (ASrvTransport, AStoreType) -> IO () From d548f84d22e8dea9b4c4ecc71db78a98afbb07a9 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:04:08 +0000 Subject: [PATCH 2/3] agent: lock the connection before deleting a message delivery on PostgreSQL --- src/Simplex/Messaging/Agent/Store/AgentStore.hs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Simplex/Messaging/Agent/Store/AgentStore.hs b/src/Simplex/Messaging/Agent/Store/AgentStore.hs index 41685f2e2..5395e0f0a 100644 --- a/src/Simplex/Messaging/Agent/Store/AgentStore.hs +++ b/src/Simplex/Messaging/Agent/Store/AgentStore.hs @@ -1324,6 +1324,7 @@ deleteDeliveredSndMsg db connId msgId = do deleteSndMsgDelivery :: DB.Connection -> ConnId -> SndQueue -> InternalId -> Bool -> IO () deleteSndMsgDelivery db connId SndQueue {dbQueueId} msgId keepForReceipt = do + lockConnForUpdate db connId DB.execute db "DELETE FROM snd_message_deliveries WHERE conn_id = ? AND snd_queue_id = ? AND internal_id = ?" From 000b81d5fcb9eec0bfbd3d2af1f3255a8ab15cb3 Mon Sep 17 00:00:00 2001 From: "Evgeny @ SimpleX Chat" <259188159+evgeny-simplex@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:58:07 +0000 Subject: [PATCH 3/3] tests: wait for the deletion blocked by the delivery itself --- tests/AgentTests/FunctionalAPITests.hs | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/tests/AgentTests/FunctionalAPITests.hs b/tests/AgentTests/FunctionalAPITests.hs index 9ed9782fc..8cd20331a 100644 --- a/tests/AgentTests/FunctionalAPITests.hs +++ b/tests/AgentTests/FunctionalAPITests.hs @@ -5176,15 +5176,6 @@ waitForLock st holder waitingQuery = timeout 5000000 waitLoop `shouldReturn` Jus DB.query db "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE ? = ANY (pg_blocking_pids(pid)) AND position(? IN query) > 0)" (holder, waitingQuery) unless waiting $ threadDelay 10000 >> waitLoop -waitForBlocked :: DBStore -> String -> IO () -waitForBlocked st waitingQuery = timeout 5000000 waitLoop `shouldReturn` Just () - where - waitLoop = do - [Only waiting] <- - withTransaction st $ \db -> - DB.query db "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0 AND position(? IN query) > 0)" (Only waitingQuery) - unless waiting $ threadDelay 10000 >> waitLoop - connectionDeletionTests :: Spec connectionDeletionTests = it "should delete a connection while the delivery of its sent message is deleted" $ @@ -5219,10 +5210,14 @@ connectionDeletionTests = (delivery, deletion) <- withTransaction st $ \db -> do _ :: [Only Int] <- DB.query_ db "SELECT 1 FROM snd_messages FOR UPDATE" [Only holder] <- DB.query_ db "SELECT pg_backend_pid()" - delivery <- async $ withTransaction st $ \db' -> deleteSndMsgDelivery db' connId sq (InternalId 1) False + deliveryPid <- newEmptyMVar + delivery <- async $ withTransaction st $ \db' -> do + [Only pid] <- DB.query_ db' "SELECT pg_backend_pid()" + putMVar deliveryPid pid + deleteSndMsgDelivery db' connId sq (InternalId 1) False waitForLock st holder "FROM snd_messages" deletion <- async $ withTransaction st $ \db' -> deleteConn db' Nothing connId - waitForBlocked st "DELETE FROM connections" + readMVar deliveryPid >>= \pid -> waitForLock st pid "DELETE FROM connections" pure (delivery, deletion) wait delivery `shouldReturn` () wait deletion `shouldReturn` Just connId