: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): mitigate process-task workflow-task deadlocks (TMPRL1101) (#71590)
Alessandro Pogliaghid8f94f04407c
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex 7c11b366ee9a..3c9953158f55 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -67,6 +67,20 @@ TASKS_USE_MODAL_RESUME_SNAPSHOTS: bool = get_from_env(type_cast=str_to_bool,)+# Force-enables process_task continue_as_new regardless of the tasks-continue-as-new flag+# (for local E2E / emergency on). The flag is the normal cloud toggle. continue_as_new bounds+# replay cost so long runs don't trip the 2s workflow-task deadlock detector on eviction.+TASKS_CONTINUE_AS_NEW_ENABLED: bool = get_from_env(+ "TASKS_CONTINUE_AS_NEW_ENABLED",+ False,+ type_cast=str_to_bool,+)++# Event-count threshold for the above; 0 relies on Temporal's is_continue_as_new_suggested().+TASKS_CONTINUE_AS_NEW_HISTORY_THRESHOLD: int = get_from_env(+ "TASKS_CONTINUE_AS_NEW_HISTORY_THRESHOLD", 4000, type_cast=int+)+# Override the process_task workflow's inactivity timeout (default 2 hours).# Set this to e.g. 30 for local testing of the shutdown / resume flow. When# set, the CI-follow-up floor is also bypassed so the timer actually firesdiff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex ffffc29bd8d7..be3ea1c1a25e 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -45,6 +45,8 @@ OVERLAP_CLONE_BOOT_FEATURE_FLAG = "tasks-overlap-clone-boot"# enabling this flag disables it fleet-wide — over any per-run override — without# an image rebuild.RTK_DISABLED_FEATURE_FLAG = "tasks-rtk-disabled"+# Gates whether long-running process_task runs continue-as-new to bound history/replay cost.+CONTINUE_AS_NEW_FEATURE_FLAG = "tasks-cloud-run-continue-as-new"SnapshotKind = Literal["filesystem", "directory"]SNAPSHOT_KIND_FILESYSTEM: SnapshotKind = "filesystem"diff --git a/products/tasks/backend/temporal/process_task/README.md b/products/tasks/backend/temporal/process_task/README.mdindex 11d240154357..23cd1268d534 100644--- a/products/tasks/backend/temporal/process_task/README.md+++ b/products/tasks/backend/temporal/process_task/README.md@@ -64,6 +64,23 @@ User ─────────────────────────4. **wait_condition** — Blocks with a 2-hour inactivity timeout. The agent sends `heartbeat` signals to keep the workflow alive; each heartbeat resets the timer. The workflow exits when it receives a `complete_task` signal or when no heartbeat arrives within 2 hours5. **cleanup_sandbox** — Destroys the sandbox container (always runs via `finally`)+#### History management (`continue_as_new`)++Long interactive runs accumulate a large event history — mostly streamed agent updates and+periodic heartbeats. A very large history makes a single workflow-task activation (notably a+cold replay after cache eviction or a deploy) slow enough to trip Temporal's 2-second deadlock+detector (`[TMPRL1101]`). Two mechanisms bound this:++- The relay coalesces streamed `agent_message_chunk` deltas into one `agent_text_delta` signal+ per second (and at turn/tool boundaries), rather than one signal per chunk — see+ `TEXT_DELTA_FLUSH_INTERVAL_SECONDS` in `activities/relay_sandbox_events.py`.+- When enabled, the workflow calls `continue_as_new` from a clean idle point once its history is+ large (Temporal's `is_continue_as_new_suggested()`, or `TASKS_CONTINUE_AS_NEW_HISTORY_THRESHOLD`+ events), re-attaching to the same running sandbox instead of re-provisioning. It's off by+ default and toggled per-org by the `tasks-cloud-run-continue-as-new` feature flag; `TASKS_CONTINUE_AS_NEW_ENABLED`+ force-enables it (local E2E / emergency on). The enable decision is captured at workflow start,+ so in-flight runs and the trigger stay deterministic across replay.+### Temporal client`backend/temporal/client.py` — `execute_task_processing_workflow()` (sync) and `execute_task_processing_workflow_async()` check the `tasks` feature flag, then fire-and-forget the workflow. Workflow IDs follow the pattern `task-processing-{task_id}-{run_id}`.diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.pyindex 0a2ca70feb85..13dd9c1db004 100644--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py@@ -12,6 +12,7 @@ from posthog.temporal.common.utils import asyncify, close_db_connectionsfrom products.tasks.backend.constants import (AGENT_PROXY_KEEP_STREAM_OPEN_FEATURE_FLAG,+ CONTINUE_AS_NEW_FEATURE_FLAG,MODAL_DIRECTORY_RESUME_SNAPSHOTS_FEATURE_FLAG,MODAL_NETWORK_ALLOWLIST_FEATURE_FLAG,OVERLAP_CLONE_BOOT_FEATURE_FLAG,@@ -93,6 +94,9 @@ class TaskProcessingContext:# The kill-switch flag wins over everything; otherwise a per-run state override# (the user's toggle) applies. Captured at workflow start so it's stable across retries.rtk_enabled: bool = True+ # Captured at workflow start so the continue_as_new trigger is deterministic across replay.+ continue_as_new_enabled: bool = False+ continue_as_new_history_threshold: int = 0@propertydef mode(self) -> str:@@ -524,6 +528,36 @@ def _is_modal_directory_resume_snapshots_enabled(return enabled+def _is_continue_as_new_enabled(+ *,+ distinct_id: str,+ organization_id: str,+ run_id: str,+) -> bool:+ # The env setting force-enables (local E2E / emergency on); otherwise the org-level flag+ # decides, so it can be toggled without a deploy. Captured at workflow start, so the+ # continue_as_new trigger stays deterministic across replay. Fails closed.+ if settings.TASKS_CONTINUE_AS_NEW_ENABLED:+ return True+ try:+ enabled = bool(+ posthoganalytics.feature_enabled(+ CONTINUE_AS_NEW_FEATURE_FLAG,+ distinct_id=distinct_id,+ groups={"organization": organization_id},+ group_properties={"organization": {"id": organization_id}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+ except Exception as e:+ log_with_activity_context("continue_as_new_flag_check_failed", run_id=run_id, error=str(e))+ return False++ log_with_activity_context("continue_as_new_flag_checked", run_id=run_id, continue_as_new_enabled=enabled)+ return enabled++@activity.defn@asyncify@close_db_connections@@ -808,4 +842,10 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskProagent_proxy_keep_stream_open=agent_proxy_keep_stream_open,custom_image_name=custom_image_name,rtk_enabled=rtk_enabled,+ continue_as_new_enabled=_is_continue_as_new_enabled(+ distinct_id=distinct_id,+ organization_id=organization_id,+ run_id=run_id,+ ),+ continue_as_new_history_threshold=settings.TASKS_CONTINUE_AS_NEW_HISTORY_THRESHOLD,)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 fc19b45b68de..31a6326822cd 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@@ -47,6 +47,9 @@ HEARTBEAT_INTERVAL_SECONDS = 30SSE_CONNECT_TIMEOUT_SECONDS = 30SSE_READ_TIMEOUT_SECONDS = 300 # 5 min per chunkMAX_RECONNECT_ATTEMPTS = 5+# Coalesce streamed prose into one agent_text_delta signal per interval instead of one per+# chunk, which would bloat the parent workflow's history and trip the 2s deadlock detector.+TEXT_DELTA_FLUSH_INTERVAL_SECONDS = 1.0TERMINAL_NOTIFICATION_METHODS = frozenset({@@ -334,6 +337,9 @@ async def _relay_loop(final_message_parts: list[str] = []# ACP emits one tool_call + N tool_call_update per id; only render the start.emitted_tool_call_ids: set[str] = set()+ # Buffered prose + last flush time (monotonic); see TEXT_DELTA_FLUSH_INTERVAL_SECONDS.+ pending_text_parts: list[str] = []+ last_text_flush: list[float] = [0.0]stop_heartbeat = asyncio.Event()heartbeat_task = asyncio.create_task(@@ -421,7 +427,11 @@ async def _relay_loop(final_message_parts.clear()if is_agent_design_enabled and slack_turn_active[0] and workflow_handle is not None:slack_turn_active[0] = False- asyncio.create_task(_signal_safely(workflow_handle, "turn_completed"))+ # Awaited in order: the final prose must be recorded before+ # turn_completed, which clears the parent's relay id and would+ # otherwise drop a delta that arrived after it.+ await _flush_pending_text(workflow_handle, pending_text_parts, last_text_flush)+ await _signal_safely(workflow_handle, "turn_completed")elif not agent_active[0] and _is_active_agent_update(event_data):agent_active[0] = True@@ -433,25 +443,31 @@ async def _relay_loop(if is_agent_design_enabled and workflow_handle is not None:if not slack_turn_active[0] and _is_session_update(event_data):slack_turn_active[0] = True- asyncio.create_task(- _signal_safely(- workflow_handle,- "turn_started",- arg={"slack_thread_context": slack_thread_context or {}},- )+ # Await so turn_started is recorded before any delta of this turn,+ # and reset the flush clock so the first delta buffers rather than+ # racing turn_started to the parent.+ last_text_flush[0] = time.monotonic()+ await _signal_safely(+ workflow_handle,+ "turn_started",+ arg={"slack_thread_context": slack_thread_context or {}},)if slack_turn_active[0]:step_payload = _extract_tool_call_step(event_data, emitted_tool_call_ids)if step_payload is not None:+ # Flush buffered prose first to keep text-before-tool order.+ await _flush_pending_text(workflow_handle, pending_text_parts, last_text_flush)asyncio.create_task(_signal_safely(workflow_handle, "agent_status_update", arg=step_payload))if slack_turn_active[0] and _is_session_update(event_data):text_delta = _extract_agent_message_text(event_data)if text_delta:- asyncio.create_task(- _signal_safely(workflow_handle, "agent_text_delta", arg=text_delta)- )+ pending_text_parts.append(text_delta)+ if (time.monotonic() - last_text_flush[0]) >= TEXT_DELTA_FLUSH_INTERVAL_SECONDS:+ await _flush_pending_text(+ workflow_handle, pending_text_parts, last_text_flush+ )now = time.monotonic()if (@@ -468,11 +484,13 @@ async def _relay_loop()if _is_terminal_event(event_data):+ await _flush_pending_text(workflow_handle, pending_text_parts, last_text_flush)if finalize_stream_on_exit:await redis_stream.mark_complete()return# SSE stream ended normally (sandbox closed connection)+ await _flush_pending_text(workflow_handle, pending_text_parts, last_text_flush)if finalize_stream_on_exit:await redis_stream.mark_complete()logger.info("relay_sandbox_events_stream_closed", run_id=run_id)@@ -483,6 +501,8 @@ async def _relay_loop(# May have missed an end_of_turn on the dropped stream — assume idle until re-confirmed.agent_active[0] = Falsefinal_message_parts.clear()+ # Drop un-flushed partial prose — the agent replays events on reconnect.+ pending_text_parts.clear()logger.warning("relay_sandbox_events_read_timeout",run_id=run_id,@@ -505,6 +525,8 @@ async def _relay_loop(reconnect_count += 1agent_active[0] = False # missed-end_of_turn guard (see ReadTimeout above)final_message_parts.clear()+ # Drop un-flushed partial prose — the agent replays events on reconnect.+ pending_text_parts.clear()logger.warning("relay_sandbox_events_http_error",run_id=run_id,@@ -518,6 +540,8 @@ async def _relay_loop(reconnect_count += 1agent_active[0] = False # missed-end_of_turn guard (see ReadTimeout above)final_message_parts.clear()+ # Drop un-flushed partial prose — the agent replays events on reconnect.+ pending_text_parts.clear()logger.warning("relay_sandbox_events_connection_error",run_id=run_id,@@ -679,6 +703,25 @@ def _extract_agent_message_text(event_data: dict) -> str | None:return text if isinstance(text, str) and text else None+async def _flush_pending_text(+ workflow_handle: temporalio.client.WorkflowHandle | None,+ pending_text_parts: list[str],+ last_text_flush: list[float],+) -> None:+ """Flush buffered prose to the parent as one agent_text_delta signal.++ Awaited (not fire-and-forget) so the delta is recorded before the caller sends the next+ boundary signal, and so a flush at turn-end / terminal / stream-close isn't abandoned+ mid-delivery. The buffer is cleared only after the send returns."""+ last_text_flush[0] = time.monotonic()+ if not pending_text_parts:+ return+ text = "".join(pending_text_parts)+ if workflow_handle is not None and text:+ await _signal_safely(workflow_handle, "agent_text_delta", arg=text)+ pending_text_parts.clear()++async def _signal_safely(workflow_handle: temporalio.client.WorkflowHandle,signal_name: str,diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.pyindex c15c8ae9520e..4ad44e04e10b 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py@@ -11,6 +11,7 @@ from posthog.models.user_integration import UserIntegrationfrom products.tasks.backend.constants import (AGENT_PROXY_KEEP_STREAM_OPEN_FEATURE_FLAG,+ CONTINUE_AS_NEW_FEATURE_FLAG,MODAL_DIRECTORY_RESUME_SNAPSHOTS_FEATURE_FLAG,MODAL_VM_SANDBOX_FEATURE_FLAG,RTK_DISABLED_FEATURE_FLAG,@@ -24,6 +25,7 @@ from products.tasks.backend.temporal.process_task.activities.get_task_processingTaskProcessingContext,_is_agent_proxy_keep_stream_open_enabled,_is_burstable_sandbox_resources_enabled,+ _is_continue_as_new_enabled,_is_modal_vm_sandbox_enabled,_is_rtk_enabled,_is_sandbox_event_ingest_enabled,@@ -595,6 +597,62 @@ class TestGetTaskProcessingContextActivity:is False)+ @pytest.mark.parametrize("flag_value, expected", [(True, True), (False, False)])+ @override_settings(TASKS_CONTINUE_AS_NEW_ENABLED=False)+ def test_continue_as_new_flag_uses_organization_rollout(self, flag_value, expected):+ with patch(+ "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",+ return_value=flag_value,+ ) as feature_enabled_mock:+ assert (+ _is_continue_as_new_enabled(+ distinct_id="distinct-id",+ organization_id="organization-id",+ run_id="run-id",+ )+ is expected+ )++ feature_enabled_mock.assert_called_once_with(+ CONTINUE_AS_NEW_FEATURE_FLAG,+ distinct_id="distinct-id",+ groups={"organization": "organization-id"},+ group_properties={"organization": {"id": "organization-id"}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )++ @override_settings(TASKS_CONTINUE_AS_NEW_ENABLED=False)+ def test_continue_as_new_fails_closed_on_flag_error(self):+ with patch(+ "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",+ side_effect=RuntimeError("flag service failed"),+ ):+ assert (+ _is_continue_as_new_enabled(+ distinct_id="distinct-id",+ organization_id="organization-id",+ run_id="run-id",+ )+ is False+ )++ @override_settings(TASKS_CONTINUE_AS_NEW_ENABLED=True)+ def test_continue_as_new_env_setting_force_enables_without_flag(self):+ # The force-on env setting must not depend on the flag service.+ with patch(+ "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",+ ) as feature_enabled_mock:+ assert (+ _is_continue_as_new_enabled(+ distinct_id="distinct-id",+ organization_id="organization-id",+ run_id="run-id",+ )+ is True+ )+ feature_enabled_mock.assert_not_called()+@pytest.mark.parametrize("payload, expected",[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 795621f0fb6b..6f72962cafac 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@@ -18,6 +18,7 @@ from products.tasks.backend.temporal.process_task.activities.get_task_processingfrom products.tasks.backend.temporal.process_task.activities.relay_sandbox_events import (RelaySandboxEventsInput,TaskRunRedisStream,+ _flush_pending_text,_is_active_agent_update,_is_end_of_turn,_is_keepalive_event,@@ -26,7 +27,6 @@ from products.tasks.backend.temporal.process_task.activities.relay_sandbox_event_relay_loop,relay_sandbox_events,)-from products.tasks.backend.temporal.process_task.activities.start_agent_server import StartAgentServerOutputfrom products.tasks.backend.temporal.process_task.workflow import (RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT,ProcessTaskWorkflow,@@ -872,7 +872,8 @@ class TestRelaySandboxEventsWorkflowOptions:monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", execute_activity_mock)await workflow._relay_sandbox_events(- StartAgentServerOutput(sandbox_url="https://sandbox.example", connect_token="connect-token"),+ "https://sandbox.example",+ "connect-token",sandbox_id="sandbox-123",)@@ -880,3 +881,35 @@ class TestRelaySandboxEventsWorkflowOptions:args, kwargs = execute_activity_mock.await_argsassert args[0] is relay_sandbox_events_module.relay_sandbox_events_deferred_completionassert kwargs["start_to_close_timeout"] == RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT+++class TestFlushPendingText:+ """Coalescing many chunks into one agent_text_delta signal keeps the parent workflow's+ history small enough to replay under the 2s deadlock budget."""++ async def test_coalesces_buffered_parts_into_one_signal(self) -> None:+ handle = AsyncMock()+ parts = ["Hel", "lo, ", "world"]+ last_flush = [0.0]++ await _flush_pending_text(handle, parts, last_flush)++ # One signal carrying the joined prose; buffer drained; flush time advanced.+ handle.signal.assert_awaited_once_with("agent_text_delta", arg="Hello, world")+ assert parts == []+ assert last_flush[0] > 0.0++ async def test_empty_buffer_sends_no_signal_but_records_flush(self) -> None:+ handle = AsyncMock()+ last_flush = [0.0]++ await _flush_pending_text(handle, [], last_flush)++ # Recording the flush time even on an empty buffer keeps the interval honest.+ assert last_flush[0] > 0.0+ handle.signal.assert_not_awaited()++ async def test_no_handle_still_clears_buffer(self) -> None:+ parts = ["dropped"]+ await _flush_pending_text(None, parts, [0.0])+ assert parts == []diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex 4a8eb82ddde5..e2cc92a4ac0c 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -4,7 +4,7 @@ import uuidimport randomimport asynciofrom concurrent.futures import ThreadPoolExecutor-from datetime import timedelta+from datetime import UTC, datetime, timedeltaimport pytestfrom unittest.mock import AsyncMock, Mock@@ -12,6 +12,7 @@ from unittest.mock import AsyncMock, Mockfrom django.conf import settingsfrom asgiref.sync import sync_to_async+from parameterized import parameterizedfrom temporalio.common import RetryPolicyfrom temporalio.exceptions import ActivityError, ApplicationError, RetryStatefrom temporalio.testing import WorkflowEnvironment@@ -1386,3 +1387,101 @@ class TestProcessTaskWorkflowUnit:await workflow._get_sandbox_for_repository()assert inject_fresh_tokens_on_resume in activity_calls+++class TestContinueAsNew:+ """continue_as_new must only fire from a clean idle point and only when enabled, and the+ loop state it carries must survive the hand-off."""++ def _idle_enabled_workflow(self, *, threshold: int = 0) -> ProcessTaskWorkflow:+ wf = ProcessTaskWorkflow()+ ctx = _build_context(github_integration_id=123)+ ctx.continue_as_new_enabled = True+ ctx.continue_as_new_history_threshold = threshold+ wf._context = ctx+ return wf++ def test_build_and_restore_round_trips_loop_state(self) -> None:+ wf = self._idle_enabled_workflow()+ wf._sandbox_url = "https://sandbox.example"+ wf._sandbox_connect_token = "tok"+ wf._ci_repetitions = 2+ wf._pr_fingerprint = "fp-1"+ wf._pr_progress_emitted = True+ wf._first_user_message_received = True+ wf._is_agent_design_enabled = True+ wf._last_active_time = datetime(2026, 7, 16, 10, 30, tzinfo=UTC)+ wf._slack_thread_context = {"channel": "C1"}+ wf._posthog_mcp_scopes = "full"++ resumed_input = wf._build_resumed_input(ProcessTaskInput(run_id="run-id", create_pr=False), sandbox_id="sb-1")++ assert resumed_input.prewarmed is False+ assert resumed_input.slack_thread_context == {"channel": "C1"}+ assert resumed_input.posthog_mcp_scopes == "full"+ rs = resumed_input.resumed_sandbox+ assert rs is not None+ assert (rs.sandbox_id, rs.sandbox_url, rs.connect_token) == ("sb-1", "https://sandbox.example", "tok")++ restored = ProcessTaskWorkflow()+ restored._restore_resumed_state(rs)++ assert restored._ci_repetitions == 2+ assert restored._pr_fingerprint == "fp-1"+ assert restored._pr_progress_emitted is True+ assert restored._first_user_message_received is True+ assert restored._is_agent_design_enabled is True+ # The datetime survives the ISO round-trip.+ assert restored._last_active_time == datetime(2026, 7, 16, 10, 30, tzinfo=UTC)++ @parameterized.expand(+ [+ ("task_completed", lambda wf: setattr(wf, "_task_completed", True)),+ ("sandbox_gone", lambda wf: setattr(wf, "_sandbox_gone", True)),+ (+ "pending_followup",+ lambda wf: setattr(wf, "_pending_followup", PendingFollowup(message="m", artifact_ids=[])),+ ),+ (+ "pending_followups",+ lambda wf: wf._pending_followups.append(PendingFollowup(message="m", artifact_ids=[])),+ ),+ (+ "pending_permission",+ lambda wf: wf._pending_permission_responses.append(+ PendingPermissionResponse(request_id="r", option_id="o", actor_user_id=1)+ ),+ ),+ ("heartbeat_pending", lambda wf: setattr(wf, "_heartbeat_received", True)),+ ("slack_relay_active", lambda wf: setattr(wf, "_current_slack_relay_workflow_id", "relay-1")),+ ]+ )+ def test_does_not_continue_when_not_idle(self, _name: str, mutate) -> None:+ wf = self._idle_enabled_workflow(threshold=1)+ mutate(wf)+ # Each of these short-circuits before workflow.info(), so no workflow env is needed.+ assert wf._should_continue_as_new("sb-1") is False++ def test_does_not_continue_when_disabled(self) -> None:+ wf = self._idle_enabled_workflow(threshold=1)+ wf.context.continue_as_new_enabled = False+ assert wf._should_continue_as_new("sb-1") is False++ def test_does_not_continue_without_sandbox(self) -> None:+ wf = self._idle_enabled_workflow(threshold=1)+ assert wf._should_continue_as_new(None) is False++ def test_continues_when_history_over_threshold(self, monkeypatch: pytest.MonkeyPatch) -> None:+ wf = self._idle_enabled_workflow(threshold=100)+ fake_info = Mock()+ fake_info.get_current_history_length.return_value = 100+ fake_info.is_continue_as_new_suggested.return_value = False+ monkeypatch.setattr(process_task_workflow_module.workflow, "info", lambda: fake_info)+ assert wf._should_continue_as_new("sb-1") is True++ def test_continues_when_temporal_suggests(self, monkeypatch: pytest.MonkeyPatch) -> None:+ wf = self._idle_enabled_workflow(threshold=0) # threshold off — fall back to the SDK signal+ fake_info = Mock()+ fake_info.is_continue_as_new_suggested.return_value = True+ monkeypatch.setattr(process_task_workflow_module.workflow, "info", lambda: fake_info)+ assert wf._should_continue_as_new("sb-1") is Truediff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 6855e6727e39..059292293392 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -101,6 +101,21 @@ def _is_dead_sandbox_failure(error: BaseException) -> bool:return isinstance(cause, temporalio.exceptions.ApplicationError) and cause.type in DEAD_SANDBOX_ERROR_TYPES+@dataclass+class ResumedSandboxState:+ """Loop state carried across continue_as_new to re-attach without re-provisioning."""++ sandbox_id: str+ sandbox_url: str+ connect_token: Optional[str]+ ci_repetitions: int+ pr_fingerprint: Optional[str]+ pr_progress_emitted: bool+ first_user_message_received: bool+ is_agent_design_enabled: bool+ last_active_time: Optional[str] # ISO8601, or None if never active++@dataclassclass ProcessTaskInput:run_id: str@@ -108,6 +123,8 @@ class ProcessTaskInput:slack_thread_context: Optional[dict[str, Any]] = Noneposthog_mcp_scopes: PosthogMcpScopes = "read_only"prewarmed: bool = False+ # Set only on a continue_as_new continuation, to skip provisioning and re-attach.+ resumed_sandbox: Optional[ResumedSandboxState] = None@dataclass@@ -231,6 +248,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._slack_thread_context: Optional[dict[str, Any]] = Noneself._posthog_mcp_scopes: PosthogMcpScopes = "read_only"self._sandbox_id_for_cleanup: Optional[str] = None+ # Captured once the agent server is up, for handing to a continue_as_new continuation.+ self._sandbox_url: Optional[str] = None+ self._sandbox_connect_token: Optional[str] = Noneself._task_completed: bool = Falseself._completion_status: str = "completed"self._completion_error: Optional[str] = None@@ -269,12 +289,16 @@ class ProcessTaskWorkflow(PostHogWorkflow):@staticmethoddef parse_inputs(inputs: list[str]) -> ProcessTaskInput:loaded = json.loads(inputs[0])+ # continue_as_new carries ProcessTaskInput through Temporal's data converter, not this+ # JSON path, but reconstruct resumed_sandbox anyway so a manual re-start keeps it.+ resumed = loaded.get("resumed_sandbox")return ProcessTaskInput(run_id=loaded["run_id"],create_pr=loaded.get("create_pr", True),slack_thread_context=loaded.get("slack_thread_context"),posthog_mcp_scopes=loaded.get("posthog_mcp_scopes", "read_only"),prewarmed=loaded.get("prewarmed", False),+ resumed_sandbox=ResumedSandboxState(**resumed) if resumed else None,)async def _wait_for_task_external_event(self):@@ -491,6 +515,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):sandbox_cleaned = Falserun_stream_completed = Falsetimed_out = False+ # Handing the live sandbox to the next execution — the finally must not tear it down.+ continuing_as_new = Falserun_id = input.run_idself._sandbox_id_for_cleanup = Noneself._slack_thread_context = input.slack_thread_context@@ -515,88 +541,26 @@ class ProcessTaskWorkflow(PostHogWorkflow):success=False,error="Run environment is 'local' (desktop-driven); refusing to execute it as a cloud workflow",)- # See _PATCH_ID_SLACK_AGENT_DESIGN_STATUS. Short-circuit on- # ``_slack_thread_context`` so non-Slack runs never call the- # workflow-scoped ``workflow.patched`` API (unit tests that- # invoke ``run`` outside a Temporal event loop would otherwise- # raise "Not in workflow event loop" here). Skipping the marker- # is safe: ``_resolve_agent_design_flag`` itself returns False- # for these runs, so recording the patch would have no- # observable effect on their behavior.- if self._slack_thread_context and workflow.patched(_PATCH_ID_SLACK_AGENT_DESIGN_STATUS):- self._is_agent_design_enabled = await self._resolve_agent_design_flag()- await self._update_task_run_status("in_progress")-- # Announce the first progress step immediately so the desktop card- # shows up before any provisioning log lines arrive.- await self._emit_progress("sandbox", "in_progress", "Setting up sandbox", "setup")-- await self._track_workflow_event(- "task_run_started",- {- "run_id": run_id,- "task_id": self.context.task_id,- "repository": self.context.repository,- "team_id": self.context.team_id,- },- )-- # Agent-design path owns this surface via per-turn relay children.- if not self._is_agent_design_enabled:- await self._post_slack_update()-- sandbox_output = await self._get_sandbox_for_repository()- sandbox_id = sandbox_output.sandbox_id-- # TODO(tasks): Re-enable snapshot creation- # if sandbox_output.should_create_snapshot and self.context.repository and self.context.github_integration_id:- # await self._trigger_snapshot_workflow()-- # See `_PATCH_ID_DROP_SLACK_POST_AFTER_PROVISIONING`: only replays of- # pre-rollout histories still post here; new executions skip the- # redundant update to keep determinism for in-flight workflows.- if not workflow.patched(_PATCH_ID_DROP_SLACK_POST_AFTER_PROVISIONING):- if not self._is_agent_design_enabled:- await self._post_slack_update()-- # Run the PostHog setup wizard before the agent, when this is a cloud wizard run.- # The wizard integrates PostHog and dirties the working tree; the agent then commits- # those changes, opens the PR, and keeps it green (it never implements PostHog itself).- await self._run_wizard_if_configured(sandbox_output)-- # Start agent-server for direct connection from PostHog Code- if sandbox_output.agent_server_launched:- agent_server_output = await self._await_agent_server_ready(sandbox_output)+ if input.resumed_sandbox is None:+ sandbox_id, sandbox_url, sandbox_connect_token = await self._provision_and_start_agent(input, run_id)else:- await self._emit_progress("agent", "in_progress", "Starting agent", "setup")- agent_server_output = await self._start_agent_server(sandbox_output)- await self._emit_progress("agent", "completed", "Started agent", "setup")-- await self._track_workflow_event(- "sandbox_started",- {- "run_id": run_id,- "task_id": self.context.task_id,- "sandbox_id": sandbox_id,- "sandbox_url": agent_server_output.sandbox_url,- "used_snapshot": sandbox_output.used_snapshot,- "repository": self.context.repository,- "boot_path": sandbox_output.boot_path,- "image_source": sandbox_output.image_source,- "boot_total_ms": agent_server_output.boot_total_ms,- "sandbox_create_ms": sandbox_output.create_ms,- "repo_clone_ms": sandbox_output.clone_ms,- "branch_checkout_ms": sandbox_output.checkout_ms,- "agent_launch_ms": sandbox_output.launch_ms,- "agent_ready_wait_ms": agent_server_output.ready_wait_ms,- "agent_session_init_ms": agent_server_output.session_init_ms,- },- )+ # continue_as_new continuation — re-attach to the running sandbox, skip setup.+ self._restore_resumed_state(input.resumed_sandbox)+ sandbox_id = input.resumed_sandbox.sandbox_id+ self._sandbox_id_for_cleanup = sandbox_id+ sandbox_url = input.resumed_sandbox.sandbox_url+ sandbox_connect_token = input.resumed_sandbox.connect_token+ workflow.logger.info(+ "process_task_resumed_after_continue_as_new",+ extra={"run_id": run_id, "sandbox_id": sandbox_id},+ )+ self._sandbox_url = sandbox_url+ self._sandbox_connect_token = sandbox_connect_tokenrelay_task: asyncio.Task[None] | None = Noneif not self.context.sandbox_event_ingest_enabled:relay_task = asyncio.ensure_future(- self._relay_sandbox_events(agent_server_output, sandbox_id=sandbox_id)+ self._relay_sandbox_events(sandbox_url, sandbox_connect_token, sandbox_id=sandbox_id))elif self._is_agent_design_enabled:# Sequenced ingest streams events straight to Redis, bypassing the SSE relay that@@ -615,13 +579,30 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._run_credential_refresh_until_sandbox_gone(sandbox_id))- if self._should_forward_pending_user_message():+ # A continuation already delivered the first user message in a prior execution.+ if input.resumed_sandbox is None and self._should_forward_pending_user_message():await self._forward_pending_user_message()# Wait for completion signal or inactivity timeout.# Heartbeat signals reset the inactivity timer, keeping the workflow alive# as long as the agent is actively producing logs.while not self._task_completed:+ if self._should_continue_as_new(sandbox_id):+ assert sandbox_id is not None+ continuing_as_new = True+ workflow.logger.info(+ "process_task_continue_as_new",+ extra={+ "run_id": run_id,+ "sandbox_id": sandbox_id,+ "history_length": workflow.info().get_current_history_length(),+ },+ )+ # Stop the background loops but leave the sandbox for the next execution.+ for task in (relay_task, credential_refresh_task, permission_response_task):+ if task is not None:+ await self._cancel_relay(task)+ workflow.continue_as_new(self._build_resumed_input(input, sandbox_id))event = await self._wait_for_event()match event:case TaskEvent.TIMEOUT_REACHED:@@ -821,30 +802,168 @@ class ProcessTaskWorkflow(PostHogWorkflow):)finally:- if credential_refresh_task is not None:- await self._cancel_relay(credential_refresh_task)- if permission_response_task is not None:- await self._cancel_relay(permission_response_task)+ # Skip teardown on a continue_as_new hand-off (a `return` here would swallow the+ # ContinueAsNewError); the loops are already stopped and the sandbox lives on.+ if not continuing_as_new:+ if credential_refresh_task is not None:+ await self._cancel_relay(credential_refresh_task)+ if permission_response_task is not None:+ await self._cancel_relay(permission_response_task)++ cleanup_sandbox_id = sandbox_id or self._sandbox_id_for_cleanup+ if cleanup_sandbox_id:+ if (+ self._context+ and self._context.mode == "interactive"+ and self._context.use_modal_resume_snapshots+ ):+ await self._create_resume_snapshot(cleanup_sandbox_id)++ await self._read_sandbox_logs(cleanup_sandbox_id)+ await self._cleanup_sandbox(+ cleanup_sandbox_id,+ complete_stream=_defer_run_stream_completion(),+ )+ sandbox_cleaned = True+ self._sandbox_id_for_cleanup = None+ elif not run_stream_completed and (+ (self._context is None or self._context.environment == "cloud") and _defer_run_stream_completion()+ ):+ await self._complete_run_stream(run_id)++ if sandbox_cleaned and self._slack_thread_context and self._context:+ await self._post_slack_update(sandbox_cleaned=True)++ async def _provision_and_start_agent(self, input: ProcessTaskInput, run_id: str) -> tuple[str, str, str | None]:+ """Initial-run setup: resolve agent-design, provision the sandbox, start the agent+ server. Returns (sandbox_id, sandbox_url, connect_token). Skipped on continue_as_new."""+ # See _PATCH_ID_SLACK_AGENT_DESIGN_STATUS. Short-circuit on+ # ``_slack_thread_context`` so non-Slack runs never call the+ # workflow-scoped ``workflow.patched`` API (unit tests that+ # invoke ``run`` outside a Temporal event loop would otherwise+ # raise "Not in workflow event loop" here). Skipping the marker+ # is safe: ``_resolve_agent_design_flag`` itself returns False+ # for these runs, so recording the patch would have no+ # observable effect on their behavior.+ if self._slack_thread_context and workflow.patched(_PATCH_ID_SLACK_AGENT_DESIGN_STATUS):+ self._is_agent_design_enabled = await self._resolve_agent_design_flag()+ await self._update_task_run_status("in_progress")++ # Announce the first progress step immediately so the desktop card+ # shows up before any provisioning log lines arrive.+ await self._emit_progress("sandbox", "in_progress", "Setting up sandbox", "setup")++ await self._track_workflow_event(+ "task_run_started",+ {+ "run_id": run_id,+ "task_id": self.context.task_id,+ "repository": self.context.repository,+ "team_id": self.context.team_id,+ },+ )- cleanup_sandbox_id = sandbox_id or self._sandbox_id_for_cleanup- if cleanup_sandbox_id:- if self._context and self._context.mode == "interactive" and self._context.use_modal_resume_snapshots:- await self._create_resume_snapshot(cleanup_sandbox_id)+ # Agent-design path owns this surface via per-turn relay children.+ if not self._is_agent_design_enabled:+ await self._post_slack_update()- await self._read_sandbox_logs(cleanup_sandbox_id)- await self._cleanup_sandbox(- cleanup_sandbox_id,- complete_stream=_defer_run_stream_completion(),- )- sandbox_cleaned = True- self._sandbox_id_for_cleanup = None- elif not run_stream_completed and (- (self._context is None or self._context.environment == "cloud") and _defer_run_stream_completion()- ):- await self._complete_run_stream(run_id)+ sandbox_output = await self._get_sandbox_for_repository()+ sandbox_id = sandbox_output.sandbox_id++ # TODO(tasks): Re-enable snapshot creation+ # if sandbox_output.should_create_snapshot and self.context.repository and self.context.github_integration_id:+ # await self._trigger_snapshot_workflow()++ # See `_PATCH_ID_DROP_SLACK_POST_AFTER_PROVISIONING`: only replays of+ # pre-rollout histories still post here; new executions skip the+ # redundant update to keep determinism for in-flight workflows.+ if not workflow.patched(_PATCH_ID_DROP_SLACK_POST_AFTER_PROVISIONING):+ if not self._is_agent_design_enabled:+ await self._post_slack_update()++ # Run the PostHog setup wizard before the agent, when this is a cloud wizard run.+ # The wizard integrates PostHog and dirties the working tree; the agent then commits+ # those changes, opens the PR, and keeps it green (it never implements PostHog itself).+ await self._run_wizard_if_configured(sandbox_output)++ # Start agent-server for direct connection from PostHog Code+ if sandbox_output.agent_server_launched:+ agent_server_output = await self._await_agent_server_ready(sandbox_output)+ else:+ await self._emit_progress("agent", "in_progress", "Starting agent", "setup")+ agent_server_output = await self._start_agent_server(sandbox_output)+ await self._emit_progress("agent", "completed", "Started agent", "setup")++ await self._track_workflow_event(+ "sandbox_started",+ {+ "run_id": run_id,+ "task_id": self.context.task_id,+ "sandbox_id": sandbox_id,+ "sandbox_url": agent_server_output.sandbox_url,+ "used_snapshot": sandbox_output.used_snapshot,+ "repository": self.context.repository,+ "boot_path": sandbox_output.boot_path,+ "image_source": sandbox_output.image_source,+ "boot_total_ms": agent_server_output.boot_total_ms,+ "sandbox_create_ms": sandbox_output.create_ms,+ "repo_clone_ms": sandbox_output.clone_ms,+ "branch_checkout_ms": sandbox_output.checkout_ms,+ "agent_launch_ms": sandbox_output.launch_ms,+ "agent_ready_wait_ms": agent_server_output.ready_wait_ms,+ "agent_session_init_ms": agent_server_output.session_init_ms,+ },+ )+ return sandbox_id, agent_server_output.sandbox_url, agent_server_output.connect_token++ def _should_continue_as_new(self, sandbox_id: str | None) -> bool:+ # Only from a clean idle point — no queued work and no live Slack relay child (which+ # is cancelled on parent close). Gated on the start-captured flag so in-flight runs+ # (decoding it to False) and the trigger stay deterministic across replay.+ if self._context is None or not self.context.continue_as_new_enabled or sandbox_id is None:+ return False+ if self._task_completed or self._sandbox_gone:+ return False+ if (+ self._pending_followup is not None+ or self._pending_followups+ or self._pending_permission_responses+ or self._heartbeat_received+ or self._current_slack_relay_workflow_id is not None+ ):+ return False+ threshold = self.context.continue_as_new_history_threshold+ if threshold and workflow.info().get_current_history_length() >= threshold:+ return True+ return workflow.info().is_continue_as_new_suggested()++ def _build_resumed_input(self, input: ProcessTaskInput, sandbox_id: str) -> ProcessTaskInput:+ return ProcessTaskInput(+ run_id=input.run_id,+ create_pr=input.create_pr,+ slack_thread_context=self._slack_thread_context,+ posthog_mcp_scopes=self._posthog_mcp_scopes,+ prewarmed=False,+ resumed_sandbox=ResumedSandboxState(+ sandbox_id=sandbox_id,+ sandbox_url=self._sandbox_url or "",+ connect_token=self._sandbox_connect_token,+ ci_repetitions=self._ci_repetitions,+ pr_fingerprint=self._pr_fingerprint,+ pr_progress_emitted=self._pr_progress_emitted,+ first_user_message_received=self._first_user_message_received,+ is_agent_design_enabled=self._is_agent_design_enabled,+ last_active_time=self._last_active_time.isoformat() if self._last_active_time else None,+ ),+ )- if sandbox_cleaned and self._slack_thread_context and self._context:- await self._post_slack_update(sandbox_cleaned=True)+ def _restore_resumed_state(self, resumed: ResumedSandboxState) -> None:+ self._is_agent_design_enabled = resumed.is_agent_design_enabled+ self._ci_repetitions = resumed.ci_repetitions+ self._pr_fingerprint = resumed.pr_fingerprint+ self._pr_progress_emitted = resumed.pr_progress_emitted+ self._first_user_message_received = resumed.first_user_message_received+ self._last_active_time = datetime.fromisoformat(resumed.last_active_time) if resumed.last_active_time else Noneasync def _get_task_processing_context(self, input: ProcessTaskInput) -> TaskProcessingContext:return await workflow.execute_activity(@@ -1397,15 +1516,15 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._task_completed = Trueasync def _relay_sandbox_events(- self, agent_server_output: StartAgentServerOutput, sandbox_id: str | None = None+ self, sandbox_url: str, connect_token: str | None, sandbox_id: str | None = None) -> None:"""Start the SSE relay activity as a concurrent task (best-effort)."""try:relay_input = RelaySandboxEventsInput(run_id=self.context.run_id,task_id=self.context.task_id,- sandbox_url=agent_server_output.sandbox_url,- sandbox_connect_token=agent_server_output.connect_token,+ sandbox_url=sandbox_url,+ sandbox_connect_token=connect_token,team_id=self.context.team_id,distinct_id=self.context.distinct_id,sandbox_id=sandbox_id,