: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): end drained terminal run streams immediately (#94344)
Alessandro Pogliaghi1624b94fa185
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex c5d866e0c3b4..bd0c0424cccc 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -2435,6 +2435,8 @@ def get_task_run_stream_info(id=run.id,state=run.state or {},origin_product=origin_product_label(run),+ is_terminal=run.is_terminal,+ state_event=run.build_stream_state_event(),)diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.pyindex bae5d0ffe219..bc773621e425 100644--- a/products/tasks/backend/facade/contracts.py+++ b/products/tasks/backend/facade/contracts.py@@ -616,13 +616,18 @@ class TaskRunCreateResult:class TaskRunStreamInfoDTO:"""The minimal run facts the SSE stream view needs without holding a model.- ``id`` keys the Redis stream, ``state`` decides dedicated-stream routing, and- ``origin_product`` is the bounded metric label resolved off the parent task.+ ``id`` keys the Redis stream, ``state`` decides dedicated-stream routing,+ ``origin_product`` is the bounded metric label resolved off the parent task, and+ ``is_terminal`` lets the view end immediately when the stream key is already gone.+ ``state_event`` is the run's current ``task_run_state`` frame, emitted before that+ immediate end so a client that never received any state still settles the run."""id: UUIDstate: dictorigin_product: str+ is_terminal: bool+ state_event: dict@dataclass(frozen=True)diff --git a/products/tasks/backend/logic/services/connection_token.py b/products/tasks/backend/logic/services/connection_token.pyindex 2e06977e0fb4..530e4acf052f 100644--- a/products/tasks/backend/logic/services/connection_token.py+++ b/products/tasks/backend/logic/services/connection_token.py@@ -57,6 +57,7 @@ class StreamReadTokenPayload:task_id: strteam_id: intpresence_gated: bool = False+ is_terminal: bool = Falseorigin_product: str | None = None@@ -320,7 +321,11 @@ def create_stream_read_token(task_run: TaskRun, ttl: timedelta = STREAM_READ_TOKtask_run,STREAM_READ_AUDIENCE,ttl,- {"presence_gated": presence_gated, "origin_product": task_run.task.origin_product},+ {+ "presence_gated": presence_gated,+ "is_terminal": task_run.is_terminal,+ "origin_product": task_run.task.origin_product,+ },)@@ -331,12 +336,15 @@ def validate_stream_read_token(token: str) -> StreamReadTokenPayload:task_id = payload.get("task_id")team_id = payload.get("team_id")presence_gated = payload.get("presence_gated", False)+ is_terminal = payload.get("is_terminal", False)origin_product = payload.get("origin_product")if not isinstance(run_id, str) or not isinstance(task_id, str) or type(team_id) is not int:raise jwt.InvalidTokenError("Stream read token has invalid claims")if not isinstance(presence_gated, bool):raise jwt.InvalidTokenError("Stream read token has invalid claims")+ if not isinstance(is_terminal, bool):+ raise jwt.InvalidTokenError("Stream read token has invalid claims")if origin_product is not None and not isinstance(origin_product, str):raise jwt.InvalidTokenError("Stream read token has invalid claims")@@ -345,5 +353,6 @@ def validate_stream_read_token(token: str) -> StreamReadTokenPayload:task_id=task_id,team_id=team_id,presence_gated=presence_gated,+ is_terminal=is_terminal,origin_product=origin_product,)diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.pyindex 4f5e7f9bde9f..ad8b70eef71c 100644--- a/products/tasks/backend/metrics.py+++ b/products/tasks/backend/metrics.py@@ -20,9 +20,10 @@ DevStackImageBakeOutcome = Literal["succeeded", "bake_failed", "failed", "dispat# completed — stream reached its completion sentinel# stream_error — Redis/stream error sentinel ended the connection# unavailable — stream key never appeared within the wait timeout+# drained — terminal run whose stream key already expired; ended immediately# client_disconnect — client went away (GeneratorExit) before completion# rotated — per-connection cap reached; clean EOF, client resumes-StreamConnectionOutcome = Literal["completed", "stream_error", "unavailable", "client_disconnect", "rotated"]+StreamConnectionOutcome = Literal["completed", "stream_error", "unavailable", "drained", "client_disconnect", "rotated"]StreamWriteSkippedPath = Literal["ingest", "mirror", "relay"]_ALLOWED_MODES = {"background", "interactive"}_ALLOWED_RUN_SOURCES = {"manual", "signal_report"}diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 8eed18714777..cbd9595896fd 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -3238,6 +3238,8 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):format_sse_event = self._format_sse_eventorigin_product = stream_info.origin_productpresence_gated = run_stream_presence_gated(stream_info.state)+ run_is_terminal = stream_info.is_terminal+ run_state_event = stream_info.state_eventasync def async_stream() -> AsyncGenerator[bytes]:redis_stream = TaskRunRedisStream(stream_key, use_dedicated_stream)@@ -3260,6 +3262,11 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):waited_for_stream = Falsewhile not await redis_stream.exists():+ if run_is_terminal:+ outcome = "drained"+ yield format_sse_event(run_state_event)+ yield format_sse_event({"status": "complete"}, event_name=TASK_RUN_STREAM_COMPLETE_EVENT_NAME)+ returnwaited_for_stream = Trueif presence_gated:breakdiff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 73da0d6e3240..e35fc8633d91 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -9178,6 +9178,23 @@ class TestTaskRunStreamAPI(BaseTaskAPITest):self.assertEqual(data_events[-1]["data"]["notification"]["params"]["message"], "late hello")self.assertEqual(events[-1]["event"], "stream-end")+ def test_stream_terminal_run_with_missing_stream_ends_immediately(self):+ task = self.create_task()+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED)++ with (+ patch.object(TaskRunRedisStream, "exists", new=AsyncMock(return_value=False)),+ patch("products.tasks.backend.presentation.views.api.TASK_RUN_STREAM_WAIT_TIMEOUT_SECONDS", 0.2),+ ):+ response = self.client.get(self._stream_url(task, run), headers={"accept": "text/event-stream"})+ events = self._collect_sse_events(response)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual([event["event"] for event in events], [None, "stream-end"])+ self.assertEqual(events[0]["data"]["type"], "task_run_state")+ self.assertEqual(events[0]["data"]["status"], TaskRun.Status.COMPLETED)+ self.assertEqual(events[1]["data"], {"status": "complete"})+@override_settings(TASK_RUN_STREAM_PRESENCE_GATED_ORIGINS=["user_created"])def test_stream_presence_gated_run_reads_missing_stream_instead_of_erroring(self):task = self.create_task()diff --git a/products/tasks/backend/tests/test_connection_token.py b/products/tasks/backend/tests/test_connection_token.pyindex 210feb8129d4..b884a5f5bb0c 100644--- a/products/tasks/backend/tests/test_connection_token.py+++ b/products/tasks/backend/tests/test_connection_token.py@@ -47,7 +47,7 @@ KEY_B = _generate_private_key_pem()KID_A = _compute_kid(_derive_public_key_pem(KEY_A))-def _fake_run(state: dict | None = None, origin_product: str = "user_created") -> TaskRun:+def _fake_run(state: dict | None = None, origin_product: str = "user_created", *, is_terminal: bool = False) -> TaskRun:# Only the attributes the token helpers read are needed, so a lightweight stand-in# avoids the DB; cast keeps the call sites type-correct.return cast(@@ -58,6 +58,7 @@ def _fake_run(state: dict | None = None, origin_product: str = "user_created") -team_id=1,mode="background",state={"sandbox_id": "sandbox-1", **(state or {})},+ is_terminal=is_terminal,task=SimpleNamespace(origin_product=origin_product),),)@@ -169,10 +170,13 @@ class TestSandboxJwtRotation(SimpleTestCase):@override_settings(SANDBOX_JWT_PRIVATE_KEY=KEY_A, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=None)def test_stream_read_token_carries_pinned_presence_gating(self, gated: bool) -> None:reset_sandbox_jwt_key_cache()- token = create_stream_read_token(_fake_run({"stream_presence_gated": gated}, "signals_scout"))+ token = create_stream_read_token(+ _fake_run({"stream_presence_gated": gated}, "signals_scout", is_terminal=gated)+ )payload = validate_stream_read_token(token)self.assertIs(payload.presence_gated, gated)+ self.assertIs(payload.is_terminal, gated)self.assertEqual(payload.origin_product, "signals_scout")@override_settings(SANDBOX_JWT_PRIVATE_KEY=KEY_A, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=None)@@ -198,6 +202,7 @@ class TestSandboxJwtRotation(SimpleTestCase):self.assertEqual(payload.run_id, str(run.id))self.assertIs(payload.presence_gated, False)+ self.assertIs(payload.is_terminal, False)self.assertIsNone(payload.origin_product)def test_ingest_token_validates_after_primary_rotation(self) -> None:@@ -275,6 +280,7 @@ def _fake_task_run(origin_product: str = "user_created") -> TaskRun:task_id=_TASK_ID,team_id=7,state={"sandbox_id": "sandbox-1"},+ is_terminal=False,task=SimpleNamespace(origin_product=origin_product),),)diff --git a/services/agent-proxy/src/hono/app.ts b/services/agent-proxy/src/hono/app.tsindex e134e240d5a3..b9fbf5a0bf4b 100644--- a/services/agent-proxy/src/hono/app.ts+++ b/services/agent-proxy/src/hono/app.ts@@ -123,6 +123,7 @@ export function createApp(redis: Redis, config: Config, publicKeys: CryptoKey[])lastEventId,startLatest,presenceGated: claims.presenceGated,+ isTerminal: claims.isTerminal,})// 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.tsindex 727ce0b4987c..2609afbcd9a5 100644--- a/services/agent-proxy/src/hono/sse-handler.ts+++ b/services/agent-proxy/src/hono/sse-handler.ts@@ -107,12 +107,14 @@ export async function* streamTaskRunEvents(lastEventId?: string | nullstartLatest?: booleanpresenceGated?: boolean+ isTerminal?: boolean}): AsyncGenerator<Buffer, void, unknown> {const originProduct = opts.originProduct ?? 'unknown'const lastEventId = opts.lastEventId ?? nullconst startLatest = opts.startLatest ?? falseconst presenceGated = opts.presenceGated ?? false+ const isTerminal = opts.isTerminal ?? falseconst redisStream = new TaskRunRedisStream(streamKey, redis)const connectionStartedAt = Date.now()@@ -152,6 +154,11 @@ export async function* streamTaskRunEvents(let lastKeepaliveAt = waitStartedAtlet waitedForStream = falsewhile (!(await redisStream.exists())) {+ if (isTerminal) {+ outcome = 'drained'+ yield formatSseEvent(SSE_PAYLOAD_STREAM_END, { eventName: SSE_EVENT_STREAM_END })+ return+ }if (!waitedForStream) {waitedForStream = truelogger.debug('stream:waiting', { streamKey })diff --git a/services/agent-proxy/src/lib/jwt.ts b/services/agent-proxy/src/lib/jwt.tsindex 3b85c5959cef..0adf9de5ae1c 100644--- a/services/agent-proxy/src/lib/jwt.ts+++ b/services/agent-proxy/src/lib/jwt.ts@@ -68,6 +68,14 @@ function assertPresenceGatedClaim(payload: Record<string, unknown>): boolean {return presenceGated ?? false}+function assertIsTerminalClaim(payload: Record<string, unknown>): boolean {+ const isTerminal = payload['is_terminal']+ if (isTerminal !== undefined && typeof isTerminal !== 'boolean') {+ throw new Error('Token has invalid claim: is_terminal must be a boolean')+ }+ return isTerminal ?? false+}+function assertOriginProductClaim(payload: Record<string, unknown>): string {const originProduct = payload['origin_product']if (originProduct !== undefined && typeof originProduct !== 'string') {@@ -104,6 +112,7 @@ async function verifyWithKeys(token: string, publicKeys: CryptoKey[], audience:// Audience: posthog:stream_read// Required claims: run_id (string), task_id (string), team_id (integer)// Optional claims: presence_gated (boolean, absent means false),+// is_terminal (boolean, absent means false),// origin_product (string, absent means "unknown")// Algorithm: RS256, no clockTolerance (matches Python leeway=0 default)//@@ -116,6 +125,7 @@ export async function validateStreamReadToken(token: string, publicKeys: CryptoKreturn {...assertStreamClaims(claims),presenceGated: assertPresenceGatedClaim(claims),+ isTerminal: assertIsTerminalClaim(claims),originProduct: assertOriginProductClaim(claims),}}diff --git a/services/agent-proxy/src/lib/types.ts b/services/agent-proxy/src/lib/types.tsindex c61c49aba476..a4074dc589b5 100644--- a/services/agent-proxy/src/lib/types.ts+++ b/services/agent-proxy/src/lib/types.ts@@ -102,6 +102,7 @@ export interface StreamReadTokenPayload {taskId: stringteamId: numberpresenceGated: boolean+ isTerminal: booleanoriginProduct: string}@@ -118,7 +119,13 @@ export interface SandboxEventIngestTokenPayload {// SSE stream connection outcome (matches Python StreamConnectionOutcome values)// ----------------------------------------------------------------------------export type StreamConnectionOutcome = 'completed' | 'stream_error' | 'unavailable' | 'client_disconnect' | 'rotated'+export type StreamConnectionOutcome =+ | 'completed'+ | 'stream_error'+ | 'unavailable'+ | 'drained'+ | 'client_disconnect'+ | 'rotated'export type DisconnectClassification = 'run_over' | 'idle' | 'mid_turn'diff --git a/services/agent-proxy/tests/hono/sse-handler.test.ts b/services/agent-proxy/tests/hono/sse-handler.test.tsindex ce1c7b432a5f..517e2d4c3ac3 100644--- a/services/agent-proxy/tests/hono/sse-handler.test.ts+++ b/services/agent-proxy/tests/hono/sse-handler.test.ts@@ -812,6 +812,17 @@ describe('sse-handler', () => {expect(body).toContain('Stream not available')})+ it('ends immediately with stream-end when the token marks the run terminal', async () => {+ const runId = uniqueRunId()+ const streamKey = makeStreamKey(runId)+ // Do NOT add any entries — the terminal run's stream already expired.++ const body = await collect(streamTaskRunEvents(streamKey, redis as unknown as Redis, { isTerminal: true }))++ expect(body).toContain(`event: ${SSE_EVENT_STREAM_END}`)+ expect(body).not.toContain(`event: ${SSE_EVENT_ERROR}`)+ })+it('emits keepalive events while waiting for the stream to appear', async () => {vi.useFakeTimers()diff --git a/services/agent-proxy/tests/lib/jwt.test.ts b/services/agent-proxy/tests/lib/jwt.test.tsindex b3154807c50e..a1e29e2ed1e5 100644--- a/services/agent-proxy/tests/lib/jwt.test.ts+++ b/services/agent-proxy/tests/lib/jwt.test.ts@@ -58,6 +58,7 @@ interface TokenOptions {omitExp?: booleansigningKey?: CryptoKeypresenceGated?: unknown+ isTerminal?: unknownoriginProduct?: unknown}@@ -71,6 +72,7 @@ async function signToken(opts: TokenOptions = {}): Promise<string> {omitExp = false,signingKey,presenceGated,+ isTerminal,originProduct,} = opts@@ -78,6 +80,9 @@ async function signToken(opts: TokenOptions = {}): Promise<string> {if (presenceGated !== undefined) {claims['presence_gated'] = presenceGated}+ if (isTerminal !== undefined) {+ claims['is_terminal'] = isTerminal+ }if (originProduct !== undefined) {claims['origin_product'] = originProduct}@@ -110,6 +115,7 @@ describe('jwt', () => {expect(payload.taskId).toBe('task-abc-123')expect(payload.teamId).toBe(42)expect(payload.presenceGated).toBe(false)+ expect(payload.isTerminal).toBe(false)})it.each([@@ -133,6 +139,27 @@ describe('jwt', () => {})+ it.each([+ { name: 'true', claim: true, expected: true },+ { name: 'false', claim: false, expected: false },+ ])('carries an is_terminal claim of $name', async ({ claim, expected }) => {+ const token = await signToken({ audience: STREAM_READ_AUDIENCE, isTerminal: claim })+ const payload = await validateStreamReadToken(token, keys.publicKeys)++ expect(payload.isTerminal).toBe(expected)+ })++ it.each([{ claim: 'yes' }, { claim: 1 }, { claim: null }])(+ 'rejects a non-boolean is_terminal claim ($claim)',+ async ({ claim }) => {+ const token = await signToken({ audience: STREAM_READ_AUDIENCE, isTerminal: claim })++ await expect(validateStreamReadToken(token, keys.publicKeys)).rejects.toThrow(+ 'is_terminal must be a boolean'+ )+ }+ )+it.each([{ name: 'a string claim', claim: 'signals_scout', expected: 'signals_scout' },{ name: 'an absent claim as unknown', claim: undefined, expected: 'unknown' },