Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(agent-proxy): resync frame for readers with a trimmed cursor (#101104)

Alessandro Pogliaghi9267e34b6181
diff --git a/services/agent-proxy/README.md b/services/agent-proxy/README.md
index aaab12e617a0..3f6e4b0f3692 100644
--- a/services/agent-proxy/README.md
+++ b/services/agent-proxy/README.md
@@ -27,7 +27,8 @@ access logs, which would expose the run-scoped JWT. The browser uses
fetch-event-source (which sets headers), not native `EventSource`.
Resume is via the `Last-Event-ID` header; `?start=latest` tails from the
-newest available entry.
+newest available entry. `?resync=1` declares that the client can rebuild from
+the durable run log when its cursor has been trimmed out of Redis.
## Environment variables
@@ -175,7 +176,20 @@ During the cutover window both services read and write the same streams safely.
To roll back: unset `TASKS_AGENT_PROXY_PUBLIC_URL` and `TASKS_AGENT_PROXY_INGEST_URL`
on Django. No data migration is needed because the stream format is identical.
-S3 hydration on resume gap is explicitly out of scope for this version — when a
-client's `Last-Event-ID` has been trimmed from Redis, the service emits a metric
-and continues reading from the oldest available entry, matching the current
-Python behavior exactly.
+When a client's `Last-Event-ID` is no longer in Redis (trimmed, or the stream of a
+finished run expired), the service emits a metric. A client that opened with
+`?resync=1` receives an `event: end` frame with `{"type":"resync","reason":"trimmed"}`
+and the connection closes. The same frame ends a resync-capable connection whose
+cursor is trimmed while the reader lags, in one pause or in many short ones, and a
+failed trim check closes such a
+connection with a stream error instead of reading from the stale cursor. To recover,
+the client drops its cursor and reopens without `Last-Event-ID` (a retained header
+takes precedence over `start` and repeats the frame). Reopen cursorless, which replays
+the whole surviving window, rather than at `?start=latest`: the run log trails the live
+stream and holds a streaming message only once the turn coalesces it into one entry, so
+a reader that skips the surviving window can miss the message it was receiving. The
+client buffers live frames, reads the durable run log and deduplicates the replay
+against it by agent event id, covering both the `first_event_id..event_id` range of a
+coalesced entry and every id in its `covered_event_ids`.
+Any other client keeps reading from the oldest available entry, matching the Python
+behavior. Server-side S3 hydration on a resume gap is out of scope for this version.
diff --git a/services/agent-proxy/docs/DURABLE_STREAMING.md b/services/agent-proxy/docs/DURABLE_STREAMING.md
index f7a23c29fd62..6a1384df6272 100644
--- a/services/agent-proxy/docs/DURABLE_STREAMING.md
+++ b/services/agent-proxy/docs/DURABLE_STREAMING.md
@@ -49,17 +49,25 @@ Reference concepts:
Ranked by how much it matters for the current use case (watching a live agent run).
-1. **Gap awareness (the real hole).** The server **detects** when a reader's resume point
- has been trimmed out of the window (`resumePointTrimmed` / `detectResumeGap` in
- `src/lib/redis-stream.ts`, surfaced as the `stream:resume_gap` metric) but it does
- **not tell the reader**. It silently continues from the oldest surviving event. So a
- client that reconnects after a long gap, or watches a long run, can silently miss a
- span of events and never know. Durable streaming's whole point is that the reader
- either receives every event or is explicitly told it lost some. This is already a known
- deferral: S3 hydration on resume gap is out of scope for now (see the `ResumeGap`
- comment in `src/lib/types.ts` and `DESIGN.md`). Closing it means either a
- client-visible "you missed events from A to B" signal, a backfill from durable storage,
- or both.
+1. **Gap awareness.** The server detects when a reader's resume point has been trimmed
+ out of the window (`resumePointTrimmed` / `detectResumeGap` in
+ `src/lib/redis-stream.ts`, surfaced as the `stream:resume_gap` metric), on attach and
+ again once a reader has waited `STREAM_CURSOR_RECHECK_STALL_MS` in total since
+ the last check, whether in one pause or in many short ones. A reader that
+ opened with `?resync=1` is told: the connection closes with an `end` frame carrying
+ `{"type":"resync","reason":"trimmed"}` (also when the stream of a finished run has
+ expired), and a failed trim check closes it with a stream error. The reader drops
+ its cursor and reopens without `Last-Event-ID`, cursorless so the surviving window
+ replays: the run log trails the live stream and holds a streaming message only once
+ the turn coalesces it into one entry, so a reader that reopens at `?start=latest`
+ can miss the message it was receiving. It buffers live frames, reads the durable run
+ log and deduplicates the replay against it by agent event id, covering both the
+ `first_event_id..event_id` range of a coalesced entry and every id in its
+ `covered_event_ids`. A reader without the
+ flag still silently continues from the oldest surviving event, so it can miss a span
+ of events and never know. Server-side backfill from durable storage (S3 hydration)
+ stays out of scope (see the `ResumeGap` comment in `src/lib/types.ts` and
+ `DESIGN.md`).
2. **Bounded retention.** "Durable" here means a sliding 6h TTL while the run is live,
a 30 minute drain window after the terminal sentinel, and a 5,000 event `MAXLEN`
(`STREAM_TTL_SECONDS`, `STREAM_COMPLETED_TTL_SECONDS`, `STREAM_MAX_LENGTH` in
@@ -83,23 +91,23 @@ Ranked by how much it matters for the current use case (watching a live agent ru
## Summary
-| Concept | Status |
-| -------------------------------------------- | ----------------------------------------- |
-| Resume from last position | Have |
-| Stable ordered positions | Have |
-| Catch-up then live tail | Have |
-| No-skip / no-duplicate within window | Have |
-| Idempotent, ordered append (single producer) | Have |
-| Completion consistency | Have |
-| Durable, observable EOF | Have |
-| Keepalive, reconnect robustness | Have |
-| Backpressure to slow readers | Have |
-| Multi-reader fan-out | Have |
-| Gap awareness on trimmed resume | **Missing** (detected, not signalled) |
-| Retention beyond 6h live / 30m terminal | **Partial** (bounded, then dropped) |
-| Caught-up-to-tail signal | Missing |
-| Producer fencing across writers | Partial (single-producer by construction) |
-| Forking / subscriptions / consumer groups | Missing (not needed) |
+| Concept | Status |
+| -------------------------------------------- | ---------------------------------------------- |
+| Resume from last position | Have |
+| Stable ordered positions | Have |
+| Catch-up then live tail | Have |
+| No-skip / no-duplicate within window | Have |
+| Idempotent, ordered append (single producer) | Have |
+| Completion consistency | Have |
+| Durable, observable EOF | Have |
+| Keepalive, reconnect robustness | Have |
+| Backpressure to slow readers | Have |
+| Multi-reader fan-out | Have |
+| Gap awareness on trimmed resume | **Partial** (signalled to `?resync=1` readers) |
+| Retention beyond 6h live / 30m terminal | **Partial** (bounded, then dropped) |
+| Caught-up-to-tail signal | Missing |
+| Producer fencing across writers | Partial (single-producer by construction) |
+| Forking / subscriptions / consumer groups | Missing (not needed) |
We have resumability, ordering, idempotent append and durable closure, which is the meat
of durable streaming. The two gaps that actually matter are **gap awareness** (the silent
diff --git a/services/agent-proxy/src/hono/app.ts b/services/agent-proxy/src/hono/app.ts
index b9fbf5a0bf4b..9c5ff00aa3c8 100644
--- a/services/agent-proxy/src/hono/app.ts
+++ b/services/agent-proxy/src/hono/app.ts
@@ -96,6 +96,7 @@ export function createApp(redis: Redis, config: Config, publicKeys: CryptoKey[])
const lastEventId = c.req.header('Last-Event-ID') ?? c.req.header('last-event-id') ?? null
const startLatest = c.req.query('start') === 'latest'
+ const resyncCapable = c.req.query('resync') === '1'
const streamKey = getStreamKey(claims.runId)
// Reserve a concurrency slot before any Redis work; each accepted stream holds a
@@ -109,7 +110,7 @@ export function createApp(redis: Redis, config: Config, publicKeys: CryptoKey[])
return c.json({ error: 'Too many concurrent stream connections' }, 503)
}
- logger.info('stream:open', { run, lastEventId: lastEventId ?? undefined, startLatest })
+ logger.info('stream:open', { run, lastEventId: lastEventId ?? undefined, startLatest, resyncCapable })
// The abort signal from the raw Request fires when the client disconnects.
const signal = c.req.raw.signal
@@ -124,6 +125,7 @@ export function createApp(redis: Redis, config: Config, publicKeys: CryptoKey[])
startLatest,
presenceGated: claims.presenceGated,
isTerminal: claims.isTerminal,
+ resyncCapable,
})
// Race each generator chunk against the client-disconnect abort signal.
diff --git a/services/agent-proxy/src/hono/sse-handler.ts b/services/agent-proxy/src/hono/sse-handler.ts
index 2609afbcd9a5..cca38bfb253d 100644
--- a/services/agent-proxy/src/hono/sse-handler.ts
+++ b/services/agent-proxy/src/hono/sse-handler.ts
@@ -16,6 +16,7 @@
// Keepalive — eventName='keepalive', data={"type":"keepalive"}
// Terminal — eventName='stream-end', data={"status":"complete"}
// Rotation — eventName='end', data={"type":"rotated"}
+// Resync — eventName='end', data={"type":"resync","reason":"trimmed"}
// Stream error — eventName='error', data={"error":"<msg>"}
// Stream unavailable — eventName='error', data={"error":"Stream not available"}
@@ -29,8 +30,10 @@ import {
SSE_EVENT_KEEPALIVE,
SSE_EVENT_STREAM_END,
SSE_PAYLOAD_KEEPALIVE,
+ SSE_PAYLOAD_RESYNC,
SSE_PAYLOAD_ROTATED,
SSE_PAYLOAD_STREAM_END,
+ STREAM_CURSOR_RECHECK_STALL_MS,
WAIT_DELAY_INCREMENT_MS,
WAIT_INITIAL_DELAY_MS,
WAIT_MAX_DELAY_MS,
@@ -41,7 +44,7 @@ import {
import { logger } from '../lib/logging.js'
import { TaskRunRedisStream } from '../lib/redis-stream.js'
import type { StreamConnectionOutcome } from '../lib/types.js'
-import { TaskRunStreamError } from '../lib/types.js'
+import { TaskRunStreamCursorTrimmedError, TaskRunStreamError } from '../lib/types.js'
import {
observeStreamConnectionClosed,
observeStreamConnectionOpened,
@@ -87,11 +90,14 @@ export function formatSseEvent(data: Record<string, unknown>, opts?: { eventId?:
* stream appears or the 120s timeout fires (yields unavailable error event
* and returns on timeout; yields keepalive every 20s while waiting).
* 3. Resolves startId from lastEventId / startLatest / '0'.
- * 4. On reconnect (lastEventId set): observes stream length and checks for
- * resume gap (best-effort — catches all exceptions, never breaks stream).
+ * 4. On reconnect (lastEventId set): observes stream length (best-effort) and
+ * checks for a resume gap. A resync-capable client gets the resync frame
+ * when its cursor was trimmed, and a stream error when the check fails.
* 5. Iterates readStreamEntries:
* - null → yield keepalive
* - entry → yield formatSseEvent(event, {eventId})
+ * A resync-capable client also gets the resync frame when its cursor is
+ * trimmed while the connection is stalled mid-stream.
* 6. After generator returns (completion sentinel consumed): yield stream-end
* terminal event; set outcome = 'completed'.
* 7. On TaskRunStreamError: yield error event; set outcome = 'stream_error'.
@@ -108,6 +114,7 @@ export async function* streamTaskRunEvents(
startLatest?: boolean
presenceGated?: boolean
isTerminal?: boolean
+ resyncCapable?: boolean
}
): AsyncGenerator<Buffer, void, unknown> {
const originProduct = opts.originProduct ?? 'unknown'
@@ -115,6 +122,7 @@ export async function* streamTaskRunEvents(
const startLatest = opts.startLatest ?? false
const presenceGated = opts.presenceGated ?? false
const isTerminal = opts.isTerminal ?? false
+ const resyncCapable = opts.resyncCapable ?? false
const redisStream = new TaskRunRedisStream(streamKey, redis)
const connectionStartedAt = Date.now()
@@ -155,6 +163,13 @@ export async function* streamTaskRunEvents(
let waitedForStream = false
while (!(await redisStream.exists())) {
if (isTerminal) {
+ if (lastEventId && resyncCapable) {
+ observeStreamResumeGap(originProduct)
+ logger.warn('stream:resume_gap', { streamKey, lastEventId, resyncCapable, reason: 'expired' })
+ outcome = 'resync'
+ yield formatSseEvent(SSE_PAYLOAD_RESYNC, { eventName: SSE_EVENT_END })
+ return
+ }
outcome = 'drained'
yield formatSseEvent(SSE_PAYLOAD_STREAM_END, { eventName: SSE_EVENT_STREAM_END })
return
@@ -203,17 +218,43 @@ export async function* streamTaskRunEvents(
startId = '0'
}
- // -- Resume gap detection (only on reconnects; best-effort) --
+ // -- Resume gap detection (only on reconnects) --
+ let resumePointTrimmed = false
if (lastEventId) {
try {
observeStreamLengthOnConnect(await redisStream.getLength())
- if (await redisStream.resumePointTrimmed(lastEventId)) {
- observeStreamResumeGap(originProduct)
- logger.warn('stream:resume_gap', { streamKey, lastEventId })
+ } catch (err) {
+ logger.warn('stream:attach_observe_failed', {
+ streamKey,
+ error: err instanceof Error ? err.message : String(err),
+ })
+ }
+ try {
+ resumePointTrimmed = await redisStream.resumePointTrimmed(lastEventId)
+ } catch (err) {
+ logger.warn('stream:resume_check_failed', {
+ streamKey,
+ lastEventId,
+ resyncCapable,
+ error: err instanceof Error ? err.message : String(err),
+ })
+ if (resyncCapable) {
+ outcome = 'stream_error'
+ yield formatSseEvent(makeSseErrorPayload('Connection lost to task run stream'), {
+ eventName: SSE_EVENT_ERROR,
+ })
+ return
}
- } catch {
- logger.warn('stream:attach_observe_failed', { streamKey })
}
+ if (resumePointTrimmed) {
+ observeStreamResumeGap(originProduct)
+ logger.warn('stream:resume_gap', { streamKey, lastEventId, resyncCapable, reason: 'trimmed' })
+ }
+ }
+ if (resumePointTrimmed && resyncCapable) {
+ outcome = 'resync'
+ yield formatSseEvent(SSE_PAYLOAD_RESYNC, { eventName: SSE_EVENT_END })
+ return
}
// Dedicated connection for the blocking XREAD loop so it cannot delay the
@@ -251,6 +292,7 @@ export async function* streamTaskRunEvents(
startId,
keepaliveIntervalMs: KEEPALIVE_INTERVAL_MS,
blockingRedis: dedupRedis,
+ ...(resyncCapable ? { cursorRecheckAfterStallMs: STREAM_CURSOR_RECHECK_STALL_MS } : {}),
})) {
await refreshWatched(Date.now())
@@ -273,7 +315,12 @@ export async function* streamTaskRunEvents(
outcome = 'completed'
yield formatSseEvent(SSE_PAYLOAD_STREAM_END, { eventName: SSE_EVENT_STREAM_END })
} catch (err) {
- if (err instanceof TaskRunStreamError) {
+ if (err instanceof TaskRunStreamCursorTrimmedError) {
+ observeStreamResumeGap(originProduct)
+ logger.warn('stream:resume_gap', { streamKey, cursor: err.cursor, resyncCapable, reason: 'stalled' })
+ outcome = 'resync'
+ yield formatSseEvent(SSE_PAYLOAD_RESYNC, { eventName: SSE_EVENT_END })
+ } else if (err instanceof TaskRunStreamError) {
outcome = 'stream_error'
logger.error('stream:error', { streamKey, error: err.message })
yield formatSseEvent(makeSseErrorPayload(err.message), { eventName: SSE_EVENT_ERROR })
diff --git a/services/agent-proxy/src/lib/constants.ts b/services/agent-proxy/src/lib/constants.ts
index 8d527205cb66..67d9be46cf28 100644
--- a/services/agent-proxy/src/lib/constants.ts
+++ b/services/agent-proxy/src/lib/constants.ts
@@ -30,6 +30,7 @@ export const STREAM_THIN_MAX_LENGTH = 500
// XREAD tuning
export const READ_COUNT = 16
+export const STREAM_CURSOR_RECHECK_STALL_MS = 2_000
export const BLOCK_MS = 100
// wait_for_stream linear backoff (mirrors Python constants, converted to ms)
@@ -112,6 +113,7 @@ export const SSE_EVENT_ERROR = 'error'
export const SSE_PAYLOAD_KEEPALIVE: Record<string, string> = { type: 'keepalive' }
export const SSE_PAYLOAD_STREAM_END: Record<string, string> = { status: 'complete' }
export const SSE_PAYLOAD_ROTATED: Record<string, string> = { type: 'rotated' }
+export const SSE_PAYLOAD_RESYNC: Record<string, string> = { type: 'resync', reason: 'trimmed' }
export function makeSseErrorPayload(error: string): Record<string, string> {
return { error }
diff --git a/services/agent-proxy/src/lib/redis-stream.ts b/services/agent-proxy/src/lib/redis-stream.ts
index 4711ff2dfd79..e7351d45d7ad 100644
--- a/services/agent-proxy/src/lib/redis-stream.ts
+++ b/services/agent-proxy/src/lib/redis-stream.ts
@@ -27,6 +27,7 @@ import type { ReadStreamEntriesOptions, ResumeGap, StreamEntryOrKeepalive, TaskR
import {
TaskRunStreamAlreadyCompleted,
TaskRunStreamCompletionSequenceMismatch,
+ TaskRunStreamCursorTrimmedError,
TaskRunStreamError,
TaskRunStreamSequenceGap,
WRITE_RESULT_DUPLICATE,
@@ -238,6 +239,14 @@ export class TaskRunRedisStream {
return streamIdLessThan(lastEventId, firstId)
}
+ async cursorUnreachable(cursor: string): Promise<boolean> {
+ if (cursor === '' || cursor === '0' || cursor === '0-0') {
+ return false
+ }
+ const firstId = await this.getFirstStreamId()
+ return firstId === null || streamIdLessThan(cursor, firstId)
+ }
+
// None for startId in ('0','0-0','$',''). None if stream empty.
// ResumeGap if startId < firstId.
async detectResumeGap(startId: string): Promise<ResumeGap | null> {
@@ -271,10 +280,23 @@ export class TaskRunRedisStream {
// one, so that XREAD BLOCK calls don't queue behind ingest XADD writes
// on the shared client.
const xreadClient = opts.blockingRedis ?? this.redis
+ const cursorRecheckAfterStallMs = opts.cursorRecheckAfterStallMs ?? null
let currentId = startId
const startTime = Date.now()
let lastYieldTime = startTime
+ let recheckCursor = false
+ let stalledMs = 0
+ const noteConsumerStall = (yieldedAt: number): void => {
+ if (cursorRecheckAfterStallMs === null) {
+ return
+ }
+ stalledMs += Date.now() - yieldedAt
+ if (stalledMs >= cursorRecheckAfterStallMs) {
+ stalledMs = 0
+ recheckCursor = true
+ }
+ }
while (true) {
const now = Date.now()
@@ -311,6 +333,19 @@ export class TaskRunRedisStream {
throw new TaskRunStreamError('Stream read error')
}
+ if (recheckCursor) {
+ recheckCursor = false
+ let unreachable: boolean
+ try {
+ unreachable = await this.cursorUnreachable(currentId)
+ } catch {
+ throw new TaskRunStreamError('Connection lost to task run stream')
+ }
+ if (unreachable) {
+ throw new TaskRunStreamCursorTrimmedError(currentId)
+ }
+ }
+
// TypeScript 6 incorrectly narrows `messages` to `never` inside an
// async generator when the catch block always throws — false positive.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
@@ -320,6 +355,7 @@ export class TaskRunRedisStream {
if (keepaliveIntervalMs !== null && idleMs >= keepaliveIntervalMs) {
lastYieldTime = Date.now()
yield null
+ noteConsumerStall(lastYieldTime)
}
continue
}
@@ -360,6 +396,7 @@ export class TaskRunRedisStream {
} else {
lastYieldTime = Date.now()
yield [normalizedId, data]
+ noteConsumerStall(lastYieldTime)
}
}
}
diff --git a/services/agent-proxy/src/lib/types.ts b/services/agent-proxy/src/lib/types.ts
index 159a757049e6..fe26801f13bd 100644
--- a/services/agent-proxy/src/lib/types.ts
+++ b/services/agent-proxy/src/lib/types.ts
@@ -17,6 +17,13 @@ export class TaskRunStreamError extends Error {
}
}
+export class TaskRunStreamCursorTrimmedError extends Error {
+ constructor(public readonly cursor: string) {
+ super(`Stream cursor ${cursor} was trimmed`)
+ this.name = 'TaskRunStreamCursorTrimmedError'
+ }
+}
+
export class TaskRunStreamSequenceGap extends Error {
constructor(
public readonly expectedSequence: number,
@@ -127,6 +134,7 @@ export type StreamConnectionOutcome =
| 'drained'
| 'client_disconnect'
| 'rotated'
+ | 'resync'
export type DisconnectClassification = 'run_over' | 'idle' | 'mid_turn'
@@ -181,4 +189,5 @@ export interface ReadStreamEntriesOptions {
// When provided, this connection is used for the blocking XREAD call instead
// of the class-level shared client — isolates blocking reads from ingest writes.
blockingRedis?: Redis
+ cursorRecheckAfterStallMs?: number
}
diff --git a/services/agent-proxy/tests/hono/sse-handler.test.ts b/services/agent-proxy/tests/hono/sse-handler.test.ts
index 517e2d4c3ac3..b7463f997437 100644
--- a/services/agent-proxy/tests/hono/sse-handler.test.ts
+++ b/services/agent-proxy/tests/hono/sse-handler.test.ts
@@ -13,12 +13,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { formatSseEvent, streamTaskRunEvents } from '@/hono/sse-handler.js'
import {
+ BLOCK_MS,
CONNECTION_MAX_MS,
KEEPALIVE_INTERVAL_MS,
SSE_EVENT_END,
SSE_EVENT_ERROR,
SSE_EVENT_KEEPALIVE,
SSE_EVENT_STREAM_END,
+ STREAM_CURSOR_RECHECK_STALL_MS,
WAIT_TIMEOUT_MS,
} from '@/lib/constants.js'
import { getWatchedKey } from '@/lib/redis-stream.js'
@@ -139,6 +141,10 @@ class FakeRedis {
this.strings.set(key, value)
}
+ _xtrimKeepLast(key: string, keep: number): void {
+ this.streams.set(key, keep <= 0 ? [] : (this.streams.get(key) ?? []).slice(-keep))
+ }
+
// ---------------------------------------------------------------------------
// ioredis-compatible API surface
// ---------------------------------------------------------------------------
@@ -658,7 +664,7 @@ describe('sse-handler', () => {
xaddComplete(redis, streamKey)
const body = await collect(
- streamTaskRunEvents(streamKey, redis as unknown as Redis, { lastEventId: firstId })
+ streamTaskRunEvents(streamKey, redis as unknown as Redis, { lastEventId: firstId, resyncCapable: true })
)
expect(body).toContain('"second"')
@@ -666,6 +672,148 @@ describe('sse-handler', () => {
expect(body).toContain(SSE_EVENT_STREAM_END)
})
+ it('tells a resync-capable client its cursor was trimmed instead of skipping ahead', async () => {
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ xaddData(redis, streamKey, { type: 'notification', msg: 'survivor' })
+ xaddComplete(redis, streamKey)
+
+ const body = await collect(
+ streamTaskRunEvents(streamKey, redis as unknown as Redis, { lastEventId: '1-0', resyncCapable: true })
+ )
+
+ expect(body).toBe(`event: ${SSE_EVENT_END}\ndata: {"type":"resync","reason":"trimmed"}\n\n`)
+ })
+
+ it('keeps reading from the oldest surviving entry for a client that cannot resync', async () => {
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ xaddData(redis, streamKey, { type: 'notification', msg: 'survivor' })
+ xaddComplete(redis, streamKey)
+
+ const body = await collect(
+ streamTaskRunEvents(streamKey, redis as unknown as Redis, { lastEventId: '1-0' })
+ )
+
+ expect(body).toContain('"survivor"')
+ expect(body).not.toContain('"resync"')
+ expect(body).toContain(SSE_EVENT_STREAM_END)
+ })
+
+ it.each([
+ { resyncCapable: true, outcome: 'closes with a stream error' },
+ { resyncCapable: false, outcome: 'keeps reading from the cursor' },
+ ])('$outcome when the trim check fails (resyncCapable=$resyncCapable)', async ({ resyncCapable }) => {
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ xaddData(redis, streamKey, { type: 'notification', msg: 'first' })
+ const msgs = await redis.xrange(streamKey, '-', '+', 'COUNT', 1)
+ const firstId = msgs[0]![0]
+ xaddData(redis, streamKey, { type: 'notification', msg: 'second' })
+ xaddComplete(redis, streamKey)
+ vi.spyOn(redis, 'xrange').mockRejectedValue(new Error('READONLY'))
+
+ const body = await collect(
+ streamTaskRunEvents(streamKey, redis as unknown as Redis, { lastEventId: firstId, resyncCapable })
+ )
+
+ expect(body).not.toContain('"resync"')
+ if (resyncCapable) {
+ expect(body).toBe(`event: ${SSE_EVENT_ERROR}\ndata: {"error":"Connection lost to task run stream"}\n\n`)
+ } else {
+ expect(body).toContain('"second"')
+ expect(body).toContain(SSE_EVENT_STREAM_END)
+ }
+ })
+
+ it.each([
+ {
+ name: 'rebuild when its cursor is trimmed while the reader is stalled',
+ keep: 1,
+ failRecheck: false,
+ shortPauses: 1,
+ trimDuringRead: false,
+ expectedFrame: `event: ${SSE_EVENT_END}\ndata: {"type":"resync","reason":"trimmed"}\n\n`,
+ },
+ {
+ name: 'rebuild when its cursor is trimmed while the reader lags in short pauses',
+ keep: 1,
+ failRecheck: false,
+ shortPauses: 4,
+ trimDuringRead: false,
+ expectedFrame: `event: ${SSE_EVENT_END}\ndata: {"type":"resync","reason":"trimmed"}\n\n`,
+ },
+ {
+ name: 'rebuild when its cursor is trimmed while the read is in flight',
+ keep: 1,
+ failRecheck: false,
+ shortPauses: 1,
+ trimDuringRead: true,
+ expectedFrame: `event: ${SSE_EVENT_END}\ndata: {"type":"resync","reason":"trimmed"}\n\n`,
+ },
+ {
+ name: 'rebuild when the whole stream expired while the reader was stalled',
+ keep: 0,
+ failRecheck: false,
+ shortPauses: 1,
+ trimDuringRead: false,
+ expectedFrame: `event: ${SSE_EVENT_END}\ndata: {"type":"resync","reason":"trimmed"}\n\n`,
+ },
+ {
+ name: 'reconnect when the stalled trim check fails',
+ keep: 1,
+ failRecheck: true,
+ shortPauses: 1,
+ trimDuringRead: false,
+ expectedFrame: `event: ${SSE_EVENT_ERROR}\ndata: {"error":"Connection lost to task run stream"}\n\n`,
+ },
+ ])(
+ 'tells a resync-capable client to $name',
+ async ({ keep, failRecheck, shortPauses, trimDuringRead, expectedFrame }) => {
+ vi.useFakeTimers()
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ xaddData(redis, streamKey, { type: 'notification', msg: 'first' })
+ const gen = streamTaskRunEvents(streamKey, redis as unknown as Redis, { resyncCapable: true })
+ const first = await gen.next()
+ expect(first.value?.toString('utf8')).toContain('"first"')
+
+ const pauseMs = Math.floor(STREAM_CURSOR_RECHECK_STALL_MS / shortPauses)
+ for (let pause = 1; pause < shortPauses; pause++) {
+ xaddData(redis, streamKey, { type: 'notification', msg: `lag-${pause}` })
+ vi.advanceTimersByTime(pauseMs)
+ const lagging = await gen.next()
+ expect(lagging.value?.toString('utf8')).toContain(`"lag-${pause}"`)
+ }
+
+ xaddData(redis, streamKey, { type: 'notification', msg: 'second' })
+ xaddData(redis, streamKey, { type: 'notification', msg: 'third' })
+ if (trimDuringRead) {
+ const readStream = redis.xread.bind(redis)
+ vi.spyOn(redis, 'xread').mockImplementation(async (...args: unknown[]) => {
+ redis._xtrimKeepLast(streamKey, keep)
+ return readStream(...args)
+ })
+ } else {
+ redis._xtrimKeepLast(streamKey, keep)
+ }
+ if (failRecheck) {
+ vi.spyOn(redis, 'xrange').mockRejectedValue(new Error('Connection is closed'))
+ }
+ vi.advanceTimersByTime(pauseMs)
+
+ const pending = gen.next()
+ await vi.advanceTimersByTimeAsync(BLOCK_MS * 2)
+ const next = await pending
+ expect(next.value?.toString('utf8')).toBe(expectedFrame)
+ expect((await gen.next()).done).toBe(true)
+ }
+ )
+
it('id field in each SSE frame matches the Redis stream ID used for resuming', async () => {
const runId = uniqueRunId()
const streamKey = makeStreamKey(runId)
@@ -823,6 +971,27 @@ describe('sse-handler', () => {
expect(body).not.toContain(`event: ${SSE_EVENT_ERROR}`)
})
+ it.each([
+ { resyncCapable: true, frame: `event: ${SSE_EVENT_END}\ndata: {"type":"resync","reason":"trimmed"}\n\n` },
+ { resyncCapable: false, frame: `event: ${SSE_EVENT_STREAM_END}\ndata: {"status":"complete"}\n\n` },
+ ])(
+ 'answers a cursor on an expired terminal stream with $frame (resyncCapable=$resyncCapable)',
+ async ({ resyncCapable, frame }) => {
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ const body = await collect(
+ streamTaskRunEvents(streamKey, redis as unknown as Redis, {
+ isTerminal: true,
+ lastEventId: '1-0',
+ resyncCapable,
+ })
+ )
+
+ expect(body).toBe(frame)
+ }
+ )
+
it('emits keepalive events while waiting for the stream to appear', async () => {
vi.useFakeTimers()