Skip to content

The agent that grows with you

fix(shared): scope canonical replay cursors to each session

unsupportedpastels249fe49b623c
diff --git a/apps/shared/src/json-rpc-gateway-replay.test.ts b/apps/shared/src/json-rpc-gateway-replay.test.ts
index a5875738308..1211a3911b4 100644
--- a/apps/shared/src/json-rpc-gateway-replay.test.ts
+++ b/apps/shared/src/json-rpc-gateway-replay.test.ts
@@ -289,6 +289,121 @@ describe('JsonRpcGatewayClient event-seq tracking + replay resume', () => {
client.close()
})
+ it('keeps canonical replay epochs session-local while retaining the legacy gateway epoch', async () => {
+ const client = makeClient()
+ const first = client.connect('ws://x')
+ let sock = sockets[sockets.length - 1]
+ sock.open()
+ await first
+
+ const ready = (epoch: string) => sock.serverFrame({
+ jsonrpc: '2.0', method: 'event', params: { type: 'gateway.ready', payload: { replay_epoch: epoch } }
+ })
+
+ const live = (session_id: string, seq: number, replay_epoch?: string) => sock.serverFrame({
+ jsonrpc: '2.0', method: 'event', params: { type: 'message.delta', session_id, seq, replay_epoch }
+ })
+
+ ready('gateway-A')
+ live('s1', 7, 's1-A')
+ live('s2', 9, 's2-A')
+ live('legacy', 20)
+ live('s1', 1, 's1-B')
+ expect(client.getSeqWatermarks()).toEqual({ s1: 1, s2: 9, legacy: 20 })
+
+ client.invalidate('drop')
+ const second = client.connect('ws://x')
+ sock = sockets[sockets.length - 1]
+ sock.open()
+ await second
+
+ const requests = sock.sent.map(raw => JSON.parse(raw) as ReturnType<FakeWebSocket['lastRequest']>)
+ expect(requests).toHaveLength(3)
+ expect(requests.map(req => req.params)).toEqual(expect.arrayContaining([
+ { session_id: 's1', last_seen: 1, replay_epoch: 's1-B' },
+ { session_id: 's2', last_seen: 9, replay_epoch: 's2-A' },
+ { session_id: 'legacy', last_seen: 20, replay_epoch: 'gateway-A' }
+ ]))
+
+ for (const req of requests) {
+ const sid = req.params.session_id
+ const epoch = req.params.replay_epoch
+ const seq = Number(req.params.last_seen) + 1
+ sock.serverFrame({
+ jsonrpc: '2.0', id: req.id,
+ result: {
+ events: [{ type: 'message.delta', session_id: sid, seq }], epoch,
+ ...(sid === 'legacy' ? {} : { replay_epoch: epoch }),
+ latest_seq: seq, truncated: false, count: 1
+ }
+ })
+ }
+
+ await vi.waitFor(() => {
+ expect(client.getSeqWatermarks()).toEqual({ s1: 2, s2: 10, legacy: 21 })
+ })
+
+ // A legacy process restart must not erase canonical session cursors.
+ ready('gateway-B')
+ expect(client.getSeqWatermarks()).toEqual({ s1: 2, s2: 10 })
+ client.close()
+ })
+
+ it('applies parked session epochs after replay so a new generation does not poison the old gap', async () => {
+ const client = makeClient()
+ const seen: string[] = []
+ client.on('message.delta', event => {
+ const frame = event as unknown as { replay_epoch: string; seq: number }
+ seen.push(`${frame.replay_epoch}:${frame.seq}`)
+ })
+ const first = client.connect('ws://x')
+ let sock = sockets[sockets.length - 1]
+ sock.open()
+ await first
+ sock.serverFrame({
+ jsonrpc: '2.0', method: 'event',
+ params: { type: 'message.delta', session_id: 's1', seq: 5, replay_epoch: 'old' }
+ })
+ client.invalidate('drop')
+ const second = client.connect('ws://x')
+ sock = sockets[sockets.length - 1]
+ sock.open()
+ await second
+ const req = sock.lastRequest()
+ expect(req.method).toBe('session.events.since')
+
+ // These arrive before the response, but belong AFTER the old replay gap.
+ for (const seq of [1, 2]) {
+ sock.serverFrame({
+ jsonrpc: '2.0', method: 'event',
+ params: { type: 'message.delta', session_id: 's1', seq, replay_epoch: 'new' }
+ })
+ }
+
+ expect(client.getSeqWatermarks()).toEqual({ s1: 5 })
+ expect(seen).toEqual(['old:5'])
+ sock.serverFrame({
+ jsonrpc: '2.0', id: req.id,
+ result: {
+ // Include an overlapping old frame: early epoch adoption would replay it twice.
+ events: [5, 6, 7].map(seq => ({ type: 'message.delta', session_id: 's1', seq, replay_epoch: 'old' })),
+ epoch: 'old', replay_epoch: 'old', latest_seq: 7, truncated: false, count: 3
+ }
+ })
+ await vi.waitFor(() => {
+ expect(seen).toEqual(['old:5', 'old:6', 'old:7', 'new:1', 'new:2'])
+ })
+ expect(client.getSeqWatermarks()).toEqual({ s1: 2 })
+
+ client.invalidate('drop')
+ const third = client.connect('ws://x')
+ sock = sockets[sockets.length - 1]
+ sock.open()
+ await third
+ expect(sock.lastRequest().params).toEqual({ session_id: 's1', last_seen: 2, replay_epoch: 'new' })
+ client.close()
+ })
+
it('clears stale watermarks when the backend epoch changes (restart poisoning)', async () => {
const client = makeClient()
diff --git a/apps/shared/src/json-rpc-gateway.ts b/apps/shared/src/json-rpc-gateway.ts
index 420555fd59f..ef002a29b1f 100644
--- a/apps/shared/src/json-rpc-gateway.ts
+++ b/apps/shared/src/json-rpc-gateway.ts
@@ -31,6 +31,8 @@ export interface GatewayEvent<P = unknown> {
/** Registry connection whose socket delivered the event (renderer-side tag;
* absent for the local/legacy primary path). */
connectionId?: string
+ /** Session-scoped replay generation on canonical gateways. */
+ replay_epoch?: string
session_id?: string
type: GatewayEventName
}
@@ -134,13 +136,14 @@ export class JsonRpcGatewayClient {
*/
private replayHold: Map<string, GatewayEvent[]> | null = null
/**
- * Server process identity for the replay contract (from gateway.ready /
+ * Legacy server process identity for the replay contract (from gateway.ready /
* session.events.since). Seq counters are in-process on the backend, so a
* restart resets them while we still hold high watermarks — without this
* check events_since(sid, 97) returns [] + truncated=false forever and we
* silently believe nothing was missed.
*/
private replayEpoch: string | null = null
+ private replayEpochBySession = new Map<string, string>()
private readonly eventHandlers = new Map<string, Set<(event: GatewayEvent) => void>>()
private readonly stateHandlers = new Set<(state: ConnectionState) => void>()
private readonly options: Required<Omit<GatewayClientOptions, 'socketFactory'>> &
@@ -504,6 +507,8 @@ export class JsonRpcGatewayClient {
const sid = event.session_id
const seq = (event as { seq?: unknown }).seq
+ if (sid) { this.adoptSessionReplayEpoch(sid, event.replay_epoch) }
+
if (!sid || typeof seq !== 'number' || !Number.isFinite(seq)) {
return
}
@@ -549,32 +554,38 @@ export class JsonRpcGatewayClient {
// One RPC per known session keeps params flat; sessions are few (<20).
const results = await Promise.allSettled(
- entries.map(([sid, lastSeen]) =>
- this.request<{ events?: Array<{ type: string; session_id?: string; seq?: number; payload?: unknown }> }>(
+ entries.map(([sid, lastSeen]) => {
+ const epoch = this.replayEpochBySession.get(sid) ?? this.replayEpoch
+
+ return this.request<{ events?: Array<{ type: string; session_id?: string; seq?: number; payload?: unknown }> }>(
'session.events.since',
- { session_id: sid, last_seen: lastSeen },
+ { session_id: sid, last_seen: lastSeen, ...(epoch ? { replay_epoch: epoch } : {}) },
REPLAY_REQUEST_TIMEOUT_MS
)
- )
+ })
)
- for (const result of results) {
+ for (const [index, result] of results.entries()) {
if (result.status !== 'fulfilled' || !Array.isArray(result.value?.events)) {
continue
}
- const epoch = (result.value as { epoch?: unknown }).epoch
+ const response = result.value as { epoch?: unknown; replay_epoch?: unknown }
+ const sessionEpoch = response.replay_epoch
+ const epoch = response.epoch
- if (typeof epoch === 'string' && epoch && this.replayEpoch && epoch !== this.replayEpoch) {
+ if (typeof sessionEpoch === 'string' && sessionEpoch) {
+ // Canonical responses also include `epoch`, but it is session-local,
+ // not the legacy process identity. Never reset unrelated cursors.
+ if (this.adoptSessionReplayEpoch(entries[index][0], sessionEpoch)) { continue }
+ } else if (typeof epoch === 'string' && epoch && this.replayEpoch && epoch !== this.replayEpoch) {
// Backend restarted: its seq numbering reset, so our watermarks —
// and this replay window — are meaningless. Drop them and start
// fresh under the new epoch.
this.adoptReplayEpoch(epoch)
continue
- }
-
- if (typeof epoch === 'string' && epoch && !this.replayEpoch) {
+ } else if (typeof epoch === 'string' && epoch && !this.replayEpoch) {
this.replayEpoch = epoch
}
@@ -602,6 +613,9 @@ export class JsonRpcGatewayClient {
const sid = event.session_id
const seq = (event as { seq?: unknown }).seq
+ // Parked frames reach here only after the replay window has been applied.
+ if (sid) { this.adoptSessionReplayEpoch(sid, event.replay_epoch) }
+
if (sid && typeof seq === 'number' && Number.isFinite(seq)) {
const prev = this.lastSeenSeq.get(sid) ?? 0
@@ -626,12 +640,26 @@ export class JsonRpcGatewayClient {
}
if (this.replayEpoch !== null) {
- this.lastSeenSeq.clear()
+ for (const sid of this.lastSeenSeq.keys()) {
+ if (!this.replayEpochBySession.has(sid)) { this.lastSeenSeq.delete(sid) }
+ }
}
this.replayEpoch = epoch
}
+ /** Returns true when an established session numbering has changed. */
+ private adoptSessionReplayEpoch(sid: string, epoch: unknown): boolean {
+ if (typeof epoch !== 'string' || !epoch) { return false }
+ const previous = this.replayEpochBySession.get(sid)
+ const changed = previous !== undefined && previous !== epoch
+
+ if (changed) { this.lastSeenSeq.delete(sid) }
+ this.replayEpochBySession.set(sid, epoch)
+
+ return changed
+ }
+
/** Release frames parked during a replay fetch, seq-gated against dupes. */
private flushReplayHold(): void {
const hold = this.replayHold