Skip to content

The agent that grows with you

fix(shared): reconnect cursors retire when their session is gone, and stay bounded

Tekniumf2c150da5e04
diff --git a/apps/shared/src/json-rpc-gateway-replay.test.ts b/apps/shared/src/json-rpc-gateway-replay.test.ts
index 0740cb2cdbf..ff72608297d 100644
--- a/apps/shared/src/json-rpc-gateway-replay.test.ts
+++ b/apps/shared/src/json-rpc-gateway-replay.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { JsonRpcGatewayClient } from './json-rpc-gateway'
+import { JsonRpcGatewayClient, REPLAY_CURSOR_MAX } from './json-rpc-gateway'
/**
* Minimal EventTarget-based WebSocket stand-in so the seq-tracking and
@@ -833,3 +833,79 @@ describe('JsonRpcGatewayClient per-session replay epochs', () => {
client.close()
})
})
+
+describe('JsonRpcGatewayClient cursor retirement', () => {
+ beforeEach(() => {
+ FakeWebSocket.instances = []
+ sockets = FakeWebSocket.instances as unknown as FakeWebSocket[]
+ })
+
+ it('retires the cursor of a session the owner no longer has, and still replays the open one', async () => {
+ const client = makeClient()
+ const seen: number[] = []
+ client.on('message.delta', event => { if (event.session_id === 'open') { seen.push(event.seq ?? 0) } })
+
+ const reconnect = async () => {
+ client.invalidate('drop')
+ const opening = client.connect('ws://x')
+ const sock = sockets[sockets.length - 1]
+ sock.open()
+ await opening
+
+ return sock
+ }
+
+ 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: 'open', seq: 2, replay_epoch: 'e-open' } })
+ sock.serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'message.delta', session_id: 'deleted', seq: 4, replay_epoch: 'e-del' } })
+
+ sock = await reconnect()
+ await vi.waitFor(() => expect(sock.sent.length).toBe(2))
+
+ for (const raw of sock.sent) {
+ const req = JSON.parse(raw) as ReturnType<FakeWebSocket['lastRequest']>
+
+ sock.serverFrame(req.params.session_id === 'deleted'
+ ? { jsonrpc: '2.0', id: req.id, error: { code: 4001, message: 'not_found', data: { reason: 'not_found' } } }
+ : { jsonrpc: '2.0', id: req.id, result: { events: [{ type: 'message.delta', session_id: 'open', seq: 3, replay_epoch: 'e-open' }], latest_seq: 3, epoch: 'e-open', replay_epoch: 'e-open' } })
+ }
+
+ await vi.waitFor(() => expect(client.getSeqWatermarks()).toEqual({ open: 3 }))
+ expect(seen).toEqual([2, 3])
+ expect([...(client as unknown as { replayEpochBySession: Map<string, string> }).replayEpochBySession.keys()]).toEqual(['open'])
+
+ // The next gap asks only about the session that still exists.
+ sock = await reconnect()
+ await vi.waitFor(() => expect(sock.sent.length).toBe(1))
+ expect(sock.lastRequest().params).toMatchObject({ session_id: 'open', last_seen: 3 })
+ client.close()
+ })
+
+ it('keeps a bounded set of cursors; a retired one announces its gap instead of vanishing', async () => {
+ const client = makeClient()
+ const gaps: string[] = []
+ client.on('session.replay_gap', event => gaps.push(String(event.session_id)))
+ const first = client.connect('ws://x')
+ const sock = sockets[sockets.length - 1]
+ sock.open()
+ await first
+
+ for (let index = 0; index <= REPLAY_CURSOR_MAX; index += 1) {
+ sock.serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'message.delta', session_id: `s${index}`, seq: 1, replay_epoch: `e${index}` } })
+
+ // s0 stays the busiest session: it is never the least recently advanced.
+ if (index % 50 === 0) { sock.serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'message.delta', session_id: 's0', seq: index + 2, replay_epoch: 'e0' } }) }
+ }
+
+ const cursors = client.getSeqWatermarks()
+ expect(Object.keys(cursors)).toHaveLength(REPLAY_CURSOR_MAX)
+ expect(cursors).toHaveProperty('s0')
+ expect(cursors).not.toHaveProperty('s1')
+ expect(gaps).toEqual(['s1'])
+ expect((client as unknown as { replayEpochBySession: Map<string, string> }).replayEpochBySession.size).toBe(REPLAY_CURSOR_MAX)
+ client.close()
+ })
+})
diff --git a/apps/shared/src/json-rpc-gateway.ts b/apps/shared/src/json-rpc-gateway.ts
index be95b34a334..a81557a1577 100644
--- a/apps/shared/src/json-rpc-gateway.ts
+++ b/apps/shared/src/json-rpc-gateway.ts
@@ -122,6 +122,19 @@ interface SessionReplay {
resolve: (valid: boolean) => void
}
+/**
+ * Most reconnect cursors one client keeps (least recently advanced retire first). Owners keep
+ * replay rings for at most 64 sessions (`tui_gateway/event_replay.py::_REPLAY_SESSIONS_MAX`), so a
+ * cursor idle behind this many busier sessions is almost never still servable. Retiring it says
+ * so the way the owner would: a `session.replay_gap`, after which a pane still showing that
+ * session re-snapshots (exactly what `snapshot_required` asks for); nothing is silently lost.
+ */
+export const REPLAY_CURSOR_MAX = 256
+
+/** The canonical owner's typed refusal for a session it no longer has. */
+const replaySessionGone = (error: unknown): boolean =>
+ (error as { data?: { reason?: unknown } } | null)?.data?.reason === 'not_found'
+
export class JsonRpcGatewayClient {
private socket: WebSocketLike | null = null
private state: ConnectionState = 'idle'
@@ -466,7 +479,26 @@ export class JsonRpcGatewayClient {
const prev = this.lastSeenSeq.get(sid) ?? 0
if (seq > prev) {
- this.lastSeenSeq.set(sid, seq)
+ this.advanceCursor(sid, seq)
+ }
+ }
+
+ /** Move a session's cursor to `seq` as its most recent; retire the least recently advanced. */
+ private advanceCursor(sid: string, seq: number): void {
+ this.lastSeenSeq.delete(sid)
+ this.lastSeenSeq.set(sid, seq)
+
+ for (const oldest of this.lastSeenSeq.keys()) {
+ if (this.lastSeenSeq.size <= REPLAY_CURSOR_MAX) { break }
+
+ // A replay in flight still owns its cursor; it is retired by a later advance.
+ if (this.replayHold?.has(oldest)) { continue }
+
+ const latest = this.lastSeenSeq.get(oldest)
+ const epoch = this.replayEpochBySession.get(oldest)
+ this.lastSeenSeq.delete(oldest)
+ this.replayEpochBySession.delete(oldest)
+ this.dispatchEvent({ type: 'session.replay_gap', session_id: oldest, payload: { replay_epoch: epoch, latest_seq: latest } })
}
}
@@ -595,8 +627,15 @@ export class JsonRpcGatewayClient {
this.dispatchIfNewer({ ...event, replayed: true })
}
}
- } catch {
- // Replay is an optimization over lossy-reconnect; never surface errors.
+ } catch (error) {
+ // Replay is an optimization over lossy-reconnect; never surface errors. But the owner's
+ // `not_found` is an answer, not a lost request: the session is gone (deleted, pruned),
+ // nothing will ever replay under that cursor, and keeping it re-asked on every reconnect
+ // while each session ever observed stayed in both maps for the client's lifetime.
+ if (this.replayGeneration === replayGeneration && replaySessionGone(error)) {
+ this.lastSeenSeq.delete(sid)
+ this.replayEpochBySession.delete(sid)
+ }
} finally {
if (this.replayGeneration === replayGeneration) {
this.flushReplayHold(sid, replayGeneration)
@@ -653,7 +692,7 @@ export class JsonRpcGatewayClient {
...[result.latest_seq, ...seqs].filter((seq): seq is number => typeof seq === 'number' && Number.isFinite(seq))
)
- this.lastSeenSeq.set(sid, head)
+ this.advanceCursor(sid, head)
}
/**
@@ -674,7 +713,7 @@ export class JsonRpcGatewayClient {
return
}
- this.lastSeenSeq.set(sid, seq)
+ this.advanceCursor(sid, seq)
}
this.dispatchEvent(event)