Skip to content

Commit b0dafb2

Browse files
authored
fix(gateway): live sessions stall or reorder across agent identities (#128265)
* fix(gateway): isolate transcript lanes by agent identity * fix(gateway): order marker-only transcript updates correctly
1 parent 09eb2f9 commit b0dafb2

2 files changed

Lines changed: 137 additions & 32 deletions

File tree

‎src/gateway/server-session-events.test.ts‎

Lines changed: 113 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,21 @@ const sessionRow = vi.hoisted(() => ({
1616
const resolveEmbeddedAgentRunProgressStateMock = vi.hoisted(() => vi.fn());
1717
const loadGatewaySessionRowMock = vi.hoisted(() => vi.fn());
1818
const projectChatDisplayMessageMock = vi.hoisted(() => vi.fn((message: unknown) => message));
19+
const listAccessorSessionEntriesReadOnlyMock = vi.hoisted(() => vi.fn());
1920
const loadAccessorSessionEntryReadOnlyMock = vi.hoisted(() => vi.fn());
2021
const loadGatewaySessionEntryReadOnlyMock = vi.hoisted(() => vi.fn());
2122
const readSessionMessageCountAsyncMock = vi.hoisted(() => vi.fn());
23+
const resolveTranscriptSessionKeyBySessionIdMock = vi.hoisted(() => vi.fn());
2224
const runtimeConfigState = vi.hoisted(() => ({ value: {} as Record<string, unknown> }));
2325

2426
vi.mock("../config/io.js", () => ({ getRuntimeConfig: () => runtimeConfigState.value }));
2527
vi.mock("../config/sessions/session-accessor.js", async (importOriginal) => {
2628
const actual = await importOriginal<typeof import("../config/sessions/session-accessor.js")>();
2729
return {
2830
...actual,
31+
listSessionEntriesReadOnly: listAccessorSessionEntriesReadOnlyMock,
2932
loadSessionEntryReadOnly: loadAccessorSessionEntryReadOnlyMock,
33+
resolveTranscriptSessionKeyBySessionId: resolveTranscriptSessionKeyBySessionIdMock,
3034
};
3135
});
3236
vi.mock("./chat-display-projection.js", () => ({
@@ -110,10 +114,12 @@ describe("createTranscriptUpdateBroadcastHandler", () => {
110114
beforeEach(() => {
111115
vi.clearAllMocks();
112116
resolveEmbeddedAgentRunProgressStateMock.mockReturnValue(undefined);
117+
listAccessorSessionEntriesReadOnlyMock.mockReturnValue([]);
113118
loadAccessorSessionEntryReadOnlyMock.mockReturnValue(undefined);
114119
loadGatewaySessionEntryReadOnlyMock.mockReturnValue({ entry: undefined, storePath: "" });
115120
loadGatewaySessionRowMock.mockReturnValue(sessionRow);
116121
readSessionMessageCountAsyncMock.mockResolvedValue(undefined);
122+
resolveTranscriptSessionKeyBySessionIdMock.mockReturnValue(undefined);
117123
loadGatewaySessionRowMock.mockReturnValue(sessionRow);
118124
runtimeConfigState.value = {};
119125
sessionRow.key = "agent:main:main";
@@ -650,14 +656,30 @@ describe("createTranscriptUpdateBroadcastHandler", () => {
650656
expect(broadcastToConnIds.mock.calls[0]?.[1]).toMatchObject({ messageSeq: 7 });
651657
});
652658

653-
it("does not stall one session's broadcasts behind another session's pending seq read", async () => {
659+
it.each([
660+
{
661+
name: "distinct session keys",
662+
slowAgentId: "main",
663+
slowSessionKey: "agent:main:slow",
664+
fastAgentId: "main",
665+
fastSessionKey: "agent:main:main",
666+
},
667+
{
668+
name: "global sessions owned by different agents",
669+
slowAgentId: "main",
670+
slowSessionKey: "global",
671+
fastAgentId: "research",
672+
fastSessionKey: "global",
673+
},
674+
])("does not stall $name behind another transcript's pending seq read", async (scenario) => {
654675
let releaseSlowCount: (value: number | undefined) => void = () => undefined;
655-
readSessionMessageCountAsyncMock.mockImplementation((params: { sessionKey?: string }) =>
656-
params.sessionKey === "agent:main:slow"
657-
? new Promise<number | undefined>((resolve) => {
658-
releaseSlowCount = resolve;
659-
})
660-
: Promise.resolve(3),
676+
readSessionMessageCountAsyncMock.mockImplementation(
677+
(params: { agentId?: string; sessionKey?: string }) =>
678+
params.agentId === scenario.slowAgentId && params.sessionKey === scenario.slowSessionKey
679+
? new Promise<number | undefined>((resolve) => {
680+
releaseSlowCount = resolve;
681+
})
682+
: Promise.resolve(3),
661683
);
662684
loadAccessorSessionEntryReadOnlyMock.mockReturnValue({ sessionId: "sess-main" });
663685
const { broadcastToConnIds, handler } = createHandler(false);
@@ -667,32 +689,81 @@ describe("createTranscriptUpdateBroadcastHandler", () => {
667689
message: { role: "assistant", content: [{ type: "text", text: "slow" }] },
668690
messageId: "slow-1",
669691
target: {
670-
agentId: "main",
692+
agentId: scenario.slowAgentId,
671693
sessionId: "sess-slow",
672-
sessionKey: "agent:main:slow",
694+
sessionKey: scenario.slowSessionKey,
673695
storePath: "/tmp/slow-sessions.json",
674696
},
675697
});
698+
await vi.waitFor(() => expect(readSessionMessageCountAsyncMock).toHaveBeenCalledOnce());
676699

677-
await handler({
700+
const fastTask = handler({
678701
sessionFile: "/tmp/sess-main.jsonl",
679-
sessionKey: "agent:main:main",
702+
agentId: scenario.fastAgentId,
703+
sessionKey: scenario.fastSessionKey,
680704
message: { role: "assistant", content: [{ type: "text", text: "fast" }] },
681705
messageId: "fast-1",
682706
messageSeq: 1,
683707
});
684708

685-
// The independent lane broadcast completed while the slow lane is parked.
686-
expect(broadcastToConnIds).toHaveBeenCalledTimes(1);
687-
expect(broadcastToConnIds.mock.calls[0]?.[1]).toMatchObject({ messageId: "fast-1" });
709+
try {
710+
// The independent lane must publish while the other transcript remains parked.
711+
await vi.waitFor(() => expect(broadcastToConnIds).toHaveBeenCalledOnce(), {
712+
timeout: 100,
713+
interval: 5,
714+
});
715+
expect(broadcastToConnIds.mock.calls[0]?.[1]).toMatchObject({ messageId: "fast-1" });
716+
} finally {
717+
releaseSlowCount(5);
718+
await Promise.allSettled([slowTask, fastTask]);
719+
}
688720

689-
releaseSlowCount(5);
690-
await slowTask;
691721
expect(broadcastToConnIds).toHaveBeenCalledTimes(2);
692722
expect(broadcastToConnIds.mock.calls[1]?.[1]).toMatchObject({ messageId: "slow-1" });
693723
});
694724

695-
it("preserves message order within one session lane", async () => {
725+
it.each([
726+
{
727+
name: "an agent-qualified session",
728+
firstSessionKey: "agent:main:main",
729+
secondSessionKey: "agent:main:main",
730+
agentId: "main",
731+
},
732+
{
733+
name: "an ownerless legacy global update",
734+
firstSessionKey: "global",
735+
secondSessionKey: "global",
736+
agentId: "main",
737+
},
738+
{
739+
name: "a global session and its agent-qualified alias",
740+
firstSessionKey: "global",
741+
secondSessionKey: "agent:main:global",
742+
agentId: "main",
743+
},
744+
{
745+
name: "a marker-only update and its canonical transcript key",
746+
firstSessionKey: "agent:main:main",
747+
secondSessionKey: "agent:main:main",
748+
agentId: "main",
749+
markerOnly: true,
750+
},
751+
{
752+
name: "an ownerless global update in its configured fixed store",
753+
firstSessionKey: "global",
754+
secondSessionKey: "global",
755+
agentId: "ops",
756+
config: {
757+
session: { store: "/tmp/owned-shared.sqlite" },
758+
agents: {
759+
ownership: "explicit",
760+
defaults: { sessionStore: { agentId: "ops" } },
761+
entries: { ops: {}, research: {} },
762+
},
763+
},
764+
},
765+
])("preserves message order for $name", async (scenario) => {
766+
runtimeConfigState.value = scenario.config ?? {};
696767
let releaseFirstCount: (value: number | undefined) => void = () => undefined;
697768
readSessionMessageCountAsyncMock.mockImplementationOnce(
698769
() =>
@@ -701,31 +772,45 @@ describe("createTranscriptUpdateBroadcastHandler", () => {
701772
}),
702773
);
703774
loadAccessorSessionEntryReadOnlyMock.mockReturnValue({ sessionId: "sess-main" });
775+
if (scenario.markerOnly) {
776+
listAccessorSessionEntriesReadOnlyMock.mockReturnValue([
777+
{ key: scenario.firstSessionKey, entry: { sessionId: "sess-main" } },
778+
]);
779+
resolveTranscriptSessionKeyBySessionIdMock.mockReturnValue(scenario.firstSessionKey);
780+
}
704781
const { broadcastToConnIds, handler } = createHandler(false);
705782

706783
const firstTask = handler({
707784
message: { role: "assistant", content: [{ type: "text", text: "first" }] },
708785
messageId: "ordered-1",
709-
target: {
710-
agentId: "main",
711-
sessionId: "sess-main",
712-
sessionKey: "agent:main:main",
713-
storePath: "/tmp/explicit-sessions.json",
714-
},
786+
...(scenario.markerOnly
787+
? { sessionFile: `sqlite:${scenario.agentId}:sess-main:/tmp/explicit-sessions.json` }
788+
: {
789+
target: {
790+
agentId: scenario.agentId,
791+
sessionId: "sess-main",
792+
sessionKey: scenario.firstSessionKey,
793+
storePath: "/tmp/explicit-sessions.json",
794+
},
795+
}),
715796
});
797+
await vi.waitFor(() => expect(readSessionMessageCountAsyncMock).toHaveBeenCalledOnce());
716798
const secondTask = handler({
717799
sessionFile: "/tmp/sess-main.jsonl",
718-
sessionKey: "agent:main:main",
800+
sessionKey: scenario.secondSessionKey,
719801
message: { role: "assistant", content: [{ type: "text", text: "second" }] },
720802
messageId: "ordered-2",
721803
messageSeq: 2,
722804
});
723805

724806
await Promise.resolve();
725-
expect(broadcastToConnIds).not.toHaveBeenCalled();
726-
727-
releaseFirstCount(1);
728-
await Promise.all([firstTask, secondTask]);
807+
await Promise.resolve();
808+
try {
809+
expect(broadcastToConnIds).not.toHaveBeenCalled();
810+
} finally {
811+
releaseFirstCount(1);
812+
await Promise.allSettled([firstTask, secondTask]);
813+
}
729814
expect(broadcastToConnIds.mock.calls.map((call) => call[1]?.messageId)).toEqual([
730815
"ordered-1",
731816
"ordered-2",

‎src/gateway/server-session-events.ts‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,10 @@ import {
2929
buildGatewaySessionEventRow,
3030
projectSessionEventActiveRunIds,
3131
} from "./session-event-payload.js";
32-
import { resolveSessionSubscriptionKeys } from "./session-subscription-keys.js";
32+
import {
33+
resolveSessionSubscriptionKey,
34+
resolveSessionSubscriptionKeys,
35+
} from "./session-subscription-keys.js";
3336
import { projectSessionMessagePayload } from "./session-transcript-message.js";
3437
import { readSessionMessageCountAsync } from "./session-transcript-readers.js";
3538
import {
@@ -149,11 +152,28 @@ export function createTranscriptUpdateBroadcastHandler(params: {
149152
? readTranscriptUpdateLifecycleOwner(update)?.lifecycleRevision
150153
: undefined);
151154
const queuedUpdate = lifecycleRevision ? { ...update, lifecycleRevision } : update;
152-
const laneKey =
155+
const legacyMarker = parseSqliteSessionFileMarker(update.sessionFile);
156+
const sessionKey =
153157
normalizeOptionalString(update.target?.sessionKey) ??
154158
normalizeOptionalString(update.sessionKey) ??
155-
normalizeOptionalString(update.sessionFile) ??
156-
"";
159+
(legacyMarker ? resolveTranscriptSessionKeyBySessionId(legacyMarker) : undefined);
160+
let agentId =
161+
normalizeOptionalString(update.target?.agentId) ??
162+
normalizeOptionalString(update.agentId) ??
163+
legacyMarker?.agentId;
164+
if (!agentId && sessionKey?.toLowerCase() === "global") {
165+
const config = getRuntimeConfig();
166+
const persistedOwner = resolvePersistedSessionStoreOwnerForKey(config, sessionKey);
167+
agentId =
168+
persistedOwner.kind === "configured"
169+
? persistedOwner.agentId
170+
: tryResolveLegacyCompatibilityAgentId(config);
171+
}
172+
// Raw global is per-agent storage identity; its qualified aliases must share a lane.
173+
const laneKey =
174+
sessionKey && agentId
175+
? resolveSessionSubscriptionKey(sessionKey, agentId)
176+
: (sessionKey ?? normalizeOptionalString(update.sessionFile) ?? "");
157177
// Preserve transcript update order within the lane even when counting
158178
// messages requires an async read from the session file.
159179
const tail = broadcastQueues.get(laneKey) ?? Promise.resolve();

0 commit comments

Comments
 (0)