Skip to content

The agent that grows with you

feat(chat-plane): trace_id + turn telemetry, transient-delta split, seq-namespace epoch

kshitijk4poor874fab0ce05d
diff --git a/apps/shared/src/json-rpc-gateway-replay.test.ts b/apps/shared/src/json-rpc-gateway-replay.test.ts
index a5875738308..af1b58f20f8 100644
--- a/apps/shared/src/json-rpc-gateway-replay.test.ts
+++ b/apps/shared/src/json-rpc-gateway-replay.test.ts
@@ -41,7 +41,6 @@ class FakeWebSocket extends EventTarget {
lastRequest(): { id: string; method: string; params: Record<string, unknown> } {
const last = this.sent[this.sent.length - 1]
-
return JSON.parse(last ?? '{}')
}
}
@@ -55,7 +54,6 @@ const makeClient = () => {
heartbeatDeadlineMs: 0,
connectTimeoutMs: 1000
})
-
return client
}
@@ -195,17 +193,16 @@ describe('JsonRpcGatewayClient event-seq tracking + replay resume', () => {
client.close()
})
- it('rejects envelope-shaped replay elements (the #94219 server-shape bug)', async () => {
+ it('does not re-dispatch replayed events already applied live during the replay window', async () => {
const client = makeClient()
- const seen: string[] = []
- client.on('message.delta', () => seen.push('delta'))
+ const seen: number[] = []
+ client.on('tool.complete', e => seen.push((e.payload as { n: number }).n))
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: 1 } })
- expect(seen).toEqual(['delta']) // the pre-drop live frame
+ sock.serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'tool.complete', session_id: 's1', seq: 3, payload: { n: 3 } } })
client.invalidate('drop')
const second = client.connect('ws://x')
@@ -216,37 +213,41 @@ describe('JsonRpcGatewayClient event-seq tracking + replay resume', () => {
await vi.waitFor(() => {
expect(sock.lastRequest().method).toBe('session.events.since')
})
+
+ // A live frame lands WHILE the replay RPC is in flight (watermark → 5)…
+ sock.serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'tool.complete', session_id: 's1', seq: 5, payload: { n: 5 } } })
+
+ // …then the replay response arrives containing that same event (seq 5,
+ // emitted after our last_seen=3) plus one genuinely missed event (seq 4).
const req = sock.lastRequest()
- // Pre-fix servers returned FULL JSON-RPC envelopes. The client must not
- // dispatch those blindly — and this documents why the server now sends
- // bare event objects.
sock.serverFrame({
jsonrpc: '2.0',
id: req.id,
result: {
- events: [{ jsonrpc: '2.0', method: 'event', params: { type: 'message.delta', session_id: 's1', seq: 2 } }],
- latest_seq: 2,
+ events: [
+ { type: 'tool.complete', session_id: 's1', seq: 4, payload: { n: 4 } },
+ { type: 'tool.complete', session_id: 's1', seq: 5, payload: { n: 5 } }
+ ],
+ latest_seq: 5,
truncated: false,
- count: 1
+ count: 2
}
})
await Promise.resolve()
- // Envelope-shaped replay elements must add nothing beyond the live frame.
- expect(seen).toEqual(['delta'])
+
+ // seq 5 was already applied live — replay must NOT double-dispatch it.
+ expect(seen).toEqual([3, 5, 4])
client.close()
})
- it('holds live frames racing the replay fetch — no double dispatch, no skipped gap', async () => {
+ it('realigns the watermark when the server reports a seq epoch reset', async () => {
const client = makeClient()
- const seen: number[] = []
- client.on('message.delta', e => seen.push((e as unknown as { seq: number }).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: 2 } })
- expect(seen).toEqual([2]) // pre-drop live frame dispatches normally
+ // Client observed a long-lived session (watermark 97) before the drop.
+ sock.serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'message.delta', session_id: 's1', seq: 97 } })
client.invalidate('drop')
const second = client.connect('ws://x')
@@ -257,80 +258,60 @@ describe('JsonRpcGatewayClient event-seq tracking + replay resume', () => {
await vi.waitFor(() => {
expect(sock.lastRequest().method).toBe('session.events.since')
})
-
- // LIVE frames 5 and 6 arrive while the replay (which carries 3,4,5) is
- // still in flight. They must be parked, not dispatched ahead of the gap.
- sock.serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'message.delta', session_id: 's1', seq: 5 } })
- sock.serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'message.delta', session_id: 's1', seq: 6 } })
- expect(seen).toEqual([2]) // still only the pre-drop frame — 5/6 parked
-
+ // Gateway restarted: its counter is behind us. truncated + latest_seq < last_seen.
const req = sock.lastRequest()
sock.serverFrame({
jsonrpc: '2.0',
id: req.id,
- result: {
- events: [
- { type: 'message.delta', session_id: 's1', seq: 3 },
- { type: 'message.delta', session_id: 's1', seq: 4 },
- { type: 'message.delta', session_id: 's1', seq: 5 }
- ],
- latest_seq: 5,
- truncated: false,
- count: 3
- }
+ result: { events: [], latest_seq: 3, truncated: true, count: 0 }
})
-
- // In-order, exactly once: replayed 3,4,5 then the parked live 6 —
- // the parked duplicate of 5 is seq-gated out.
await vi.waitFor(() => {
- expect(seen).toEqual([2, 3, 4, 5, 6])
+ // Watermark re-adopts the server's epoch so future replays work again.
+ expect(client.getSeqWatermarks().s1).toBe(3)
})
- expect(client.getSeqWatermarks().s1).toBe(6)
+
+ // Next live frame in the new epoch advances normally.
+ sock.serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'message.delta', session_id: 's1', seq: 4 } })
+ expect(client.getSeqWatermarks().s1).toBe(4)
client.close()
})
- it('clears stale watermarks when the backend epoch changes (restart poisoning)', async () => {
+ it('resets seq watermarks when gateway.ready arrives with a NEW epoch', async () => {
const client = makeClient()
+ const p = client.connect('ws://x')
+ sockets[0].open()
+ await p
- const first = client.connect('ws://x')
- let sock = sockets[sockets.length - 1]
- sock.open()
- await first
- // Learn epoch A and a high watermark.
- sock.serverFrame({
- jsonrpc: '2.0',
- method: 'event',
- params: { type: 'gateway.ready', payload: { replay_epoch: 'epoch-A' } }
- })
- sock.serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'message.delta', session_id: 's1', seq: 97 } })
- expect(client.getSeqWatermarks()).toEqual({ s1: 97 })
+ // First connect: epoch A adopted, watermarks accumulate.
+ sockets[0].serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'gateway.ready', payload: { epoch: 'aaaa1111' } } })
+ sockets[0].serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'message.complete', session_id: 's1', seq: 40 } })
+ expect(client.getSeqWatermarks()).toEqual({ s1: 40 })
- // Backend restarts: reconnect, replay under a NEW epoch returns nothing
- // (fresh process, empty ring) — pre-fix the client kept watermark 97 and
- // silently believed it missed nothing, forever.
- client.invalidate('drop')
- const second = client.connect('ws://x')
- sock = sockets[sockets.length - 1]
- sock.open()
- await second
+ // Same epoch re-announced (same process, reconnect): watermarks KEPT.
+ sockets[0].serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'gateway.ready', payload: { epoch: 'aaaa1111' } } })
+ expect(client.getSeqWatermarks()).toEqual({ s1: 40 })
- await vi.waitFor(() => {
- expect(sock.lastRequest().method).toBe('session.events.since')
- })
- const req = sock.lastRequest()
- sock.serverFrame({
- jsonrpc: '2.0',
- id: req.id,
- result: { events: [], latest_seq: 0, truncated: false, count: 0, epoch: 'epoch-B' }
- })
+ // New epoch (gateway restarted, seq namespace reset): stale watermark 40
+ // would be AHEAD of the new counter and suppress replay forever — must
+ // be dropped.
+ sockets[0].serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'gateway.ready', payload: { epoch: 'bbbb2222' } } })
+ expect(client.getSeqWatermarks()).toEqual({})
- await vi.waitFor(() => {
- expect(client.getSeqWatermarks()).toEqual({})
- })
+ // Fresh seqs in the new namespace accumulate normally.
+ sockets[0].serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'message.start', session_id: 's1', seq: 1 } })
+ expect(client.getSeqWatermarks()).toEqual({ s1: 1 })
+ client.close()
+ })
- // New-epoch events build fresh watermarks from scratch.
- sock.serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'message.delta', session_id: 's1', seq: 3 } })
- expect(client.getSeqWatermarks()).toEqual({ s1: 3 })
+ it('ignores gateway.ready without an epoch (legacy backend)', async () => {
+ const client = makeClient()
+ const p = client.connect('ws://x')
+ sockets[0].open()
+ await p
+
+ sockets[0].serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'message.complete', session_id: 's1', seq: 7 } })
+ sockets[0].serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'gateway.ready', payload: { skin: {} } } })
+ expect(client.getSeqWatermarks()).toEqual({ s1: 7 })
client.close()
})
})
diff --git a/apps/shared/src/json-rpc-gateway.ts b/apps/shared/src/json-rpc-gateway.ts
index f061abf323a..35071cb8e98 100644
--- a/apps/shared/src/json-rpc-gateway.ts
+++ b/apps/shared/src/json-rpc-gateway.ts
@@ -111,22 +111,12 @@ export class JsonRpcGatewayClient {
private lastSeenSeq = new Map<string, number>()
/** Set while a post-reconnect replay fetch is in flight (dedup guard). */
private replayInFlight = false
- /**
- * While a replay fetch is in flight, live seq'd frames for the sessions
- * being replayed are parked here instead of dispatching immediately.
- * Without this hold, a live frame racing the replay response is dispatched
- * twice (once live, once when the replay returns the same seq) or, worse,
- * advances the watermark so the gap events the replay carries get skipped.
- */
- private replayHold: Map<string, GatewayEvent[]> | null = null
- /**
- * 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
+ /** Server boot epoch from gateway.ready — seq watermarks are only valid
+ * within one epoch; a change (gateway restart) resets them. */
+ private serverEpoch: string | null = null
+ /** Seqs dispatched LIVE while a replay RPC is in flight, per session —
+ * the replay response overlaps with these and must not re-dispatch them. */
+ private liveSeqsDuringReplay: Map<string, Set<number>> | null = null
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'>> &
@@ -471,25 +461,45 @@ export class JsonRpcGatewayClient {
}
}
- const epoch = (frame.params.payload as { replay_epoch?: unknown } | undefined)?.replay_epoch
+ // Seq-namespace epoch: a new epoch means the gateway restarted and
+ // its per-session seq counters reset. Our stored watermarks are from
+ // the previous namespace — a stale HIGH watermark would make every
+ // replay return empty ("client ahead") and can suppress gap
+ // detection forever. Drop all watermarks so this connection starts
+ // fresh; the app layer re-hydrates state via session.resume anyway.
+ const payload = frame.params.payload as { epoch?: unknown } | undefined
+ const epoch = typeof payload?.epoch === 'string' ? payload.epoch : null
+
+ if (epoch) {
+ if (this.serverEpoch && this.serverEpoch !== epoch) {
+ this.lastSeenSeq.clear()
+ }
- if (typeof epoch === 'string' && epoch) {
- this.adoptReplayEpoch(epoch)
+ this.serverEpoch = epoch
}
}
- const sid = frame.params.session_id
- const seqValue = (frame.params as { seq?: unknown }).seq
+ this.recordSeq(frame.params)
+
+ // While a replay RPC is in flight, remember which seqs arrived live —
+ // the replay response overlaps with them (server returns everything
+ // > our pre-replay watermark) and must not re-dispatch those.
+ if (this.liveSeqsDuringReplay) {
+ const sid = frame.params.session_id
+ const seq = (frame.params as { seq?: unknown }).seq
- if (this.replayHold && sid && typeof seqValue === 'number' && this.replayHold.has(sid)) {
- // Replay in flight for this session: park the frame; flushReplayHold
- // dispatches it after the replayed gap, gated on seq.
- this.replayHold.get(sid)?.push(frame.params)
+ if (sid && typeof seq === 'number') {
+ let set = this.liveSeqsDuringReplay.get(sid)
- return
+ if (!set) {
+ set = new Set()
+ this.liveSeqsDuringReplay.set(sid, set)
+ }
+
+ set.add(seq)
+ }
}
- this.recordSeq(frame.params)
this.dispatchEvent(frame.params)
}
}
@@ -521,8 +531,11 @@ export class JsonRpcGatewayClient {
/**
* After a reconnect, ask the gateway to replay every event newer than our
* per-session watermarks. Replayed frames go through the SAME dispatchEvent
- * path as live frames — dedupe happens naturally because recordSeq ignores
- * non-increasing seqs and downstream stores key on event identity.
+ * path as live frames. Frames that arrived LIVE while the replay RPC was in
+ * flight are tracked and skipped here — the server returns everything past
+ * the pre-replay watermark, so those overlap, and re-dispatching them would
+ * double-append streamed text (message.delta has no identity; it's
+ * append-only downstream).
* Best-effort: failures are swallowed (the next reconnect retries).
*/
private async fetchReplay(): Promise<void> {
@@ -531,118 +544,61 @@ export class JsonRpcGatewayClient {
}
this.replayInFlight = true
- // Park live frames for the sessions we're about to replay so a frame
- // racing the replay response can't dispatch ahead of (or duplicate) the
- // gap events. Sessions without watermarks are unaffected.
- const hold = new Map<string, GatewayEvent[]>()
-
- for (const sid of this.lastSeenSeq.keys()) {
- hold.set(sid, [])
- }
-
- this.replayHold = hold
+ this.liveSeqsDuringReplay = new Map()
try {
const entries = Object.entries(this.getSeqWatermarks())
-
// 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 }> }>(
- 'session.events.since',
- { session_id: sid, last_seen: lastSeen },
- REPLAY_REQUEST_TIMEOUT_MS
- )
- )
- )
+ await Promise.allSettled(
+ entries.map(async ([sid, lastSeen]) => {
+ const result = await this.request<{
+ events?: Array<{ type: string; session_id?: string; seq?: number; payload?: unknown }>
+ latest_seq?: number
+ truncated?: boolean
+ }>('session.events.since', { session_id: sid, last_seen: lastSeen }, REPLAY_REQUEST_TIMEOUT_MS)
+
+ // Seq epoch reset (gateway restart / server-side eviction): the
+ // server's counter is now BEHIND our watermark, so replay could
+ // never deliver again. Re-adopt the server's epoch so future
+ // reconnects work; the gap itself is unrecoverable (truncated).
+ const latest = typeof result?.latest_seq === 'number' ? result.latest_seq : 0
+
+ if (result?.truncated && latest < lastSeen) {
+ if (latest > 0) {
+ this.lastSeenSeq.set(sid, latest)
+ } else {
+ this.lastSeenSeq.delete(sid)
+ }
- for (const result of results) {
- if (result.status !== 'fulfilled' || !Array.isArray(result.value?.events)) {
- continue
- }
+ return
+ }
- const epoch = (result.value as { epoch?: unknown }).epoch
+ if (!Array.isArray(result?.events)) {
+ return
+ }
- 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)
+ const liveSeqs = this.liveSeqsDuringReplay?.get(sid)
- continue
- }
+ for (const event of result.events) {
+ if (!event?.type) {
+ continue
+ }
- if (typeof epoch === 'string' && epoch && !this.replayEpoch) {
- this.replayEpoch = epoch
- }
+ // Skip events already dispatched live during the replay window.
+ if (typeof event.seq === 'number' && liveSeqs?.has(event.seq)) {
+ continue
+ }
- for (const event of result.value.events) {
- if (!event?.type) {
- continue
+ this.recordSeq(event as GatewayEvent)
+ this.dispatchEvent(event as GatewayEvent)
}
-
- this.dispatchIfNewer(event as GatewayEvent)
- }
- }
+ })
+ )
} catch {
// Replay is an optimization over lossy-reconnect; never surface errors.
} finally {
- this.flushReplayHold()
this.replayInFlight = false
- }
- }
-
- /**
- * Dispatch an event only when its seq advances the session watermark.
- * Seq-less events always dispatch (no ordering contract to violate).
- */
- private dispatchIfNewer(event: GatewayEvent): void {
- const sid = event.session_id
- const seq = (event as { seq?: unknown }).seq
-
- if (sid && typeof seq === 'number' && Number.isFinite(seq)) {
- const prev = this.lastSeenSeq.get(sid) ?? 0
-
- if (seq <= prev) {
- return
- }
-
- this.lastSeenSeq.set(sid, seq)
- }
-
- this.dispatchEvent(event)
- }
-
- /**
- * Record the server's replay epoch; on change (backend restart) the old
- * seq watermarks describe a numbering that no longer exists — clear them
- * so the next reconnect doesn't silently believe it missed nothing.
- */
- private adoptReplayEpoch(epoch: string): void {
- if (this.replayEpoch === epoch) {
- return
- }
-
- if (this.replayEpoch !== null) {
- this.lastSeenSeq.clear()
- }
-
- this.replayEpoch = epoch
- }
-
- /** Release frames parked during a replay fetch, seq-gated against dupes. */
- private flushReplayHold(): void {
- const hold = this.replayHold
- this.replayHold = null
-
- if (!hold) {
- return
- }
-
- for (const parked of hold.values()) {
- for (const event of parked) {
- this.dispatchIfNewer(event)
- }
+ this.liveSeqsDuringReplay = null
}
}
diff --git a/tests/test_tui_gateway_event_replay.py b/tests/test_tui_gateway_event_replay.py
index 5e431c29ddf..f0b434dd816 100644
--- a/tests/test_tui_gateway_event_replay.py
+++ b/tests/test_tui_gateway_event_replay.py
@@ -6,10 +6,11 @@ import pytest
from tui_gateway import event_replay
from tui_gateway.event_replay import (
- latest_seq,
- reset_replay_state,
events_since,
+ latest_seq,
replay_stats,
+ reset_replay_state,
+ stamp_event,
)
@@ -20,7 +21,9 @@ def _clean():
reset_replay_state()
-def _frame(sid, etype="message.delta"):
+def _frame(sid, etype="status.update"):
+ # status.update is a DURABLE event type (buffered for replay).
+ # message.delta / thinking.delta are transient — stamped, never buffered.
return {
"jsonrpc": "2.0",
"method": "event",
@@ -33,9 +36,9 @@ def test_stamp_adds_monotonic_seq_per_session():
f2 = _frame("s1")
other = _frame("s2")
- event_replay._stamp_event(f1)
- event_replay._stamp_event(other)
- event_replay._stamp_event(f2)
+ stamp_event(f1)
+ stamp_event(other)
+ stamp_event(f2)
assert f1["params"]["seq"] == 1
assert f2["params"]["seq"] == 2 # per-session counter, unaffected by s2
@@ -46,70 +49,164 @@ def test_stamp_ignores_non_event_and_sessionless_frames():
rpc = {"jsonrpc": "2.0", "id": 1, "result": {}}
no_sid = {"jsonrpc": "2.0", "method": "event", "params": {"type": "skin.changed"}}
- event_replay._stamp_event(rpc)
- event_replay._stamp_event(no_sid)
+ stamp_event(rpc)
+ stamp_event(no_sid)
assert "seq" not in rpc
assert "seq" not in no_sid["params"]
assert replay_stats()["events"] == 0
-def test_events_since_returns_only_newer_frames_in_order():
+def test_events_since_returns_bare_params_only_newer_in_order():
frames = [_frame("s1") for _ in range(5)]
for f in frames:
- event_replay._stamp_event(f)
+ stamp_event(f)
- got = events_since("s1", 3)
+ got, latest, truncated = events_since("s1", 3)
assert [e["seq"] for e in got] == [4, 5]
- assert events_since("s1", 0) == [f["params"] for f in frames]
- assert events_since("s1", 99) == []
+ # Replay returns the bare event params (what live dispatch sees), NOT the
+ # full JSON-RPC frame envelope — the client reads event.type at top level.
+ assert all("jsonrpc" not in e and e["type"] == "status.update" for e in got)
+ assert latest == 5
+ assert truncated is False
+
+ all_events, _, _ = events_since("s1", 0)
+ assert all_events == [f["params"] for f in frames]
+ assert events_since("s1", 5) == ([], 5, False)
assert latest_seq("s1") == 5
-def test_events_since_returns_client_dispatchable_event_objects():
- """Cross-language contract: the client's replay loop dispatches an element
- only when it has a TOP-LEVEL ``type`` (json-rpc-gateway.ts fetchReplay:
- ``if (!event?.type) continue``). Returning full JSON-RPC envelopes here
- makes every replayed event silently droppable — the original #94219 bug.
- """
- event_replay._stamp_event(_frame("s1"))
- (event,) = events_since("s1", 0)
+def test_unknown_session_returns_empty():
+ assert events_since("nope", 0) == ([], 0, False)
+ assert latest_seq("nope") == 0
- # Bare event object, not an envelope.
- assert event["type"] == "message.delta"
- assert event["session_id"] == "s1"
- assert event["seq"] == 1
- assert "jsonrpc" not in event
- assert "method" not in event
- assert "params" not in event
+def test_transient_deltas_stamped_but_not_buffered():
+ """Streaming token deltas get seqs (live wire ordering) but never enter
+ the replay ring — one streaming turn must not evict durable control
+ events (message.start/complete, session.info) from replay coverage."""
+ start = _frame("s1", "message.start")
+ deltas = [_frame("s1", "message.delta") for _ in range(100)]
+ thinking = [_frame("s1", "thinking.delta") for _ in range(50)]
+ complete = _frame("s1", "message.complete")
-def test_unknown_session_returns_empty():
- assert events_since("nope", 0) == []
- assert latest_seq("nope") == 0
+ stamp_event(start)
+ for f in deltas:
+ stamp_event(f)
+ for f in thinking:
+ stamp_event(f)
+ stamp_event(complete)
+ # All frames got seqs, in one monotonic namespace.
+ assert start["params"]["seq"] == 1
+ assert complete["params"]["seq"] == 152
+ assert deltas[0]["params"]["seq"] == 2
-def test_ring_buffer_is_bounded():
- for i in range(event_replay._REPLAY_BUFFER_MAX + 50):
- event_replay._stamp_event(_frame("s1"))
+ # But only the 2 durable frames are buffered.
+ assert replay_stats()["events"] == 2
+
+ # Replay from 0 returns just the durable frames — and the delta-only
+ # gaps between them are NOT truncation (nothing recoverable was lost).
+ got, latest, truncated = events_since("s1", 0)
+ assert [e["type"] for e in got] == ["message.start", "message.complete"]
+ assert latest == 152
+ assert truncated is False
+
+ # A client that saw the whole live stream is fully covered too.
+ assert events_since("s1", 152) == ([], 152, False)
+
+
+def test_ring_buffer_is_bounded_and_reports_truncation():
+ for _ in range(event_replay._REPLAY_BUFFER_MAX + 50):
+ stamp_event(_frame("s1"))
stats = replay_stats()
assert stats["events"] == event_replay._REPLAY_BUFFER_MAX
- # Oldest evicted: last_seen=0 must report truncation via the RPC contract.
- buf = event_replay._replay_buffers["s1"]
- assert buf[0][0] > 1
+ # Client that saw nothing (last_seen=0) has a gap older than the ring —
+ # durable frames were evicted, so the gap is real truncation.
+ got, latest, truncated = events_since("s1", 0)
+ assert truncated is True
+ assert latest == event_replay._REPLAY_BUFFER_MAX + 50
+ assert len(got) == event_replay._REPLAY_BUFFER_MAX
+
+ # Client aligned with the buffer start: fully covered, not truncated.
+ oldest = got[0]["seq"]
+ covered, _, covered_truncated = events_since("s1", oldest - 1)
+ assert covered_truncated is False
+ assert len(covered) == event_replay._REPLAY_BUFFER_MAX
+
+
+def test_eviction_of_durable_frames_is_precise():
+ """Truncation is keyed to the highest EVICTED durable seq, not the buffer
+ floor: a client whose last_seen covers everything evicted is not
+ truncated even when younger frames were dropped for other clients."""
+ overflow = 50
+ for _ in range(event_replay._REPLAY_BUFFER_MAX + overflow):
+ stamp_event(_frame("s1"))
+
+ # The first `overflow` durable frames (seq 1..50) were evicted.
+ # A client at last_seen=overflow saw all of them — not truncated.
+ _, _, at_boundary = events_since("s1", overflow)
+ assert at_boundary is False
+
+ # A client one behind the boundary lost seq=overflow — truncated.
+ _, _, behind = events_since("s1", overflow - 1)
+ assert behind is True
-def test_session_count_bounded_with_fifo_eviction():
+
+def test_epoch_reset_reports_truncated():
+ """Client watermark AHEAD of the server (gateway restart) must be flagged.
+
+ Without this, a restarted server returns [] / truncated=False and the
+ client's stuck watermark silently kills replay forever.
+ """
+ for _ in range(3):
+ stamp_event(_frame("s1"))
+
+ got, latest, truncated = events_since("s1", 97)
+ assert got == []
+ assert latest == 3
+ assert truncated is True
+
+ # Session the server has never seen but the client has a watermark for.
+ assert events_since("gone", 42) == ([], 0, True)
+
+
+def test_epoch_constant_is_stable_and_shaped():
+ """EPOCH identifies this process's seq namespace: 8 hex chars, constant
+ for the process lifetime (clients compare it across reconnects)."""
+ assert isinstance(event_replay.EPOCH, str)
+ assert len(event_replay.EPOCH) == 8
+ int(event_replay.EPOCH, 16) # hex
+ assert event_replay.EPOCH == event_replay.EPOCH # stable reference
+
+
+def test_session_count_bounded_with_lru_eviction():
for i in range(event_replay._REPLAY_SESSIONS_MAX + 10):
- event_replay._stamp_event(_frame(f"s{i}"))
+ stamp_event(_frame(f"s{i}"))
stats = replay_stats()
assert stats["sessions"] == event_replay._REPLAY_SESSIONS_MAX
- assert events_since("s0", 0) == [] # oldest session fully evicted
+ assert events_since("s0", 0)[0] == [] # oldest session fully evicted
assert latest_seq(f"s{event_replay._REPLAY_SESSIONS_MAX + 9}") == 1
+def test_active_session_survives_eviction_lru():
+ """Eviction is least-recently-ACTIVE, not first-created: a session that
+ keeps streaming must outlive idle sessions created after it."""
+ stamp_event(_frame("active"))
+ for i in range(event_replay._REPLAY_SESSIONS_MAX - 1):
+ stamp_event(_frame(f"idle{i}"))
+
+ # "active" is now the oldest by creation. Touch it, then overflow.
+ stamp_event(_frame("active"))
+ stamp_event(_frame("newcomer"))
+
+ assert latest_seq("active") == 2 # survived — it was most recently active
+ assert events_since("idle0", 0) == ([], 0, False) # idle0 evicted instead
+
+
def test_concurrent_stamping_never_drops_or_duplicates_seq():
errors = []
@@ -118,7 +215,7 @@ def test_concurrent_stamping_never_drops_or_duplicates_seq():
seen = set()
for _ in range(200):
f = _frame(sid)
- event_replay._stamp_event(f)
+ stamp_event(f)
seq = f["params"]["seq"]
assert seq not in seen
seen.add(seq)
@@ -133,22 +230,3 @@ def test_concurrent_stamping_never_drops_or_duplicates_seq():
assert not errors
assert replay_stats()["events"] == 8 * 200
-
-
-def test_truncation_detection_semantics():
- """The RPC handler's truncated flag: gap between last_seen and buffer start."""
- # Overflow the ring so the oldest events are genuinely evicted.
- for _ in range(event_replay._REPLAY_BUFFER_MAX + 10):
- event_replay._stamp_event(_frame("s1"))
-
- with event_replay._replay_lock:
- oldest = event_replay._replay_buffers["s1"][0][0]
-
- assert oldest > 1 # eviction happened
-
- # Client saw everything up to just before the buffer → NOT truncated.
- assert not event_replay.is_truncated("s1", oldest - 1)
- # Client saw seq 5, buffer starts later → truncated.
- assert event_replay.is_truncated("s1", 5)
- # Unknown session: nothing evicted, nothing truncated.
- assert not event_replay.is_truncated("nope", 0)
diff --git a/tui_gateway/event_replay.py b/tui_gateway/event_replay.py
index 0ec4e2a86b4..3b9e2c0d90c 100644
--- a/tui_gateway/event_replay.py
+++ b/tui_gateway/event_replay.py
@@ -9,11 +9,12 @@ replays everything newer from the buffer, then live events resume seamlessly.
Design constraints honored:
- stdio TUI path unaffected: frames gain a ``seq`` field only on event frames;
Ink ignores unknown params keys.
-- Thread safety: a single module lock guards counters + buffers; write_json
- already serializes per-transport writes, so stamping under the lock cannot
- reorder frames relative to each other.
+- Thread safety: a single module lock guards counters + buffers, so buffer
+ order always matches seq order. Wire order is enforced separately by the
+ per-transport write path; two racing writers can briefly invert seq order
+ on the wire, which the client tolerates (watermarks are monotonic-max).
- Memory bound: _REPLAY_BUFFER_MAX events / _REPLAY_SESSIONS_MAX sessions,
- oldest session evicted FIFO.
+ least-recently-active session evicted first.
"""
from __future__ import annotations
@@ -22,34 +23,47 @@ import threading
import uuid
from collections import OrderedDict, deque
-# Process identity for the replay contract. Seq counters live in-process, so
-# a gateway restart silently resets them to 1 while clients still hold high
-# watermarks — events_since(sid, 97) then returns [] with truncated=False and
-# the client believes it missed nothing (and its stale watermark makes every
-# future replay empty too). The epoch lets clients detect the restart and
-# reset their watermarks.
-_REPLAY_EPOCH = uuid.uuid4().hex
-
-# Replay ring per session. A long turn emits ~hundreds of token events; this
-# covers several minutes of streaming plus all control events.
+# Replay ring per session. Sized for control events only — streaming token
+# deltas are transient (stamped but not buffered, see _TRANSIENT_EVENT_TYPES),
+# so 512 slots cover hours of durable events instead of ~one streaming burst.
_REPLAY_BUFFER_MAX = 512
# Distinct sessions remembered. Desktop users rarely exceed a dozen live chats.
_REPLAY_SESSIONS_MAX = 64
+# Transient event types: delivered live but never buffered for replay.
+# One streaming turn emits hundreds of per-token delta frames; buffering them
+# would evict every durable control event from the ring (OpenHands makes the
+# same split with StreamingDeltaEvent — published, never persisted). A
+# reconnecting client recovers partial streamed text from the inflight
+# snapshot in ``session.resume``, not from delta replay. These frames still
+# get seqs (so ordering holds live), but replay skips them and gap detection
+# ignores them via the durable-seq watermark below.
+_TRANSIENT_EVENT_TYPES = frozenset({
+ "message.delta",
+ "thinking.delta",
+})
+
+# Server boot epoch: lets a client detect that the seq namespace was reset
+# (gateway restart) — a stale high watermark from the previous process must
+# not suppress live events forever (Goose clamps; we reset via epoch).
+EPOCH = uuid.uuid4().hex[:8]
+
_replay_lock = threading.Lock()
-# sid -> deque of (seq, event_object) where event_object is the frame's
-# ``params`` dict (bare event: type/session_id/seq/payload) — the exact shape
-# the client's dispatch path consumes.
+# sid -> deque of (seq, params_dict). params is the same dict written to the
+# wire and already carries its stamped "seq" key — the replay RPC returns
+# these bare event objects, matching what the client's live dispatch sees.
+# Manual eviction (no maxlen): we must record the seq of every DURABLE frame
+# we drop, so gap detection can distinguish "durable data lost" from "the
+# missing seqs were transient deltas that were never replayable anyway".
_replay_buffers: "OrderedDict[str, deque]" = OrderedDict()
_replay_next_seq: dict[str, int] = {}
+# sid -> highest DURABLE seq evicted from the ring (0 = nothing evicted).
+# Precise truncation signal: durable data is lost for a client at last_seen
+# iff an evicted durable frame had seq > last_seen.
+_replay_evicted_seq: dict[str, int] = {}
-def replay_epoch() -> str:
- """Opaque token identifying this server process's seq numbering."""
- return _REPLAY_EPOCH
-
-
-def _stamp_event(obj: dict) -> None:
+def stamp_event(obj: dict) -> None:
"""Stamp one outgoing event frame (mutates obj in place) and record it."""
if obj.get("method") != "event":
return
@@ -61,45 +75,59 @@ def _stamp_event(obj: dict) -> None:
# Session-less global events (skin.changed etc.) are re-fetchable via
# their own RPCs; no replay contract for them.
return
+ transient = params.get("type") in _TRANSIENT_EVENT_TYPES
with _replay_lock:
seq = _replay_next_seq.get(sid, 0) + 1
_replay_next_seq[sid] = seq
params["seq"] = seq
+ if transient:
+ # Live-only: seq stamped for wire ordering, never buffered.
+ return
buf = _replay_buffers.get(sid)
if buf is None:
- buf = deque(maxlen=_REPLAY_BUFFER_MAX)
+ buf = deque()
_replay_buffers[sid] = buf
while len(_replay_buffers) > _REPLAY_SESSIONS_MAX:
_oldest_sid, _oldest_buf = _replay_buffers.popitem(last=False)
_replay_next_seq.pop(_oldest_sid, None)
+ _replay_evicted_seq.pop(_oldest_sid, None)
+ else:
+ # LRU, not insertion-FIFO: an actively streaming session must not
+ # be evicted just because it was created before idle newer ones.
+ _replay_buffers.move_to_end(sid)
buf.append((seq, params))
-
-
-def events_since(sid: str, last_seen: int) -> list[dict]:
- """Return recorded EVENT OBJECTS with seq > last_seen for *sid*, in order.
-
- Shape contract: each element is the frame's ``params`` dict — a bare event
- object with top-level ``type`` / ``session_id`` / ``seq`` — because that is
- exactly what the client's dispatch path consumes. Returning the full
- JSON-RPC envelope here would make every replayed event fail the client's
- ``event.type`` gate and be silently dropped.
+ while len(buf) > _REPLAY_BUFFER_MAX:
+ dropped_seq, _dropped = buf.popleft()
+ _replay_evicted_seq[sid] = dropped_seq
+
+
+def events_since(sid: str, last_seen: int) -> tuple[list[dict], int, bool]:
+ """Replay contract for one session, computed atomically.
+
+ Returns ``(events, latest_seq, truncated)``:
+
+ - ``events``: bare event params dicts (``type``/``session_id``/``seq``/
+ ``payload``) with ``seq > last_seen``, in seq order. Transient delta
+ frames are never included (they were never buffered).
+ - ``latest_seq``: current highest stamped seq (0 when unknown).
+ - ``truncated``: durable data the client has not seen is unrecoverable —
+ either a DURABLE frame with ``seq > last_seen`` was evicted from the
+ ring, or ``last_seen`` is AHEAD of ``latest_seq`` (seq namespace reset
+ after a gateway restart / session eviction — the client should compare
+ ``EPOCH`` and do a full state reload). Gaps consisting only of
+ transient delta seqs are NOT truncation: those frames were never
+ replayable and the resume snapshot covers their content.
"""
+ sid = sid or ""
with _replay_lock:
- buf = _replay_buffers.get(sid or "")
- if not buf:
- return []
- return [event for seq, event in buf if seq > last_seen]
-
-
-def is_truncated(sid: str, last_seen: int) -> bool:
- """True when events between *last_seen* and the ring's oldest retained
- seq were evicted — the client must refetch history instead of trusting
- the replay to be gap-free."""
- with _replay_lock:
- buf = _replay_buffers.get(sid or "")
+ latest = _replay_next_seq.get(sid, 0)
+ evicted = _replay_evicted_seq.get(sid, 0)
+ buf = _replay_buffers.get(sid)
if not buf:
- return False
- return last_seen + 1 < buf[0][0]
+ return [], latest, last_seen > latest or evicted > last_seen
+ frames = [params for seq, params in buf if seq > last_seen]
+ truncated = last_seen > latest or evicted > last_seen
+ return frames, latest, truncated
def latest_seq(sid: str) -> int:
@@ -113,13 +141,42 @@ def reset_replay_state() -> None:
with _replay_lock:
_replay_buffers.clear()
_replay_next_seq.clear()
+ _replay_evicted_seq.clear()
+
+
+def replay_epoch() -> str:
+ """This process's seq-namespace epoch (see :data:`EPOCH`)."""
+ return EPOCH
def replay_stats() -> dict:
- """Telemetry: buffer occupancy for the ops/debug surface."""
+ """Telemetry: buffer occupancy + per-turn timing for the ops/debug surface."""
with _replay_lock:
- return {
+ stats = {
"sessions": len(_replay_buffers),
"events": sum(len(b) for b in _replay_buffers.values()),
"max_per_session": _REPLAY_BUFFER_MAX,
+ "max_sessions": _REPLAY_SESSIONS_MAX,
}
+ # Per-turn timing from the live session table (not under the replay lock —
+ # the session table has its own lock).
+ try:
+ import time as _time
+
+ from tui_gateway.server import _sessions, _sessions_lock
+
+ with _sessions_lock:
+ active_turns = []
+ for sid, session in _sessions.items():
+ inflight = session.get("inflight_turn")
+ if isinstance(inflight, dict) and inflight.get("started_at"):
+ active_turns.append({
+ "session_id": sid,
+ "trace_id": inflight.get("trace_id"),
+ "elapsed_s": round(_time.time() - float(inflight["started_at"]), 2),
+ "streaming": inflight.get("streaming", False),
+ })
+ stats["active_turns"] = active_turns
+ except Exception:
+ stats["active_turns"] = []
+ return stats
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index b82c4df7175..f9162a5d9f1 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -3654,17 +3654,18 @@ def _(rid, params: dict) -> dict:
return _err(rid, -32602, "invalid params: last_seen must be an integer")
from tui_gateway import event_replay
- frames = event_replay.events_since(sid, last_seen)
+ frames, latest, truncated = event_replay.events_since(sid, last_seen)
return _ok(rid, {
"events": frames,
- "latest_seq": event_replay.latest_seq(sid),
- "truncated": event_replay.is_truncated(sid, last_seen),
+ "latest_seq": latest,
+ "truncated": truncated,
"count": len(frames),
- # Restart detection: seq counters are in-process, so after a gateway
+ # Server boot epoch: seq counters are in-process, so after a gateway
# restart a client's old high watermark would silently match nothing.
# Clients compare this against the epoch they learned at gateway.ready
- # and reset watermarks on mismatch.
- "epoch": event_replay.replay_epoch(),
+ # and reset watermarks on mismatch, doing a full state reload instead
+ # of trusting replay.
+ "epoch": event_replay.EPOCH,
})
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 408cde2b887..9a14db10b48 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -39,7 +39,7 @@ from agent.compaction_display import project_compaction_message_for_display
from agent.skill_commands import describe_skill_invocation
from agent.conversation_loop import INTERRUPT_WAITING_FOR_MODEL_PREFIX
from tui_gateway import git_probe
-from tui_gateway.event_replay import _stamp_event
+from tui_gateway.event_replay import stamp_event as _stamp_event
from tui_gateway.turn_marker import (
clear_turn_marker,
read_turn_marker,
@@ -2021,6 +2021,17 @@ def _event_frame(event: str, sid: str, payload: dict | None = None) -> dict:
params: dict = {"type": event, "session_id": sid}
if payload is not None:
params["payload"] = payload
+ # Stamp the current turn's trace_id onto every event frame so the client
+ # can correlate the full turn lifecycle from one identifier. Looks up
+ # the inflight turn for this session; events outside a turn (session.info
+ # on idle, skin.changed) have no trace_id.
+ session = _sessions.get(sid)
+ if session is not None:
+ inflight = session.get("inflight_turn")
+ if isinstance(inflight, dict):
+ trace_id = inflight.get("trace_id")
+ if trace_id:
+ params["trace_id"] = trace_id
return {"jsonrpc": "2.0", "method": "event", "params": params}
@@ -8419,6 +8430,11 @@ def _start_inflight_turn(session: dict, text: Any) -> None:
"streaming": True,
"updated_at": now,
"user": _inflight_text(text),
+ # Per-turn trace ID: stamped on every event frame emitted during this
+ # turn so a client can correlate the full lifecycle (dispatch → first
+ # token → tool calls → complete) from a single identifier. Cleared
+ # when the turn ends.
+ "trace_id": uuid.uuid4().hex[:12],
}
diff --git a/tui_gateway/ws.py b/tui_gateway/ws.py
index ce0cbc70215..dce70f57ba0 100644
--- a/tui_gateway/ws.py
+++ b/tui_gateway/ws.py
@@ -33,7 +33,6 @@ import time
from typing import Any
from tui_gateway import server
-from tui_gateway.event_replay import replay_epoch
_log = logging.getLogger(__name__)
@@ -366,6 +365,7 @@ async def handle_ws(
# (#60800). The skin payload is small (a dict of strings/arrays),
# so the to_thread overhead is negligible.
skin_payload = await asyncio.to_thread(server.resolve_skin)
+ from tui_gateway.event_replay import EPOCH as _replay_epoch
ready_ok = await transport.write_async(
{
"jsonrpc": "2.0",
@@ -379,10 +379,12 @@ async def handle_ws(
"skin": skin_payload,
"change_events": True,
"heartbeat": True,
- # Replay-contract process identity: lets reconnecting
- # clients detect a backend restart and reset their
- # per-session seq watermarks (see event_replay).
- "replay_epoch": replay_epoch(),
+ # Seq-namespace epoch: changes on every gateway boot.
+ # A client whose stored epoch differs must reset its
+ # per-session seq watermarks and reload state instead
+ # of trusting replay (stale high watermarks from the
+ # previous process would suppress live events).
+ "epoch": _replay_epoch,
},
},
}