: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
feat(tasks): serve stream backlog from the run log behind a thin-tail gate (#94383)
Alessandro Pogliaghicb4188b081d2
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex a40bf3162284..8a986faf5eb5 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -180,6 +180,18 @@ TASK_RUN_LOGS_MIRROR_OTLP_URL: str | None = get_from_env("TASK_RUN_LOGS_MIRROR_OTASK_RUN_LOGS_MIRROR_OTLP_TOKEN: str | None = get_from_env("TASK_RUN_LOGS_MIRROR_OTLP_TOKEN", None, optional=True)TASK_RUN_STREAM_PRESENCE_GATED_ORIGINS: list[str] = get_list(os.getenv("TASK_RUN_STREAM_PRESENCE_GATED_ORIGINS", ""))+TASK_RUN_STREAM_THIN_TAIL_ORIGINS: list[str] = get_list(os.getenv("TASK_RUN_STREAM_THIN_TAIL_ORIGINS", ""))+# Connect-time backlog replay parses the whole run log in worker memory; past this+# byte cap the connection degrades to the plain Redis window instead.+TASK_RUN_STREAM_BACKLOG_MAX_BYTES: int = get_from_env(+ "TASK_RUN_STREAM_BACKLOG_MAX_BYTES", 50 * 1024 * 1024, type_cast=int+)+# Total log bytes one worker process replays concurrently across connections; a+# connection past the budget gets a retryable error frame instead of a replay.+# Must exceed TASK_RUN_STREAM_BACKLOG_MAX_BYTES or a single large log can never replay.+TASK_RUN_STREAM_BACKLOG_INFLIGHT_MAX_BYTES: int = get_from_env(+ "TASK_RUN_STREAM_BACKLOG_INFLIGHT_MAX_BYTES", 256 * 1024 * 1024, type_cast=int+)TEMPORAL_LOG_LEVEL_PRODUCE: str = os.getenv("TEMPORAL_LOG_LEVEL_PRODUCE", "DEBUG")TEMPORAL_EXTERNAL_LOGS_QUEUE_SIZE: int = get_from_env("TEMPORAL_EXTERNAL_LOGS_QUEUE_SIZE", 0, type_cast=int)diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex bd0c0424cccc..71cd911a1ffd 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -264,6 +264,9 @@ __all__ = ["presign_task_run_artifact","presign_task_run_artifact_download","read_task_run_artifact",+ "get_task_run_log_urls",+ "get_task_run_log_size",+ "read_task_run_log_content","read_task_run_logs","record_comment_activity","signal_task_run_client_activity",@@ -2197,6 +2200,7 @@ _PROTECTED_RUN_STATE_KEYS = frozenset(AGENT_OTEL_TELEMETRY_STATE_KEY,"sandbox_event_ingest_enabled","stream_presence_gated",+ "stream_thin_tail",PR_LOOP_ENABLED_STATE_KEY,"snapshot_external_id","snapshot_kind",@@ -3783,19 +3787,43 @@ def report_task_analysis_insight(run_id: str | UUID, task_id: str | UUID, team_idef read_task_run_logs(run_id: str | UUID, task_id: str | UUID, team_id: int) -> str | None:"""Concatenated JSONL logs across the run's resume chain (oldest ancestor first)."""- from posthog.storage import object_storage # noqa: PLC0415 — keep storage deps off the api import path+ log_urls = get_task_run_log_urls(run_id, task_id, team_id)+ if log_urls is None:+ return None+ return read_task_run_log_content(log_urls)++def get_task_run_log_urls(run_id: str | UUID, task_id: str | UUID, team_id: int) -> list[str] | None:+ """Log URLs across the run's resume chain (oldest ancestor first). ``None`` if the run isn't found."""run = _get_visible_run(run_id, task_id, team_id)if run is None:return None+ return [ancestor.log_url for ancestor in run.get_resume_chain()]+++def get_task_run_log_size(log_urls: list[str]) -> int:+ """Total byte size of the given log objects, without downloading them. Storage-only: safe off the request thread."""+ from posthog.storage import object_storage # noqa: PLC0415 — keep storage deps off the api import path++ def _size(log_url: str) -> int:+ head = object_storage.head_object(log_url)+ return int(head.get("ContentLength", 0)) if head else 0++ if len(log_urls) == 1:+ return _size(log_urls[0])+ return sum(_TASK_LOG_READ_EXECUTOR.map(_size, log_urls))+++def read_task_run_log_content(log_urls: list[str]) -> str:+ """Concatenated JSONL content for the given log URLs. Storage-only: safe off the request thread."""+ from posthog.storage import object_storage # noqa: PLC0415 — keep storage deps off the api import path- resume_chain = run.get_resume_chain()chunks: Iterable[str]- if len(resume_chain) == 1:- chunks = [object_storage.read(resume_chain[0].log_url, missing_ok=True) or ""]+ if len(log_urls) == 1:+ chunks = [object_storage.read(log_urls[0], missing_ok=True) or ""]else:chunks = _TASK_LOG_READ_EXECUTOR.map(- lambda ancestor: object_storage.read(ancestor.log_url, missing_ok=True) or "", resume_chain+ lambda log_url: object_storage.read(log_url, missing_ok=True) or "", log_urls)parts: list[str] = []diff --git a/products/tasks/backend/facade/metrics.py b/products/tasks/backend/facade/metrics.pyindex be5dd1178f4e..5e89b80600de 100644--- a/products/tasks/backend/facade/metrics.py+++ b/products/tasks/backend/facade/metrics.py@@ -8,6 +8,11 @@ view imports them from here rather than reaching the internal ``metrics`` modulefrom products.tasks.backend.metrics import (StreamConnectionOutcome,+ observe_stream_backlog_bytes,+ observe_stream_backlog_gap,+ observe_stream_backlog_oversized,+ observe_stream_backlog_served,+ observe_stream_backlog_throttled,observe_stream_connection_closed,observe_stream_connection_opened,observe_stream_length_on_connect,@@ -17,6 +22,11 @@ from products.tasks.backend.metrics import (__all__ = ["StreamConnectionOutcome",+ "observe_stream_backlog_bytes",+ "observe_stream_backlog_gap",+ "observe_stream_backlog_oversized",+ "observe_stream_backlog_served",+ "observe_stream_backlog_throttled","observe_stream_connection_closed","observe_stream_connection_opened","observe_stream_length_on_connect",diff --git a/products/tasks/backend/facade/streams.py b/products/tasks/backend/facade/streams.pyindex 4fb9ae09d25d..002d1f071237 100644--- a/products/tasks/backend/facade/streams.py+++ b/products/tasks/backend/facade/streams.py@@ -7,7 +7,8 @@ stream client. The SSE stream view also reads the connection-wait tuning constandedicated-stream flag helper from here."""-from products.tasks.backend.feature_flags import run_stream_presence_gated+from products.tasks.backend.feature_flags import run_stream_presence_gated, run_stream_thin_tail+from products.tasks.backend.logic.stream.backlog import TaskRunStreamBacklogIndex, format_log_cursor, parse_log_cursorfrom products.tasks.backend.logic.stream.event_ingest import handle_task_run_event_ingestfrom products.tasks.backend.logic.stream.redis_stream import (TASK_RUN_STREAM_WAIT_DELAY_INCREMENT_SECONDS,@@ -29,10 +30,14 @@ __all__ = ["TASK_RUN_STREAM_WAIT_TIMEOUT_SECONDS","TASK_RUN_STREAM_WATCHED_REFRESH_INTERVAL_SECONDS","TaskRunRedisStream",+ "TaskRunStreamBacklogIndex","TaskRunStreamError",+ "format_log_cursor","get_task_run_stream_key","handle_task_run_event_ingest",+ "parse_log_cursor","reset_task_run_stream","run_stream_presence_gated",+ "run_stream_thin_tail","run_uses_dedicated_stream",]diff --git a/products/tasks/backend/feature_flags.py b/products/tasks/backend/feature_flags.pyindex 72c428b7d7ba..febf4ca79691 100644--- a/products/tasks/backend/feature_flags.py+++ b/products/tasks/backend/feature_flags.py@@ -75,6 +75,15 @@ def run_stream_presence_gated(state: dict | None) -> bool:return bool((state or {}).get("stream_presence_gated", False))+def is_task_run_stream_thin_tail(origin_product: str) -> bool:+ return origin_product in settings.TASK_RUN_STREAM_THIN_TAIL_ORIGINS+++def run_stream_thin_tail(state: dict | None) -> bool:+ """Pinned onto TaskRun.state at creation so writers and readers agree for the run's life; absent means full tail."""+ return bool((state or {}).get("stream_thin_tail", False))++def is_dev_stack_image_bake_enabled() -> bool:"""Gates the nightly prebaked dev-stack image bake (a paid Modal VM run per tick).diff --git a/products/tasks/backend/logic/services/connection_token.py b/products/tasks/backend/logic/services/connection_token.pyindex 530e4acf052f..398f5d715a79 100644--- a/products/tasks/backend/logic/services/connection_token.py+++ b/products/tasks/backend/logic/services/connection_token.py@@ -12,7 +12,7 @@ import jwtfrom cryptography.hazmat.backends import default_backendfrom cryptography.hazmat.primitives import serialization-from products.tasks.backend.feature_flags import run_stream_presence_gated+from products.tasks.backend.feature_flags import run_stream_presence_gated, run_stream_thin_tailfrom products.tasks.backend.logic.services.sandbox_config import SANDBOX_TTL_SECONDSif TYPE_CHECKING:@@ -41,6 +41,7 @@ class SandboxEventIngestTokenPayload:team_id: intsandbox_id: str | Nonepresence_gated: bool = False+ thin_tail: bool = Falseorigin_product: str | None = None@@ -266,6 +267,7 @@ def create_sandbox_event_ingest_token(if not isinstance(active_sandbox_id, str) or not active_sandbox_id:raise ValueError("Task run has no active sandbox identity")presence_gated = run_stream_presence_gated(task_run.state)+ thin_tail = run_stream_thin_tail(task_run.state)return _encode_run_scoped_token(task_run,SANDBOX_EVENT_INGEST_AUDIENCE,@@ -273,6 +275,7 @@ def create_sandbox_event_ingest_token({"sandbox_id": active_sandbox_id,"presence_gated": presence_gated,+ "thin_tail": thin_tail,"origin_product": task_run.task.origin_product,},)@@ -286,6 +289,7 @@ def validate_sandbox_event_ingest_token(token: str) -> SandboxEventIngestTokenPateam_id = payload.get("team_id")sandbox_id = payload.get("sandbox_id")presence_gated = payload.get("presence_gated", False)+ thin_tail = payload.get("thin_tail", 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:@@ -294,6 +298,8 @@ def validate_sandbox_event_ingest_token(token: str) -> SandboxEventIngestTokenParaise jwt.InvalidTokenError("Sandbox event ingest token has invalid claims")if not isinstance(presence_gated, bool):raise jwt.InvalidTokenError("Sandbox event ingest token has invalid claims")+ if not isinstance(thin_tail, bool):+ raise jwt.InvalidTokenError("Sandbox event ingest token has invalid claims")if origin_product is not None and not isinstance(origin_product, str):raise jwt.InvalidTokenError("Sandbox event ingest token has invalid claims")@@ -303,6 +309,7 @@ def validate_sandbox_event_ingest_token(token: str) -> SandboxEventIngestTokenPateam_id=team_id,sandbox_id=sandbox_id,presence_gated=presence_gated,+ thin_tail=thin_tail,origin_product=origin_product,)diff --git a/products/tasks/backend/logic/stream/backlog.py b/products/tasks/backend/logic/stream/backlog.pynew file mode 100644index 000000000000..b73fb5257250--- /dev/null+++ b/products/tasks/backend/logic/stream/backlog.py@@ -0,0 +1,98 @@+"""Connect-time merge support for thin-tail task run streams.++A thin-tail run keeps only a short live tail in Redis and serves history from+the durable run log. The agent stamps a shared ``event_id`` on each event in+both stores (format ``<boot>-<seq>``: a random per-boot prefix and a counter+monotonic within that boot). A log entry coalesced from a run of chunk events+carries the covered range as ``first_event_id``..``event_id``.++``TaskRunStreamBacklogIndex`` collects the ids (and ranges) present in the log+backlog so the SSE view can drop live-tail entries the backlog already covers.+Entries without ids (older agents, server-published events) are never dropped.+"""++TASK_RUN_STREAM_LOG_CURSOR_PREFIX = "log-"+++def _parse_event_id(event_id: str) -> tuple[str, int] | None:+ boot, _, seq = event_id.rpartition("-")+ if not boot:+ return None+ try:+ return boot, int(seq)+ except ValueError:+ return None+++def parse_log_cursor(last_event_id: str) -> int | None:+ """Index of the last served backlog entry, or ``None`` for any other cursor.++ Accepts only what ``format_log_cursor`` emits: plain non-negative ASCII+ decimals. ``int()`` alone would also take signs, whitespace, underscores and+ non-ASCII digits, turning a caller-supplied header into a negative or+ out-of-range list index downstream.+ """+ if not last_event_id.startswith(TASK_RUN_STREAM_LOG_CURSOR_PREFIX):+ return None+ suffix = last_event_id[len(TASK_RUN_STREAM_LOG_CURSOR_PREFIX) :]+ if not suffix.isascii() or not suffix.isdigit():+ return None+ return int(suffix)+++def format_log_cursor(index: int) -> str:+ return f"{TASK_RUN_STREAM_LOG_CURSOR_PREFIX}{index}"+++class TaskRunStreamBacklogIndex:+ def __init__(self, entries: list[dict]) -> None:+ self._ids: set[str] = set()+ self._ranges: dict[str, list[tuple[int, int]]] = {}+ for entry in entries:+ event_id = entry.get("event_id")+ if not isinstance(event_id, str) or not event_id:+ continue+ self._ids.add(event_id)+ first_event_id = entry.get("first_event_id")+ if not isinstance(first_event_id, str) or not first_event_id:+ continue+ first = _parse_event_id(first_event_id)+ last = _parse_event_id(event_id)+ if first is None or last is None or first[0] != last[0]:+ self._ids.add(first_event_id)+ continue+ self._ranges.setdefault(first[0], []).append((first[1], last[1]))++ def covers(self, event: dict) -> bool:+ event_id = event.get("event_id")+ if not isinstance(event_id, str) or not event_id:+ return False+ if event_id in self._ids:+ return True+ parsed = _parse_event_id(event_id)+ if parsed is None:+ return False+ return self._covers_parsed(*parsed)++ def has_gap_before(self, event: dict) -> bool:+ """True when the event's per-boot predecessor is missing from the log backlog.++ Meaningful only for the first id-carrying live entry the backlog does not+ cover: a hole before it means Redis evicted events whose log batch never+ landed, which is the one loss mode thin-tail trimming cannot rule out.+ """+ event_id = event.get("event_id")+ if not isinstance(event_id, str) or not event_id:+ return False+ parsed = _parse_event_id(event_id)+ if parsed is None:+ return False+ boot, seq = parsed+ if seq <= 1:+ return False+ return not self._covers_parsed(boot, seq - 1)++ def _covers_parsed(self, boot: str, seq: int) -> bool:+ if f"{boot}-{seq}" in self._ids:+ return True+ return any(lo <= seq <= hi for lo, hi in self._ranges.get(boot, ()))diff --git a/products/tasks/backend/logic/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.pyindex e3c3710abbea..5fe006a11fe7 100644--- a/products/tasks/backend/logic/stream/event_ingest.py+++ b/products/tasks/backend/logic/stream/event_ingest.py@@ -129,6 +129,7 @@ async def handle_task_run_event_ingest(scope: ASGIMessage, receive: ASGIReceive,redis_stream = TaskRunRedisStream(get_task_run_stream_key(claims.run_id),presence_gated=claims.presence_gated,+ thin_tail=claims.thin_tail,origin_product=claims.origin_product,)diff --git a/products/tasks/backend/logic/stream/redis_stream.py b/products/tasks/backend/logic/stream/redis_stream.pyindex ea9228d2a66d..06a56563c03c 100644--- a/products/tasks/backend/logic/stream/redis_stream.py+++ b/products/tasks/backend/logic/stream/redis_stream.py@@ -21,6 +21,10 @@ logger = structlog.get_logger(__name__)# Keep enough live history for users who open an in-progress run late while# still bounding Redis growth to the sandbox lifetime.TASK_RUN_STREAM_MAX_LENGTH = 5_000+# Thin-tail runs serve connect-time backlog from the durable run log, so Redis+# only needs a live tail. Applied per write, and only to id-carrying events, so+# a run on an agent that predates event ids keeps the full window.+TASK_RUN_STREAM_THIN_MAX_LENGTH = 500TASK_RUN_STREAM_TIMEOUT = SANDBOX_TTL_SECONDSTASK_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())@@ -168,6 +172,7 @@ class TaskRunRedisStream:max_length: int = TASK_RUN_STREAM_MAX_LENGTH,*,presence_gated: bool = False,+ thin_tail: bool = False,origin_product: str | None = None,):self._stream_key = stream_key@@ -177,6 +182,7 @@ class TaskRunRedisStream:self._completed_timeout = min(timeout, TASK_RUN_STREAM_COMPLETED_TIMEOUT)self._max_length = max_lengthself._presence_gated = presence_gated+ self._thin_tail = thin_tailself._origin_product = origin_productself._watched_cached_until = 0.0self._last_watched_refresh_at: float | None = None@@ -333,12 +339,17 @@ class TaskRunRedisStream:except redis_exceptions.RedisError:raise TaskRunStreamError("Stream read error")+ def _maxlen_for_event(self, event: dict) -> int:+ if self._thin_tail and event.get("event_id"):+ return TASK_RUN_STREAM_THIN_MAX_LENGTH+ return self._max_length+async def _xadd_event(self, event: dict, *, ttl: int | None = None) -> str:raw = json.dumps(event)stream_id = await self._redis_client.xadd(self._stream_key,{DATA_KEY: raw},- maxlen=self._max_length,+ maxlen=self._maxlen_for_event(event),approximate=True,)await self._redis_client.expire(self._stream_key, self._timeout if ttl is None else ttl)@@ -517,7 +528,7 @@ class TaskRunRedisStream:pipe.xadd(self._stream_key,{DATA_KEY: json.dumps(event)},- maxlen=self._max_length,+ maxlen=self._maxlen_for_event(event),approximate=True,)pipe.expire(self._stream_key, self._timeout)diff --git a/products/tasks/backend/logic/stream/tests/test_backlog.py b/products/tasks/backend/logic/stream/tests/test_backlog.pynew file mode 100644index 000000000000..42ffb79b9153--- /dev/null+++ b/products/tasks/backend/logic/stream/tests/test_backlog.py@@ -0,0 +1,73 @@+from django.test import SimpleTestCase++from parameterized import parameterized++from products.tasks.backend.logic.stream.backlog import TaskRunStreamBacklogIndex, format_log_cursor, parse_log_cursor+++class TestLogCursor(SimpleTestCase):+ @parameterized.expand(+ [+ ("log_cursor", "log-0", 0),+ ("log_cursor_large", "log-1234", 1234),+ ("redis_id", "1725370000000-0", None),+ ("malformed_index", "log-abc", None),+ ("empty", "", None),+ ("negative", "log--100", None),+ ("signed", "log-+7", None),+ ("underscored", "log-1_0", None),+ ("whitespace", "log- 1", None),+ ("non_ascii_digit", "log-١", None),+ ]+ )+ def test_parse_log_cursor(self, _name: str, cursor: str, expected: int | None) -> None:+ assert parse_log_cursor(cursor) == expected++ def test_format_round_trips(self) -> None:+ assert parse_log_cursor(format_log_cursor(42)) == 42+++class TestTaskRunStreamBacklogIndex(SimpleTestCase):+ def test_covers_exact_ids_and_coalesced_ranges(self) -> None:+ index = TaskRunStreamBacklogIndex(+ [+ {"type": "notification", "event_id": "boot1-10"},+ {"type": "notification", "event_id": "boot1-20", "first_event_id": "boot1-14"},+ {"type": "notification"},+ ]+ )++ assert index.covers({"event_id": "boot1-10"})+ assert index.covers({"event_id": "boot1-14"})+ assert index.covers({"event_id": "boot1-17"})+ assert index.covers({"event_id": "boot1-20"})+ assert not index.covers({"event_id": "boot1-13"})+ assert not index.covers({"event_id": "boot1-21"})+ assert not index.covers({"event_id": "boot2-17"})+ assert not index.covers({"type": "notification"})+ assert not index.covers({"event_id": ""})++ def test_range_across_boot_prefixes_falls_back_to_exact_ids(self) -> None:+ index = TaskRunStreamBacklogIndex(+ [{"type": "notification", "event_id": "boot2-3", "first_event_id": "boot1-90"}]+ )++ assert index.covers({"event_id": "boot1-90"})+ assert index.covers({"event_id": "boot2-3"})+ assert not index.covers({"event_id": "boot1-91"})+ assert not index.covers({"event_id": "boot2-1"})++ def test_has_gap_before(self) -> None:+ index = TaskRunStreamBacklogIndex(+ [+ {"type": "notification", "event_id": "boot1-10"},+ {"type": "notification", "event_id": "boot1-20", "first_event_id": "boot1-14"},+ ]+ )++ assert not index.has_gap_before({"event_id": "boot1-11"}) # predecessor is an exact id+ assert not index.has_gap_before({"event_id": "boot1-21"}) # predecessor closes a range+ assert index.has_gap_before({"event_id": "boot1-13"}) # boot1-12 is in neither store+ assert index.has_gap_before({"event_id": "boot2-5"}) # unknown boot, mid-sequence+ assert not index.has_gap_before({"event_id": "boot2-1"}) # a boot's first event has no predecessor+ assert not index.has_gap_before({"type": "notification"}) # unstamped entries carry no signaldiff --git a/products/tasks/backend/logic/stream/tests/test_redis_stream.py b/products/tasks/backend/logic/stream/tests/test_redis_stream.pyindex 8d309607f22e..5a5e2e70030d 100644--- a/products/tasks/backend/logic/stream/tests/test_redis_stream.py+++ b/products/tasks/backend/logic/stream/tests/test_redis_stream.py@@ -431,3 +431,35 @@ async def test_resume_point_trimmed_false_when_stream_empty() -> None:assert await redis_stream.resume_point_trimmed("123-0") is Falsefinally:await redis_stream.delete_stream()+++async def test_thin_tail_trims_only_id_carrying_events() -> None:+ redis_stream = TaskRunRedisStream(f"task-run-stream:test:{uuid4()}", thin_tail=True)+ try:+ with patch("products.tasks.backend.logic.stream.redis_stream.TASK_RUN_STREAM_THIN_MAX_LENGTH", 2):+ for sequence in range(1, 5):+ await redis_stream.write_event_with_sequence(+ {"type": "notification", "event_id": f"boot1-{sequence}"}, sequence+ )+ events = await _read_stream_events(redis_stream)+ assert [event["event_id"] for event in events] == ["boot1-3", "boot1-4"]++ await redis_stream.write_event_with_sequence({"type": "notification"}, 5)+ assert len(await _read_stream_events(redis_stream)) == 3+ finally:+ await redis_stream.delete_stream()+++async def test_thin_tail_off_keeps_full_window_for_id_carrying_events() -> None:+ redis_stream = _new_stream()+ try:+ with patch("products.tasks.backend.logic.stream.redis_stream.TASK_RUN_STREAM_THIN_MAX_LENGTH", 2):+ for sequence in range(1, 5):+ await redis_stream.write_event_with_sequence(+ {"type": "notification", "event_id": f"boot1-{sequence}"}, sequence+ )+ assert len(await _read_stream_events(redis_stream)) == 4+ finally:+ await redis_stream.delete_stream()diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.pyindex ad8b70eef71c..f63cd8c866e2 100644--- a/products/tasks/backend/metrics.py+++ b/products/tasks/backend/metrics.py@@ -23,7 +23,18 @@ DevStackImageBakeOutcome = Literal["succeeded", "bake_failed", "failed", "dispat# 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", "drained", "client_disconnect", "rotated"]+# backlog_error — run-log read for connect-time backlog failed; client retries+# backlog_busy — worker at its in-flight replay byte budget; client retries+StreamConnectionOutcome = Literal[+ "completed",+ "stream_error",+ "unavailable",+ "drained",+ "client_disconnect",+ "rotated",+ "backlog_error",+ "backlog_busy",+]StreamWriteSkippedPath = Literal["ingest", "mirror", "relay"]_ALLOWED_MODES = {"background", "interactive"}_ALLOWED_RUN_SOURCES = {"manual", "signal_report"}@@ -222,6 +233,48 @@ TASK_RUN_STREAM_CONNECTIONS_OPENED_TOTAL = Counter(labelnames=["origin_product"],)+TASK_RUN_STREAM_BACKLOG_ENTRIES_TOTAL = Counter(+ "posthog_tasks_task_run_stream_backlog_entries_total",+ "Run-log entries served as connect-time backlog on thin-tail SSE stream connections",+ labelnames=["origin_product"],+)++TASK_RUN_STREAM_BACKLOG_GAP_TOTAL = Counter(+ "posthog_tasks_task_run_stream_backlog_gap_total",+ "Thin-tail SSE connections whose first uncovered live entry was not contiguous with the log backlog",+ labelnames=["origin_product"],+)++STREAM_BACKLOG_BYTES_BUCKETS = [+ 65_536.0,+ 262_144.0,+ 1_048_576.0,+ 4_194_304.0,+ 16_777_216.0,+ 52_428_800.0,+ 134_217_728.0,+ 536_870_912.0,+]++TASK_RUN_STREAM_BACKLOG_BYTES = Histogram(+ "posthog_tasks_task_run_stream_backlog_bytes",+ "Run-log byte size measured before a connect-time backlog replay on thin-tail SSE stream connections",+ labelnames=["origin_product"],+ buckets=STREAM_BACKLOG_BYTES_BUCKETS,+)++TASK_RUN_STREAM_BACKLOG_OVERSIZED_TOTAL = Counter(+ "posthog_tasks_task_run_stream_backlog_oversized_total",+ "Thin-tail SSE connections whose run log exceeded the backlog byte cap and degraded to the Redis window",+ labelnames=["origin_product"],+)++TASK_RUN_STREAM_BACKLOG_THROTTLED_TOTAL = Counter(+ "posthog_tasks_task_run_stream_backlog_throttled_total",+ "Thin-tail SSE connections refused a backlog replay because the worker's in-flight replay byte budget was full",+ labelnames=["origin_product"],+)+TASK_RUN_STREAM_CONNECTIONS_CLOSED_TOTAL = Counter("posthog_tasks_task_run_stream_connections_closed_total","SSE task-run stream connections closed, labeled by how they ended",@@ -577,6 +630,27 @@ def observe_stream_connection_opened(origin_product: str) -> None:TASK_RUN_STREAM_CONNECTIONS_OPENED_TOTAL.labels(origin_product=origin_product).inc()+def observe_stream_backlog_served(origin_product: str, entries: int) -> None:+ if entries > 0:+ TASK_RUN_STREAM_BACKLOG_ENTRIES_TOTAL.labels(origin_product=origin_product).inc(entries)+++def observe_stream_backlog_gap(origin_product: str) -> None:+ TASK_RUN_STREAM_BACKLOG_GAP_TOTAL.labels(origin_product=origin_product).inc()+++def observe_stream_backlog_bytes(origin_product: str, size_bytes: int) -> None:+ TASK_RUN_STREAM_BACKLOG_BYTES.labels(origin_product=origin_product).observe(size_bytes)+++def observe_stream_backlog_oversized(origin_product: str) -> None:+ TASK_RUN_STREAM_BACKLOG_OVERSIZED_TOTAL.labels(origin_product=origin_product).inc()+++def observe_stream_backlog_throttled(origin_product: str) -> None:+ TASK_RUN_STREAM_BACKLOG_THROTTLED_TOTAL.labels(origin_product=origin_product).inc()++def observe_stream_connection_closed(origin_product: str, outcome: StreamConnectionOutcome, duration_seconds: float) -> None:diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 1aa454088eb5..b2cd1fda596f 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -43,7 +43,11 @@ from posthog.uuidt import uuid7from products.tasks.backend.constants import DEFAULT_TRUSTED_DOMAINS, PR_LOOP_ENABLED_STATE_KEYfrom products.tasks.backend.error_telemetry import truncate_error_message-from products.tasks.backend.feature_flags import is_task_run_stream_presence_gated, run_stream_presence_gated+from products.tasks.backend.feature_flags import (+ is_task_run_stream_presence_gated,+ is_task_run_stream_thin_tail,+ run_stream_presence_gated,+)from products.tasks.backend.logic.stream.redis_stream import publish_task_run_stream_eventfrom products.tasks.backend.metrics import observe_task_run_created, observe_task_run_dispatch_callbackfrom products.tasks.backend.pr_urls import read_pr_urls@@ -760,6 +764,12 @@ class Task(DeletedMetaFields, models.Model):# Pin the stream-routing decision once so every reader/writer agrees for this run's life.state.setdefault("use_dedicated_stream", dedicated_stream)state.setdefault("stream_presence_gated", is_task_run_stream_presence_gated(task.origin_product))+ # Pi tasks are forced onto the agent-proxy read leg, which serves Redis only —+ # no durable backlog — so they must keep the full live window.+ state.setdefault(+ "stream_thin_tail",+ task.runtime != Task.Runtime.PI and is_task_run_stream_thin_tail(task.origin_product),+ )is_resume = bool(resume_from_run_id)has_pending = _has_pending_user_input(extra_state or {})stamp_pending_user_message_id(state)diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex cbd9595896fd..14c50542b340 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -81,6 +81,11 @@ from products.tasks.backend.facade.compute_quota import ComputeBillingLimitExceefrom products.tasks.backend.facade.contracts import TaskAnalysisErrorfrom products.tasks.backend.facade.metrics import (StreamConnectionOutcome,+ observe_stream_backlog_bytes,+ observe_stream_backlog_gap,+ observe_stream_backlog_oversized,+ observe_stream_backlog_served,+ observe_stream_backlog_throttled,observe_stream_connection_closed,observe_stream_connection_opened,observe_stream_length_on_connect,@@ -94,9 +99,13 @@ from products.tasks.backend.facade.streams import (TASK_RUN_STREAM_WAIT_MAX_DELAY_SECONDS,TASK_RUN_STREAM_WAIT_TIMEOUT_SECONDS,TaskRunRedisStream,+ TaskRunStreamBacklogIndex,TaskRunStreamError,+ format_log_cursor,get_task_run_stream_key,+ parse_log_cursor,run_stream_presence_gated,+ run_stream_thin_tail,run_uses_dedicated_stream,)from products.tasks.backend.presentation.serializers import (@@ -253,6 +262,43 @@ TASK_RUN_STREAM_ROTATED_PAYLOAD = {"type": "rotated"}# Distinct from the rotation `end` event above: this fires once when the run itself# completes, so clients stop reconnecting instead of resuming from Last-Event-ID.TASK_RUN_STREAM_COMPLETE_EVENT_NAME = "stream-end"+# A backlog replay holds its whole parsed run log in memory for the length of the+# replay, and SSE admission is shared across endpoints with no per-user bound, so+# concurrent replays are budgeted by byte size per process. All mutation happens+# on the event loop with no await between check and update, so a plain int is safe.+_backlog_inflight_bytes = 0+++def _try_reserve_backlog_bytes(size_bytes: int) -> bool:+ global _backlog_inflight_bytes+ if _backlog_inflight_bytes + size_bytes > settings.TASK_RUN_STREAM_BACKLOG_INFLIGHT_MAX_BYTES:+ return False+ _backlog_inflight_bytes += size_bytes+ return True+++def _release_backlog_bytes(size_bytes: int) -> None:+ global _backlog_inflight_bytes+ _backlog_inflight_bytes -= size_bytes+++def _parse_backlog(log_content: str) -> tuple[list[dict], TaskRunStreamBacklogIndex]:+ # Runs via asyncio.to_thread: parsing a log at the byte cap takes long+ # enough to stall every other stream on the ASGI event loop.+ entries: list[dict] = []+ for log_line in log_content.splitlines():+ log_line = log_line.strip()+ if not log_line:+ continue+ try:+ parsed_line = json.loads(log_line)+ except json.JSONDecodeError:+ continue+ if isinstance(parsed_line, dict):+ entries.append(parsed_line)+ return entries, TaskRunStreamBacklogIndex(entries)++TASK_RUN_ARTIFACT_UPLOAD_EXPIRATION_SECONDS = 60 * 60@@ -2617,13 +2663,21 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)def stream_token(self, request, pk=None, **kwargs):task_id = self._ensure_task_accessible()+ stream_info = tasks_facade.get_task_run_stream_info(pk, task_id, self.team_id)token = tasks_facade.create_task_run_stream_read_token(pk, task_id, self.team_id)- if token is None:+ if stream_info is None or token is None:raise NotFound()- stream_base_url = tasks_facade.resolve_stream_base_url(- distinct_id=request.user.distinct_id,- organization_id=self.team.organization_id,- force_proxy=tasks_facade.task_uses_pi_runtime(task_id, self.team_id),+ # Only the Django read leg serves the durable backlog, so thin-tail runs must+ # not be routed to the agent-proxy — a proxy reader would silently lose+ # everything behind the 500-entry live window.+ stream_base_url = (+ None+ if run_stream_thin_tail(stream_info.state)+ else tasks_facade.resolve_stream_base_url(+ distinct_id=request.user.distinct_id,+ organization_id=self.team.organization_id,+ force_proxy=tasks_facade.task_uses_pi_runtime(task_id, self.team_id),+ ))return Response(StreamReadTokenResponseSerializer({"token": token, "stream_base_url": stream_base_url}).data)@@ -3183,16 +3237,28 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):@extend_schema(description=("Server-Sent Events stream of task run events. Events carry an `id:` line "- "(a Redis stream id) usable as a resume cursor.\n\n"+ "(a Redis stream id, or a synthetic `log-<n>` id during backlog replay) usable as a "+ "resume cursor.\n\n"f"The server caps each connection at {TASK_RUN_STREAM_CONNECTION_MAX_SECONDS} seconds: it emits "'`event: end` with `data: {"type": "rotated"}` and closes. This does NOT mean the run '"finished — reconnect with the `Last-Event-ID` header set to the last received event id to "- "resume without gaps or duplicates. Only treat the stream as complete when the run itself "+ "resume. Only treat the stream as complete when the run itself ""reaches a terminal status.\n\n""Resume guarantees cover mirrored events only: on runs where live mirroring is ""presence-gated, events produced while no viewer was connected are not in the live stream. ""Reload the run's session logs to recover the agent's output; run-state and progress ""frames are not in those logs, so refetch the run itself for its current state.\n\n"+ "On runs with durable backlog serving, a connection without `Last-Event-ID` first replays "+ "history from the run log under synthetic `log-<n>` event ids, then attaches the live "+ "stream, skipping live entries the backlog already covered. Reconnecting with a `log-<n>` "+ "id resumes the backlog replay from that point; reconnecting with a Redis id resumes the "+ "live stream, may re-deliver a few events already served as backlog frames, and falls back "+ "to a full backlog replay when the resume point was trimmed or the stream expired. Runs "+ "whose log exceeds the backlog byte cap skip the replay and serve only the recent live "+ "window. When the backlog is temporarily unavailable (a storage read failure, or a worker "+ "at its concurrent replay budget), the stream emits an `event: error` frame and closes; "+ "reconnect with the same cursor to retry. Treat delivery as at-least-once across "+ "reconnects.\n\n""`?start=latest` consumers must also carry `Last-Event-ID` across reconnects: reconnecting ""without it re-resolves to the then-current latest event, silently skipping anything published ""while disconnected.\n\n"@@ -3241,6 +3307,20 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):run_is_terminal = stream_info.is_terminalrun_state_event = stream_info.state_event+ # Thin-tail runs keep only a short live tail in Redis; history is served+ # from the durable run log at connect time, under `log-<n>` event ids.+ # Only cheap resolution happens here — the log read and parse run inside+ # the generator, after SSE admission, off the event loop.+ thin_tail = run_stream_thin_tail(stream_info.state) and not start_latest+ backlog_serve_after: int | None = None+ backlog_log_urls: list[str] = []+ if thin_tail:+ if not last_event_id:+ backlog_serve_after = -1+ else:+ backlog_serve_after = parse_log_cursor(last_event_id)+ backlog_log_urls = tasks_facade.get_task_run_log_urls(pk, task_id, self.team_id) or []+async def async_stream() -> AsyncGenerator[bytes]:redis_stream = TaskRunRedisStream(stream_key, use_dedicated_stream)connection_started_at = asyncio.get_running_loop().time()@@ -3251,6 +3331,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):# the open succeeded — keeps opened/closed balanced for the# active-connections gauge regardless of which increment fails.opened = False+ resume_cursor = last_event_id+ serve_after = backlog_serve_after+ backlog_index: TaskRunStreamBacklogIndex | None = None+ backlog_contiguity_pending = Falsetry:observe_stream_connection_opened(origin_product)@@ -3260,6 +3344,109 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):last_keepalive_at = wait_started_atawait redis_stream.refresh_watched()+ if thin_tail and serve_after is None and resume_cursor:+ # A Redis-id reconnect whose resume point was trimmed — or+ # whose stream key expired entirely — would silently skip+ # the evicted interval; fall back to a full backlog replay+ # instead (at-least-once, per the endpoint description).+ # Best-effort: never break the stream.+ try:+ stream_exists = await redis_stream.exists()+ if not stream_exists or await redis_stream.resume_point_trimmed(resume_cursor):+ observe_stream_resume_gap(origin_product)+ logger.warning(+ "task_run_stream_resume_gap",+ extra={+ "stream_key": stream_key,+ "last_event_id": resume_cursor,+ "reason": "trimmed" if stream_exists else "expired",+ },+ )+ serve_after = -1+ except Exception:+ logger.warning(+ "task_run_stream_attach_observe_failed",+ extra={"stream_key": stream_key},+ exc_info=True,+ )++ if serve_after is not None:+ resume_cursor = None+ backlog_reserved = 0+ try:+ try:+ backlog_bytes = await asyncio.to_thread(+ tasks_facade.get_task_run_log_size, backlog_log_urls+ )+ observe_stream_backlog_bytes(origin_product, backlog_bytes)+ backlog_oversized = backlog_bytes > settings.TASK_RUN_STREAM_BACKLOG_MAX_BYTES+ if backlog_oversized:+ # Parsing a log past the byte cap risks the worker's+ # memory; degrade to the plain Redis window instead.+ observe_stream_backlog_oversized(origin_product)+ logger.warning(+ "task_run_stream_backlog_oversized",+ extra={"stream_key": stream_key, "backlog_bytes": backlog_bytes},+ )+ log_content = ""+ elif not _try_reserve_backlog_bytes(backlog_bytes):+ # The worker already holds its budget's worth of parsed+ # logs; refuse this replay so RSS stays bounded no matter+ # how many connections arrive. Transient — retryable.+ outcome = "backlog_busy"+ observe_stream_backlog_throttled(origin_product)+ logger.warning(+ "task_run_stream_backlog_throttled",+ extra={"stream_key": stream_key, "backlog_bytes": backlog_bytes},+ )+ yield format_sse_event({"error": "Backlog busy"}, event_name="error")+ return+ else:+ backlog_reserved = backlog_bytes+ log_content = await asyncio.to_thread(+ tasks_facade.read_task_run_log_content, backlog_log_urls+ )+ backlog_entries, backlog_index = await asyncio.to_thread(_parse_backlog, log_content)+ del log_content+ except Exception:+ outcome = "backlog_error"+ logger.exception("task_run_stream_backlog_read_failed", extra={"stream_key": stream_key})+ yield format_sse_event({"error": "Backlog unavailable"}, event_name="error")+ return+ # An oversized backlog serves nothing, so an empty index would+ # flag every stamped live entry as a false gap — skip the check.+ backlog_contiguity_pending = not backlog_oversized+ if serve_after >= len(backlog_entries):+ # Cursor beyond the loaded log: not one we issued — replay in full.+ serve_after = -1+ backlog_served = 0+ try:+ for backlog_position in range(serve_after + 1, len(backlog_entries)):+ yield format_sse_event(+ backlog_entries[backlog_position],+ event_id=format_log_cursor(backlog_position),+ )+ backlog_served += 1+ await redis_stream.refresh_watched()+ now = asyncio.get_running_loop().time()+ if now - connection_started_at >= TASK_RUN_STREAM_CONNECTION_MAX_SECONDS:+ outcome = "rotated"+ yield format_sse_event(+ TASK_RUN_STREAM_ROTATED_PAYLOAD,+ event_name=TASK_RUN_STREAM_END_EVENT_NAME,+ )+ return+ finally:+ # In a finally so a client that goes away mid-replay still+ # counts the frames it was sent.+ observe_stream_backlog_served(origin_product, backlog_served)+ backlog_entries.clear()+ finally:+ # Covers every exit — replay done, rotation, read failure,+ # client disconnect mid-replay — so the budget never leaks.+ if backlog_reserved:+ _release_backlog_bytes(backlog_reserved)+waited_for_stream = Falsewhile not await redis_stream.exists():if run_is_terminal:@@ -3294,14 +3481,14 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):# point, and that's the only case where stream depth vs the trim# cap is interesting — so skip the extra Redis reads on fresh# connects. Best-effort: never break the stream.- if last_event_id:+ if resume_cursor:try:observe_stream_length_on_connect(await redis_stream.get_length())- if await redis_stream.resume_point_trimmed(last_event_id):+ if await redis_stream.resume_point_trimmed(resume_cursor):observe_stream_resume_gap(origin_product)logger.warning("task_run_stream_resume_gap",- extra={"stream_key": stream_key, "last_event_id": last_event_id},+ extra={"stream_key": stream_key, "last_event_id": resume_cursor},)except Exception:logger.warning(@@ -3310,8 +3497,8 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):exc_info=True,)- start_id = last_event_id or "0"- if not last_event_id and start_latest and not waited_for_stream:+ start_id = resume_cursor or "0"+ if not resume_cursor and start_latest and not waited_for_stream:start_id = await redis_stream.get_latest_stream_id() or "0"try:async for stream_item in redis_stream.read_stream_entries(@@ -3325,7 +3512,20 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)else:event_id, event = stream_item- yield format_sse_event(event, event_id=event_id)+ if backlog_index is None or not backlog_index.covers(event):+ if backlog_contiguity_pending and backlog_index is not None and event.get("event_id"):+ # First id-carrying live entry past the backlog: a+ # hole before it means Redis evicted events whose+ # log batch never landed — the loss mode thin-tail+ # trimming assumes away. Count it before rollout.+ backlog_contiguity_pending = False+ if backlog_index.has_gap_before(event):+ observe_stream_backlog_gap(origin_product)+ logger.warning(+ "task_run_stream_backlog_gap",+ extra={"stream_key": stream_key, "event_id": event.get("event_id")},+ )+ yield format_sse_event(event, event_id=event_id)now = asyncio.get_running_loop().time()await redis_stream.refresh_watched()if now - connection_started_at >= TASK_RUN_STREAM_CONNECTION_MAX_SECONDS:@@ -3354,7 +3554,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):# Releases the request-thread DB connection (auth, task lookup) before the# long-lived stream begins — see sse_streaming_response. The stream body is- # Redis-only, so it never re-acquires one.+ # Redis and object storage only, so it never re-acquires one.return sse_streaming_response(async_stream() if settings.SERVER_GATEWAY_INTERFACE == "ASGI" else async_to_sync(lambda: async_stream()),endpoint="task_run_log",diff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.pyindex 76d53b749ea8..34d6c05531b9 100644--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py@@ -19,7 +19,7 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.temporal.common.utils import close_db_connections-from products.tasks.backend.feature_flags import run_stream_presence_gated+from products.tasks.backend.feature_flags import run_stream_presence_gated, run_stream_thin_tailfrom products.tasks.backend.logic.services.agent_command import sandbox_transport_token, validate_sandbox_urlfrom products.tasks.backend.logic.services.connection_token import create_sandbox_connection_tokenfrom products.tasks.backend.logic.services.permission_broker import (@@ -150,6 +150,7 @@ async def _relay_sandbox_events(input: RelaySandboxEventsInput, *, finalize_strerun_uses_dedicated_stream(task_run.state),presence_gated=run_stream_presence_gated(task_run.state),origin_product=origin_product,+ thin_tail=run_stream_thin_tail(task_run.state),)await redis_stream.initialize()diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.pyindex b3b4a4464e80..61062d041003 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py@@ -292,6 +292,7 @@ class TestRelaySandboxEventsCancellation:*,presence_gated: bool = False,origin_product: str | None = None,+ thin_tail: bool = False,) -> None:self.stream_key = stream_key@@ -344,11 +345,11 @@ class TestRelaySandboxEventsCancellation:class TestRelaySandboxEventsPresenceGating:@pytest.mark.parametrize(- "run_state,expected_presence_gated",+ "run_state,expected_presence_gated,expected_thin_tail",[- pytest.param({"stream_presence_gated": True}, True, id="run_pinned_gated"),- pytest.param({"stream_presence_gated": False}, False, id="run_pinned_ungated"),- pytest.param({}, False, id="legacy_run_without_pin"),+ pytest.param({"stream_presence_gated": True, "stream_thin_tail": True}, True, True, id="run_pinned_gated"),+ pytest.param({"stream_presence_gated": False}, False, False, id="run_pinned_ungated"),+ pytest.param({}, False, False, id="legacy_run_without_pin"),],)async def test_stream_presence_gating_follows_pinned_run_state(@@ -356,8 +357,9 @@ class TestRelaySandboxEventsPresenceGating:monkeypatch: pytest.MonkeyPatch,run_state: dict,expected_presence_gated: bool,+ expected_thin_tail: bool,) -> None:- constructed: list[bool] = []+ constructed: list[tuple[bool, bool]] = []class StubTaskRunRedisStream:def __init__(@@ -367,8 +369,9 @@ class TestRelaySandboxEventsPresenceGating:*,presence_gated: bool = False,origin_product: str | None = None,+ thin_tail: bool = False,) -> None:- constructed.append(presence_gated)+ constructed.append((presence_gated, thin_tail))async def initialize(self) -> None:return None@@ -413,7 +416,7 @@ class TestRelaySandboxEventsPresenceGating:))- assert constructed == [expected_presence_gated]+ assert constructed == [(expected_presence_gated, expected_thin_tail)]class TestRelaySandboxEventsMissingActor:@@ -435,6 +438,7 @@ class TestRelaySandboxEventsMissingActor:*,presence_gated: bool = False,origin_product: str | None = None,+ thin_tail: bool = False,) -> None:self.stream_key = stream_key@@ -1042,6 +1046,7 @@ class TestRelaySandboxEventsErrorHandling:*,presence_gated: bool = False,origin_product: str | None = None,+ thin_tail: bool = False,) -> None:self.stream_key = stream_keydiff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex e35fc8633d91..3cf367c65afe 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -96,6 +96,7 @@ from products.tasks.backend.presentation.serializers import (TaskRunLivingArtifactChartRequestSerializer,TaskSerializer,)+from products.tasks.backend.presentation.views import api as views_apifrom products.tasks.backend.temporal.process_task.utils import get_cached_github_user_token@@ -5467,6 +5468,7 @@ class TestTaskRunAPI(BaseTaskAPITest):"agent_otel_telemetry_enabled": False,"sandbox_event_ingest_enabled": False,"stream_presence_gated": True,+ "stream_thin_tail": True,"snapshot_external_id": "im-real","snapshot_kind": "directory","snapshot_mount_path": "/tmp",@@ -5522,6 +5524,7 @@ class TestTaskRunAPI(BaseTaskAPITest):"agent_otel_telemetry_enabled": True,"sandbox_event_ingest_enabled": True,"stream_presence_gated": False,+ "stream_thin_tail": False,"snapshot_external_id": "im-attacker","snapshot_kind": "directory","snapshot_mount_path": "/tmp/workspace",@@ -5581,6 +5584,7 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["agent_otel_telemetry_enabled"] is Falseassert run.state["sandbox_event_ingest_enabled"] is Falseassert run.state["stream_presence_gated"] is True+ assert run.state["stream_thin_tail"] is Trueassert run.state["snapshot_external_id"] == "im-real"assert run.state["snapshot_kind"] == "directory"assert run.state["snapshot_mount_path"] == "/tmp"@@ -5619,6 +5623,7 @@ class TestTaskRunAPI(BaseTaskAPITest):"github_credential_source","agent_otel_telemetry_enabled","stream_presence_gated",+ "stream_thin_tail","sandbox_id","use_modal_directory_resume_snapshots","use_modal_vm_sandbox",@@ -5655,6 +5660,7 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["github_credential_source"] == "caller_token" # protected key survives removalassert run.state["agent_otel_telemetry_enabled"] is False # protected key survives removalassert run.state["stream_presence_gated"] is True # protected key survives removal+ assert run.state["stream_thin_tail"] is True # protected key survives removalassert run.state["sandbox_id"] == "sb-real" # protected key survives removalassert run.state["use_modal_directory_resume_snapshots"] is True # protected key survives removalassert run.state["use_modal_vm_sandbox"] is False # protected key survives removal@@ -8125,6 +8131,23 @@ class TestTaskRunAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json()["stream_base_url"], "https://agent-proxy.example.com")+ def test_stream_token_omits_proxy_url_for_thin_tail_run(self):+ # Only the Django read leg serves the durable backlog, so a thin-tail run must+ # never be routed to the agent-proxy even with the proxy flag enabled.+ task = self.create_task()+ run = TaskRun.objects.create(+ task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS, state={"stream_thin_tail": True}+ )++ with (+ self.settings(TASKS_AGENT_PROXY_PUBLIC_URL="https://agent-proxy.example.com", DEBUG=False),+ patch("products.tasks.backend.facade.api.posthoganalytics.feature_enabled", return_value=True),+ ):+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/stream_token/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertIsNone(response.json()["stream_base_url"])+def test_stream_token_omits_proxy_url_when_flag_disabled(self):task = self.create_task()run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)@@ -9178,6 +9201,193 @@ class TestTaskRunStreamAPI(BaseTaskAPITest):self.assertEqual(data_events[-1]["data"]["notification"]["params"]["message"], "late hello")self.assertEqual(events[-1]["event"], "stream-end")+ def _make_thin_tail_run_with_backlog(self) -> tuple[Task, TaskRun]:+ task = self.create_task()+ run = TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.IN_PROGRESS,+ state={"stream_thin_tail": True},+ )+ backlog = [+ {+ "type": "notification",+ "timestamp": "2026-01-01T00:00:01Z",+ "event_id": "boot1-2",+ "first_event_id": "boot1-1",+ "notification": {"jsonrpc": "2.0", "method": "session/update", "params": {}},+ },+ {+ "type": "notification",+ "timestamp": "2026-01-01T00:00:02Z",+ "event_id": "boot1-3",+ "notification": {"jsonrpc": "2.0", "method": "_posthog/console", "params": {}},+ },+ ]+ object_storage.write(run.log_url, "\n".join(json.dumps(entry) for entry in backlog).encode("utf-8"))++ async def _write() -> None:+ redis_stream = TaskRunRedisStream(get_task_run_stream_key(str(run.id)))+ for event in [+ {"type": "notification", "event_id": "boot1-1", "notification": {"method": "chunk"}},+ {"type": "notification", "event_id": "boot1-3", "notification": {"method": "_posthog/console"}},+ {"type": "notification", "event_id": "boot1-4", "notification": {"method": "_posthog/live"}},+ {"type": "notification", "notification": {"method": "_posthog/unstamped"}},+ ]:+ await redis_stream.write_event(event)+ await redis_stream.mark_complete()++ asyncio.run(_write())+ return task, run++ def test_stream_thin_tail_serves_backlog_then_deduped_tail(self):+ task, run = self._make_thin_tail_run_with_backlog()++ 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)+ data_events = [event for event in events if event["event"] is None]+ self.assertEqual([event["id"] for event in data_events[:2]], ["log-0", "log-1"])+ self.assertEqual(+ [event["data"].get("event_id") for event in data_events[2:]],+ ["boot1-4", None],+ )+ self.assertEqual(events[-1]["event"], "stream-end")+ self.assertEqual(views_api._backlog_inflight_bytes, 0)++ def test_stream_thin_tail_resumes_backlog_from_log_cursor(self):+ task, run = self._make_thin_tail_run_with_backlog()++ response = self.client.get(self._stream_url(task, run), headers={"last-event-id": "log-0"})+ events = self._collect_sse_events(response)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data_events = [event for event in events if event["event"] is None]+ self.assertEqual(data_events[0]["id"], "log-1")+ self.assertNotIn("log-0", [event["id"] for event in data_events])+ self.assertEqual(+ [event["data"].get("event_id") for event in data_events[1:]],+ ["boot1-4", None],+ )++ @override_settings(TASK_RUN_STREAM_THIN_TAIL_ORIGINS=["user_created"])+ def test_stream_thin_tail_pinned_at_run_creation_except_pi(self):+ run = self.create_task().create_run()+ self.assertIs(run.state["stream_thin_tail"], True)++ # Pi tasks are forced onto the agent-proxy read leg, which has no backlog.+ pi_run = self.create_task(runtime=Task.Runtime.PI).create_run()+ self.assertIs(pi_run.state["stream_thin_tail"], False)++ def test_stream_thin_tail_trimmed_redis_cursor_falls_back_to_backlog(self):+ task, run = self._make_thin_tail_run_with_backlog()++ # A Redis id older than the oldest surviving entry: the resume point was trimmed.+ response = self.client.get(self._stream_url(task, run), headers={"last-event-id": "0-1"})+ events = self._collect_sse_events(response)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data_events = [event for event in events if event["event"] is None]+ self.assertEqual([event["id"] for event in data_events[:2]], ["log-0", "log-1"])+ self.assertEqual(+ [event["data"].get("event_id") for event in data_events[2:]],+ ["boot1-4", None],+ )+ self.assertEqual(events[-1]["event"], "stream-end")++ def test_stream_thin_tail_out_of_range_log_cursor_replays_in_full(self):+ task, run = self._make_thin_tail_run_with_backlog()++ response = self.client.get(self._stream_url(task, run), headers={"last-event-id": "log-99"})+ events = self._collect_sse_events(response)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data_events = [event for event in events if event["event"] is None]+ self.assertEqual([event["id"] for event in data_events[:2]], ["log-0", "log-1"])+ self.assertEqual(events[-1]["event"], "stream-end")++ def test_stream_thin_tail_rotates_during_backlog_replay(self):+ task, run = self._make_thin_tail_run_with_backlog()++ # A cap of 0 trips the elapsed check on the first backlog frame; without the+ # in-loop check a slow replay would hold its stream slot past the cap.+ with patch("products.tasks.backend.presentation.views.api.TASK_RUN_STREAM_CONNECTION_MAX_SECONDS", 0):+ 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)+ data_events = [event for event in events if event["event"] is None]+ self.assertEqual([event["id"] for event in data_events], ["log-0"])+ self.assertEqual(events[-1], {"event": "end", "id": None, "data": {"type": "rotated"}})+ self.assertEqual(views_api._backlog_inflight_bytes, 0)++ def test_stream_thin_tail_backlog_read_failure_emits_retryable_error(self):+ task, run = self._make_thin_tail_run_with_backlog()++ with patch(+ "products.tasks.backend.facade.api.read_task_run_log_content",+ side_effect=Exception("storage timeout"),+ ):+ 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], ["error"])+ self.assertEqual(events[0]["data"], {"error": "Backlog unavailable"})+ self.assertEqual(views_api._backlog_inflight_bytes, 0)++ def test_stream_thin_tail_expired_redis_cursor_replays_backlog_before_drained_end(self):+ task = self.create_task()+ run = TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.COMPLETED,+ state={"stream_thin_tail": True},+ )+ backlog = [+ {"type": "notification", "event_id": "boot1-1", "notification": {"method": "chunk"}},+ {"type": "notification", "event_id": "boot1-2", "notification": {"method": "chunk"}},+ ]+ object_storage.write(run.log_url, "\n".join(json.dumps(entry) for entry in backlog).encode("utf-8"))++ response = self.client.get(self._stream_url(task, run), headers={"last-event-id": "0-1"})+ events = self._collect_sse_events(response)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual([event["event"] for event in events], [None, None, None, "stream-end"])+ self.assertEqual([event["id"] for event in events[:2]], ["log-0", "log-1"])+ self.assertEqual(events[2]["data"]["type"], "task_run_state")+ self.assertEqual(events[-1]["data"], {"status": "complete"})++ @override_settings(TASK_RUN_STREAM_BACKLOG_INFLIGHT_MAX_BYTES=0)+ def test_stream_thin_tail_backlog_over_replay_budget_emits_retryable_error(self):+ task, run = self._make_thin_tail_run_with_backlog()++ 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], ["error"])+ self.assertEqual(events[0]["data"], {"error": "Backlog busy"})+ self.assertEqual(views_api._backlog_inflight_bytes, 0)++ @override_settings(TASK_RUN_STREAM_BACKLOG_MAX_BYTES=1)+ def test_stream_thin_tail_oversized_backlog_degrades_to_live_window(self):+ task, run = self._make_thin_tail_run_with_backlog()++ 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)+ data_events = [event for event in events if event["event"] is None]+ self.assertNotIn("log-0", [event["id"] for event in data_events])+ self.assertEqual(+ [event["data"].get("event_id") for event in data_events],+ ["boot1-1", "boot1-3", "boot1-4", None],+ )+ 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)diff --git a/products/tasks/backend/tests/test_connection_token.py b/products/tasks/backend/tests/test_connection_token.pyindex b884a5f5bb0c..95f14606f129 100644--- a/products/tasks/backend/tests/test_connection_token.py+++ b/products/tasks/backend/tests/test_connection_token.py@@ -154,16 +154,20 @@ class TestSandboxJwtRotation(SimpleTestCase):self.assertEqual(payload.run_id, str(run.id))self.assertIsNone(payload.sandbox_id)self.assertIs(payload.presence_gated, False)+ self.assertIs(payload.thin_tail, False)self.assertIsNone(payload.origin_product)@parameterized.expand([(True,), (False,)])@override_settings(SANDBOX_JWT_PRIVATE_KEY=KEY_A, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=None)def test_ingest_token_carries_pinned_presence_gating(self, gated: bool) -> None:reset_sandbox_jwt_key_cache()- token = create_sandbox_event_ingest_token(_fake_run({"stream_presence_gated": gated}, "signals_scout"))+ token = create_sandbox_event_ingest_token(+ _fake_run({"stream_presence_gated": gated, "stream_thin_tail": gated}, "signals_scout")+ )payload = validate_sandbox_event_ingest_token(token)self.assertIs(payload.presence_gated, gated)+ self.assertIs(payload.thin_tail, gated)self.assertEqual(payload.origin_product, "signals_scout")@parameterized.expand([(True,), (False,)])diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.tsindex 3f48e57a7622..6546afc37a76 100644--- a/products/tasks/frontend/generated/api.ts+++ b/products/tasks/frontend/generated/api.ts@@ -2306,12 +2306,14 @@ export const getTasksRunsStreamRetrieveUrl = (}/**- * Server-Sent Events stream of task run events. Events carry an `id:` line (a Redis stream id) usable as a resume cursor.+ * Server-Sent Events stream of task run events. Events carry an `id:` line (a Redis stream id, or a synthetic `log-<n>` id during backlog replay) usable as a resume cursor.*- * The server caps each connection at 900 seconds: it emits `event: end` with `data: {"type": "rotated"}` and closes. This does NOT mean the run finished — reconnect with the `Last-Event-ID` header set to the last received event id to resume without gaps or duplicates. Only treat the stream as complete when the run itself reaches a terminal status.+ * The server caps each connection at 900 seconds: it emits `event: end` with `data: {"type": "rotated"}` and closes. This does NOT mean the run finished — reconnect with the `Last-Event-ID` header set to the last received event id to resume. Only treat the stream as complete when the run itself reaches a terminal status.** Resume guarantees cover mirrored events only: on runs where live mirroring is presence-gated, events produced while no viewer was connected are not in the live stream. Reload the run's session logs to recover the agent's output; run-state and progress frames are not in those logs, so refetch the run itself for its current state.*+ * On runs with durable backlog serving, a connection without `Last-Event-ID` first replays history from the run log under synthetic `log-<n>` event ids, then attaches the live stream, skipping live entries the backlog already covered. Reconnecting with a `log-<n>` id resumes the backlog replay from that point; reconnecting with a Redis id resumes the live stream, may re-deliver a few events already served as backlog frames, and falls back to a full backlog replay when the resume point was trimmed or the stream expired. Runs whose log exceeds the backlog byte cap skip the replay and serve only the recent live window. When the backlog is temporarily unavailable (a storage read failure, or a worker at its concurrent replay budget), the stream emits an `event: error` frame and closes; reconnect with the same cursor to retry. Treat delivery as at-least-once across reconnects.+ ** `?start=latest` consumers must also carry `Last-Event-ID` across reconnects: reconnecting without it re-resolves to the then-current latest event, silently skipping anything published while disconnected.** **SDK consumers**: do not call the generated fetch wrapper for this path — it will buffer the entire stream. Use the URL builder (`getTasksRunsStreamRetrieveUrl`) with a streaming `fetch`/`EventSource`-style consumer and the `Last-Event-ID` header instead.diff --git a/services/agent-proxy/src/hono/ingest-handler.ts b/services/agent-proxy/src/hono/ingest-handler.tsindex f5fc9d24d81e..d04d1c37d069 100644--- a/services/agent-proxy/src/hono/ingest-handler.ts+++ b/services/agent-proxy/src/hono/ingest-handler.ts@@ -105,7 +105,10 @@ export async function handleIngest(// NDJSON body parsing + Redis writes.const streamKey = getStreamKey(claims.runId)- const redisStream = new TaskRunRedisStream(streamKey, redis, { presenceGated: claims.presenceGated })+ const redisStream = new TaskRunRedisStream(streamKey, redis, {+ presenceGated: claims.presenceGated,+ thinTail: claims.thinTail,+ })const bodyTiming: IngestBodyTiming = {startedAt: Date.now(),diff --git a/services/agent-proxy/src/lib/constants.ts b/services/agent-proxy/src/lib/constants.tsindex 276b942dafb6..8d527205cb66 100644--- a/services/agent-proxy/src/lib/constants.ts+++ b/services/agent-proxy/src/lib/constants.ts@@ -23,6 +23,10 @@ export const WATCHED_REFRESH_INTERVAL_MS = 120_000// Redis XADD MAXLEN ~ (approximate trim, not exact).export const STREAM_MAX_LENGTH = 5_000+// Thin-tail runs serve connect-time backlog from the durable run log, so Redis+// only needs a live tail. Applied per write, and only to id-carrying events, so+// a run on an agent that predates event ids keeps the full window.+export const STREAM_THIN_MAX_LENGTH = 500// XREAD tuningexport const READ_COUNT = 16diff --git a/services/agent-proxy/src/lib/jwt.ts b/services/agent-proxy/src/lib/jwt.tsindex 0adf9de5ae1c..559f78c10d69 100644--- a/services/agent-proxy/src/lib/jwt.ts+++ b/services/agent-proxy/src/lib/jwt.ts@@ -76,6 +76,14 @@ function assertIsTerminalClaim(payload: Record<string, unknown>): boolean {return isTerminal ?? false}+function assertThinTailClaim(payload: Record<string, unknown>): boolean {+ const thinTail = payload['thin_tail']+ if (thinTail !== undefined && typeof thinTail !== 'boolean') {+ throw new Error('Token has invalid claim: thin_tail must be a boolean')+ }+ return thinTail ?? false+}+function assertOriginProductClaim(payload: Record<string, unknown>): string {const originProduct = payload['origin_product']if (originProduct !== undefined && typeof originProduct !== 'string') {@@ -137,6 +145,7 @@ export async function validateStreamReadToken(token: string, publicKeys: CryptoK// Audience: posthog:sandbox_event_ingest// Required claims: run_id (string), task_id (string), team_id (integer)// Optional claims: presence_gated (boolean, absent means false),+// thin_tail (boolean, absent means false),// origin_product (string, absent means "unknown")// Algorithm: RS256, no clockTolerance (matches Python leeway=0 default)//@@ -150,6 +159,7 @@ export async function validateSandboxEventIngestToken(return {...assertStreamClaims(claims),presenceGated: assertPresenceGatedClaim(claims),+ thinTail: assertThinTailClaim(claims),originProduct: assertOriginProductClaim(claims),}}diff --git a/services/agent-proxy/src/lib/redis-stream.ts b/services/agent-proxy/src/lib/redis-stream.tsindex aada93ac399d..4711ff2dfd79 100644--- a/services/agent-proxy/src/lib/redis-stream.ts+++ b/services/agent-proxy/src/lib/redis-stream.ts@@ -14,6 +14,7 @@ import {SEQUENCE_TTL_SECONDS,STREAM_COMPLETED_TTL_SECONDS,STREAM_MAX_LENGTH,+ STREAM_THIN_MAX_LENGTH,STREAM_PREFIX,STREAM_TTL_SECONDS,STREAM_WATCHED_TTL_SECONDS,@@ -137,6 +138,7 @@ export class TaskRunRedisStream {private readonly completedTimeout: numberprivate readonly maxLength: numberprivate readonly presenceGated: boolean+ private readonly thinTail: booleanconstructor(streamKey: string,@@ -145,6 +147,7 @@ export class TaskRunRedisStream {timeout?: numbermaxLength?: numberpresenceGated?: boolean+ thinTail?: boolean}) {this.streamKey = streamKey@@ -155,6 +158,14 @@ export class TaskRunRedisStream {this.completedTimeout = Math.min(this.timeout, STREAM_COMPLETED_TTL_SECONDS)this.maxLength = opts?.maxLength ?? STREAM_MAX_LENGTHthis.presenceGated = opts?.presenceGated ?? false+ this.thinTail = opts?.thinTail ?? false+ }++ private maxlenForEvent(event: Record<string, unknown>): number {+ if (this.thinTail && event['event_id']) {+ return STREAM_THIN_MAX_LENGTH+ }+ return this.maxLength}// SET EXPIRE on the stream key; does not create it.@@ -359,7 +370,15 @@ export class TaskRunRedisStream {// Refreshes TTL on every write (sliding window).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)+ const streamId = await this.redis.xadd(+ this.streamKey,+ 'MAXLEN',+ '~',+ this.maxlenForEvent(event),+ '*',+ 'data',+ raw+ )await this.redis.expire(this.streamKey, ttl ?? this.timeout)return normalizeStreamId(streamId)}@@ -462,7 +481,15 @@ export class TaskRunRedisStream {const pipeline = this.redis.multi()if (mirror) {- pipeline.xadd(this.streamKey, 'MAXLEN', '~', this.maxLength, '*', 'data', JSON.stringify(event))+ pipeline.xadd(+ this.streamKey,+ 'MAXLEN',+ '~',+ this.maxlenForEvent(event),+ '*',+ 'data',+ JSON.stringify(event)+ )pipeline.expire(this.streamKey, this.timeout)}pipeline.set(sequenceKey, String(sequence), 'EX', this.sequenceTimeout)diff --git a/services/agent-proxy/src/lib/types.ts b/services/agent-proxy/src/lib/types.tsindex a4074dc589b5..2c285d48fb4c 100644--- a/services/agent-proxy/src/lib/types.ts+++ b/services/agent-proxy/src/lib/types.ts@@ -112,6 +112,7 @@ export interface SandboxEventIngestTokenPayload {taskId: stringteamId: numberpresenceGated: boolean+ thinTail: booleanoriginProduct: string}diff --git a/services/agent-proxy/tests/hono/app.test.ts b/services/agent-proxy/tests/hono/app.test.tsindex 10ff4da79e47..fe1c79486406 100644--- a/services/agent-proxy/tests/hono/app.test.ts+++ b/services/agent-proxy/tests/hono/app.test.ts@@ -40,6 +40,7 @@ describe('app onError', () => {taskId: 'task-abc',teamId: 42,presenceGated: false,+ thinTail: false,originProduct: 'unknown',})})diff --git a/services/agent-proxy/tests/hono/ingest-handler.test.ts b/services/agent-proxy/tests/hono/ingest-handler.test.tsindex c0b76ce574ac..1dab64f6c2de 100644--- a/services/agent-proxy/tests/hono/ingest-handler.test.ts+++ b/services/agent-proxy/tests/hono/ingest-handler.test.ts@@ -305,6 +305,7 @@ function makeClaims(overrides?: Partial<SandboxEventIngestTokenPayload>): SandbotaskId: 'task-abc',teamId: 42,presenceGated: false,+ thinTail: false,originProduct: 'unknown',...overrides,}diff --git a/services/agent-proxy/tests/lib/jwt.test.ts b/services/agent-proxy/tests/lib/jwt.test.tsindex a1e29e2ed1e5..3880527c2152 100644--- a/services/agent-proxy/tests/lib/jwt.test.ts+++ b/services/agent-proxy/tests/lib/jwt.test.ts@@ -59,6 +59,7 @@ interface TokenOptions {signingKey?: CryptoKeypresenceGated?: unknownisTerminal?: unknown+ thinTail?: unknownoriginProduct?: unknown}@@ -73,6 +74,7 @@ async function signToken(opts: TokenOptions = {}): Promise<string> {signingKey,presenceGated,isTerminal,+ thinTail,originProduct,} = opts@@ -83,6 +85,9 @@ async function signToken(opts: TokenOptions = {}): Promise<string> {if (isTerminal !== undefined) {claims['is_terminal'] = isTerminal}+ if (thinTail !== undefined) {+ claims['thin_tail'] = thinTail+ }if (originProduct !== undefined) {claims['origin_product'] = originProduct}@@ -257,8 +262,30 @@ describe('jwt', () => {expect(payload.taskId).toBe('task-abc-123')expect(payload.teamId).toBe(42)expect(payload.presenceGated).toBe(false)+ expect(payload.thinTail).toBe(false)+ })++ it.each([+ { name: 'true', claim: true, expected: true },+ { name: 'false', claim: false, expected: false },+ ])('carries a thin_tail claim of $name', async ({ claim, expected }) => {+ const token = await signToken({ audience: SANDBOX_EVENT_INGEST_AUDIENCE, thinTail: claim })+ const payload = await validateSandboxEventIngestToken(token, keys.publicKeys)++ expect(payload.thinTail).toBe(expected)})+ it.each([{ claim: 'yes' }, { claim: 1 }, { claim: null }])(+ 'rejects a non-boolean thin_tail claim ($claim)',+ async ({ claim }) => {+ const token = await signToken({ audience: SANDBOX_EVENT_INGEST_AUDIENCE, thinTail: claim })++ await expect(validateSandboxEventIngestToken(token, keys.publicKeys)).rejects.toThrow(+ 'thin_tail must be a boolean'+ )+ }+ )+it.each([{ name: 'true', claim: true, expected: true },{ name: 'false', claim: false, expected: false },diff --git a/services/agent-proxy/tests/lib/redis-stream.test.ts b/services/agent-proxy/tests/lib/redis-stream.test.tsindex 21dba6ed5021..136542afdb13 100644--- a/services/agent-proxy/tests/lib/redis-stream.test.ts+++ b/services/agent-proxy/tests/lib/redis-stream.test.ts@@ -51,11 +51,15 @@ class FakeRedis {private _nextSeq = 0private _xaddCallCount = 0private _expireCallCount = 0+ private _xaddMaxlens: number[] = []// Counters exposed for TTL/MAXLEN assertionsget xaddCallCount(): number {return this._xaddCallCount}+ get xaddMaxlens(): number[] {+ return this._xaddMaxlens+ }get expireCallCount(): number {return this._expireCallCount}@@ -168,6 +172,9 @@ class FakeRedis {async xadd(key: string, ...args: unknown[]): Promise<string | null> {this._xaddCallCount+++ if (args[0] === 'MAXLEN' && args[1] === '~') {+ this._xaddMaxlens.push(Number(args[2]))+ }// Parse: MAXLEN ~ N * 'data' valuelet i = 0while (i < args.length && args[i] !== '*') {@@ -430,7 +437,7 @@ let _runCounter = 0function newStream(redis?: FakeRedis,- opts?: { presenceGated?: boolean }+ opts?: { presenceGated?: boolean; thinTail?: boolean }): { stream: TaskRunRedisStream; redis: FakeRedis; streamKey: string } {const r = redis ?? new FakeRedis()_runCounter++@@ -439,6 +446,7 @@ function newStream(const stream = new TaskRunRedisStream(streamKey, r as unknown as import('ioredis').Redis, {timeout: 60,presenceGated: opts?.presenceGated ?? false,+ thinTail: opts?.thinTail ?? false,})return { stream, redis: r, streamKey }}@@ -613,6 +621,23 @@ describe('redis-stream', () => {expect(err!.lastAcceptedSeq).toBe(2)})+ it('trims id-carrying events to the thin window on thin-tail streams', async () => {+ const { stream, redis } = newStream(undefined, { thinTail: true })++ await stream.writeEventWithSequence({ type: 'a', event_id: 'boot1-1' }, 1)+ await stream.writeEventWithSequence({ type: 'b' }, 2)++ expect(redis.xaddMaxlens).toEqual([500, 5_000])+ })++ it('keeps the full window for id-carrying events when thin tail is off', async () => {+ const { stream, redis } = newStream()++ await stream.writeEventWithSequence({ type: 'a', event_id: 'boot1-1' }, 1)++ expect(redis.xaddMaxlens).toEqual([5_000])+ })+it('applies MAXLEN on every XADD', async () => {const { stream, redis } = newStream()