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.

fix(tasks): expire task-run streams shortly after terminal (#91994)

Alessandro Pogliaghieb49a2efcddb
diff --git a/products/tasks/backend/logic/stream/redis_stream.py b/products/tasks/backend/logic/stream/redis_stream.py
index 6daa2c2fb0c4..c27e7304880b 100644
--- a/products/tasks/backend/logic/stream/redis_stream.py
+++ b/products/tasks/backend/logic/stream/redis_stream.py
@@ -18,6 +18,7 @@ logger = structlog.get_logger(__name__)
# still bounding Redis growth to the sandbox lifetime.
TASK_RUN_STREAM_MAX_LENGTH = 5_000
TASK_RUN_STREAM_TIMEOUT = SANDBOX_TTL_SECONDS
+TASK_RUN_STREAM_COMPLETED_TIMEOUT = min(30 * 60, TASK_RUN_STREAM_TIMEOUT // 3)
TASK_RUN_STREAM_SEQUENCE_TIMEOUT = int(SANDBOX_EVENT_INGEST_TOKEN_TTL.total_seconds())
TASK_RUN_STREAM_PREFIX = "task-run-stream:"
TASK_RUN_STREAM_READ_COUNT = 16
@@ -138,6 +139,7 @@ class TaskRunRedisStream:
self._redis_client = get_tasks_stream_redis_async(use_dedicated)
self._timeout = timeout
self._sequence_timeout = max(timeout, TASK_RUN_STREAM_SEQUENCE_TIMEOUT)
+ self._completed_timeout = min(timeout, TASK_RUN_STREAM_COMPLETED_TIMEOUT)
self._max_length = max_length
async def initialize(self) -> None:
@@ -292,12 +294,13 @@ class TaskRunRedisStream:
except redis_exceptions.RedisError:
raise TaskRunStreamError("Stream read error")
- async def write_event(self, event: dict) -> str:
+ async def write_event(self, event: dict, *, ttl: int | None = None) -> str:
"""Write a single event to the stream.
Refreshes TTL on every write (sliding window) so long-running tasks
- don't expire mid-stream. This is especially important for the sync
- publish path (publish_task_run_stream_event) which bypasses initialize().
+ don't expire mid-stream, unless `ttl` overrides it for terminal writes.
+ This is especially important for the sync publish path
+ (publish_task_run_stream_event) which bypasses initialize().
"""
raw = json.dumps(event)
stream_id = await self._redis_client.xadd(
@@ -306,7 +309,7 @@ class TaskRunRedisStream:
maxlen=self._max_length,
approximate=True,
)
- await self._redis_client.expire(self._stream_key, self._timeout)
+ await self._redis_client.expire(self._stream_key, self._timeout if ttl is None else ttl)
return _normalize_stream_id(stream_id)
async def get_last_sequence(self) -> int:
@@ -481,6 +484,7 @@ class TaskRunRedisStream:
try:
await pipe.watch(completed_key)
if await pipe.exists(completed_key):
+ await self._redis_client.expire(self._stream_key, self._completed_timeout)
return
pipe.multi()
@@ -490,7 +494,7 @@ class TaskRunRedisStream:
maxlen=self._max_length,
approximate=True,
)
- pipe.expire(self._stream_key, self._timeout)
+ pipe.expire(self._stream_key, self._completed_timeout)
pipe.set(completed_key, "1", ex=self._sequence_timeout)
await pipe.execute()
return
@@ -500,9 +504,10 @@ class TaskRunRedisStream:
async def _mark_complete_for_tests(self) -> None:
completed_key = get_task_run_stream_completed_key(self._stream_key)
if await self._redis_client.exists(completed_key):
+ await self._redis_client.expire(self._stream_key, self._completed_timeout)
return
- await self.write_event({"type": "STREAM_STATUS", "status": "complete"})
+ await self.write_event({"type": "STREAM_STATUS", "status": "complete"}, ttl=self._completed_timeout)
await self._redis_client.set(completed_key, "1", ex=self._sequence_timeout)
async def mark_complete_after_sequence(self, final_sequence: int) -> None:
@@ -522,6 +527,7 @@ class TaskRunRedisStream:
last_sequence_raw = await pipe.get(sequence_key)
last_sequence = _normalize_redis_int(last_sequence_raw)
if await pipe.exists(completed_key):
+ await self._redis_client.expire(self._stream_key, self._completed_timeout)
return
if last_sequence != final_sequence:
@@ -537,7 +543,7 @@ class TaskRunRedisStream:
maxlen=self._max_length,
approximate=True,
)
- pipe.expire(self._stream_key, self._timeout)
+ pipe.expire(self._stream_key, self._completed_timeout)
if last_sequence_raw is not None:
pipe.expire(sequence_key, self._sequence_timeout)
pipe.set(completed_key, "1", ex=self._sequence_timeout)
@@ -553,6 +559,7 @@ class TaskRunRedisStream:
last_sequence = _normalize_redis_int(last_sequence_raw)
if await self._redis_client.exists(completed_key):
+ await self._redis_client.expire(self._stream_key, self._completed_timeout)
return
if last_sequence != final_sequence:
@@ -561,14 +568,19 @@ class TaskRunRedisStream:
last_accepted_seq=last_sequence,
)
- await self.write_event({"type": "STREAM_STATUS", "status": "complete"})
+ await self.write_event({"type": "STREAM_STATUS", "status": "complete"}, ttl=self._completed_timeout)
if last_sequence_raw is not None:
await self._redis_client.expire(sequence_key, self._sequence_timeout)
await self._redis_client.set(completed_key, "1", ex=self._sequence_timeout)
async def mark_error(self, error: str) -> None:
"""Write an error sentinel to signal stream failure."""
- await self.write_event({"type": "STREAM_STATUS", "status": "error", "error": error[:500]})
+ await self.write_event(
+ {"type": "STREAM_STATUS", "status": "error", "error": error[:500]}, ttl=self._completed_timeout
+ )
+ await self._redis_client.set(
+ get_task_run_stream_completed_key(self._stream_key), "1", ex=self._sequence_timeout
+ )
async def delete_stream(self) -> bool:
"""Delete the Redis stream. Returns True if deleted."""
@@ -635,7 +647,8 @@ def publish_task_run_stream_event(run_id: str, event: dict, use_dedicated: bool
raw = json.dumps(event)
try:
stream_id = client.xadd(stream_key, {DATA_KEY: raw}, maxlen=TASK_RUN_STREAM_MAX_LENGTH, approximate=True)
- client.expire(stream_key, TASK_RUN_STREAM_TIMEOUT)
+ completed = client.exists(get_task_run_stream_completed_key(stream_key))
+ client.expire(stream_key, TASK_RUN_STREAM_COMPLETED_TIMEOUT if completed else TASK_RUN_STREAM_TIMEOUT)
return _normalize_stream_id(stream_id)
except Exception:
logger.exception("task_run_stream_publish_failed", run_id=run_id)
@@ -654,9 +667,10 @@ def publish_task_run_stream_complete(run_id: str, use_dedicated: bool = False) -
# fakeredis doesn't support WATCH/MULTI; the sequencing race the
# transaction guards against can't happen under the test harness.
if client.exists(completed_key):
+ client.expire(stream_key, TASK_RUN_STREAM_COMPLETED_TIMEOUT)
return True
client.xadd(stream_key, {DATA_KEY: raw}, maxlen=TASK_RUN_STREAM_MAX_LENGTH, approximate=True)
- client.expire(stream_key, TASK_RUN_STREAM_TIMEOUT)
+ client.expire(stream_key, TASK_RUN_STREAM_COMPLETED_TIMEOUT)
client.set(completed_key, "1", ex=TASK_RUN_STREAM_SEQUENCE_TIMEOUT)
return True
@@ -666,10 +680,11 @@ def publish_task_run_stream_complete(run_id: str, use_dedicated: bool = False) -
pipe.watch(completed_key)
if pipe.exists(completed_key):
pipe.reset()
+ client.expire(stream_key, TASK_RUN_STREAM_COMPLETED_TIMEOUT)
return True
pipe.multi()
pipe.xadd(stream_key, {DATA_KEY: raw}, maxlen=TASK_RUN_STREAM_MAX_LENGTH, approximate=True)
- pipe.expire(stream_key, TASK_RUN_STREAM_TIMEOUT)
+ pipe.expire(stream_key, TASK_RUN_STREAM_COMPLETED_TIMEOUT)
pipe.set(completed_key, "1", ex=TASK_RUN_STREAM_SEQUENCE_TIMEOUT)
pipe.execute()
return True
diff --git a/products/tasks/backend/logic/stream/tests/test_redis_stream.py b/products/tasks/backend/logic/stream/tests/test_redis_stream.py
index 5cf3dcfbf1e9..49f1d08f1462 100644
--- a/products/tasks/backend/logic/stream/tests/test_redis_stream.py
+++ b/products/tasks/backend/logic/stream/tests/test_redis_stream.py
@@ -1,20 +1,30 @@
import json
+from collections.abc import Awaitable, Callable
from uuid import uuid4
import pytest
from products.tasks.backend.logic.stream.redis_stream import (
DATA_KEY,
+ TASK_RUN_STREAM_COMPLETED_TIMEOUT,
+ TASK_RUN_STREAM_SEQUENCE_TIMEOUT,
+ TASK_RUN_STREAM_TIMEOUT,
TaskRunRedisStream,
TaskRunStreamAlreadyCompleted,
TaskRunStreamCompletionSequenceMismatch,
TaskRunStreamSequenceGap,
_stream_id_sort_key,
+ get_task_run_stream_completed_key,
+ get_task_run_stream_key,
+ publish_task_run_stream_complete,
+ publish_task_run_stream_event,
+ reset_task_run_stream,
)
+from products.tasks.backend.redis import get_tasks_stream_redis_sync
-def _new_stream() -> TaskRunRedisStream:
- return TaskRunRedisStream(f"task-run-stream:test:{uuid4()}", timeout=60)
+def _new_stream(timeout: int = 60) -> TaskRunRedisStream:
+ return TaskRunRedisStream(f"task-run-stream:test:{uuid4()}", timeout=timeout)
async def _read_stream_events(redis_stream: TaskRunRedisStream) -> list[dict]:
@@ -66,12 +76,21 @@ async def test_write_event_with_sequence_ignores_duplicate_sequence() -> None:
await redis_stream.delete_stream()
+ "terminal",
+ [
+ pytest.param(lambda stream: stream.mark_complete_after_sequence(1), id="mark_complete_after_sequence"),
+ pytest.param(lambda stream: stream.mark_error("boom"), id="mark_error"),
+ ],
+)
@pytest.mark.asyncio
-async def test_write_event_with_sequence_rejects_write_after_completion() -> None:
+async def test_write_event_with_sequence_rejects_write_after_completion(
+ terminal: Callable[[TaskRunRedisStream], Awaitable[None]],
+) -> None:
redis_stream = _new_stream()
try:
await redis_stream.write_event_with_sequence({"type": "message"}, 1)
- await redis_stream.mark_complete_after_sequence(1)
+ await terminal(redis_stream)
with pytest.raises(TaskRunStreamAlreadyCompleted) as exc:
await redis_stream.write_event_with_sequence({"type": "late"}, 2)
@@ -109,6 +128,66 @@ async def test_mark_complete_is_idempotent() -> None:
await redis_stream.delete_stream()
+ "terminal",
+ [
+ pytest.param(lambda stream: stream.mark_complete(), id="mark_complete"),
+ pytest.param(lambda stream: stream.mark_complete_after_sequence(1), id="mark_complete_after_sequence"),
+ pytest.param(lambda stream: stream.mark_error("boom"), id="mark_error"),
+ ],
+)
+async def test_terminal_sentinel_shortens_stream_ttl(
+ terminal: Callable[[TaskRunRedisStream], Awaitable[None]],
+) -> None:
+ redis_stream = _new_stream(timeout=TASK_RUN_STREAM_TIMEOUT)
+ try:
+ await redis_stream.write_event_with_sequence({"type": "message"}, 1)
+ assert await redis_stream._redis_client.ttl(redis_stream._stream_key) > TASK_RUN_STREAM_COMPLETED_TIMEOUT
+
+ await terminal(redis_stream)
+
+ stream_ttl = await redis_stream._redis_client.ttl(redis_stream._stream_key)
+ assert 0 < stream_ttl <= TASK_RUN_STREAM_COMPLETED_TIMEOUT
+ finally:
+ await redis_stream.delete_stream()
+
+
[email protected]("already_completed", [False, True])
+def test_publish_task_run_stream_complete_shortens_stream_ttl(already_completed: bool) -> None:
+ run_id = f"test:{uuid4()}"
+ stream_key = get_task_run_stream_key(run_id)
+ client = get_tasks_stream_redis_sync()
+ try:
+ assert publish_task_run_stream_event(run_id, {"type": "message"}) is not None
+ if already_completed:
+ client.set(get_task_run_stream_completed_key(stream_key), "1", ex=TASK_RUN_STREAM_SEQUENCE_TIMEOUT)
+ assert client.ttl(stream_key) > TASK_RUN_STREAM_COMPLETED_TIMEOUT
+
+ assert publish_task_run_stream_complete(run_id) is True
+
+ stream_ttl = client.ttl(stream_key)
+ assert 0 < stream_ttl <= TASK_RUN_STREAM_COMPLETED_TIMEOUT
+ finally:
+ reset_task_run_stream(run_id)
+
+
+def test_publish_stream_event_after_completion_keeps_short_ttl() -> None:
+ run_id = f"test:{uuid4()}"
+ stream_key = get_task_run_stream_key(run_id)
+ client = get_tasks_stream_redis_sync()
+ try:
+ assert publish_task_run_stream_event(run_id, {"type": "message"}) is not None
+ assert publish_task_run_stream_complete(run_id) is True
+
+ assert publish_task_run_stream_event(run_id, {"type": "task_run_state"}) is not None
+
+ stream_ttl = client.ttl(stream_key)
+ assert 0 < stream_ttl <= TASK_RUN_STREAM_COMPLETED_TIMEOUT
+ finally:
+ reset_task_run_stream(run_id)
+
+
@pytest.mark.parametrize(
"left,right,expected_less",
[
diff --git a/services/agent-proxy/docs/DURABLE_STREAMING.md b/services/agent-proxy/docs/DURABLE_STREAMING.md
index a46b6367a816..f7a23c29fd62 100644
--- a/services/agent-proxy/docs/DURABLE_STREAMING.md
+++ b/services/agent-proxy/docs/DURABLE_STREAMING.md
@@ -60,11 +60,14 @@ Ranked by how much it matters for the current use case (watching a live agent ru
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.
-2. **Bounded retention.** "Durable" here means roughly a 6h TTL plus a ~20k event
- `MAXLEN` (`STREAM_TTL_SECONDS`, `STREAM_MAX_LENGTH` in `src/lib/constants.ts`), after
- which data is gone. That bound is the cause of gap awareness above. It is fine for
- watching a run live, but not for replaying a run's stream much later. If long replay
- becomes a goal, this is the lever.
+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
+ `src/lib/constants.ts`), after which data is gone. A reader arriving after expiry gets
+ `Stream not available`; the durable transcript lives in the run's session logs
+ (`session_logs` on the task-run API). That bound is the cause of gap awareness above.
+ It is fine for watching a run live, but not for replaying a run's stream much later.
+ If long replay becomes a goal, this is the lever.
3. **No "caught up to the tail" signal.** A reader cannot tell when it transitions from
replaying history to being live at the tail. This is minor for a live UI, which just
keeps tailing, but it is a real durable-streaming concept that is not exposed.
@@ -93,7 +96,7 @@ Ranked by how much it matters for the current use case (watching a live agent ru
| Backpressure to slow readers | Have |
| Multi-reader fan-out | Have |
| Gap awareness on trimmed resume | **Missing** (detected, not signalled) |
-| Retention beyond ~6h / ~20k | **Partial** (bounded, then dropped) |
+| 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) |
diff --git a/services/agent-proxy/src/lib/constants.ts b/services/agent-proxy/src/lib/constants.ts
index 177e343993d3..abb1f13577e2 100644
--- a/services/agent-proxy/src/lib/constants.ts
+++ b/services/agent-proxy/src/lib/constants.ts
@@ -13,6 +13,10 @@ export const STREAM_TTL_SECONDS = 6 * 60 * 60 // 21600
// (mirrors SANDBOX_EVENT_INGEST_TOKEN_TTL in connection_token.py).
export const SEQUENCE_TTL_SECONDS = STREAM_TTL_SECONDS + 3600 // 25200
+// Drain window for a stream after its terminal sentinel
+// (mirrors TASK_RUN_STREAM_COMPLETED_TIMEOUT in redis_stream.py).
+export const STREAM_COMPLETED_TTL_SECONDS = Math.min(30 * 60, Math.floor(STREAM_TTL_SECONDS / 3)) // 1800
+
// Redis XADD MAXLEN ~ (approximate trim, not exact).
export const STREAM_MAX_LENGTH = 5_000
diff --git a/services/agent-proxy/src/lib/redis-stream.ts b/services/agent-proxy/src/lib/redis-stream.ts
index 51d5d7948005..04b9cb13e171 100644
--- a/services/agent-proxy/src/lib/redis-stream.ts
+++ b/services/agent-proxy/src/lib/redis-stream.ts
@@ -12,6 +12,7 @@ import {
BLOCK_MS,
READ_COUNT,
SEQUENCE_TTL_SECONDS,
+ STREAM_COMPLETED_TTL_SECONDS,
STREAM_MAX_LENGTH,
STREAM_PREFIX,
STREAM_TTL_SECONDS,
@@ -126,6 +127,7 @@ export class TaskRunRedisStream {
private readonly redis: Redis
private readonly timeout: number
private readonly sequenceTimeout: number
+ private readonly completedTimeout: number
private readonly maxLength: number
constructor(
@@ -141,6 +143,7 @@ export class TaskRunRedisStream {
this.timeout = opts?.timeout ?? STREAM_TTL_SECONDS
// sequence key TTL must be at least timeout + SEQUENCE_TTL_SECONDS
this.sequenceTimeout = Math.max(this.timeout, SEQUENCE_TTL_SECONDS)
+ this.completedTimeout = Math.min(this.timeout, STREAM_COMPLETED_TTL_SECONDS)
this.maxLength = opts?.maxLength ?? STREAM_MAX_LENGTH
}
@@ -344,10 +347,10 @@ export class TaskRunRedisStream {
// XADD + EXPIRE; no sequence check. Returns Redis stream ID string.
// Refreshes TTL on every write (sliding window).
- async writeEvent(event: Record<string, unknown>): Promise<string> {
+ async writeEvent(event: Record<string, unknown>, ttl?: number): Promise<string> {
const raw = JSON.stringify(event)
const streamId = await this.redis.xadd(this.streamKey, 'MAXLEN', '~', this.maxLength, '*', 'data', raw)
- await this.redis.expire(this.streamKey, this.timeout)
+ await this.redis.expire(this.streamKey, ttl ?? this.timeout)
return normalizeStreamId(streamId)
}
@@ -470,12 +473,13 @@ export class TaskRunRedisStream {
const completedExists = (await this.redis.exists(completedKey)) > 0
if (completedExists) {
await this.redis.unwatch()
+ await this.redis.expire(this.streamKey, this.completedTimeout)
return
}
const pipeline = this.redis.multi()
pipeline.xadd(this.streamKey, 'MAXLEN', '~', this.maxLength, '*', 'data', raw)
- pipeline.expire(this.streamKey, this.timeout)
+ pipeline.expire(this.streamKey, this.completedTimeout)
pipeline.set(completedKey, '1', 'EX', this.sequenceTimeout)
const results = await pipeline.exec()
@@ -506,6 +510,7 @@ export class TaskRunRedisStream {
if (completedExists) {
await this.redis.unwatch()
+ await this.redis.expire(this.streamKey, this.completedTimeout)
return
}
@@ -518,7 +523,7 @@ export class TaskRunRedisStream {
const pipeline = this.redis.multi()
pipeline.xadd(this.streamKey, 'MAXLEN', '~', this.maxLength, '*', 'data', raw)
- pipeline.expire(this.streamKey, this.timeout)
+ pipeline.expire(this.streamKey, this.completedTimeout)
// Only EXPIRE the sequence key if it existed before the transaction;
// matches Python: `if last_sequence_raw is not None: pipe.expire(sequence_key, ...)`
if (seqKeyExisted) {
@@ -539,7 +544,11 @@ export class TaskRunRedisStream {
// No WATCH/MULTI. XADD error sentinel, truncated to 500 chars.
async markError(error: string): Promise<void> {
- await this.writeEvent({ type: 'STREAM_STATUS', status: 'error', error: error.slice(0, 500) })
+ await this.writeEvent(
+ { type: 'STREAM_STATUS', status: 'error', error: error.slice(0, 500) },
+ this.completedTimeout
+ )
+ await this.redis.set(getCompletedKey(this.streamKey), '1', 'EX', this.sequenceTimeout)
}
async deleteStream(): Promise<boolean> {
diff --git a/services/agent-proxy/tests/lib/redis-stream.test.ts b/services/agent-proxy/tests/lib/redis-stream.test.ts
index 31aa7999f8ba..0bba0402f775 100644
--- a/services/agent-proxy/tests/lib/redis-stream.test.ts
+++ b/services/agent-proxy/tests/lib/redis-stream.test.ts
@@ -11,6 +11,7 @@
import { describe, it, expect } from 'vitest'
+import { STREAM_COMPLETED_TTL_SECONDS } from '@/lib/constants.js'
import {
TaskRunRedisStream,
getStreamKey,
@@ -668,7 +669,7 @@ describe('redis-stream', () => {
expect(data).toHaveLength(1)
})
- it('refreshes stream TTL on completion', async () => {
+ it('drops stream TTL to the drain window on completion', async () => {
const { stream, redis, streamKey } = newStream()
await stream.markComplete()
@@ -676,6 +677,20 @@ describe('redis-stream', () => {
const exp = redis.getExpiryMs(streamKey)
expect(exp).not.toBeNull()
expect(exp!).toBeGreaterThan(Date.now())
+ expect(exp!).toBeLessThanOrEqual(Date.now() + STREAM_COMPLETED_TTL_SECONDS * 1000)
+ })
+
+ it('drops stream TTL to the drain window when already completed', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.writeEvent({ type: 'msg' })
+ await redis.set(getCompletedKey(streamKey), '1')
+
+ await stream.markComplete()
+
+ const exp = redis.getExpiryMs(streamKey)
+ expect(exp).not.toBeNull()
+ expect(exp!).toBeLessThanOrEqual(Date.now() + STREAM_COMPLETED_TTL_SECONDS * 1000)
})
})
@@ -774,7 +789,7 @@ describe('redis-stream', () => {
expect((error as string).length).toBe(500)
})
- it('refreshes stream TTL when writing the error sentinel', async () => {
+ it('drops stream TTL to the drain window when writing the error sentinel', async () => {
const { stream, redis, streamKey } = newStream()
await stream.markError('oops')
@@ -782,6 +797,18 @@ describe('redis-stream', () => {
const exp = redis.getExpiryMs(streamKey)
expect(exp).not.toBeNull()
expect(exp!).toBeGreaterThan(Date.now())
+ expect(exp!).toBeLessThanOrEqual(Date.now() + STREAM_COMPLETED_TTL_SECONDS * 1000)
+ })
+
+ it('sets the completed key so later sequenced writes are rejected', async () => {
+ const { stream, redis, streamKey } = newStream()
+
+ await stream.markError('oops')
+
+ expect(redis.getStringValue(getCompletedKey(streamKey))).toBe('1')
+ await expect(stream.writeEventWithSequence({ type: 'late' }, 1)).rejects.toThrow(
+ TaskRunStreamAlreadyCompleted
+ )
})
})