@@ -18,6 +18,8 @@ import kotlinx.coroutines.test.runTest
1818import kotlinx.coroutines.withContext
1919import kotlinx.coroutines.withTimeout
2020import kotlinx.serialization.json.Json
21+ import kotlinx.serialization.json.jsonObject
22+ import kotlinx.serialization.json.jsonPrimitive
2123import org.junit.After
2224import org.junit.Assert.assertEquals
2325import org.junit.Assert.assertFalse
@@ -63,11 +65,14 @@ class ChatControllerBranchCoordinationTest {
6365 )
6466 }
6567
66- private suspend fun enqueue (text : String = "queued"): ChatOutboxItem =
68+ private suspend fun enqueue (
69+ text : String = "queued",
70+ sessionKey : String = "main",
71+ ): ChatOutboxItem =
6772 (
6873 outbox.enqueue(
6974 gatewayId = " gateway-a" ,
70- sessionKey = " main " ,
75+ sessionKey = sessionKey ,
7176 text = text,
7277 thinkingLevel = " off" ,
7378 nowMs = System .currentTimeMillis(),
@@ -723,52 +728,16 @@ class ChatControllerBranchCoordinationTest {
723728 ownerAgentId = " main" ,
724729 )
725730 val gateway = ScriptedGateway (json)
726- gateway.respondWith(
727- " chat.history" ,
728- historyResponse(
729- sessionId = " background" ,
730- messages = listOf (ReplayHistoryMessage (" user" , " old" , 1 , entryId = " leaf-old" )),
731- ),
732- )
733- gateway.respondWith(
734- " sessions.branches.list" ,
735- """ {"branches":[{"leafEntryId":"leaf-old","headline":"Old","messageCount":1,"active":true}]}""" ,
736- )
737- val controller = controller(gateway)
731+ val controller = controller(gateway, StandardTestDispatcher (testScheduler))
732+ runCurrent()
738733 controller.awaitOutboxRestore()
739- controller.load(backgroundKey)
740- withContext(Dispatchers .Default .limitedParallelism(1 )) {
741- withTimeout(5_000 ) { controller.sessionBranches.first { it.isNotEmpty() } }
742- }
743- controller.switchSession(" main" )
744- gateway.respondWith(
745- " chat.history" ,
746- historyResponse(
747- sessionId = " background" ,
748- messages = listOf (ReplayHistoryMessage (" user" , " new" , 2 , entryId = " leaf-new" )),
749- ),
750- )
751- gateway.respondWith(
752- " sessions.branches.list" ,
753- """ {"branches":[
754- {"leafEntryId":"leaf-old","headline":"Old","messageCount":1,"active":false},
755- {"leafEntryId":"leaf-new","headline":"New","messageCount":1,"active":true}
756- ]}""" ,
757- )
758734
759735 controller.handleGatewayEvent(
760736 " sessions.changed" ,
761737 """ {"reason":"branch-switch","sessionKey":"$backgroundKey ","agentId":"main"}""" ,
762738 )
763- withContext(Dispatchers .Default .limitedParallelism(1 )) {
764- withTimeout(5_000 ) {
765- while (outbox.load(" gateway-a" ).single().status != ChatOutboxStatus .Failed ) {
766- kotlinx.coroutines.delay(10 )
767- }
768- }
769- }
770-
771- assertEquals(ChatOutboxStatus .Failed , outbox.load(" gateway-a" ).single().status)
739+ runCurrent()
740+ assertTrue(outbox.branchState(" gateway-a" , backgroundScope)?.needsReconciliation == true )
772741 }
773742
774743 @Test
@@ -822,63 +791,75 @@ class ChatControllerBranchCoordinationTest {
822791 @Test
823792 fun reconcileOwnerDrainsRequestsQueuedDuringAnActivePass () =
824793 runTest {
825- val branchScope = ChatOutboxScope (" main" , " main" )
826- val initial = requireNotNull(outbox.branchState(" gateway-a" , branchScope))
827- assertTrue(outbox.updateLastActiveLeafEntryId(" gateway-a" , branchScope, " leaf-current" , initial.epoch, initial.revision))
828- enqueue(" first queued" )
829- assertTrue(outbox.demoteSessionMutationToReconciliation(" gateway-a" , branchScope, lease = null ))
794+ val backgroundScope = ChatOutboxScope (" background" , " main" )
795+ val backgroundState = requireNotNull(outbox.branchState(" gateway-a" , backgroundScope))
796+ assertTrue(
797+ outbox.updateLastActiveLeafEntryId(
798+ " gateway-a" ,
799+ backgroundScope,
800+ " leaf-current" ,
801+ backgroundState.epoch,
802+ backgroundState.revision,
803+ ),
804+ )
805+ val visibleScope = ChatOutboxScope (" main" , " main" )
806+ val visibleState = requireNotNull(outbox.branchState(" gateway-a" , visibleScope))
807+ assertTrue(
808+ outbox.updateLastActiveLeafEntryId(
809+ " gateway-a" ,
810+ visibleScope,
811+ " leaf-current" ,
812+ visibleState.epoch,
813+ visibleState.revision,
814+ ),
815+ )
816+ enqueue(" first queued" , sessionKey = " background" )
817+ assertTrue(outbox.demoteSessionMutationToReconciliation(" gateway-a" , backgroundScope, lease = null ))
830818
831819 val gateway = ScriptedGateway (json)
832820 val branchesEntered = CompletableDeferred <Unit >()
833821 val releaseBranches = CompletableDeferred <Unit >()
834- gateway.respondWith(
835- " chat.history" ,
822+ val requestsDrained = CompletableDeferred <Unit >()
823+ val sendCalls = AtomicInteger ()
824+ gateway.respond(" chat.history" ) { paramsJson ->
836825 historyResponse(
837- sessionId = " main" ,
826+ sessionId = gateway.sessionKeyOf(paramsJson) ? : " main" ,
838827 messages = listOf (ReplayHistoryMessage (" user" , " current" , 1 , entryId = " leaf-current" )),
839- ),
840- )
828+ )
829+ }
841830 gateway.respond(" sessions.branches.list" ) {
842- branchesEntered.complete(Unit )
843- releaseBranches.await()
831+ if (! branchesEntered.isCompleted) {
832+ branchesEntered.complete(Unit )
833+ releaseBranches.await()
834+ }
844835 """ {"branches":[{"leafEntryId":"leaf-current","headline":"Current","messageCount":1,"active":true}]}"""
845836 }
846- gateway.respondChatSend(" started" )
847- gateway.respond(" chat.history" ) {
848- val idempotencyKey = gateway.lastRunId?.let { " $it :user" }
849- historyResponse(
850- sessionId = " main" ,
851- messages =
852- listOf (
853- ReplayHistoryMessage (
854- " user" ,
855- " current" ,
856- 1 ,
857- idempotencyKey = idempotencyKey,
858- entryId = " leaf-current" ,
859- ),
860- ),
861- )
837+ gateway.respond(" chat.send" ) { paramsJson ->
838+ val runId =
839+ requireNotNull(paramsJson)
840+ .let (json::parseToJsonElement)
841+ .jsonObject
842+ .getValue(" idempotencyKey" )
843+ .jsonPrimitive
844+ .content
845+ if (sendCalls.incrementAndGet() == 2 ) requestsDrained.complete(Unit )
846+ """ {"runId":"$runId ","status":"started"}"""
862847 }
863- val controller = controller(gateway)
848+ val controller = controller(gateway, StandardTestDispatcher (testScheduler))
849+ runCurrent()
864850 controller.awaitOutboxRestore()
865851 controller.handleGatewayEvent(" health" , null )
866- withContext(Dispatchers .Default .limitedParallelism(1 )) {
867- withTimeout(5_000 ) { controller.healthOk.first { it } }
868- }
852+ runCurrent()
853+ assertTrue(controller.healthOk.value)
869854 branchesEntered.await()
870855
871856 assertTrue(controller.sendMessageAwaitAcceptance(" second queued" , " off" , emptyList()))
857+ assertEquals(2 , outbox.load(" gateway-a" ).size)
872858 releaseBranches.complete(Unit )
873859 withContext(Dispatchers .Default .limitedParallelism(1 )) {
874- withTimeout(5_000 ) {
875- while (outbox.branchState(" gateway-a" , branchScope)?.needsReconciliation != false ) {
876- kotlinx.coroutines.delay(10 )
877- }
878- }
860+ withTimeout(5_000 ) { requestsDrained.await() }
879861 }
880862
881- assertEquals(2 , outbox.load(" gateway-a" ).size)
882- assertTrue(outbox.load(" gateway-a" ).none { it.status == ChatOutboxStatus .Failed })
863+ assertEquals(2 , gateway.callCount(" chat.send" ))
883864 }
884865}
0 commit comments