: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
chore(tasks): retire drained process-task temporal patches (#120438)
Alessandro Pogliaghi7d4b057bbc60
diff --git a/products/tasks/backend/temporal/process_task/credential_refresh.py b/products/tasks/backend/temporal/process_task/credential_refresh.pyindex d22fcf2a5aff..56e68f21e001 100644--- a/products/tasks/backend/temporal/process_task/credential_refresh.py+++ b/products/tasks/backend/temporal/process_task/credential_refresh.py@@ -69,7 +69,8 @@ async def run_credential_refresh_loop(return CredentialRefreshExitReason.CREDENTIALS_UNAVAILABLEnext_refresh_seconds = result.next_refresh_secondsexcept Exception as e:- if is_cancelled_exception(e) and workflow.patched("tasks-credential-refresh-propagate-cancel"):+ if is_cancelled_exception(e):+ workflow.deprecate_patch("tasks-credential-refresh-propagate-cancel")raise# Non-fatal: keep the run alive and retry on the default cadence.workflow.logger.warning(f"Sandbox credential refresh failed (non-fatal): {e}")diff --git a/products/tasks/backend/temporal/process_task/tests/histories/turn_ended_before_patch.json b/products/tasks/backend/temporal/process_task/tests/histories/turn_ended_before_patch.jsondeleted file mode 100644index 66fc67239d77..000000000000--- a/products/tasks/backend/temporal/process_task/tests/histories/turn_ended_before_patch.json+++ /dev/null@@ -1,320 +0,0 @@-{- "events": [- {- "eventId": "1",- "eventTime": "2026-09-21T14:33:18.010Z",- "eventType": "EVENT_TYPE_WORKFLOW_EXECUTION_STARTED",- "workflowExecutionStartedEventAttributes": {- "workflowType": {- "name": "process-task"- },- "taskQueue": {- "name": "process-task-replay"- },- "input": {- "payloads": [- {- "metadata": {- "encoding": "anNvbi9wbGFpbg=="- },- "data": "eyJjcmVhdGVfcHIiOmZhbHNlLCJpbml0aWFsX21lc3NhZ2UiOm51bGwsInBvc3Rob2dfbWNwX3Njb3BlcyI6InJlYWRfb25seSIsInByZXdhcm1lZCI6ZmFsc2UsInJlc3VtZWRfc2FuZGJveCI6eyJhY2NlcHRlZF9tZXNzYWdlX2lkcyI6W10sImFnZW50X2FjdGl2ZSI6dHJ1ZSwiYWdlbnRfYm9vdF9pbnRlcmFjdGlvbl90ZWxlbWV0cnlfZW5hYmxlZCI6bnVsbCwiYWdlbnRfcmVhZHlfYXQiOm51bGwsImJhYnlzaXRfam91cm5hbCI6eyJjb21tZW50X2lkcyI6W10sImhlYWRfa2V5cyI6W10sImhlYWRfc2hhIjoiIiwidGhyZWFkcyI6e319LCJib290X3BhdGgiOm51bGwsImNoYWluX3N0YXJ0ZWRfYXQiOm51bGwsImNpX3JlcGV0aXRpb25zIjowLCJjaV9yZXN1bWVfc25hcHNob3RfY3JlYXRlZCI6ZmFsc2UsImNvbm5lY3RfdG9rZW4iOm51bGwsImRldl9zdGFja19wcmV2aWV3X2VuYWJsZWQiOmZhbHNlLCJlbmRfb2ZfdHVybl9yZWNlaXZlZCI6ZmFsc2UsImZpcnN0X2FnZW50X2FjdGl2aXR5X3JlY29yZGVkIjpmYWxzZSwiZmlyc3RfY29tbWFuZF9kaXNwYXRjaGVkX3JlY29yZGVkIjpmYWxzZSwiZmlyc3RfdXNlcl9tZXNzYWdlX3JlY2VpdmVkIjp0cnVlLCJpbWFnZV9zb3VyY2UiOm51bGwsImlzX2FnZW50X2Rlc2lnbl9lbmFibGVkIjpmYWxzZSwiand0X2tpZCI6bnVsbCwibGFzdF9hY3RpdmVfdGltZSI6bnVsbCwibGFzdF9hZ2VudF9oZWFydGJlYXRfYXQiOm51bGwsInByX2ZpbmdlcnByaW50IjpudWxsLCJwcl9wcm9ncmVzc19lbWl0dGVkIjpmYWxzZSwicHJfdW5yZXNvbHZlZF90aHJlYWRzIjowLCJzYW5kYm94X2lkIjoic2FuZGJveC1leGFtcGxlIiwic2FuZGJveF90dGxfZXhwaXJlc19hdCI6bnVsbCwic2FuZGJveF90dGxfc25hcHNob3RfdGFrZW4iOmZhbHNlLCJzYW5kYm94X3VybCI6Imh0dHBzOi8vc2FuZGJveC5leGFtcGxlLmNvbSJ9LCJydW5faWQiOiJydW4tZXhhbXBsZSIsInNsYWNrX3RocmVhZF9jb250ZXh0IjpudWxsfQ=="- }- ]- },- "workflowExecutionTimeout": "315360000s",- "workflowRunTimeout": "315360000s",- "workflowTaskTimeout": "10s",- "originalExecutionRunId": "306b319b-5a03-4169-b3df-100e51ea821e",- "identity": "replay-test-worker",- "firstExecutionRunId": "306b319b-5a03-4169-b3df-100e51ea821e",- "attempt": 1,- "firstWorkflowTaskBackoff": "0s",- "priority": {}- }- },- {- "eventId": "2",- "eventTime": "2026-09-21T14:33:18.010Z",- "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",- "workflowTaskScheduledEventAttributes": {- "taskQueue": {- "name": "process-task-replay"- },- "startToCloseTimeout": "10s",- "attempt": 1- }- },- {- "eventId": "3",- "eventTime": "2026-09-21T14:33:18.010Z",- "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",- "workflowTaskStartedEventAttributes": {- "scheduledEventId": "2",- "identity": "replay-test-worker",- "historySizeBytes": "1257"- }- },- {- "eventId": "4",- "eventTime": "2026-09-21T14:33:18.019Z",- "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",- "workflowTaskCompletedEventAttributes": {- "scheduledEventId": "2",- "identity": "replay-test-worker",- "binaryChecksum": "e3cdf4f5d3052d99fcab05212271a0ba",- "sdkMetadata": {- "coreUsedFlags": [3, 1, 2],- "sdkName": "temporal-python",- "sdkVersion": "1.24.0"- },- "meteringMetadata": {}- }- },- {- "eventId": "5",- "eventTime": "2026-09-21T14:33:18.019Z",- "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",- "activityTaskScheduledEventAttributes": {- "activityId": "1",- "activityType": {- "name": "get_task_processing_context"- },- "taskQueue": {- "name": "process-task-replay",- "kind": "TASK_QUEUE_KIND_NORMAL"- },- "header": {},- "input": {- "payloads": [- {- "metadata": {- "encoding": "anNvbi9wbGFpbg=="- },- "data": "eyJjcmVhdGVfcHIiOmZhbHNlLCJydW5faWQiOiJydW4tZXhhbXBsZSJ9"- }- ]- },- "scheduleToCloseTimeout": "315360000s",- "scheduleToStartTimeout": "315360000s",- "startToCloseTimeout": "120s",- "heartbeatTimeout": "0s",- "workflowTaskCompletedEventId": "4",- "retryPolicy": {- "initialInterval": "1s",- "backoffCoefficient": 2.0,- "maximumInterval": "100s",- "maximumAttempts": 3- },- "priority": {}- }- },- {- "eventId": "6",- "eventTime": "2026-09-21T14:33:18.019Z",- "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",- "activityTaskStartedEventAttributes": {- "scheduledEventId": "5",- "identity": "replay-test-worker",- "attempt": 1- }- },- {- "eventId": "7",- "eventTime": "2026-09-21T14:33:18.021Z",- "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",- "activityTaskCompletedEventAttributes": {- "result": {- "payloads": [- {- "metadata": {- "encoding": "anNvbi9wbGFpbg=="- },- "data": "eyJfYnJhbmNoIjpudWxsLCJhZ2VudF9vdGVsX3RlbGVtZXRyeV9lbmFibGVkIjpmYWxzZSwiYWdlbnRfcHJveHlfa2VlcF9zdHJlYW1fb3BlbiI6ZmFsc2UsImFnZW50c2hfZG9tYWluX2FsbG93bGlzdCI6bnVsbCwiYWxsb3dlZF9kb21haW5zIjpudWxsLCJiZW5qYW1pbl9lbmFibGVkIjpmYWxzZSwiYnVyc3RhYmxlX3NhbmRib3hfcmVzb3VyY2VzX2VuYWJsZWQiOnRydWUsImNpX3Byb21wdCI6bnVsbCwiY2xhdWRlX21vZGVsX2FjY2VzcyI6InBvc3Rob2ctZ2F0ZXdheSIsImNvbnRleHRfbGF5ZXJfZW5hYmxlZCI6ZmFsc2UsImNvbnRpbnVlX2FzX25ld19lbmFibGVkIjpmYWxzZSwiY29udGludWVfYXNfbmV3X2hpc3RvcnlfdGhyZXNob2xkIjowLCJjcmVhdGVfcHIiOmZhbHNlLCJjdXN0b21faW1hZ2VfbmFtZSI6bnVsbCwiZGVza3RvcF93b3Jrc3BhY2Vfd2FybV9lbmFibGVkIjpmYWxzZSwiZGV2X3N0YWNrX3ByZXZpZXdfZW5hYmxlZCI6ZmFsc2UsImRpc3RpbmN0X2lkIjoidXNlci1leGFtcGxlIiwiZW52aXJvbm1lbnQiOm51bGwsImdpdGh1Yl9pbnRlZ3JhdGlvbl9pZCI6bnVsbCwiZ2l0aHViX3VzZXJfaW50ZWdyYXRpb25faWQiOm51bGwsImludGVyYWN0aXZlX21heF9ydW5fZHVyYXRpb25fc2Vjb25kcyI6bnVsbCwianNvbl9zY2hlbWEiOm51bGwsIm1vZGFsX2RvbWFpbl9hbGxvd2xpc3QiOm51bGwsIm5ldHdvcmtfcG9saWN5X2ZpbmdlcnByaW50IjpudWxsLCJvcmdhbml6YXRpb25faWQiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDIiLCJvcmlnaW5fcHJvZHVjdCI6bnVsbCwib3ZlcmxhcF9jbG9uZV9ib290X2VuYWJsZWQiOmZhbHNlLCJwZWVyX21lc3NhZ2luZ19lbmFibGVkIjpmYWxzZSwicHJfYmFieXNpdF9lbmFibGVkIjpmYWxzZSwicHJfbG9vcF9lbmFibGVkIjpmYWxzZSwicmVwb3NpdG9yeSI6bnVsbCwicnRrX2VuYWJsZWQiOnRydWUsInJ1bl9pZCI6InJ1bi1leGFtcGxlIiwic2FuZGJveF9iYWNrZW5kIjoibW9kYWwiLCJzYW5kYm94X2Vudmlyb25tZW50X25hbWUiOm51bGwsInNhbmRib3hfZXZlbnRfaW5nZXN0X2VuYWJsZWQiOnRydWUsInNhbmRib3hfcm90YXRpb25fZW5hYmxlZCI6ZmFsc2UsInN0YXRlIjp7ImluYWN0aXZpdHlfdGltZW91dF9zZWNvbmRzIjoxMjAsIm1vZGUiOiJpbnRlcmFjdGl2ZSJ9LCJ0YXNrX2NyZWF0ZWRfYnlfaWQiOm51bGwsInRhc2tfaWQiOiJ0YXNrLWV4YW1wbGUiLCJ0YXNrX3J1bnRpbWUiOiJhY3AiLCJ0ZWFtX2lkIjoxLCJ0ZWFtX3V1aWQiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDEiLCJ1c2VfbW9kYWxfZGlyZWN0b3J5X3Jlc3VtZV9zbmFwc2hvdHMiOmZhbHNlLCJ1c2VfbW9kYWxfbmV0d29ya19hbGxvd2xpc3QiOmZhbHNlLCJ1c2VfbW9kYWxfcmVzdW1lX3NuYXBzaG90cyI6ZmFsc2UsInVzZV9tb2RhbF92bV9zYW5kYm94IjpmYWxzZX0="- }- ]- },- "scheduledEventId": "5",- "startedEventId": "6",- "identity": "replay-test-worker"- }- },- {- "eventId": "8",- "eventTime": "2026-09-21T14:33:18.021Z",- "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",- "workflowTaskScheduledEventAttributes": {- "taskQueue": {- "name": "process-task-replay"- },- "startToCloseTimeout": "10s",- "attempt": 1- }- },- {- "eventId": "9",- "eventTime": "2026-09-21T14:33:18.021Z",- "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",- "workflowTaskStartedEventAttributes": {- "scheduledEventId": "8",- "identity": "replay-test-worker",- "historySizeBytes": "3231"- }- },- {- "eventId": "10",- "eventTime": "2026-09-21T14:33:18.023Z",- "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",- "workflowTaskCompletedEventAttributes": {- "scheduledEventId": "8",- "identity": "replay-test-worker",- "binaryChecksum": "e3cdf4f5d3052d99fcab05212271a0ba",- "sdkMetadata": {},- "meteringMetadata": {}- }- },- {- "eventId": "11",- "eventTime": "2026-09-21T14:33:18.023Z",- "eventType": "EVENT_TYPE_TIMER_STARTED",- "timerStartedEventAttributes": {- "timerId": "1",- "startToFireTimeout": "600s",- "workflowTaskCompletedEventId": "10"- }- },- {- "eventId": "12",- "eventTime": "2026-09-21T14:33:18.035Z",- "eventType": "EVENT_TYPE_WORKFLOW_EXECUTION_SIGNALED",- "workflowExecutionSignaledEventAttributes": {- "signalName": "agent_state_changed",- "input": {- "payloads": [- {- "metadata": {- "encoding": "anNvbi9wbGFpbg=="- },- "data": "ZmFsc2U="- }- ]- },- "identity": "replay-test-worker"- }- },- {- "eventId": "13",- "eventTime": "2026-09-21T14:33:18.035Z",- "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",- "workflowTaskScheduledEventAttributes": {- "taskQueue": {- "name": "process-task-replay"- },- "startToCloseTimeout": "10s",- "attempt": 1- }- },- {- "eventId": "14",- "eventTime": "2026-09-21T14:33:18.035Z",- "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",- "workflowTaskStartedEventAttributes": {- "scheduledEventId": "13",- "identity": "replay-test-worker",- "historySizeBytes": "3528"- }- },- {- "eventId": "15",- "eventTime": "2026-09-21T14:33:18.036Z",- "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",- "workflowTaskCompletedEventAttributes": {- "scheduledEventId": "13",- "identity": "replay-test-worker",- "binaryChecksum": "e3cdf4f5d3052d99fcab05212271a0ba",- "sdkMetadata": {},- "meteringMetadata": {}- }- },- {- "eventId": "16",- "eventTime": "2026-09-21T14:43:18.023Z",- "eventType": "EVENT_TYPE_TIMER_FIRED",- "timerFiredEventAttributes": {- "timerId": "1",- "startedEventId": "11"- }- },- {- "eventId": "17",- "eventTime": "2026-09-21T14:43:18.023Z",- "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",- "workflowTaskScheduledEventAttributes": {- "taskQueue": {- "name": "process-task-replay"- },- "startToCloseTimeout": "10s",- "attempt": 1- }- },- {- "eventId": "18",- "eventTime": "2026-09-21T14:43:18.023Z",- "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",- "workflowTaskStartedEventAttributes": {- "scheduledEventId": "17",- "identity": "replay-test-worker",- "historySizeBytes": "3724"- }- },- {- "eventId": "19",- "eventTime": "2026-09-21T14:43:18.025Z",- "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",- "workflowTaskCompletedEventAttributes": {- "scheduledEventId": "17",- "identity": "replay-test-worker",- "binaryChecksum": "e3cdf4f5d3052d99fcab05212271a0ba",- "sdkMetadata": {},- "meteringMetadata": {}- }- },- {- "eventId": "20",- "eventTime": "2026-09-21T14:43:18.025Z",- "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",- "activityTaskScheduledEventAttributes": {- "activityId": "2",- "activityType": {- "name": "update_task_run_status"- },- "taskQueue": {- "name": "process-task-replay",- "kind": "TASK_QUEUE_KIND_NORMAL"- },- "header": {},- "input": {- "payloads": [- {- "metadata": {- "encoding": "anNvbi9wbGFpbg=="- },- "data": "eyJhZ2VudF9hY3RpdmVfYXRfdGVybWluYXRpb24iOmZhbHNlLCJlbmRfb2ZfdHVybl9yZWNlaXZlZCI6dHJ1ZSwiZXJyb3JfbWVzc2FnZSI6bnVsbCwiZXJyb3JfdHlwZSI6bnVsbCwibGFzdF9hZ2VudF9oZWFydGJlYXRfYXQiOm51bGwsInJ1bl9pZCI6InJ1bi1leGFtcGxlIiwic2Vjb25kc19zaW5jZV9sYXN0X2FnZW50X2hlYXJ0YmVhdCI6bnVsbCwic3RhdHVzIjoiY29tcGxldGVkIiwidGltZWRfb3V0X2luYWN0aXZpdHkiOnRydWUsInRpbWVvdXRfbWFya2VyIjpudWxsfQ=="- }- ]- },- "scheduleToCloseTimeout": "315360000s",- "scheduleToStartTimeout": "315360000s",- "startToCloseTimeout": "60s",- "heartbeatTimeout": "0s",- "workflowTaskCompletedEventId": "19",- "retryPolicy": {- "initialInterval": "1s",- "backoffCoefficient": 2.0,- "maximumInterval": "100s",- "maximumAttempts": 3- },- "priority": {}- }- }- ]-}diff --git a/products/tasks/backend/temporal/process_task/tests/test_ci_follow_up_decision.py b/products/tasks/backend/temporal/process_task/tests/test_ci_follow_up_decision.pyindex 793ba9cc5a93..a96ab4fb292a 100644--- a/products/tasks/backend/temporal/process_task/tests/test_ci_follow_up_decision.py+++ b/products/tasks/backend/temporal/process_task/tests/test_ci_follow_up_decision.py@@ -252,7 +252,7 @@ class TestBabysitFollowUpDecision:return snapshot if activity_fn is get_pr_babysit_snapshot else Falsemonkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", execute)- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", lambda _: True)+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())await wf._should_run_ci_follow_up()@@ -298,21 +298,14 @@ class TestBabysitFollowUpDecision:assert await wf._should_run_ci_follow_up() is expected_decision- @pytest.mark.parametrize(- "patch_recorded,expected_decision",- [- (True, CIFollowUpDecision.WAIT),- (False, CIFollowUpDecision.FIRE),- ],- )- async def test_merge_queue_skip_follows_the_patch_marker(self, monkeypatch, patch_recorded, expected_decision):+ async def test_merge_queue_push_waits_instead_of_firing(self, monkeypatch):wf = _babysit_workflow()_patch_snapshot(monkeypatch, _babysit_snapshot(failing_checks=[BABYSIT_CHECK], merge_queue_push_would_eject=True))- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", lambda _: patch_recorded)+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())- assert await wf._should_run_ci_follow_up() is expected_decision+ assert await wf._should_run_ci_follow_up() is CIFollowUpDecision.WAITasync def test_dispatched_check_is_silenced_until_a_new_head(self, monkeypatch):wf = _babysit_workflow()diff --git a/products/tasks/backend/temporal/process_task/tests/test_credential_refresh.py b/products/tasks/backend/temporal/process_task/tests/test_credential_refresh.pyindex d0a471782ac5..883db2b1e6c7 100644--- a/products/tasks/backend/temporal/process_task/tests/test_credential_refresh.py+++ b/products/tasks/backend/temporal/process_task/tests/test_credential_refresh.py@@ -21,10 +21,7 @@ class TestRunCredentialRefreshLoop:monkeypatch.setattr(credential_refresh_module.workflow, "sleep", AsyncMock())monkeypatch.setattr(credential_refresh_module.workflow, "logger", MagicMock())- @pytest.mark.parametrize("patched", [True, False])- async def test_cancel_during_activity_propagates_only_for_patched_histories(- self, monkeypatch: pytest.MonkeyPatch, patched: bool- ) -> None:+ async def test_cancel_during_activity_propagates(self, monkeypatch: pytest.MonkeyPatch) -> None:activity_started = asyncio.Event()cancelled = ActivityError("Activity cancelled",@@ -47,8 +44,7 @@ class TestRunCredentialRefreshLoop:execute_activity = AsyncMock(side_effect=blocked_activity)self._patch_workflow(monkeypatch, execute_activity)- patch = MagicMock(return_value=patched)- monkeypatch.setattr(credential_refresh_module.workflow, "patched", patch)+ monkeypatch.setattr(credential_refresh_module.workflow, "deprecate_patch", MagicMock())task = asyncio.create_task(run_credential_refresh_loop(MagicMock(), "sb-1"))await activity_started.wait()execute_activity.side_effect = None@@ -57,15 +53,10 @@ class TestRunCredentialRefreshLoop:)task.cancel()- if patched:- with pytest.raises(ActivityError) as error:- await task- assert error.value is cancelled- assert execute_activity.await_count == 1- else:- assert await task == CredentialRefreshExitReason.SANDBOX_GONE- assert execute_activity.await_count == 2- patch.assert_called_once_with("tasks-credential-refresh-propagate-cancel")+ with pytest.raises(ActivityError) as error:+ await task+ assert error.value is cancelled+ assert execute_activity.await_count == 1async def test_non_cancellation_failure_retries(self, monkeypatch: pytest.MonkeyPatch) -> None:execute_activity = AsyncMock(diff --git a/products/tasks/backend/temporal/process_task/tests/test_replay.py b/products/tasks/backend/temporal/process_task/tests/test_replay.pyindex b548cb9fa510..0483e01fd933 100644--- a/products/tasks/backend/temporal/process_task/tests/test_replay.py+++ b/products/tasks/backend/temporal/process_task/tests/test_replay.py@@ -10,16 +10,12 @@ from temporalio.worker import Replayer, UnsandboxedWorkflowRunnerfrom products.tasks.backend.temporal.process_task.workflow import ProcessTaskWorkflow[email protected](params=["turn_ended_before_patch", "continued_open_turn"])-def history(request: pytest.FixtureRequest) -> WorkflowHistory:- return WorkflowHistory.from_json(- "process-task-replay", (Path(__file__).parent / "histories" / f"{request.param}.json").read_text()- )--@pytest.mark.asyncio@override_settings(TASKS_INACTIVITY_TIMEOUT_SECONDS=0)-async def test_saved_history_replays(history: WorkflowHistory) -> None:+async def test_saved_history_replays() -> None:+ history = WorkflowHistory.from_json(+ "process-task-replay", (Path(__file__).parent / "histories" / "continued_open_turn.json").read_text()+ )await Replayer(workflows=[ProcessTaskWorkflow],workflow_runner=UnsandboxedWorkflowRunner(),diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex e195d434b65b..41cab81e0536 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -617,31 +617,13 @@ class TestSandboxRotation:assert (wf._sandbox_rotation_block_reason() is None) is expected- def test_open_turn_guard_preserves_pre_patch_rotation(self, monkeypatch):- wf = ProcessTaskWorkflow()- wf._context = _build_context(github_integration_id=123, state={"mode": "interactive"})- wf._context.sandbox_rotation_enabled = True- wf._sandbox_rotation_idle = True- wf._agent_active = None- wf._end_of_turn_received = False- monkeypatch.setattr(process_task_workflow_module.workflow, "in_workflow", Mock(return_value=True))- patched = Mock(return_value=False)- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", patched)-- assert wf._sandbox_rotation_block_reason() is None- assert patched.call_args_list == [- call("tasks-block-rotation-on-open-turn"),- call("tasks-rotation-activity-guard"),- ]-- @pytest.mark.parametrize("patched", [True, False])async def test_background_heartbeats_block_rotation_without_reopening_the_user_turn(- self, monkeypatch: pytest.MonkeyPatch, patched: bool+ self, monkeypatch: pytest.MonkeyPatch) -> None:wf = self._workflow(monkeypatch)monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=datetime.now(UTC)))monkeypatch.setattr(process_task_workflow_module.workflow, "in_workflow", Mock(return_value=True))- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=patched))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())await wf.agent_state_changed(False)assert wf._sandbox_rotation_block_reason() is None@@ -650,7 +632,7 @@ class TestSandboxRotation:assert wf._end_of_turn_received is Trueassert wf._agent_active is False- assert wf._sandbox_rotation_block_reason() == ("agent_activity" if patched else None)+ assert wf._sandbox_rotation_block_reason() == "agent_activity"await wf.agent_state_changed(False)assert wf._sandbox_rotation_block_reason() is None@@ -1102,7 +1084,6 @@ class TestProcessTaskFollowupDispatch:monkeypatch.setattr(workflow, "_send_followup_to_sandbox", fake_send_followup)monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=Mock()))- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())@@ -1246,7 +1227,6 @@ class TestProcessTaskFollowupDispatch:monkeypatch.setattr(workflow, "_send_followup_to_sandbox", fake_send_followup)monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=Mock()))- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())@@ -1314,7 +1294,6 @@ class TestProcessTaskFollowupDispatch:monkeypatch.setattr(workflow, "_send_followup_to_sandbox", fake_send_followup)monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=Mock()))- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())@@ -1332,7 +1311,7 @@ class TestProcessTaskFollowupDispatch:class TestFollowupDeliveryFailureBookkeeping:- def _workflow(self, monkeypatch, *, mode: str, patched: bool):+ def _workflow(self, monkeypatch, *, mode: str):workflow = ProcessTaskWorkflow()workflow._context = _build_context(github_integration_id=123, state={"mode": mode})emitted: list[EmitProgressInput] = []@@ -1345,13 +1324,12 @@ class TestFollowupDeliveryFailureBookkeeping:return Nonemonkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", fake_execute_activity)- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=patched))monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())return workflow, emittedasync def test_failed_interactive_delivery_releases_the_message_for_retry(self, monkeypatch):- workflow, emitted = self._workflow(monkeypatch, mode="interactive", patched=True)+ workflow, emitted = self._workflow(monkeypatch, mode="interactive")await workflow.send_followup_message("try this", [], "msg-1")assert len(workflow._pending_followups) == 1@@ -1366,9 +1344,8 @@ class TestFollowupDeliveryFailureBookkeeping:await workflow.send_followup_message("try this", [], "msg-1")assert len(workflow._pending_followups) == 2- @pytest.mark.parametrize("mode,patched", [("interactive", False), ("background", True)])- async def test_failed_delivery_terminalizes_when_keep_alive_does_not_apply(self, monkeypatch, mode, patched):- workflow, emitted = self._workflow(monkeypatch, mode=mode, patched=patched)+ async def test_failed_background_delivery_terminalizes_the_run(self, monkeypatch):+ workflow, emitted = self._workflow(monkeypatch, mode="background")result = await workflow._send_followup_to_sandbox("try this", [], message_id="msg-1")@@ -1633,7 +1610,7 @@ async def test_sandbox_started_carries_run_attribution(origin_product, team_id,_build_context(github_integration_id=123, origin_product=origin_product), team_id=team_id)- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())monkeypatch.setattr(workflow_instance, "_update_task_run_status", AsyncMock())monkeypatch.setattr(workflow_instance, "_emit_progress", AsyncMock())monkeypatch.setattr(workflow_instance, "_post_slack_update", AsyncMock())@@ -1760,9 +1737,7 @@ class TestProcessTaskWorkflowUnit:async def test_send_followup_message_can_arrive_before_context_is_loaded(self, monkeypatch):logger = Mock()- deprecate_patch = Mock()monkeypatch.setattr(process_task_workflow_module.workflow, "logger", logger)- monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", deprecate_patch)workflow = ProcessTaskWorkflow()await workflow.send_followup_message("first", ["artifact-1"])@@ -1775,7 +1750,6 @@ class TestProcessTaskWorkflowUnit:PendingFollowup(message="legacy-steer", artifact_ids=["artifact-3"], steer=True, sequence=2),]assert workflow._pending_followup is None- deprecate_patch.assert_called_with(process_task_workflow_module._PATCH_ID_FOLLOWUP_QUEUE)logger.info.assert_any_call("send_followup_signal_received",extra={@@ -2060,9 +2034,8 @@ class TestProcessTaskWorkflowUnit:monkeypatch.setattr(workflow, "_wait_for_inactivity", inactivity_mock)monkeypatch.setattr(workflow, "_wait_for_task_external_event", AsyncMock(side_effect=never))- monkeypatch.setattr(process_task_workflow_module, "_run_lifecycle_bounds_enabled", Mock(return_value=False))monkeypatch.setattr(process_task_workflow_module.workflow, "wait", asyncio.wait)- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())monkeypatch.setattr(process_task_workflow_module.workflow, "set_current_details", Mock())assert await workflow._wait_for_event() == process_task_workflow_module.TaskEvent.TIMEOUT_REACHED@@ -2070,11 +2043,11 @@ class TestProcessTaskWorkflowUnit:assert inactivity_mock.await_args.args[0] == timedelta(seconds=expected_seconds)@pytest.mark.parametrize(- "patched, minutes_since_active, expected_sleep_seconds",- [(True, 25, 300), (True, 35, None), (True, None, 1800), (False, 25, 1800)],+ "minutes_since_active, expected_sleep_seconds",+ [(25, 300), (35, None), (None, 1800)],)async def test_a_non_activity_wake_does_not_restart_the_inactivity_timer(- self, monkeypatch, patched, minutes_since_active, expected_sleep_seconds+ self, monkeypatch, minutes_since_active, expected_sleep_seconds):now = datetime(2026, 1, 1, 12, 0, tzinfo=UTC)workflow = ProcessTaskWorkflow()@@ -2082,7 +2055,7 @@ class TestProcessTaskWorkflowUnit:workflow._last_active_time = now - timedelta(minutes=minutes_since_active)sleep_mock = AsyncMock()monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=now))- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=patched))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())monkeypatch.setattr(process_task_workflow_module.workflow, "sleep", sleep_mock)result = await workflow._wait_for_inactivity(timedelta(minutes=30))@@ -2092,8 +2065,7 @@ class TestProcessTaskWorkflowUnit:sleep_mock.assert_not_awaited()else:sleep_mock.assert_awaited_once_with(expected_sleep_seconds)- if patched:- assert workflow._last_active_time is not None+ assert workflow._last_active_time is not Noneasync def test_an_overdue_inactivity_timeout_yields_to_a_queued_signal(self, monkeypatch):workflow = ProcessTaskWorkflow()@@ -2108,33 +2080,26 @@ class TestProcessTaskWorkflowUnit:"_wait_for_task_external_event",AsyncMock(return_value=process_task_workflow_module.TaskEvent.SIGNAL_RECEIVED),)- monkeypatch.setattr(process_task_workflow_module, "_run_lifecycle_bounds_enabled", Mock(return_value=False))monkeypatch.setattr(process_task_workflow_module.workflow, "wait", asyncio.wait)- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())monkeypatch.setattr(process_task_workflow_module.workflow, "set_current_details", Mock())assert await workflow._wait_for_event() == process_task_workflow_module.TaskEvent.SIGNAL_RECEIVED- @pytest.mark.parametrize("patched", [True, False])- async def test_turn_end_wakes_the_wait_only_once_the_patch_is_recorded(self, monkeypatch, patched):+ async def test_turn_end_wakes_the_wait(self, monkeypatch):workflow = ProcessTaskWorkflow()workflow._context = _build_context(github_integration_id=123)- monkeypatch.setattr(process_task_workflow_module.workflow, "in_workflow", Mock(return_value=True))- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=patched))await workflow.agent_state_changed(False)assert workflow._end_of_turn_received is True- assert workflow._turn_ended_received is patched- if patched:+ assert workflow._turn_ended_received is True- async def fake_wait_condition(condition):- assert condition()+ async def fake_wait_condition(condition):+ assert condition()- monkeypatch.setattr(process_task_workflow_module.workflow, "wait_condition", fake_wait_condition)- assert (- await workflow._wait_for_task_external_event() == process_task_workflow_module.TaskEvent.SIGNAL_RECEIVED- )+ monkeypatch.setattr(process_task_workflow_module.workflow, "wait_condition", fake_wait_condition)+ assert await workflow._wait_for_task_external_event() == process_task_workflow_module.TaskEvent.SIGNAL_RECEIVEDasync def test_a_late_heartbeat_does_not_reopen_an_ended_turn(self, monkeypatch):workflow = ProcessTaskWorkflow()@@ -2182,7 +2147,7 @@ class TestProcessTaskWorkflowUnit:# ingest-only run must not inherit it, or a lost agent later this turn is hidden.workflow._agent_active = Falsemonkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())monkeypatch.setattr(process_task_workflow_module.workflow, "uuid4", Mock(return_value="uuid"))monkeypatch.setattr(workflow, "_emit_progress", AsyncMock())activity = AsyncMock(side_effect=outcome) if isinstance(outcome, Exception) else AsyncMock(return_value=outcome)@@ -2221,7 +2186,7 @@ class TestProcessTaskWorkflowUnit:return outcomemonkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())monkeypatch.setattr(process_task_workflow_module.workflow, "uuid4", Mock(return_value="uuid"))monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=datetime.now(UTC)))monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", deliver_after_turn_completes)@@ -2240,30 +2205,6 @@ class TestProcessTaskWorkflowUnit:assert workflow._end_of_turn_received is (expected_status == "completed")assert workflow._agent_active is (False if expected_status == "completed" else None)- async def test_followup_delivery_preserves_the_pre_patch_turn_reset(self, monkeypatch):- workflow = ProcessTaskWorkflow()- workflow._context = _build_context(github_integration_id=123)- workflow._end_of_turn_received = True- workflow._agent_active = False-- async def deliver_after_turn_completes(*_args, **_kwargs):- await workflow.agent_state_changed(False)- return None-- def patched(patch_id: str) -> bool:- return patch_id == process_task_workflow_module._PATCH_ID_TURN_OPENS_ON_DISPATCH-- monkeypatch.setattr(process_task_workflow_module.workflow, "in_workflow", Mock(return_value=True))- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", patched)- monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())- monkeypatch.setattr(process_task_workflow_module.workflow, "uuid4", Mock(return_value="uuid"))- monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", deliver_after_turn_completes)-- await workflow._send_followup_to_sandbox("go", [])-- assert workflow._end_of_turn_received is False- assert workflow._agent_active is None-async def test_credential_refresh_exit_marks_sandbox_gone(self, monkeypatch):workflow = ProcessTaskWorkflow()workflow._context = _build_context(github_integration_id=123)@@ -2289,16 +2230,13 @@ class TestProcessTaskWorkflowUnit:)@pytest.mark.parametrize(- "patched, lookup_result, expected_error",+ "lookup_result, expected_error",[- (True, "timed out", "Sandbox stopped: timed out. Resume to continue."),- (True, RuntimeError("lookup failed"), "Sandbox stopped; resume to continue"),- (False, "timed out", "Sandbox stopped; resume to continue"),+ ("timed out", "Sandbox stopped: timed out. Resume to continue."),+ (RuntimeError("lookup failed"), "Sandbox stopped; resume to continue"),],)- async def test_relay_sandbox_loss_records_the_sandbox_exit_reason(- self, monkeypatch, patched, lookup_result, expected_error- ):+ async def test_relay_sandbox_loss_records_the_sandbox_exit_reason(self, monkeypatch, lookup_result, expected_error):workflow = ProcessTaskWorkflow()workflow._context = _build_context(github_integration_id=123)lookups: list[str] = []@@ -2312,7 +2250,7 @@ class TestProcessTaskWorkflowUnit:return Truemonkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", fake_execute_activity)- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=patched))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())await workflow._relay_sandbox_events("https://sandbox.example", "connect-token", sandbox_id="sandbox-123")@@ -2322,7 +2260,7 @@ class TestProcessTaskWorkflowUnit:await workflow._mark_sandbox_gone()- assert lookups == (["sandbox-123"] if patched else [])+ assert lookups == ["sandbox-123"]assert workflow._completion_error == expected_errorasync def test_completion_signal_during_the_exit_reason_lookup_wins(self, monkeypatch):@@ -2336,7 +2274,7 @@ class TestProcessTaskWorkflowUnit:return "timed out"monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", fake_execute_activity)- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())await workflow._mark_sandbox_gone()@@ -2437,7 +2375,7 @@ class TestProcessTaskWorkflowUnit:monkeypatch.setattr(workflow, "_post_slack_update", AsyncMock())monkeypatch.setattr(workflow, "_emit_progress", AsyncMock())monkeypatch.setattr(workflow, "_get_sandbox_for_repository", get_sandbox_mock)- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())result = await workflow.run(ProcessTaskInput(run_id="run-id"))@@ -2560,7 +2498,8 @@ class TestProcessTaskWorkflowUnit:workflow, "_wait_for_event", AsyncMock(return_value=process_task_workflow_module.TaskEvent.TIMEOUT_REACHED))monkeypatch.setattr(workflow, "_relay_sandbox_events", relay_sandbox_events_mock)- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())+ monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=datetime.now(UTC)))result = await workflow.run(ProcessTaskInput(run_id="run-id"))@@ -2614,6 +2553,8 @@ class TestProcessTaskWorkflowUnit:start_slack_relay_mock = AsyncMock()monkeypatch.setattr(workflow, "_start_slack_agent_design_relay", start_slack_relay_mock)monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())+ monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=datetime.now(UTC)))result = await workflow.run(ProcessTaskInput(@@ -2750,6 +2691,8 @@ class TestProcessTaskWorkflowUnit:monkeypatch.setattr(workflow, "_wait_for_event", wait_for_event)monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())+ monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=datetime.now(UTC)))# run() awaits the permission-response drainer on the completion path; outside a# Temporal event loop the real workflow.wait_condition raises immediately.@@ -2964,6 +2907,8 @@ class TestProcessTaskWorkflowUnit:monkeypatch.setattr(workflow, "_wait_for_event", wait_for_event)monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())+ monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=datetime.now(UTC)))# workflow.logger resolves the replay flag off the workflow event loop, which this# loop-free unit test doesn't have.monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())@@ -2994,73 +2939,11 @@ class TestProcessTaskWorkflowUnit:workflow._context = _build_context(github_integration_id=123, origin_product="onboarding", create_pr=create_pr)workflow._pr_progress_emitted = pr_progress_emittedworkflow._ci_repetitions = ci_repetitions- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())assert workflow._onboarding_exit_is_failure() is expected- async def test_run_keeps_completing_inactivity_timeouts_before_the_lifecycle_patch(self, monkeypatch):- # Replaying a pre-patch history: the onboarding FAILED terminalization must not apply, or the- # replay would write a different terminal status than the recorded one.- workflow = ProcessTaskWorkflow()- context = _build_context(github_integration_id=123, origin_product="onboarding")- update_task_run_status_mock = AsyncMock()-- monkeypatch.setattr(workflow, "_get_task_processing_context", AsyncMock(return_value=context))- monkeypatch.setattr(workflow, "_update_task_run_status", update_task_run_status_mock)- monkeypatch.setattr(workflow, "_track_workflow_event", AsyncMock())- monkeypatch.setattr(workflow, "_post_slack_update", AsyncMock())- monkeypatch.setattr(workflow, "_read_sandbox_logs", AsyncMock())- monkeypatch.setattr(workflow, "_cleanup_sandbox", AsyncMock())- monkeypatch.setattr(workflow, "_create_resume_snapshot", AsyncMock())- monkeypatch.setattr(workflow, "_emit_progress", AsyncMock())- monkeypatch.setattr(workflow, "_forward_pending_user_message", AsyncMock())- monkeypatch.setattr(- workflow,- "_get_sandbox_for_repository",- AsyncMock(- return_value=GetSandboxForRepositoryOutput(- sandbox_id="sandbox-123",- sandbox_url="https://sandbox.example",- connect_token="connect-token",- used_snapshot=False,- should_create_snapshot=False,- )- ),- )- monkeypatch.setattr(- workflow,- "_start_agent_server",- AsyncMock(- return_value=StartAgentServerOutput(- sandbox_url="https://sandbox.example",- connect_token="connect-token",- )- ),- )- monkeypatch.setattr(workflow, "_relay_sandbox_events", AsyncMock())- monkeypatch.setattr(- workflow, "_wait_for_event", AsyncMock(return_value=process_task_workflow_module.TaskEvent.TIMEOUT_REACHED)- )- # The patch helpers short-circuit to "enabled" outside a workflow, so the replay case only- # exists once in_workflow() is true and the marker is absent.- monkeypatch.setattr(process_task_workflow_module.workflow, "in_workflow", Mock(return_value=True))- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=False))-- result = await workflow.run(ProcessTaskInput(run_id="run-id"))-- assert result.success is True- update_task_run_status_mock.assert_any_await("completed", timed_out_inactivity=True)-- @pytest.mark.parametrize(- "patched, expected_post_slack_calls",- [- (True, 2), # post-rollout: the provisioning post is skipped (initial + completion remain)- (False, 3), # pre-rollout replay: provisioning post is still scheduled to match history- ],- )- async def test_run_gates_slack_post_after_provisioning_on_patch(- self, monkeypatch, patched, expected_post_slack_calls- ):+ async def test_run_skips_slack_post_after_provisioning(self, monkeypatch):workflow = ProcessTaskWorkflow()post_slack_update_mock = AsyncMock()@@ -3102,12 +2985,13 @@ class TestProcessTaskWorkflowUnit:workflow, "_wait_for_event", AsyncMock(return_value=process_task_workflow_module.TaskEvent.TIMEOUT_REACHED))monkeypatch.setattr(workflow, "_relay_sandbox_events", AsyncMock())- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=patched))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())+ monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=datetime.now(UTC)))result = await workflow.run(ProcessTaskInput(run_id="run-id"))assert result.success is True- assert post_slack_update_mock.await_count == expected_post_slack_calls+ assert post_slack_update_mock.await_count == 2async def test_run_drains_boot_progress_cards_still_pending_at_exit(self, monkeypatch):workflow_instance = ProcessTaskWorkflow()@@ -3165,8 +3049,8 @@ class TestProcessTaskWorkflowUnit:AsyncMock(return_value=process_task_workflow_module.TaskEvent.TIMEOUT_REACHED),)monkeypatch.setattr(workflow_instance, "_relay_sandbox_events", AsyncMock())- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))- monkeypatch.setattr(process_task_workflow_module, "_progress_emit_nonblocking", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())+ monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=datetime.now(UTC)))monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", fake_execute_activity)run_task = asyncio.create_task(workflow_instance.run(ProcessTaskInput(run_id="run-id")))@@ -3268,7 +3152,7 @@ class TestProcessTaskWorkflowUnit:process_workflow._task_completed = Trueassert predicate()- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", lambda _patch_id: True)+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())monkeypatch.setattr(process_task_workflow_module.workflow, "start_activity", fake_start_activity)monkeypatch.setattr(process_task_workflow_module.workflow, "wait_condition", fake_wait_condition)@@ -3422,7 +3306,8 @@ class TestProcessTaskWorkflowUnit:raise AssertionError(f"Unexpected activity call: {activity_fn}")monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", fake_execute_activity)- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", lambda _: True)+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())result = await workflow._get_sandbox_for_repository()@@ -3491,7 +3376,8 @@ class TestProcessTaskWorkflowUnit:raise AssertionError(f"Unexpected activity call: {activity_fn}")monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", fake_execute_activity)- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", lambda _: True)+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())result = await workflow._get_sandbox_for_repository()@@ -3562,6 +3448,7 @@ class TestProcessTaskWorkflowUnit:or patch_id != process_task_workflow_module._PATCH_ID_FAIL_RUN_ON_PRIMARY_CLONE_FAILURE),)+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())if fail_on_primary_clone_failure:@@ -3572,6 +3459,7 @@ class TestProcessTaskWorkflowUnit:returnresult = await workflow._get_sandbox_for_repository()+ await workflow._flush_pending_progress_activities()assert result.agent_server_launched is Trueassert mark_repo_ready in calls@@ -3622,65 +3510,14 @@ class TestProcessTaskWorkflowUnit:raise AssertionError(f"Unexpected activity call: {activity_fn}")monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", fake_execute_activity)- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", lambda _: True)+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())with pytest.raises(ApplicationError, match="sandbox disappeared"):await workflow._get_sandbox_for_repository()assert mark_repo_ready not in calls- async def test_overlap_preserves_legacy_repo_ready_order_on_replay(self, monkeypatch):- workflow = ProcessTaskWorkflow()- workflow._context = _build_context(- github_integration_id=123,- state={"repositories": ["posthog/posthog", "posthog/code"]},- )- workflow._context.overlap_clone_boot_enabled = True- prepared = PrepareSandboxForRepositoryOutput(- sandbox_name="sandbox-name",- repository="posthog/posthog",- github_token="ghs_token",- branch=None,- environment_variables={},- snapshot_id=None,- snapshot_external_id=None,- used_snapshot=False,- should_create_snapshot=True,- shallow_clone=True,- image_source="base_image",- image_source_label="published sandbox base image",- )- created = CreateSandboxForRepositoryOutput(- sandbox_id="sandbox-123",- sandbox_url="https://sandbox.example",- connect_token="connect-token",- )- calls: list[str] = []-- async def fake_execute_activity(activity_fn: Any, *args: Any, **kwargs: Any) -> Any:- if activity_fn is prepare_sandbox_for_repository:- return prepared- if activity_fn is create_sandbox_for_repository:- return created- if activity_fn is launch_agent_server:- return StartAgentServerOutput(sandbox_url=created.sandbox_url)- if activity_fn is clone_repository_in_sandbox:- calls.append(f"clone:{args[0].repository}")- return None- if activity_fn is mark_repo_ready:- calls.append("ready")- return None- if activity_fn is emit_progress_activity:- return None- raise AssertionError(f"Unexpected activity call: {activity_fn}")-- monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", fake_execute_activity)- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", lambda _: False)-- await workflow._get_sandbox_for_repository()-- assert calls == ["clone:posthog/posthog", "clone:posthog/code", "ready"]-@pytest.mark.parametrize("custom_image_name, expected_image_source, expected_image_source_label",[@@ -3749,7 +3586,8 @@ class TestProcessTaskWorkflowUnit:monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", fake_execute_activity)monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())- monkeypatch.setattr(process_task_workflow_module.workflow, "patched", lambda _: True)+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())result = await workflow._get_sandbox_for_repository()diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 4c0260cd9da5..1dade7446b4e 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -105,11 +105,7 @@ from .activities.record_peer_message_outcome import (peer_message_id_from_context,record_peer_message_outcome,)-from .activities.relay_sandbox_events import (- RelaySandboxEventsInput,- relay_sandbox_events,- relay_sandbox_events_deferred_completion,-)+from .activities.relay_sandbox_events import RelaySandboxEventsInput, relay_sandbox_events_deferred_completionfrom .activities.run_wizard import RunWizardInput, run_wizardfrom .activities.send_followup_to_sandbox import (SEND_FOLLOWUP_MAX_ATTEMPTS,@@ -351,59 +347,22 @@ from products.tasks.backend.temporal.constants import ( # noqa: E402WARM_IDLE_TIMEOUT,)-# Rolling-deploy deprecation bundle (TODO slug: tasks-ci-follow-up-pr-context-cleanup)-# ----------------------------------------------------------------------------# The PR-context guard inserted a new `get_pr_context` activity before the-# existing CI follow-up dispatch. Without versioning, replay of pre-rollout-# histories failed with nondeterminism because those histories scheduled-# `send_followup_to_sandbox` directly at this point in the workflow.-#-# Cleanup follows the standard two-step Temporal patch lifecycle:-# 1. First cleanup PR: replace `workflow.patched(...)` with-# `workflow.deprecate_patch(...)` and remove the legacy replay-only path.-# 2. Second cleanup PR (after another full drain): delete this helper and-# `_PATCH_ID_CI_FOLLOW_UP_PR_CONTEXT`.-_PATCH_ID_CI_FOLLOW_UP_PR_CONTEXT = "tasks-ci-follow-up-pr-context"--# The follow-up queue patch swapped the single-slot `_pending_followup` for a-# `_pending_followups` list inside the `send_followup_message` signal handler.-# Calling `workflow.patched(...)` from a signal handler is unsafe: signals can-# land in different workflow-task boundaries across replays (rolling deploys,-# sticky-cache eviction, worker restarts), which leaves the patch marker in-# history with no matching command on replay (TMPRL1100). Switch to-# `deprecate_patch(...)` so the marker is treated as compatible regardless of-# which workflow task records it. Same two-step lifecycle as above.-_PATCH_ID_FOLLOWUP_QUEUE = "tasks-follow-up-message-queue"-# Follow-up delivery waits synchronously for the sandbox turn to finish. Keep# that delivery in the background so a later steer signal can reach the active# turn, while ordinary follow-ups remain queued behind it._PATCH_ID_CONCURRENT_FOLLOWUP_STEERING = "tasks-concurrent-followup-steering"-# Existing onboarding histories include the setup agent in boot_total_ms, so replay must-# preserve that input while new histories subtract the setup agent's elapsed time._PATCH_ID_EXCLUDE_WIZARD_FROM_BOOT_TOTAL = "tasks-exclude-wizard-from-boot-total"-# Multi-repo histories before this patch release the agent only after every clone completes.-# Preserve that command order on replay while new runs can release it after the primary clone._PATCH_ID_AGENT_READY_AFTER_PRIMARY_CLONE = "tasks-agent-ready-after-primary-clone"_DEV_STACK_PREVIEW_WAIT_TIMEOUT = timedelta(minutes=15)-# #60923 dropped the redundant slack post that ran immediately after sandbox-# provisioning — between `_get_sandbox_for_repository` and the agent-start-# progress emit. Pre-rollout histories scheduled a `post_slack_update` activity-# at that point, so removing it unconditionally broke replay of in-flight-# workflows with TMPRL1100: the next command (`emit_progress_activity`) no-# longer matched the recorded `post_slack_update` event. Gate the removal —-# post-rollout executions skip the call, replays of older histories still-# schedule it. Same two-step cleanup lifecycle as the patches above._PATCH_ID_DROP_SLACK_POST_AFTER_PROVISIONING = "tasks-drop-slack-post-after-provisioning"# Self-driving-origin implementation runs periodically re-check the org's self-driving credits quota and-# cancel themselves before opening the billable PR when the org crossed its limit mid-run. Gates-# the recheck timer + activity commands so pre-rollout histories replay without them.+# cancel themselves before opening the billable PR when the org crossed its limit mid-run._PATCH_ID_SELF_DRIVING_QUOTA_KILL = "tasks-self-driving-quota-kill"# How often a PR-less self-driving run re-checks the quota while waiting on agent activity. Frequent@@ -412,34 +371,23 @@ SELF_DRIVING_QUOTA_RECHECK_INTERVAL = timedelta(minutes=5)_ORIGIN_PRODUCT_SIGNAL_REPORT = "signal_report"-# Gates the new agent-design flag-eval execute_activity site.-# Two-step deprecate-then-delete cleanup lifecycle as above._PATCH_ID_SLACK_AGENT_DESIGN_STATUS = "tasks-slack-agent-design-status"# Gates the forward of the agent_final_text signal to the Slack relay. A worker without the# handler records that signal in history and sends nothing, so a replay that forwards it emits a-# command the history does not have (TMPRL1100). Same two-step cleanup lifecycle as above.+# command the history does not have (TMPRL1100)._PATCH_ID_SLACK_AGENT_FINAL_TEXT = "tasks-slack-agent-final-text"# Progress steps of sandbox setup. The Slack plan shows them until the first turn starts._SLACK_SETUP_PROGRESS_STEPS = frozenset({"sandbox", "clone", "checkout", "wizard", "agent"})-# Gates the refusal to execute local-environment (desktop-driven) runs. Pre-guard-# histories of such runs proceeded into provisioning; the marker keeps their replays-# deterministic. Same two-step cleanup lifecycle as above._PATCH_ID_SKIP_LOCAL_ENVIRONMENT_RUNS = "tasks-skip-local-environment-runs"-# Defers stream completion to cleanup without breaking existing histories._PATCH_ID_DEFER_RUN_STREAM_COMPLETION = "tasks-defer-run-stream-completion"_PATCH_ID_COMPLETE_STREAM_AFTER_CLEANUP_FAILURE = "tasks-complete-stream-after-cleanup-failure"-# Gates the run lifecycle bounds: the hard wall-clock timer added to `_wait_for_event`-# (a new Timer command, so replays of pre-rollout histories must not schedule it) and the-# onboarding-origin FAILED terminalizations for the inactivity and sandbox-gone paths.-# Same two-step deprecate-then-delete cleanup lifecycle as the patches above._PATCH_ID_RUN_LIFECYCLE_BOUNDS = "tasks-run-lifecycle-bounds"-# Keep histories that already recorded a failed wall-clock exit on their original branch._PATCH_ID_DELIVERED_PR_TIMEOUT_STATUS = "tasks-delivered-pr-timeout-status"_PATCH_ID_SNAPSHOT_BEFORE_CI_FOLLOW_UP = "tasks-snapshot-before-ci-follow-up"@@ -447,15 +395,10 @@ _PATCH_ID_CI_IDLE_SKIP_CAP = "tasks-ci-idle-skip-cap"AGENT_LOST_ERROR_MESSAGE = "The agent stopped before finishing its turn"-# Replays of pre-rollout histories must keep recording an idle exit as completed._PATCH_ID_TURN_OPENS_ON_DISPATCH = "tasks-turn-opens-on-dispatch"-# Changing the deadline branch changes the activities it schedules, so pre-rollout histories-# must retain the old rotation decision when replayed._PATCH_ID_BLOCK_ROTATION_ON_OPEN_TURN = "tasks-block-rotation-on-open-turn"-# Preserving a completion signal can enable later command-producing branches, so histories that-# already recorded the post-delivery reset must retain it during replay._PATCH_ID_PRESERVE_COMPLETION_DURING_DELIVERY = "tasks-preserve-completion-during-delivery"_PATCH_ID_ROTATION_ACTIVITY_GUARD = "tasks-rotation-activity-guard"@@ -463,28 +406,24 @@ _PATCH_ID_ROTATION_ACTIVITY_GUARD = "tasks-rotation-activity-guard"_PATCH_ID_ROTATION_ACTIVITY_BEFORE_BOOT = "tasks-rotation-activity-before-boot"-def _turn_opens_on_dispatch() -> bool:- if not workflow.in_workflow():- return True- return workflow.patched(_PATCH_ID_TURN_OPENS_ON_DISPATCH)+def _turn_opens_on_dispatch() -> None:+ if workflow.in_workflow():+ workflow.deprecate_patch(_PATCH_ID_TURN_OPENS_ON_DISPATCH)-def _block_rotation_on_open_turn() -> bool:- if not workflow.in_workflow():- return True- return workflow.patched(_PATCH_ID_BLOCK_ROTATION_ON_OPEN_TURN)+def _block_rotation_on_open_turn() -> None:+ if workflow.in_workflow():+ workflow.deprecate_patch(_PATCH_ID_BLOCK_ROTATION_ON_OPEN_TURN)-def _preserve_completion_during_delivery() -> bool:- if not workflow.in_workflow():- return True- return workflow.patched(_PATCH_ID_PRESERVE_COMPLETION_DURING_DELIVERY)+def _preserve_completion_during_delivery() -> None:+ if workflow.in_workflow():+ workflow.deprecate_patch(_PATCH_ID_PRESERVE_COMPLETION_DURING_DELIVERY)-def _rotation_activity_guard() -> bool:- if not workflow.in_workflow():- return True- return workflow.patched(_PATCH_ID_ROTATION_ACTIVITY_GUARD)+def _rotation_activity_guard() -> None:+ if workflow.in_workflow():+ workflow.deprecate_patch(_PATCH_ID_ROTATION_ACTIVITY_GUARD)def _check_rotation_activity_before_boot() -> bool:@@ -495,14 +434,12 @@ def _check_rotation_activity_before_boot() -> bool:# Keeps an interactive run alive when follow-up delivery exhausts retries, releasing# the message's dedupe key so a retry can land; background runs keep the fail-fast-# terminalization poll_for_turn callers rely on. Same cleanup lifecycle as above.+# terminalization poll_for_turn callers rely on._PATCH_ID_FOLLOWUP_FAILURE_KEEPS_RUN = "tasks-followup-failure-keeps-run"_PATCH_ID_DEV_STACK_PREVIEW = "tasks-dev-stack-preview"_PATCH_ID_PROGRESS_EMIT_NONBLOCKING = "progress-emit-nonblocking-2026-09"-# A new activity worker can record the merge queue flag as true while an old workflow worker-# ignores it and dispatches, so replay takes the skip only where the marker was recorded._PATCH_ID_MERGE_QUEUE_SKIP = "tasks-merge-queue-skip-2026-09"_PATCH_ID_INACTIVITY_ANCHORED_ON_LAST_ACTIVITY = "tasks-inactivity-anchored-on-last-activity"_PATCH_ID_SANDBOX_EXIT_REASON_ON_RELAY_LOSS = "tasks-sandbox-exit-reason-on-relay-loss"@@ -517,38 +454,34 @@ _ONBOARDING_ORIGIN_PRODUCT = "onboarding"_WORKFLOW_ORIGIN_PRODUCT = "workflow"-def _deprecate_ci_follow_up_pr_context_patch() -> None:- workflow.deprecate_patch(_PATCH_ID_CI_FOLLOW_UP_PR_CONTEXT)---def _defer_run_stream_completion() -> bool:- if not workflow.in_workflow():- return True- return workflow.patched(_PATCH_ID_DEFER_RUN_STREAM_COMPLETION)+def _defer_run_stream_completion() -> None:+ if workflow.in_workflow():+ workflow.deprecate_patch(_PATCH_ID_DEFER_RUN_STREAM_COMPLETION)-def _complete_stream_after_cleanup_failure() -> bool:- if not workflow.in_workflow():- return True- return workflow.patched(_PATCH_ID_COMPLETE_STREAM_AFTER_CLEANUP_FAILURE)+def _complete_stream_after_cleanup_failure() -> None:+ if workflow.in_workflow():+ workflow.deprecate_patch(_PATCH_ID_COMPLETE_STREAM_AFTER_CLEANUP_FAILURE)-def _run_lifecycle_bounds_enabled() -> bool:- if not workflow.in_workflow():- return True- return workflow.patched(_PATCH_ID_RUN_LIFECYCLE_BOUNDS)+def _run_lifecycle_bounds_enabled() -> None:+ if workflow.in_workflow():+ workflow.deprecate_patch(_PATCH_ID_RUN_LIFECYCLE_BOUNDS)-def _dev_stack_preview_enabled() -> bool:- return workflow.in_workflow() and workflow.patched(_PATCH_ID_DEV_STACK_PREVIEW)+def _dev_stack_preview_enabled() -> None:+ if workflow.in_workflow():+ workflow.deprecate_patch(_PATCH_ID_DEV_STACK_PREVIEW)-def _agent_boot_interaction_telemetry_enabled() -> bool:- return workflow.in_workflow() and workflow.patched(_PATCH_ID_AGENT_BOOT_INTERACTION_TELEMETRY)+def _agent_boot_interaction_telemetry_enabled() -> None:+ if workflow.in_workflow():+ workflow.deprecate_patch(_PATCH_ID_AGENT_BOOT_INTERACTION_TELEMETRY)-def _progress_emit_nonblocking() -> bool:- return workflow.in_workflow() and workflow.patched(_PATCH_ID_PROGRESS_EMIT_NONBLOCKING)+def _progress_emit_nonblocking() -> None:+ if workflow.in_workflow():+ workflow.deprecate_patch(_PATCH_ID_PROGRESS_EMIT_NONBLOCKING)@temporalio.workflow.defn(name="process-task")@@ -788,22 +721,19 @@ class ProcessTaskWorkflow(PostHogWorkflow):if self._pending_followup is None and not self._pending_followups:return- if not workflow.patched(_PATCH_ID_CONCURRENT_FOLLOWUP_STEERING):- return+ workflow.deprecate_patch(_PATCH_ID_CONCURRENT_FOLLOWUP_STEERING)followup = self._pop_next_followup()if followup is not None:await self._dispatch_followup(followup)async def _wait_for_inactivity(self, timeout: timedelta = INACTIVITY_TIMEOUT):- if workflow.patched(_PATCH_ID_INACTIVITY_ANCHORED_ON_LAST_ACTIVITY):- if self._last_active_time is None:- self._last_active_time = workflow.now()- remaining = timeout - (workflow.now() - self._last_active_time)- if remaining.total_seconds() > 0:- await workflow.sleep(remaining.total_seconds())- else:- await workflow.sleep(timeout.total_seconds())+ workflow.deprecate_patch(_PATCH_ID_INACTIVITY_ANCHORED_ON_LAST_ACTIVITY)+ if self._last_active_time is None:+ self._last_active_time = workflow.now()+ remaining = timeout - (workflow.now() - self._last_active_time)+ if remaining.total_seconds() > 0:+ await workflow.sleep(remaining.total_seconds())return TaskEvent.TIMEOUT_REACHEDasync def _wait_for_max_run_duration(self, cap: timedelta):@@ -840,7 +770,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):return TaskEvent.CI_FOLLOW_UPdef _self_driving_quota_recheck_scheduled(self) -> bool:- return (+ scheduled = (self._self_driving_quota_checks_activeand self._context is not Noneand self.context.origin_product == _ORIGIN_PRODUCT_SIGNAL_REPORT@@ -848,8 +778,10 @@ class ProcessTaskWorkflow(PostHogWorkflow):# never open the billable PR; rechecking them would let the quota gate cancel# in-flight research.and self.context.create_pr- and workflow.patched(_PATCH_ID_SELF_DRIVING_QUOTA_KILL))+ if scheduled:+ workflow.deprecate_patch(_PATCH_ID_SELF_DRIVING_QUOTA_KILL)+ return scheduleddef _record_sandbox_deadline(self, created: CreateSandboxForRepositoryOutput) -> None:"""Remember when the provider will kill this sandbox, so the run can snapshot first.@@ -907,13 +839,15 @@ class ProcessTaskWorkflow(PostHogWorkflow):return "flag_disabled"if self._agent_active:return "agent_active"- if self._end_of_turn_received is False and _block_rotation_on_open_turn():+ if self._end_of_turn_received is False:+ _block_rotation_on_open_turn()return "turn_open"if self._active_followup_task is not None and not self._active_followup_task.done():return "followup_in_flight"if self._task_completed:return "run_completed"- if _rotation_activity_guard() and not self._sandbox_rotation_idle:+ _rotation_activity_guard()+ if not self._sandbox_rotation_idle:return "agent_activity"return None@@ -1002,13 +936,12 @@ class ProcessTaskWorkflow(PostHogWorkflow):asyncio.create_task(self._wait_for_task_external_event()),asyncio.create_task(self._wait_for_inactivity(inactivity_timeout)),]- # Hard wall-clock cap, independent of the heartbeat-reset inactivity timer. The- # patch gate keeps replays of pre-rollout histories from scheduling the new timer;+ # Hard wall-clock cap, independent of the heartbeat-reset inactivity timer.# None means the run is exempt (interactive sessions a human may keep open for hours).- if _run_lifecycle_bounds_enabled():- max_run_duration = self.context.max_run_duration()- if max_run_duration is not None:- possible_events.append(asyncio.create_task(self._wait_for_max_run_duration(max_run_duration)))+ _run_lifecycle_bounds_enabled()+ max_run_duration = self.context.max_run_duration()+ if max_run_duration is not None:+ possible_events.append(asyncio.create_task(self._wait_for_max_run_duration(max_run_duration)))if self._sandbox_deadline_snapshot_scheduled():possible_events.append(asyncio.create_task(self._wait_for_sandbox_deadline()))if ci_follow_up_scheduled:@@ -1021,12 +954,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):pending_tasks_results = await asyncio.gather(*pending, return_exceptions=True) # Ensure all pending tasks are cancelled- completed_events = (- self._completed_events_in_priority_order(done)- if workflow.patched(_PATCH_ID_INACTIVITY_ANCHORED_ON_LAST_ACTIVITY)- else done- )- for task in completed_events:+ workflow.deprecate_patch(_PATCH_ID_INACTIVITY_ANCHORED_ON_LAST_ACTIVITY)+ for task in self._completed_events_in_priority_order(done):if task.exception():workflow.logger.warning("Event wait task failed",@@ -1106,7 +1035,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):},)return CIFollowUpDecision.SKIP- if pr_context.merge_queue_push_would_eject and workflow.patched(_PATCH_ID_MERGE_QUEUE_SKIP):+ if pr_context.merge_queue_push_would_eject:+ workflow.deprecate_patch(_PATCH_ID_MERGE_QUEUE_SKIP)workflow.logger.info("PR is in the merge queue, skipping CI follow-up",extra={"run_id": self.context.run_id, "pr_url": pr_context.pr_url},@@ -1236,7 +1166,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):label = "PR merged" if snapshot.pr_state == "merged" else "PR closed"await self._emit_progress("ci", "completed", label, "setup")return CIFollowUpDecision.TERMINAL- if snapshot.merge_queue_push_would_eject and workflow.patched(_PATCH_ID_MERGE_QUEUE_SKIP):+ if snapshot.merge_queue_push_would_eject:+ workflow.deprecate_patch(_PATCH_ID_MERGE_QUEUE_SKIP)# The journal stays untouched, so the feedback waits for the next tick after the PR# leaves the queue instead of being marked handled.workflow.logger.info(@@ -1254,8 +1185,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):and not self._pending_followupsand not self._task_completedand snapshot.can_mark_ready- and workflow.patched("tasks-pr-auto-ready-v1")):+ workflow.deprecate_patch("tasks-pr-auto-ready-v1")try:changed = await workflow.execute_activity(mark_pr_ready,@@ -1346,9 +1277,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):permission_response_task: asyncio.Task[None] | None = Nonepreview_task: asyncio.Task[None] | None = Noneagent_shadow_task: asyncio.Task[None] | None = None- self._agent_boot_interaction_telemetry_enabled = (- input.resumed_sandbox is None and _agent_boot_interaction_telemetry_enabled()- )+ self._agent_boot_interaction_telemetry_enabled = input.resumed_sandbox is None+ if input.resumed_sandbox is None:+ _agent_boot_interaction_telemetry_enabled()try:self._context = await self._get_task_processing_context(input)if self._stream_generation is not None:@@ -1359,10 +1290,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):# A local-environment run is driven by the user's desktop agent — QUEUED does not# mean "awaiting a cloud workflow". Executing it here would boot a sandbox the repo# was never cloned into and, once the attempts burn out, stomp the live local- # session's status. Refuse without touching the run. The environment check comes- # first so cloud runs (and unit tests exercising them outside a workflow event- # loop) never call ``workflow.patched``.- if self.context.environment == "local" and workflow.patched(_PATCH_ID_SKIP_LOCAL_ENVIRONMENT_RUNS):+ # session's status. Refuse without touching the run.+ if self.context.environment == "local":+ workflow.deprecate_patch(_PATCH_ID_SKIP_LOCAL_ENVIRONMENT_RUNS)workflow.logger.warning("Refusing to process local-environment run in cloud workflow",extra={"run_id": run_id, "task_id": self.context.task_id},@@ -1374,7 +1304,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):if input.resumed_sandbox is None:self._dev_stack_preview_enabled = self.context.dev_stack_preview_enabledsandbox_id, sandbox_url, sandbox_connect_token = await self._provision_and_start_agent(input, run_id)- if self._agent_shadow_launched and workflow.patched(_PATCH_ID_ASYNC_AGENT_SHADOW_RESULT):+ if self._agent_shadow_launched:+ workflow.deprecate_patch(_PATCH_ID_ASYNC_AGENT_SHADOW_RESULT)agent_shadow_task = asyncio.create_task(self._collect_agent_shadow_result(sandbox_id))else:# continue_as_new continuation — re-attach to the running sandbox, skip setup.@@ -1408,7 +1339,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._run_credential_refresh_until_sandbox_gone(sandbox_id))- if self._dev_stack_preview_enabled and _dev_stack_preview_enabled():+ if self._dev_stack_preview_enabled:+ _dev_stack_preview_enabled()preview_task = self._start_dev_stack_preview(sandbox_id)# A continuation already delivered the first user message in a prior execution.@@ -1417,8 +1349,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):await self._dispatch_next_followup()elif input.resumed_sandbox is None and self._should_forward_pending_user_message():# A non-interactive agent starts its first turn on boot, before any event arrives.- if _turn_opens_on_dispatch():- self._end_of_turn_received = False+ _turn_opens_on_dispatch()+ self._end_of_turn_received = Falseawait self._forward_pending_user_message()# Wait for completion signal or inactivity timeout.@@ -1466,7 +1398,6 @@ class ProcessTaskWorkflow(PostHogWorkflow):"CI follow-up event triggered",extra={"run_id": self.context.run_id, "repetitions": self._ci_repetitions},)- _deprecate_ci_follow_up_pr_context_patch()follow_up_result = await self._should_run_ci_follow_up()if (not self._ci_resume_snapshot_created@@ -1475,8 +1406,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):and follow_up_result not in (CIFollowUpDecision.NO_PR, CIFollowUpDecision.TERMINAL)and self.context.mode == "interactive"and self.context.use_modal_resume_snapshots- and workflow.patched(_PATCH_ID_SNAPSHOT_BEFORE_CI_FOLLOW_UP)):+ workflow.deprecate_patch(_PATCH_ID_SNAPSHOT_BEFORE_CI_FOLLOW_UP)self._ci_resume_snapshot_created = await self._create_resume_snapshot(sandbox_id,reason="ci_follow_up",@@ -1497,11 +1428,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):# whenever last_active_time is older than the delay, and the# workflow tight-loops calling GET /repos/.../pulls/{n}.self._last_active_time = workflow.now()- if (- follow_up_result == CIFollowUpDecision.SKIP- and self.context.mode != "interactive"- and workflow.patched(_PATCH_ID_CI_IDLE_SKIP_CAP)- ):+ if follow_up_result == CIFollowUpDecision.SKIP and self.context.mode != "interactive":+ workflow.deprecate_patch(_PATCH_ID_CI_IDLE_SKIP_CAP)self._ci_idle_skips += 1case _:raise ValueError(f"Unknown CIFollowUpDecision: {follow_up_result}")@@ -1536,7 +1464,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):rotation_reason = rotation.reasonif rotated_sandbox_id:sandbox_id = rotated_sandbox_id- if self._dev_stack_preview_enabled and _dev_stack_preview_enabled():+ if self._dev_stack_preview_enabled:+ _dev_stack_preview_enabled()if preview_task is not None:await self._cancel_relay(preview_task)preview_task = self._start_dev_stack_preview(sandbox_id)@@ -1628,41 +1557,20 @@ class ProcessTaskWorkflow(PostHogWorkflow):case TaskEvent.SANDBOX_GONE:await self._mark_sandbox_gone()case TaskEvent.SIGNAL_RECEIVED:- if workflow.patched(_PATCH_ID_CONCURRENT_FOLLOWUP_STEERING):- if self._has_dispatchable_followup():- pending_followup_count = len(self._pending_followups) + (- 1 if self._pending_followup is not None else 0- )- workflow.logger.info(- "Pending follow-up message received, sending to sandbox",- extra={- "run_id": self.context.run_id,- "pending_followup_count": pending_followup_count,- },- )- if await self._dispatch_next_followup():- continue- else:+ workflow.deprecate_patch(_PATCH_ID_CONCURRENT_FOLLOWUP_STEERING)+ if self._has_dispatchable_followup():pending_followup_count = len(self._pending_followups) + (1 if self._pending_followup is not None else 0)- if pending_followup_count == 0:- pending_followup = None- elif self._pending_followup is not None:- pending_followup = self._pending_followup- self._pending_followup = None- else:- pending_followup = self._pending_followups.pop(0)- if pending_followup is not None:- workflow.logger.info(- "Pending follow-up message received, sending to sandbox",- extra={- "run_id": self.context.run_id,- "pending_followup_count": pending_followup_count,- },- )- await self._dispatch_followup(pending_followup)- continue+ workflow.logger.info(+ "Pending follow-up message received, sending to sandbox",+ extra={+ "run_id": self.context.run_id,+ "pending_followup_count": pending_followup_count,+ },+ )+ if await self._dispatch_next_followup():+ continueif self._heartbeat_received and not self._task_completed:workflow.logger.info(@@ -1714,12 +1622,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):timeout_marker=self._completion_timeout_marker,)elif timeout_event == TaskEvent.MAX_DURATION_REACHED:- # Only reachable under the lifecycle-bounds patch (the timer is gated on it).- status = (- "completed"- if workflow.patched(_PATCH_ID_DELIVERED_PR_TIMEOUT_STATUS) and self._delivered_pr_watch_complete()- else "failed"- )+ workflow.deprecate_patch(_PATCH_ID_DELIVERED_PR_TIMEOUT_STATUS)+ status = "completed" if self._delivered_pr_watch_complete() else "failed"await self._update_task_run_status(status, timeout_marker=TIMED_OUT_WALL_CLOCK_STATE_KEY)elif timeout_event is not None and self._agent_lost_exit_is_failure():await self._update_task_run_status(@@ -1765,12 +1669,12 @@ class ProcessTaskWorkflow(PostHogWorkflow):)await self._update_task_run_status("cancelled", run_id=run_id)if current_sandbox_id:- complete_stream = _defer_run_stream_completion()+ _defer_run_stream_completion()await self._cleanup_sandbox(current_sandbox_id,- complete_stream=complete_stream,+ complete_stream=True,)- run_stream_completed = complete_stream+ run_stream_completed = Truesandbox_id = Noneself._sandbox_id_for_cleanup = Noneraise@@ -1878,15 +1782,15 @@ class ProcessTaskWorkflow(PostHogWorkflow):)await self._read_sandbox_logs(cleanup_sandbox_id)+ _defer_run_stream_completion()await self._cleanup_sandbox(cleanup_sandbox_id,- complete_stream=_defer_run_stream_completion(),+ complete_stream=True,)sandbox_cleaned = Trueself._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()- ):+ elif not run_stream_completed and (self._context is None or self._context.environment == "cloud"):+ _defer_run_stream_completion()await self._complete_run_stream(run_id)if sandbox_cleaned and self._slack_thread_context and self._context:@@ -1910,15 +1814,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):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 agentserver. 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):+ if self._slack_thread_context:+ workflow.deprecate_patch(_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")@@ -1956,12 +1853,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):# 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()+ workflow.deprecate_patch(_PATCH_ID_DROP_SLACK_POST_AFTER_PROVISIONING)# 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@@ -2204,11 +2096,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._sandbox_jwt_kid = created.jwt_kidself._dev_stack_preview_enabled = self._dev_stack_preview_enabled and created.dev_stack_preview_sizedself._record_sandbox_deadline(created)- if (- self._task_completed- and prepared.sandbox_creation_cancellable- and workflow.patched(_PATCH_ID_CANCEL_SANDBOX_CREATION_ON_COMPLETION)- ):+ if self._task_completed and prepared.sandbox_creation_cancellable:+ workflow.deprecate_patch(_PATCH_ID_CANCEL_SANDBOX_CREATION_ON_COMPLETION)raise _TaskCompletedDuringSandboxCreationused_snapshot = created.used_snapshot if created.used_snapshot is not None else prepared.used_snapshotif used_snapshot:@@ -2297,11 +2186,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._sandbox_jwt_kid = created.jwt_kidself._dev_stack_preview_enabled = self._dev_stack_preview_enabled and created.dev_stack_preview_sizedself._record_sandbox_deadline(created)- if (- self._task_completed- and prepared.sandbox_creation_cancellable- and workflow.patched(_PATCH_ID_CANCEL_SANDBOX_CREATION_ON_COMPLETION)- ):+ if self._task_completed and prepared.sandbox_creation_cancellable:+ workflow.deprecate_patch(_PATCH_ID_CANCEL_SANDBOX_CREATION_ON_COMPLETION)raise _TaskCompletedDuringSandboxCreationused_snapshot = Falseawait self._emit_progress("sandbox", "completed", "Sandbox ready", "setup", wait=False)@@ -2331,12 +2217,12 @@ class ProcessTaskWorkflow(PostHogWorkflow):failed_repositories: set[str] = set()materialized_failed_repositories: set[str] = set()repo_ready_released = False- release_after_primary_clone = bool(- overlap and len(repositories_to_clone) > 1 and workflow.patched(_PATCH_ID_AGENT_READY_AFTER_PRIMARY_CLONE)- )+ release_after_primary_clone = overlap and len(repositories_to_clone) > 1+ if release_after_primary_clone:+ workflow.deprecate_patch(_PATCH_ID_AGENT_READY_AFTER_PRIMARY_CLONE)if will_clone:await self._emit_progress("clone", "in_progress", "Cloning repository", "setup", wait=False)- continue_after_clone_failure = workflow.patched(_PATCH_ID_CONTINUE_AFTER_REPOSITORY_CLONE_FAILURE)+ workflow.deprecate_patch(_PATCH_ID_CONTINUE_AFTER_REPOSITORY_CLONE_FAILURE)fail_on_primary_clone_failure = workflow.patched(_PATCH_ID_FAIL_RUN_ON_PRIMARY_CLONE_FAILURE)async def clone_repository(@@ -2356,7 +2242,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(maximum_attempts=3),)except Exception as error:- if _is_dead_sandbox_failure(error) or not continue_after_clone_failure:+ if _is_dead_sandbox_failure(error):raiseif fail_on_primary_clone_failure and repository == repositories_to_clone[0]:raise@@ -2490,15 +2376,14 @@ class ProcessTaskWorkflow(PostHogWorkflow):activity_input = CreateSandboxForRepositoryInput(context=self.context, prepared=prepared)creation_timeout = timedelta(seconds=prepared.sandbox_creation_timeout_seconds)retry_policy = RetryPolicy(maximum_attempts=3)- if not prepared.sandbox_creation_cancellable or not workflow.patched(- _PATCH_ID_CANCEL_SANDBOX_CREATION_ON_COMPLETION- ):+ if not prepared.sandbox_creation_cancellable:return await workflow.execute_activity(create_sandbox_for_repository,activity_input,start_to_close_timeout=creation_timeout,retry_policy=retry_policy,)+ workflow.deprecate_patch(_PATCH_ID_CANCEL_SANDBOX_CREATION_ON_COMPLETION)creation = workflow.start_activity(create_sandbox_for_repository,@@ -2541,7 +2426,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(maximum_attempts=3),)except Exception:- if context and complete_stream and _complete_stream_after_cleanup_failure():+ if context and complete_stream:+ _complete_stream_after_cleanup_failure()await self._complete_run_stream(context.run_id)raise@@ -2580,9 +2466,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):if self.context.wizard_config is None or not repository:return 0- exclude_from_boot_total = workflow.patched(_PATCH_ID_EXCLUDE_WIZARD_FROM_BOOT_TOTAL)+ workflow.deprecate_patch(_PATCH_ID_EXCLUDE_WIZARD_FROM_BOOT_TOTAL)await self._emit_progress("wizard", "in_progress", "Running PostHog setup wizard", "setup", wait=False)- started_at = workflow.now() if exclude_from_boot_total else None+ started_at = workflow.now()await workflow.execute_activity(run_wizard,RunWizardInput(@@ -2595,7 +2481,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):start_to_close_timeout=timedelta(minutes=50),retry_policy=RetryPolicy(maximum_attempts=1),)- wizard_ms = int((workflow.now() - started_at).total_seconds() * 1000) if started_at is not None else 0+ wizard_ms = int((workflow.now() - started_at).total_seconds() * 1000)await self._emit_progress("wizard", "completed", "Ran PostHog setup wizard", "setup", wait=False)return wizard_ms@@ -2998,10 +2884,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):group=f"{group}:{self.context.run_id}",detail=detail,)- if not _progress_emit_nonblocking():- if await self._run_progress_activity(step, status, activity_input):- self._record_progress_step(step, label, group, status)- return+ _progress_emit_nonblocking()self._record_progress_step(step, label, group, status)emission = asyncio.create_task(self._emit_progress_in_order(self._progress_chain, step, status, activity_input))self._progress_chain = emission@@ -3168,8 +3051,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):completed follow-up round makes the downgrade evidence-based; a run that never intendedto open a PR needs no observation, since there is nothing for it to have delivered."""- if self.context.origin_product != _ONBOARDING_ORIGIN_PRODUCT or not _run_lifecycle_bounds_enabled():+ if self.context.origin_product != _ONBOARDING_ORIGIN_PRODUCT:return False+ _run_lifecycle_bounds_enabled()if self._pr_progress_emitted:return Falsereturn not self.context.create_pr or self._ci_repetitions > 0@@ -3207,11 +3091,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):return self.context.origin_product == _WORKFLOW_ORIGIN_PRODUCT and self._agent_lost_mid_turn()async def _mark_sandbox_gone(self) -> None:- if (- self._sandbox_exit_reason is None- and self._sandbox_exit_reason_lookup_id is not None- and workflow.patched(_PATCH_ID_SANDBOX_EXIT_REASON_ON_RELAY_LOSS)- ):+ if self._sandbox_exit_reason is None and self._sandbox_exit_reason_lookup_id is not None:+ workflow.deprecate_patch(_PATCH_ID_SANDBOX_EXIT_REASON_ON_RELAY_LOSS)self._sandbox_exit_reason = await self._lookup_sandbox_exit_reason(self._sandbox_exit_reason_lookup_id)if self._task_completed:return@@ -3245,14 +3126,14 @@ class ProcessTaskWorkflow(PostHogWorkflow):"""self._resume_snapshot_invalidated = Falseactivity_count = self._sandbox_activity_count- guard_activity = _rotation_activity_guard()+ _rotation_activity_guard()snapshot = await self._create_resume_snapshot_output(old_sandbox_id, reason="ttl_rotation", allow_pruning=False)if snapshot is None or not snapshot.external_id:return SandboxRotation(relay_task=relay_task, credential_refresh_task=credential_refresh_task, reason="snapshot_missing")- if guard_activity and self._sandbox_activity_count != activity_count:+ if self._sandbox_activity_count != activity_count:return SandboxRotation(relay_task=relay_task,credential_refresh_task=credential_refresh_task,@@ -3276,9 +3157,6 @@ class ProcessTaskWorkflow(PostHogWorkflow):ttl_snapshot_taken=self._sandbox_ttl_snapshot_taken,)- if relay_task is not None and not guard_activity:- await self._cancel_relay(relay_task)- relay_task = Noneif credential_refresh_task is not None:await self._cancel_relay(credential_refresh_task)credential_refresh_task = None@@ -3287,7 +3165,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):try:try:sandbox_output = await self._get_sandbox_for_repository()- if check_activity_before_boot and guard_activity and self._sandbox_activity_count != activity_count:+ if check_activity_before_boot and self._sandbox_activity_count != activity_count:return await self._abandon_rotation(live_sandbox, reason="activity_during_handoff", snapshot_activity_count=activity_count)@@ -3309,7 +3187,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):return await self._abandon_rotation(live_sandbox,reason="provision_failed",- snapshot_activity_count=activity_count if guard_activity else None,+ snapshot_activity_count=activity_count,)if not sandbox_output.used_snapshot:@@ -3329,10 +3207,10 @@ class ProcessTaskWorkflow(PostHogWorkflow):return await self._abandon_rotation(live_sandbox,reason="snapshot_unused",- snapshot_activity_count=activity_count if guard_activity else None,+ snapshot_activity_count=activity_count,)- if not check_activity_before_boot and guard_activity and self._sandbox_activity_count != activity_count:+ if not check_activity_before_boot and self._sandbox_activity_count != activity_count:return await self._abandon_rotation(live_sandbox, reason="activity_during_handoff", snapshot_activity_count=activity_count)@@ -3456,11 +3334,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):is_agent_design_enabled=self._is_agent_design_enabled,stream_generation=self.context.stream_generation,)- relay_activity = (- relay_sandbox_events_deferred_completion if _defer_run_stream_completion() else relay_sandbox_events- )+ _defer_run_stream_completion()sandbox_gone = await workflow.execute_activity(- relay_activity,+ relay_sandbox_events_deferred_completion,relay_input,start_to_close_timeout=RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT,schedule_to_close_timeout=RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT,@@ -3807,8 +3683,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._last_turn_succeeded = Falseif not agent_active:self._turn_completion_signal_count += 1- if _turn_opens_on_dispatch():- self._turn_ended_received = True+ _turn_opens_on_dispatch()+ self._turn_ended_received = True@temporalio.workflow.signalasync def agent_turn_completed(self, succeeded: bool = False) -> None:@@ -3913,12 +3789,6 @@ class ProcessTaskWorkflow(PostHogWorkflow):sequence=self._next_followup_sequence,)self._next_followup_sequence += 1- # Always queue. `deprecate_patch` accepts existing non-deprecated- # markers from workflows that ran the prior `workflow.patched(...)`- # gate, so this is safe to deploy alongside in-flight workflows. The- # consumption loop in `run()` still drains a stray `_pending_followup`- # for defense in depth, but new code never sets it.- workflow.deprecate_patch(_PATCH_ID_FOLLOWUP_QUEUE)self._pending_followups.append(pending_followup)@temporalio.workflow.signal@@ -4013,12 +3883,10 @@ class ProcessTaskWorkflow(PostHogWorkflow):)# A delivered message opens a turn: the first heartbeat may lag or be throttled away.if outcome != STEER_DECLINED_OUTCOME:- turn_opens_on_dispatch = _turn_opens_on_dispatch()- preserve_completion = _preserve_completion_during_delivery()+ _turn_opens_on_dispatch()+ _preserve_completion_during_delivery()completion_arrived = self._turn_completion_signal_count != turn_completion_count- if turn_opens_on_dispatch and (- outcome == TURN_IN_FLIGHT_OUTCOME or not completion_arrived or not preserve_completion- ):+ if outcome == TURN_IN_FLIGHT_OUTCOME or not completion_arrived:self._end_of_turn_received = False# The ingest plane never reports a turn active, only inactive at its close, so a# stale `False` from the turn that just ended must not carry into this one — it@@ -4052,7 +3920,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):return Noneawait self._record_peer_message_delivery_failure(peer_message_id, cause_message or str(e))return None- if self.context.mode == "interactive" and workflow.patched(_PATCH_ID_FOLLOWUP_FAILURE_KEEPS_RUN):+ if self.context.mode == "interactive":+ workflow.deprecate_patch(_PATCH_ID_FOLLOWUP_FAILURE_KEEPS_RUN)if message_id:dedupe_key = _message_dedupe_key(message_id, actor_user_id, context)if dedupe_key in self._accepted_message_id_set: