: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,wizard): bound SSE connection time and cut idle polling (#63120)
Stephen Schmidt0224d34d379d
diff --git a/posthog/api/streaming.py b/posthog/api/streaming.pyindex 3e94e5d92733..fceb53e90589 100644--- a/posthog/api/streaming.py+++ b/posthog/api/streaming.py@@ -1,7 +1,7 @@from collections.abc import AsyncIterator, Iteratorfrom http import HTTPStatus-from django.db import close_old_connections+from django.db import connectionsfrom django.http import StreamingHttpResponse# Disable proxy buffering/caching so SSE chunks reach the client immediately@@ -12,6 +12,27 @@ _SSE_DEFAULT_HEADERS = {}+def _release_request_connections() -> None:+ """Close this thread's DB connections, unless a transaction is open.++ Closes unconditionally (``conn.close()``) rather than via+ ``close_if_unusable_or_obsolete()``, which only closes connections past their+ ``CONN_MAX_AGE`` — that would make this helper a silent no-op if the setting+ ever became nonzero, re-pinning a pgbouncer slot per stream. Closing an idle+ autocommit connection is always safe; Django reopens on next use.++ Connections inside an atomic block are skipped: severing an open transaction+ corrupts it. PostHog never streams from inside ``transaction.atomic()``, so in+ production this closes everything; the case that does hit the guard is Django+ ``TestCase``'s per-test transaction wrapper, which the test client only shields+ from the signal-dispatched ``close_old_connections``, not from direct calls+ like this one.+ """+ for conn in connections.all(initialized_only=True):+ if not conn.in_atomic_block:+ conn.close()++def sse_streaming_response(stream: Iterator[bytes] | AsyncIterator[bytes],*,@@ -31,15 +52,20 @@ def sse_streaming_response(serializer/ORM reads in the sync view) stays pinned to a pgbouncer clientslot for the *entire* stream — ``request_finished`` only frees it once thestream ends, which for SSE is many minutes. At scale that turns every- concurrent subscriber into a held connection and exhausts the pool. Calling- ``close_old_connections()`` here releases the request-thread connection- before the stream starts.+ concurrent subscriber into a held connection and exhausts the pool. Releasing+ the request-thread connections here frees them before the stream starts.The stream body must not rely on the request-thread connection: do anyin-stream DB work through ``posthog.sync.database_sync_to_async`` so itacquires and releases its own connection.++ Limitation: this runs at view-return time, but response-phase middleware runs+ after the view returns and before the stream body is consumed — middleware+ that touches the DB in ``process_response`` lazily reopens a connection that+ then stays pinned for the whole stream. Keep response middleware DB-free on+ SSE paths."""- close_old_connections()+ _release_request_connections()return StreamingHttpResponse(stream,status=status,diff --git a/posthog/api/test/test_streaming.py b/posthog/api/test/test_streaming.pyindex d9038689fb12..a93af5008cc0 100644--- a/posthog/api/test/test_streaming.py+++ b/posthog/api/test/test_streaming.py@@ -13,10 +13,20 @@ def _gen() -> Iterator[bytes]:class TestSSEStreamingResponse:- def test_releases_db_connection_before_streaming(self):- with mock.patch("posthog.api.streaming.close_old_connections") as release:+ def test_releases_db_connections_before_streaming(self):+ idle = mock.Mock(in_atomic_block=False)+ with mock.patch("posthog.api.streaming.connections") as connections:+ connections.all.return_value = [idle]sse_streaming_response(_gen())- release.assert_called_once()+ connections.all.assert_called_once_with(initialized_only=True)+ idle.close.assert_called_once()++ def test_does_not_sever_connections_with_an_open_transaction(self):+ in_transaction = mock.Mock(in_atomic_block=True)+ with mock.patch("posthog.api.streaming.connections") as connections:+ connections.all.return_value = [in_transaction]+ sse_streaming_response(_gen())+ in_transaction.close.assert_not_called()def test_sets_event_stream_content_type_and_default_headers(self):response = sse_streaming_response(_gen())diff --git a/products/tasks/backend/logic/stream/redis_stream.py b/products/tasks/backend/logic/stream/redis_stream.pyindex 9d7c601564e0..f2139b5855a8 100644--- a/products/tasks/backend/logic/stream/redis_stream.py+++ b/products/tasks/backend/logic/stream/redis_stream.py@@ -22,6 +22,10 @@ TASK_RUN_STREAM_TIMEOUT = SANDBOX_TTL_SECONDSTASK_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+# XREAD BLOCK is push-based (XADD wakes the blocked client immediately), so a+# longer block only cuts idle polling — it never delays delivery. Keep it under+# the keepalive interval so idle readers still wake in time to emit one.+TASK_RUN_STREAM_READ_BLOCK_MS = 5_000TASK_RUN_STREAM_WAIT_INITIAL_DELAY_SECONDS = 0.05TASK_RUN_STREAM_WAIT_DELAY_INCREMENT_SECONDS = 0.15TASK_RUN_STREAM_WAIT_MAX_DELAY_SECONDS = 2.0@@ -194,7 +198,7 @@ class TaskRunRedisStream:async def read_stream(self,start_id: str = "0",- block_ms: int = 100,+ block_ms: int = TASK_RUN_STREAM_READ_BLOCK_MS,count: Optional[int] = TASK_RUN_STREAM_READ_COUNT,keepalive_interval_seconds: float | None = None,) -> AsyncGenerator[dict]:@@ -212,7 +216,7 @@ class TaskRunRedisStream:async def read_stream_entries(self,start_id: str = "0",- block_ms: int = 100,+ block_ms: int = TASK_RUN_STREAM_READ_BLOCK_MS,count: Optional[int] = TASK_RUN_STREAM_READ_COUNT,keepalive_interval_seconds: float | None = None,) -> AsyncGenerator[TaskRunStreamEntryOrKeepalive]:diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.pyindex 9fcb085b8c24..4ffb6c072de3 100644--- a/products/tasks/backend/metrics.py+++ b/products/tasks/backend/metrics.py@@ -12,7 +12,8 @@ TaskWorkflowStartOutcome = Literal["attempted", "blocked", "failed", "started"]# stream_error — Redis/stream error sentinel ended the connection# unavailable — stream key never appeared within the wait timeout# client_disconnect — client went away (GeneratorExit) before completion-StreamConnectionOutcome = Literal["completed", "stream_error", "unavailable", "client_disconnect"]+# rotated — per-connection cap reached; clean EOF, client resumes+StreamConnectionOutcome = Literal["completed", "stream_error", "unavailable", "client_disconnect", "rotated"]_ALLOWED_MODES = {"background", "interactive"}_ALLOWED_RUN_SOURCES = {"manual", "signal_report"}_ALLOWED_RUNTIME_ADAPTERS = {"claude", "codex"}@@ -54,9 +55,9 @@ TASK_RUN_FAILED_TOTAL = Counter()-# Connection lifetimes span a few seconds (cold reconnect) to the 6h sandbox TTL.-# The 120s bucket is deliberate: it isolates connections cut at the Envoy/Contour-# response_timeout boundary from genuinely long-lived ones.+# Connection lifetimes range from a few seconds (cold reconnect) to the+# per-connection cap. The 120s bucket isolates connections cut at the+# Envoy/Contour response_timeout boundary from genuinely long-lived ones.STREAM_CONNECTION_DURATION_BUCKETS = [1.0,5.0,@@ -66,6 +67,7 @@ STREAM_CONNECTION_DURATION_BUCKETS = [120.0,300.0,600.0,+ 960.0,1_800.0,3_600.0,7_200.0,diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 4dbb6a7e2e67..ba06cc2f5b88 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -9,7 +9,7 @@ from typing import Anyfrom urllib.parse import parse_qs, urlparsefrom django.conf import settings-from django.http import HttpResponse, JsonResponse, StreamingHttpResponse+from django.http import HttpResponse, JsonResponseimport requests as http_requestsfrom drf_spectacular.types import OpenApiTypes@@ -24,6 +24,7 @@ from rest_framework.response import Responsefrom posthog.api.mixins import validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.streaming import sse_streaming_responsefrom posthog.api.utils import ServerTimingsGatheredfrom posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthenticationfrom posthog.permissions import APIScopePermission@@ -106,6 +107,12 @@ logger = logging.getLogger(__name__)TASK_RUN_STREAM_KEEPALIVE_INTERVAL_SECONDS = 20.0TASK_RUN_STREAM_KEEPALIVE_EVENT_NAME = "keepalive"TASK_RUN_STREAM_KEEPALIVE_PAYLOAD = {"type": "keepalive"}+# Long-lived SSE connections pin NGINX Unit processes during recycle-drain, so+# cap each one: emit `event: end` so clients can tell rotation from run+# completion, then close. Clients resume from their Last-Event-ID cursor.+TASK_RUN_STREAM_CONNECTION_MAX_SECONDS = 15 * 60+TASK_RUN_STREAM_END_EVENT_NAME = "end"+TASK_RUN_STREAM_ROTATED_PAYLOAD = {"type": "rotated"}TASK_RUN_ARTIFACT_UPLOAD_EXPIRATION_SECONDS = 60 * 60@@ -1590,6 +1597,40 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):parts.append(f"data: {json.dumps(data)}")return ("\n".join(parts) + "\n\n").encode()+ @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"+ 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 "+ "reaches a terminal status.\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"+ "**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."+ ),+ parameters=[+ OpenApiParameter(+ name="start",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Set to `latest` to skip the event backlog and only receive events published after connecting.",+ ),+ OpenApiParameter(+ name="Last-Event-ID",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.HEADER,+ required=False,+ description="Resume cursor: the `id:` of the last event received on a previous connection. Events strictly after it are delivered.",+ ),+ ],+ responses={(200, "text/event-stream"): OpenApiTypes.STR},+ )@action(detail=True,methods=["get"],@@ -1680,9 +1721,22 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):TASK_RUN_STREAM_KEEPALIVE_PAYLOAD,event_name=TASK_RUN_STREAM_KEEPALIVE_EVENT_NAME,)- continue- event_id, event = stream_item- yield format_sse_event(event, event_id=event_id)+ else:+ event_id, event = stream_item+ yield format_sse_event(event, event_id=event_id)+ if (+ asyncio.get_running_loop().time() - connection_started_at+ >= TASK_RUN_STREAM_CONNECTION_MAX_SECONDS+ ):+ outcome = "rotated"+ # Without this marker a rotation EOF would be+ # indistinguishable from run completion for API+ # consumers reading until EOF.+ yield format_sse_event(+ TASK_RUN_STREAM_ROTATED_PAYLOAD,+ event_name=TASK_RUN_STREAM_END_EVENT_NAME,+ )+ returnoutcome = "completed"except TaskRunStreamError as e:outcome = "stream_error"@@ -1693,10 +1747,11 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):duration = asyncio.get_running_loop().time() - connection_started_atobserve_stream_connection_closed(origin_product, outcome, duration)- return StreamingHttpResponse(- async_stream() if settings.SERVER_GATEWAY_INTERFACE == "ASGI" else async_to_sync(lambda: async_stream()),- content_type="text/event-stream",- headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},+ # 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.+ return sse_streaming_response(+ async_stream() if settings.SERVER_GATEWAY_INTERFACE == "ASGI" else async_to_sync(lambda: async_stream()))@staticmethoddiff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 35871ec31e2d..429653a62b7b 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -3,9 +3,9 @@ import timeimport uuidimport base64import asyncio-from collections.abc import Iterator+from collections.abc import AsyncGenerator, Iteratorfrom datetime import timedelta-from typing import ClassVar, cast+from typing import Any, ClassVar, castfrom urllib.parse import quotefrom unittest.mock import AsyncMock, MagicMock, patch@@ -45,7 +45,11 @@ from products.tasks.backend.logic.services.staged_artifacts import (cache_task_staged_artifact,get_task_staged_artifacts,)-from products.tasks.backend.logic.stream.redis_stream import TaskRunRedisStream, get_task_run_stream_key+from products.tasks.backend.logic.stream.redis_stream import (+ TaskRunRedisStream,+ TaskRunStreamEntryOrKeepalive,+ get_task_run_stream_key,+)from products.tasks.backend.models import (CodeInvite,CodeInviteRedemption,@@ -5449,6 +5453,149 @@ class TestTaskRunStreamKeepaliveAPI(BaseTaskAPITest):self.assertIn("after idle gap", content)+class TestTaskRunStreamConnectionCapAPI(BaseTaskAPITest):+ def _stream_url(self, task: Task, run: TaskRun) -> str:+ return f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/stream/"++ def _mark_stream_complete(self, run: TaskRun) -> None:+ async def _mark() -> None:+ redis_stream = TaskRunRedisStream(get_task_run_stream_key(str(run.id)))+ await redis_stream.mark_complete()++ asyncio.run(_mark())++ def _read_stream_ids(self, run: TaskRun) -> list[str]:+ async def _read() -> list[str]:+ redis_stream = TaskRunRedisStream(get_task_run_stream_key(str(run.id)))+ messages = await redis_stream._redis_client.xrange(get_task_run_stream_key(str(run.id)))+ return [msg_id.decode("utf-8") if isinstance(msg_id, bytes) else msg_id for msg_id, _ in messages]++ return asyncio.run(_read())++ def _collect_sse_events(self, response: StreamingHttpResponse) -> list[dict]:+ content = b"".join(cast(Iterator[bytes], response.streaming_content)).decode("utf-8")+ events: list[dict] = []+ for block in [part.strip() for part in content.split("\n\n") if part.strip()]:+ event_name = None+ event_id = None+ data = None+ for line in block.splitlines():+ if line.startswith("event: "):+ event_name = line[7:]+ elif line.startswith("id: "):+ event_id = line[4:]+ elif line.startswith("data: "):+ data = json.loads(line[6:])+ events.append({"event": event_name, "id": event_id, "data": data})+ return events++ @parameterized.expand(+ [+ ("after_real_event", False, "before cap"),+ ("on_keepalive_only_iteration", True, "event: keepalive"),+ ]+ )+ def test_stream_rotates_cleanly_when_connection_cap_elapses(+ self, _name: str, idle_first: bool, expected_marker: str+ ) -> None:+ task = self.create_task()+ run = task.create_run()++ def _console_event(message: str) -> dict:+ return {+ "type": "notification",+ "timestamp": "2026-01-01T00:00:01Z",+ "notification": {+ "jsonrpc": "2.0",+ "method": "_posthog/console",+ "params": {"sessionId": str(run.id), "level": "info", "message": message},+ },+ }++ async def fake_read_stream_entries(+ self: TaskRunRedisStream, *args: Any, **kwargs: Any+ ) -> AsyncGenerator[TaskRunStreamEntryOrKeepalive]:+ if idle_first:+ yield None+ else:+ yield ("1-0", _console_event("before cap"))+ yield ("2-0", _console_event("after cap"))++ observe_closed = MagicMock()+ with (+ patch.object(TaskRunRedisStream, "read_stream_entries", new=fake_read_stream_entries),+ # A cap of 0 trips the elapsed check on the first yield, so the test+ # exercises the rotation path without sleeping through real time. The+ # keepalive case proves the check runs on idle yields too: if it only+ # ran after real events, an idle stream would never rotate.+ patch("products.tasks.backend.presentation.views.api.TASK_RUN_STREAM_CONNECTION_MAX_SECONDS", 0),+ patch("products.tasks.backend.presentation.views.api.observe_stream_connection_closed", observe_closed),+ ):+ response = cast(+ StreamingHttpResponse,+ self.client.get(self._stream_url(task, run), headers={"accept": "text/event-stream"}),+ )+ content = b"".join(cast(Iterator[bytes], response.streaming_content)).decode("utf-8")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ # Whatever was already delivered is kept; the stream then signals rotation+ # (so clients can tell it apart from run completion) and ends without an+ # error event, letting the client resume from its Last-Event-ID cursor.+ self.assertIn(expected_marker, content)+ self.assertNotIn("after cap", content)+ self.assertNotIn("event: error", content)+ self.assertTrue(content.endswith('event: end\ndata: {"type": "rotated"}\n\n'))+ observe_closed.assert_called_once()+ self.assertEqual(observe_closed.call_args.args[1], "rotated")++ def test_stream_resumes_after_rotation_without_gap_or_duplicate(self) -> None:+ task = self.create_task()+ run = task.create_run()+ run.emit_console_event("info", "first message")+ run.emit_console_event("info", "second message")+ stream_ids = self._read_stream_ids(run)++ # A cap of 0 rotates the first connection after its first yield, leaving+ # the two console events for the resumed connection to pick up.+ with patch("products.tasks.backend.presentation.views.api.TASK_RUN_STREAM_CONNECTION_MAX_SECONDS", 0):+ first_response = cast(+ StreamingHttpResponse,+ self.client.get(self._stream_url(task, run), headers={"accept": "text/event-stream"}),+ )+ first_events = self._collect_sse_events(first_response)++ self.assertEqual(first_response.status_code, status.HTTP_200_OK)+ # The rotation marker is the last thing on the wire and carries no id, so+ # it can't poison the client's resume cursor.+ self.assertEqual(first_events[-1], {"event": "end", "id": None, "data": {"type": "rotated"}})+ first_data_events = first_events[:-1]+ self.assertEqual([event["id"] for event in first_data_events], [stream_ids[0]])+ # stream_ids[0] is the task_run_state event create_run publishes — the+ # console events are deliberately left for the resumed connection.+ self.assertEqual(first_data_events[0]["data"]["type"], "task_run_state")++ self._mark_stream_complete(run)++ second_response = cast(+ StreamingHttpResponse,+ self.client.get(+ self._stream_url(task, run),+ headers={"accept": "text/event-stream", "last-event-id": first_data_events[0]["id"]},+ ),+ )++ self.assertEqual(second_response.status_code, status.HTTP_200_OK)+ second_events = self._collect_sse_events(second_response)+ # Resuming from the rotated connection's last id delivers the remaining+ # events exactly once — no gap, no duplicate — then completes without a+ # rotation marker.+ self.assertEqual([event["id"] for event in second_events], stream_ids[1:])+ self.assertEqual(+ [event["data"]["notification"]["params"]["message"] for event in second_events],+ ["first message", "second message"],+ )++class TestTasksAPIPermissions(BaseTaskAPITest):def setUp(self):super().setUp()diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex ca14ddaaeaf5..c69d90749289 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -1988,6 +1988,13 @@ export type TasksRunsSessionLogsRetrieveParams = {offset?: number}+export type TasksRunsStreamRetrieveParams = {+ /**+ * Set to `latest` to skip the event backlog and only receive events published after connecting.+ */+ start?: string+}+export type TasksRepositoryReadinessRetrieveParams = {refresh?: boolean/**diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.tsindex 8e58bf76090b..fbfa4d402f72 100644--- a/products/tasks/frontend/generated/api.ts+++ b/products/tasks/frontend/generated/api.ts@@ -59,6 +59,7 @@ import type {TasksRepositoryReadinessRetrieveParams,TasksRunsListParams,TasksRunsSessionLogsRetrieveParams,+ TasksRunsStreamRetrieveParams,TasksSlackThreadContextRetrieveParams,TasksSummariesCreateParams,} from './api.schemas'@@ -968,20 +969,44 @@ export const tasksRunsStartCreate = async (})}-export const getTasksRunsStreamRetrieveUrl = (projectId: string, taskId: string, id: string) => {- return `/api/projects/${projectId}/tasks/${taskId}/runs/${id}/stream/`+export const getTasksRunsStreamRetrieveUrl = (+ projectId: string,+ taskId: string,+ id: string,+ params?: TasksRunsStreamRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/tasks/${taskId}/runs/${id}/stream/?${stringifiedParams}`+ : `/api/projects/${projectId}/tasks/${taskId}/runs/${id}/stream/`}/**- * API for managing task runs. Each run represents an execution of a task.+ * Server-Sent Events stream of task run events. Events carry an `id:` line (a Redis stream id) 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.+ *+ * `?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.*/export const tasksRunsStreamRetrieve = async (projectId: string,taskId: string,id: string,+ params?: TasksRunsStreamRetrieveParams,options?: RequestInit-): Promise<TaskRunDetailDTOApi> => {- return apiMutator<TaskRunDetailDTOApi>(getTasksRunsStreamRetrieveUrl(projectId, taskId, id), {+): Promise<string> => {+ return apiMutator<string>(getTasksRunsStreamRetrieveUrl(projectId, taskId, id, params), {...options,method: 'GET',})diff --git a/products/tasks/frontend/logics/taskDetailSceneLogic.test.ts b/products/tasks/frontend/logics/taskDetailSceneLogic.test.tsindex 0400c666ca8a..11fa68c7a019 100644--- a/products/tasks/frontend/logics/taskDetailSceneLogic.test.ts+++ b/products/tasks/frontend/logics/taskDetailSceneLogic.test.ts@@ -41,7 +41,7 @@ const createMockRun = (id: string, status: TaskRunStatus): TaskRun => ({completed_at: null,})-function buildReadableStream(chunks: string[], keepOpen = false): ReadableStream<Uint8Array> {+function buildReadableStream(chunks: string[], keepOpen = false, onClose?: () => void): ReadableStream<Uint8Array> {const encoder = new TextEncoder()let index = 0const StreamConstructor = globalThis.ReadableStream ?? NodeReadableStream@@ -52,16 +52,17 @@ function buildReadableStream(chunks: string[], keepOpen = false): ReadableStreamcontroller.enqueue(encoder.encode(chunks[index]))index += 1} else if (!keepOpen) {+ onClose?.()controller.close()}},})}-function createSseResponse(chunks: string[], keepOpen = false): Response {+function createSseResponse(chunks: string[], keepOpen = false, onClose?: () => void): Response {return {ok: true,- body: buildReadableStream(chunks, keepOpen),+ body: buildReadableStream(chunks, keepOpen, onClose),} as Response}@@ -298,6 +299,244 @@ describe('taskDetailSceneLogic', () => {logic.unmount()})+ it('resumes the automatic restart with Last-Event-ID and ignores replayed events', async () => {+ const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)+ global.fetch = createFetchMock({+ runs: { [run.id]: run },+ streamResponses: [+ createSseResponse([createConsoleSseEvent('1-0', 'first message')]),+ createSseResponse(+ [createConsoleSseEvent('1-0', 'first message'), createConsoleSseEvent('2-0', 'second message')],+ true+ ),+ ],+ })++ const logic = taskDetailSceneLogic({ taskId: 'task-123' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setSelectedRunId(run.id, 'task-123')+ await expectLogic(logic).toFinishAllListeners()+ await flushStreaming()+ await flushStreaming()++ const streamCalls = (global.fetch as jest.Mock).mock.calls.filter(([url]) =>+ String(url).includes('/stream/')+ )+ expect(streamCalls).toHaveLength(2)+ expect((streamCalls[1][1] as RequestInit)?.headers).toMatchObject({+ Accept: 'text/event-stream',+ 'Last-Event-ID': '1-0',+ })+ expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual([+ 'first message',+ 'second message',+ ])++ logic.unmount()+ })++ it('ignores the rotation end marker and skips the log refetch on rotation resume', async () => {+ const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)+ global.fetch = createFetchMock({+ runs: { [run.id]: run },+ streamResponses: [+ createSseResponse([+ createConsoleSseEvent('1-0', 'first message'),+ 'event: end\ndata: {"type": "rotated"}\n\n',+ ]),+ createSseResponse([createConsoleSseEvent('2-0', 'second message')], true),+ ],+ })++ const logic = taskDetailSceneLogic({ taskId: 'task-123' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setSelectedRunId(run.id, 'task-123')+ await expectLogic(logic).toFinishAllListeners()+ await flushStreaming()+ await flushStreaming()++ const fetchCalls = (global.fetch as jest.Mock).mock.calls.map(([url]) => String(url))+ expect(fetchCalls.filter((url) => url.includes('/stream/'))).toHaveLength(2)+ // The rotation marker is not rendered as a log entry+ expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual([+ 'first message',+ 'second message',+ ])+ // The rotation resume skips the redundant log-file refetch — only the+ // initial run selection fetches it while entries are streaming+ expect(fetchCalls.filter((url) => url.includes('/logs/'))).toHaveLength(1)++ logic.unmount()+ })++ it('drains the missed tail when a rotation EOF races run completion', async () => {+ const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)+ global.fetch = createFetchMock({+ runs: { [run.id]: run },+ streamResponses: [+ createSseResponse(+ [createConsoleSseEvent('1-0', 'first message'), 'event: end\ndata: {"type": "rotated"}\n\n'],+ false,+ // The run completes while the rotated connection is reconnecting,+ // so the post-EOF refetch sees a terminal run+ () => {+ run.status = TaskRunStatus.COMPLETED+ }+ ),+ // The drain connection delivers the tail then EOFs naturally+ createSseResponse([createConsoleSseEvent('2-0', 'tail message')]),+ ],+ })++ const logic = taskDetailSceneLogic({ taskId: 'task-123' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setSelectedRunId(run.id, 'task-123')+ await expectLogic(logic).toFinishAllListeners()+ await flushStreaming()+ await flushStreaming()+ await expectLogic(logic).toFinishAllListeners()++ const streamCalls = (global.fetch as jest.Mock).mock.calls.filter(([url]) =>+ String(url).includes('/stream/')+ )+ expect(streamCalls).toHaveLength(2)+ expect((streamCalls[1][1] as RequestInit)?.headers).toMatchObject({+ Accept: 'text/event-stream',+ 'Last-Event-ID': '1-0',+ })+ expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['first message', 'tail message'])++ logic.unmount()+ })++ it('does not re-drain when the drain connection itself ends with a rotation marker', async () => {+ const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)+ global.fetch = createFetchMock({+ runs: { [run.id]: run },+ streamResponses: [+ createSseResponse(+ [createConsoleSseEvent('1-0', 'first message'), 'event: end\ndata: {"type": "rotated"}\n\n'],+ false,+ // The run completes while the rotated connection is reconnecting+ () => {+ run.status = TaskRunStatus.COMPLETED+ }+ ),+ // The completion sentinel was never written, so the drain connection+ // also rotates instead of EOFing naturally+ createSseResponse([+ createConsoleSseEvent('2-0', 'tail message'),+ 'event: end\ndata: {"type": "rotated"}\n\n',+ ]),+ ],+ })++ const logic = taskDetailSceneLogic({ taskId: 'task-123' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setSelectedRunId(run.id, 'task-123')+ await expectLogic(logic).toFinishAllListeners()+ await flushStreaming()+ await flushStreaming()+ await expectLogic(logic).toFinishAllListeners()+ await flushStreaming()+ await expectLogic(logic).toFinishAllListeners()++ const streamCalls = (global.fetch as jest.Mock).mock.calls.filter(([url]) =>+ String(url).includes('/stream/')+ )+ expect(streamCalls).toHaveLength(2)+ expect(logic.values.isStreaming).toBe(false)+ expect(logic.values.streamEntries.map((entry) => entry.message)).toEqual(['first message', 'tail message'])++ logic.unmount()+ })++ it('falls back to polling after repeated immediate EOFs instead of reconnecting in a tight loop', async () => {+ const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)+ global.fetch = createFetchMock({+ runs: { [run.id]: run },+ streamResponses: [createSseResponse([]), createSseResponse([]), createSseResponse([])],+ })++ const logic = taskDetailSceneLogic({ taskId: 'task-123' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setSelectedRunId(run.id, 'task-123')+ await expectLogic(logic).toFinishAllListeners()+ for (let i = 0; i < 6; i++) {+ await flushStreaming()+ }+ await expectLogic(logic).toFinishAllListeners()++ const streamCalls = (global.fetch as jest.Mock).mock.calls.filter(([url]) =>+ String(url).includes('/stream/')+ )+ expect(streamCalls).toHaveLength(3)+ expect(logic.values.streamingFailed).toBe(true)+ expect(logic.values.isStreaming).toBe(false)++ logic.unmount()+ })++ it('starts polling when the post-EOF run refresh fails for an active run', async () => {+ const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)+ global.fetch = createFetchMock({+ runs: { [run.id]: run },+ streamResponses: [createSseResponse([], true)],+ })++ const logic = taskDetailSceneLogic({ taskId: 'task-123' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setSelectedRunId(run.id, 'task-123')+ await expectLogic(logic).toFinishAllListeners()+ await flushStreaming()++ // Mirror the real sequence: the stream EOFs (stopStreaming), then the+ // post-EOF run refresh fails+ logic.actions.stopStreaming()+ await expectLogic(logic, () => {+ logic.actions.loadSelectedRunFailure('network error')+ }).toDispatchActions(['startPolling'])++ logic.unmount()+ })++ it.each<[string, TaskRunStatus | null]>([+ ['no run has loaded', null],+ ['the loaded run is terminal', TaskRunStatus.COMPLETED],+ ])('does not start polling when the run refresh fails and %s', async (_desc, status) => {+ if (status) {+ const run = createMockRun('run-1', status)+ global.fetch = createFetchMock({ runs: { [run.id]: run } })+ }++ const logic = taskDetailSceneLogic({ taskId: 'task-123' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ if (status) {+ logic.actions.setSelectedRunId('run-1', 'task-123')+ await expectLogic(logic).toFinishAllListeners()+ }++ await expectLogic(logic, () => {+ logic.actions.loadSelectedRunFailure('network error')+ }).toNotHaveDispatchedActions(['startPolling'])++ logic.unmount()+ })+it('does not restart an active stream when selected run reloads', async () => {const run = createMockRun('run-1', TaskRunStatus.IN_PROGRESS)global.fetch = createFetchMock({diff --git a/products/tasks/frontend/logics/taskDetailSceneLogic.ts b/products/tasks/frontend/logics/taskDetailSceneLogic.tsindex 2392879863fc..2ea87f071591 100644--- a/products/tasks/frontend/logics/taskDetailSceneLogic.ts+++ b/products/tasks/frontend/logics/taskDetailSceneLogic.ts@@ -28,6 +28,12 @@ import { TaskLogicProps, taskLogic } from './taskLogic'import { tasksLogic } from './tasksLogic'const LOG_POLL_INTERVAL_MS = 1000+// The server rotates stream connections on a fixed cap (clean EOF + Last-Event-ID+// resume), so reconnect-after-EOF is a routine loop. If connections start dying+// this quickly, something is wrong server-side — stop hammering it and fall back+// to polling instead of reconnecting in a tight loop.+const STREAM_MIN_HEALTHY_CONNECTION_MS = 5000+const STREAM_MAX_CONSECUTIVE_SHORT_CONNECTIONS = 3export type TaskDetailSceneLogicProps = TaskLogicProps@@ -103,7 +109,7 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([markStreamingFailed: true,appendStreamEntries: (entries: LogEntry[]) => ({ entries }),updateStreamEntries: (entries: LogEntry[]) => ({ entries }),- recordStreamProgress: (lastEventId: string | null, seenEventIds: string[]) => ({ lastEventId, seenEventIds }),+ recordStreamProgress: (lastEventId: string) => ({ lastEventId }),setLogs: (logs: string) => ({ logs }),updateRun: (run: TaskRun) => ({ run }),}),@@ -185,22 +191,7 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([null as string | null,{setSelectedRunId: (state, { taskId }) => (taskId === props.taskId ? null : state),- recordStreamProgress: (state, { lastEventId }) => lastEventId ?? state,- },- ],- seenStreamEventIds: [- {} as Record<string, true>,- {- setSelectedRunId: (state, { taskId }) => (taskId === props.taskId ? {} : state),- recordStreamProgress: (state, { seenEventIds }) => {- if (seenEventIds.length === 0) {- return state- }- return {- ...state,- ...Object.fromEntries(seenEventIds.map((eventId) => [eventId, true])),- }- },+ recordStreamProgress: (_, { lastEventId }) => lastEventId,},],isStreaming: [@@ -237,10 +228,19 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([return null}const run = await api.tasks.runs.get(props.taskId, values.selectedRunId, phDebugQueryParams())- // Use proxy endpoint to avoid CORS issues with direct S3 access- actions.loadLogs({- url: `/api/projects/${values.currentProjectId}/tasks/${props.taskId}/runs/${values.selectedRunId}/logs/${phDebugQuerySuffix()}`,- })+ const runActive = run?.status === TaskRunStatus.QUEUED || run?.status === TaskRunStatus.IN_PROGRESS+ // While live stream entries are rendered the log file isn't shown, so+ // skip refetching it on every stream rotation. Once the run is terminal+ // (or streaming has fallen back to polling) the fetch always happens —+ // it backs the non-streaming fallback view; any tail a rotation cut off+ // is recovered by the final drain connection in loadSelectedRunSuccess.+ const streamRendersEntries = !values.streamingFailed && values.streamEntries.length > 0+ if (!(runActive && streamRendersEntries)) {+ // Use proxy endpoint to avoid CORS issues with direct S3 access+ actions.loadLogs({+ url: `/api/projects/${values.currentProjectId}/tasks/${props.taskId}/runs/${values.selectedRunId}/logs/${phDebugQuerySuffix()}`,+ })+ }return run},},@@ -317,6 +317,10 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([if (taskId !== props.taskId) {return}+ cache.seenStreamEventIds = new Set<string>()+ cache.consecutiveShortStreamConnections = 0+ cache.streamEndedWithRotation = false+ cache.finalDrainAttempted = falseactions.stopPolling()actions.stopStreaming()actions.loadSelectedRun()@@ -341,6 +345,18 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([actions.loadSelectedRun()}},+ loadSelectedRunFailure: () => {+ // Stream rotation routes through loadSelectedRun (EOF → refresh → restart),+ // so a transient failure here must not strand the run view with neither+ // stream nor polling. Polling self-heals: the next successful load restarts+ // streaming or stops everything once the run is terminal. Gate on the last+ // loaded run still being active (shouldPoll) — a run that never loaded or+ // already finished must not arm a forever-retrying poll loop against a+ // permanently failing endpoint.+ if (values.shouldPoll && !values.isStreaming) {+ actions.startPolling()+ }+ },loadSelectedRunSuccess: ({ selectedRunData }) => {if (selectedRunData) {actions.updateRun(selectedRunData)@@ -354,7 +370,27 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([}} else {actions.stopPolling()- actions.stopStreaming()+ if (+ cache.streamEndedWithRotation &&+ !cache.finalDrainAttempted &&+ !values.isStreaming &&+ !values.streamingFailed &&+ values.streamEntries.length > 0+ ) {+ // The rotation EOF raced run completion: events published after the+ // resume cursor would otherwise never render (streamEntries shadow the+ // log file). One final drain connection delivers them, then normally+ // EOFs via the completion sentinel — no rotation marker. But the+ // sentinel is best-effort and can be missing, in which case the drain+ // itself rotates and re-sets the flag; finalDrainAttempted makes the+ // drain one-shot so a finished run can't re-drain in 15-minute cycles+ // until the stream key expires.+ cache.streamEndedWithRotation = false+ cache.finalDrainAttempted = true+ actions.startStreaming()+ } else {+ actions.stopStreaming()+ }}},loadTaskSuccess: ({ task }) => {@@ -383,8 +419,14 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([const streamUrl = `/api/projects/@current/tasks/${props.taskId}/runs/${runId}/stream/`const toolMap = buildToolMap(values.streamEntries)let eventIndex = values.streamEntries.length+ // Dedupes events replayed across rotated connections. Lives in cache+ // (reset per selected run) so it survives reconnects without an O(n)+ // reducer copy per chunk batch on long runs.+ const seenStreamEventIds: Set<string> = (cache.seenStreamEventIds ??= new Set<string>())const consume = async (): Promise<void> => {+ const connectionStartedAt = performance.now()+ cache.streamEndedWithRotation = falsetry {const response = await fetch(streamUrl, {signal: abortController.signal,@@ -419,22 +461,24 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([const batch: LogEntry[] = []const updatedEntriesById = new Map<string, LogEntry>()let lastProcessedEventId: string | null = null- const newlySeenEventIds: string[] = []for (const block of blocks) {const parsedEvent = parseSseEventBlock(block)+ if (parsedEvent?.eventType === 'end') {+ // `event: end` marks a connection-cap rotation, not run+ // completion — the EOF that follows triggers the restart.+ cache.streamEndedWithRotation = true+ continue+ }if (!parsedEvent || parsedEvent.eventType === 'keepalive' || !parsedEvent.data) {continue}if (parsedEvent.id) {- if (- values.seenStreamEventIds[parsedEvent.id] ||- newlySeenEventIds.includes(parsedEvent.id)- ) {+ if (seenStreamEventIds.has(parsedEvent.id)) {continue}- newlySeenEventIds.push(parsedEvent.id)+ seenStreamEventIds.add(parsedEvent.id)lastProcessedEventId = parsedEvent.id}@@ -463,8 +507,8 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([}}- if (newlySeenEventIds.length > 0) {- actions.recordStreamProgress(lastProcessedEventId, newlySeenEventIds)+ if (lastProcessedEventId) {+ actions.recordStreamProgress(lastProcessedEventId)}if (updatedEntriesById.size > 0) {actions.updateStreamEntries(Array.from(updatedEntriesById.values()))@@ -474,9 +518,20 @@ export const taskDetailSceneLogic = kea<taskDetailSceneLogicType>([}}+ if (performance.now() - connectionStartedAt < STREAM_MIN_HEALTHY_CONNECTION_MS) {+ cache.consecutiveShortStreamConnections = (cache.consecutiveShortStreamConnections ?? 0) + 1+ } else {+ cache.consecutiveShortStreamConnections = 0+ }// Clear streaming state before refreshing the run so in-progress// runs can reconnect cleanly after an EOF.actions.stopStreaming()+ if (cache.consecutiveShortStreamConnections >= STREAM_MAX_CONSECUTIVE_SHORT_CONNECTIONS) {+ console.warn('SSE stream ended immediately several times in a row, falling back to polling')+ actions.markStreamingFailed()+ actions.startPolling()+ return+ }// Stream ended normally — do a final poll to get the latest run statusactions.loadSelectedRun()} catch (e) {diff --git a/products/wizard/backend/presentation/views.py b/products/wizard/backend/presentation/views.pyindex 2a7bbb12c360..701b43696a56 100644--- a/products/wizard/backend/presentation/views.py+++ b/products/wizard/backend/presentation/views.py@@ -96,7 +96,10 @@ def _log_request_auth(request: Request, *, action: str, team_id: int | None) ->SSE_HEARTBEAT_INTERVAL_SECONDS = 15.0SSE_POLL_TIMEOUT_SECONDS = 1.0-SSE_MAX_DURATION_SECONDS = 30 * 60+# Long-lived connections pin NGINX Unit processes during recycle-drain; the+# `event: end` close makes EventSource reconnect, so the cap is near-invisible to+# users (the progress tracker may show a brief "reconnecting" blip per rotation).+SSE_MAX_DURATION_SECONDS = 15 * 60WIZARD_SYNC_KILLSWITCH_FLAG = "onboarding-wizard-sync-killswitch"diff --git a/products/wizard/frontend/generated/api.ts b/products/wizard/frontend/generated/api.tsindex ab2bff261025..71f828cc2661 100644--- a/products/wizard/frontend/generated/api.ts+++ b/products/wizard/frontend/generated/api.ts@@ -132,7 +132,7 @@ export const getWizardSessionsStreamRetrieveUrl = (projectId: string, params: Wi}/**- * Server-Sent Events stream of wizard session updates for a (workflow_id, skill_id) pair. On connect, the current latest session (if any) is emitted as the first event; subsequent upserts are streamed in real time. The server closes the connection after 1800 seconds with an `event: end` line so the client (EventSource) can reconnect.+ * Server-Sent Events stream of wizard session updates for a (workflow_id, skill_id) pair. On connect, the current latest session (if any) is emitted as the first event; subsequent upserts are streamed in real time. The server closes the connection after 900 seconds with an `event: end` line so the client (EventSource) can reconnect.** **SDK consumers**: do not call the generated fetch wrapper for this path — it will buffer the entire infinite stream. Use the URL builder (`getWizardSessionsStreamRetrieveUrl`) with the browser's `EventSource` API instead.*/diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 21bc4836fe9c..61ac5b287568 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -61873,6 +61873,13 @@ export namespace Schemas {offset?: number;};+ export type TasksRunsStreamRetrieveParams = {+ /**+ * Set to `latest` to skip the event backlog and only receive events published after connecting.+ */+ start?: string;+ };+export type TasksRepositoryReadinessRetrieveParams = {refresh?: boolean;/**