:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): stop counting in-flight chunks as stream backlog gaps (#99181)
Alessandro Pogliaghiebb0a4578550
diff --git a/products/tasks/backend/facade/streams.py b/products/tasks/backend/facade/streams.pyindex 002d1f071237..51c93edf12b5 100644--- a/products/tasks/backend/facade/streams.py+++ b/products/tasks/backend/facade/streams.py@@ -8,7 +8,13 @@ dedicated-stream flag helper from here."""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_cursor+from products.tasks.backend.logic.services.run_log_mirror import MAX_IDENTIFIER_CHARS+from products.tasks.backend.logic.stream.backlog import (+ TaskRunStreamBacklogIndex,+ format_log_cursor,+ parse_log_cursor,+ session_update_type,+)from 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,@@ -24,6 +30,7 @@ from products.tasks.backend.logic.stream.redis_stream import (from products.tasks.backend.redis import run_uses_dedicated_stream__all__ = [+ "MAX_IDENTIFIER_CHARS","TASK_RUN_STREAM_WAIT_DELAY_INCREMENT_SECONDS","TASK_RUN_STREAM_WAIT_INITIAL_DELAY_SECONDS","TASK_RUN_STREAM_WAIT_MAX_DELAY_SECONDS",@@ -40,4 +47,5 @@ __all__ = ["run_stream_presence_gated","run_stream_thin_tail","run_uses_dedicated_stream",+ "session_update_type",]diff --git a/products/tasks/backend/logic/stream/backlog.py b/products/tasks/backend/logic/stream/backlog.pyindex b73fb5257250..398add5afc8c 100644--- a/products/tasks/backend/logic/stream/backlog.py+++ b/products/tasks/backend/logic/stream/backlog.py@@ -13,6 +13,18 @@ Entries without ids (older agents, server-published events) are never dropped.TASK_RUN_STREAM_LOG_CURSOR_PREFIX = "log-"+STREAMING_CHUNK_UPDATES = frozenset({"agent_message_chunk", "agent_thought_chunk"})+++def session_update_type(event: dict) -> str | None:+ notification = event.get("notification")+ if not isinstance(notification, dict) or notification.get("method") != "session/update":+ return None+ params = notification.get("params")+ update = params.get("update") if isinstance(params, dict) else None+ session_update = update.get("sessionUpdate") if isinstance(update, dict) else None+ return session_update if isinstance(session_update, str) else None+def _parse_event_id(event_id: str) -> tuple[str, int] | None:boot, _, seq = event_id.rpartition("-")@@ -75,11 +87,11 @@ class TaskRunStreamBacklogIndex: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.+ """True when the oldest id-carrying tail entry shows the log lagging behind the Redis trim.- 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.+ A covered entry means the log reaches into the tail; a streaming chunk means an+ in-flight message outgrew the tail, which the log only carries once it completes.+ Otherwise a missing per-boot predecessor is the loss mode thin-tail trimming cannot rule out."""event_id = event.get("event_id")if not isinstance(event_id, str) or not event_id:@@ -88,7 +100,9 @@ class TaskRunStreamBacklogIndex:if parsed is None:return Falseboot, seq = parsed- if seq <= 1:+ if seq <= 1 or self._covers_parsed(boot, seq):+ return False+ if session_update_type(event) in STREAMING_CHUNK_UPDATES:return Falsereturn not self._covers_parsed(boot, seq - 1)diff --git a/products/tasks/backend/logic/stream/tests/test_backlog.py b/products/tasks/backend/logic/stream/tests/test_backlog.pyindex 42ffb79b9153..9022168c1768 100644--- a/products/tasks/backend/logic/stream/tests/test_backlog.py+++ b/products/tasks/backend/logic/stream/tests/test_backlog.py@@ -71,3 +71,15 @@ class TestTaskRunStreamBacklogIndex(SimpleTestCase):assert index.has_gap_before({"event_id": "boot2-5"}) # unknown boot, mid-sequenceassert not index.has_gap_before({"event_id": "boot2-1"}) # a boot's first event has no predecessorassert not index.has_gap_before({"type": "notification"}) # unstamped entries carry no signal+ assert not index.has_gap_before({"event_id": "boot1-16"})+ assert not index.has_gap_before(_chunk("boot1-13", "agent_message_chunk"))+ assert not index.has_gap_before(_chunk("boot1-13", "agent_thought_chunk"))+ assert index.has_gap_before(_chunk("boot1-13", "tool_call_update"))+++def _chunk(event_id: str, session_update: str) -> dict:+ return {+ "type": "notification",+ "event_id": event_id,+ "notification": {"method": "session/update", "params": {"update": {"sessionUpdate": session_update}}},+ }diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 0d3754ed1461..8ee77421731c 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -2,7 +2,6 @@ import osimport reimport jsonimport asyncio-import loggingfrom collections.abc import AsyncGeneratorfrom datetime import datetimefrom time import perf_counter@@ -16,6 +15,7 @@ from django.utils.html import escapeimport pydanticimport requests as http_requests+import structlogimport posthoganalyticsfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema@@ -94,6 +94,7 @@ from products.tasks.backend.facade.metrics import (from products.tasks.backend.facade.model_catalogue import TASK_RUN_GATEWAY_PRODUCT, available_model_choicesfrom products.tasks.backend.facade.run_config import WARMABLE_ORIGIN_PRODUCTS, TaskArtifactAdapter, TaskArtifactTypefrom products.tasks.backend.facade.streams import (+ MAX_IDENTIFIER_CHARS,TASK_RUN_STREAM_WAIT_DELAY_INCREMENT_SECONDS,TASK_RUN_STREAM_WAIT_INITIAL_DELAY_SECONDS,TASK_RUN_STREAM_WAIT_MAX_DELAY_SECONDS,@@ -107,6 +108,7 @@ from products.tasks.backend.facade.streams import (run_stream_presence_gated,run_stream_thin_tail,run_uses_dedicated_stream,+ session_update_type,)from products.tasks.backend.presentation.serializers import (ConnectionTokenResponseSerializer,@@ -223,7 +225,11 @@ class OctetStreamParser(BaseParser):return content-logger = logging.getLogger(__name__)+logger = structlog.get_logger(__name__)+++def _log_field(value: object) -> str | None:+ return None if value is None else str(value)[:MAX_IDENTIFIER_CHARS]def _pi_cloud_runtime_disabled_response() -> Response:@@ -3519,19 +3525,13 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):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",- },+ stream_key=stream_key,+ last_event_id=_log_field(resume_cursor),+ reason="trimmed" if stream_exists else "expired",)serve_after = -1except Exception:- logger.warning(- "task_run_stream_attach_observe_failed",- extra={"stream_key": stream_key},- exc_info=True,- )+ logger.warning("task_run_stream_attach_observe_failed", stream_key=stream_key, exc_info=True)if serve_after is not None:resume_cursor = None@@ -3549,7 +3549,8 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):observe_stream_backlog_oversized(origin_product)logger.warning("task_run_stream_backlog_oversized",- extra={"stream_key": stream_key, "backlog_bytes": backlog_bytes},+ stream_key=stream_key,+ backlog_bytes=backlog_bytes,)log_content = ""elif not _try_reserve_backlog_bytes(backlog_bytes):@@ -3560,7 +3561,8 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):observe_stream_backlog_throttled(origin_product)logger.warning("task_run_stream_backlog_throttled",- extra={"stream_key": stream_key, "backlog_bytes": backlog_bytes},+ stream_key=stream_key,+ backlog_bytes=backlog_bytes,)yield format_sse_event({"error": "Backlog busy"}, event_name="error")return@@ -3573,7 +3575,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):del log_contentexcept Exception:outcome = "backlog_error"- logger.exception("task_run_stream_backlog_read_failed", extra={"stream_key": stream_key})+ logger.exception("task_run_stream_backlog_read_failed", 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@@ -3651,18 +3653,17 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):observe_stream_resume_gap(origin_product)logger.warning("task_run_stream_resume_gap",- extra={"stream_key": stream_key, "last_event_id": resume_cursor},+ stream_key=stream_key,+ last_event_id=_log_field(resume_cursor),+ reason="trimmed",)except Exception:- logger.warning(- "task_run_stream_attach_observe_failed",- extra={"stream_key": stream_key},- exc_info=True,- )+ logger.warning("task_run_stream_attach_observe_failed", stream_key=stream_key, exc_info=True)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"+ backlog_contiguity_pending = Falsetry:async for stream_item in redis_stream.read_stream_entries(start_id=start_id,@@ -3675,19 +3676,22 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)else:event_id, event = stream_item+ if backlog_contiguity_pending and backlog_index is not None and event.get("event_id"):+ # Oldest id-carrying live entry: 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",+ stream_key=stream_key,+ event_id=_log_field(event.get("event_id")),+ session_update=_log_field(session_update_type(event)),+ reason="log_behind_trim",+ )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()diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 439a2a23d177..9f22b31f08cb 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -9460,7 +9460,9 @@ 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]:+ def _make_thin_tail_run_with_backlog(+ self, tail_event_ids: list[str] | None = None, tail_method: str = "_posthog/live"+ ) -> tuple[Task, TaskRun]:task = self.create_task()run = TaskRun.objects.create(task=task,@@ -9485,14 +9487,27 @@ class TestTaskRunStreamAPI(BaseTaskAPITest):]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 [+ if tail_event_ids is None:+ tail = [{"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"}},- ]:+ ]+ else:+ notification: dict = (+ {"method": "session/update", "params": {"update": {"sessionUpdate": tail_method}}}+ if tail_method.startswith("agent_")+ else {"method": tail_method}+ )+ tail = [+ {"type": "notification", "event_id": event_id, "notification": notification}+ for event_id in tail_event_ids+ ]++ async def _write() -> None:+ redis_stream = TaskRunRedisStream(get_task_run_stream_key(str(run.id)))+ for event in tail:await redis_stream.write_event(event)await redis_stream.mark_complete()@@ -9555,6 +9570,26 @@ class TestTaskRunStreamAPI(BaseTaskAPITest):)self.assertEqual(events[-1]["event"], "stream-end")+ @parameterized.expand(+ [+ ("overlap", ["boot1-3", "boot1-6"], "_posthog/live", False),+ ("in_flight_chunks", ["boot1-6", "boot1-7"], "agent_message_chunk", False),+ ("trimmed_unlogged", ["boot1-6", "boot1-7"], "_posthog/live", True),+ ]+ )+ def test_stream_thin_tail_backlog_gap_counted_only_when_log_lags_trim(+ self, _name: str, tail_event_ids: list[str], method: str, expect_gap: bool+ ):+ task, run = self._make_thin_tail_run_with_backlog(tail_event_ids=tail_event_ids, tail_method=method)++ with patch.object(views_api, "observe_stream_backlog_gap") as observe_gap:+ 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(events[-1]["event"], "stream-end")+ self.assertEqual(observe_gap.call_count, 1 if expect_gap else 0)+def test_stream_thin_tail_out_of_range_log_cursor_replays_in_full(self):task, run = self._make_thin_tail_run_with_backlog()