: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): make cloud follow-up recovery durable (#71945)
Alessandro Pogliaghi1c745a317a5c
diff --git a/products/tasks/backend/temporal/task_management/activities/__init__.py b/products/tasks/backend/temporal/task_management/activities/__init__.pyindex 2e4db9ffe5c2..0d9e34fa44ea 100644--- a/products/tasks/backend/temporal/task_management/activities/__init__.py+++ b/products/tasks/backend/temporal/task_management/activities/__init__.py@@ -1,18 +1,22 @@from .ensure_execute_sandbox_started import EnsureExecuteSandboxStartedInput, ensure_execute_sandbox_startedfrom .pending_followups import (PersistPendingFollowupsInput,+ PersistPendingFollowupsV2Input,ReadPendingFollowupsInput,ReadPendingFollowupsResult,persist_pending_followups,+ persist_pending_followups_v2,read_pending_followups,)__all__ = ["EnsureExecuteSandboxStartedInput","PersistPendingFollowupsInput",+ "PersistPendingFollowupsV2Input","ReadPendingFollowupsInput","ReadPendingFollowupsResult","ensure_execute_sandbox_started","persist_pending_followups",+ "persist_pending_followups_v2","read_pending_followups",]diff --git a/products/tasks/backend/temporal/task_management/activities/pending_followups.py b/products/tasks/backend/temporal/task_management/activities/pending_followups.pyindex 5a3e704d0994..8b75a13e469b 100644--- a/products/tasks/backend/temporal/task_management/activities/pending_followups.py+++ b/products/tasks/backend/temporal/task_management/activities/pending_followups.py@@ -18,6 +18,7 @@ from dataclasses import dataclassfrom typing import Anyfrom temporalio import activity+from temporalio.exceptions import ApplicationErrorfrom posthog.temporal.common.utils import asyncify@@ -25,6 +26,8 @@ from products.tasks.backend.models import TaskRunfrom products.tasks.backend.temporal.observability import log_activity_executionPENDING_FOLLOWUPS_STATE_KEY = "pending_external_followups"+PENDING_FOLLOWUPS_GENERATION_STATE_KEY = "pending_external_followups_generation"+TASK_RUN_NOT_FOUND_ERROR_TYPE = "PendingFollowupsTaskRunNotFound"@dataclass@@ -36,6 +39,13 @@ class PersistPendingFollowupsInput:followups: list[dict[str, Any]]+@dataclass+class PersistPendingFollowupsV2Input:+ run_id: str+ followups: list[dict[str, Any]]+ generation: int++@dataclassclass ReadPendingFollowupsInput:run_id: str@@ -62,10 +72,47 @@ def persist_pending_followups(input: PersistPendingFollowupsInput) -> None:run_id=input.run_id,count=len(input.followups),):++ def _persist_if_unversioned(state: dict[str, Any]) -> None:+ if isinstance(state.get(PENDING_FOLLOWUPS_GENERATION_STATE_KEY), int):+ return+ if input.followups:+ state[PENDING_FOLLOWUPS_STATE_KEY] = input.followups+ else:+ state.pop(PENDING_FOLLOWUPS_STATE_KEY, None)++ TaskRun.mutate_state_atomic(input.run_id, _persist_if_unversioned)+++@asyncify+def persist_pending_followups_v2(input: PersistPendingFollowupsV2Input) -> None:+ """Persist a queue snapshot unless a newer generation already won."""++ def _persist_if_newer(state: dict[str, Any]) -> None:+ current_generation = state.get(PENDING_FOLLOWUPS_GENERATION_STATE_KEY)+ if isinstance(current_generation, int) and current_generation >= input.generation:+ return+ state[PENDING_FOLLOWUPS_GENERATION_STATE_KEY] = input.generationif input.followups:- TaskRun.update_state_atomic(input.run_id, updates={PENDING_FOLLOWUPS_STATE_KEY: input.followups})+ state[PENDING_FOLLOWUPS_STATE_KEY] = input.followupselse:- TaskRun.update_state_atomic(input.run_id, remove_keys=[PENDING_FOLLOWUPS_STATE_KEY])+ state.pop(PENDING_FOLLOWUPS_STATE_KEY, None)++ with log_activity_execution(+ "persist_pending_followups_v2",+ run_id=input.run_id,+ count=len(input.followups),+ generation=input.generation,+ ):+ try:+ TaskRun.mutate_state_atomic(input.run_id, _persist_if_newer)+ except TaskRun.DoesNotExist as error:+ raise ApplicationError(+ f"Task run {input.run_id} no longer exists",+ type=TASK_RUN_NOT_FOUND_ERROR_TYPE,+ non_retryable=True,+ ) from error@activity.defndiff --git a/products/tasks/backend/temporal/task_management/activities/tests/test_pending_followups.py b/products/tasks/backend/temporal/task_management/activities/tests/test_pending_followups.pyindex 272dd2cda0dd..c48c0fab7264 100644--- a/products/tasks/backend/temporal/task_management/activities/tests/test_pending_followups.py+++ b/products/tasks/backend/temporal/task_management/activities/tests/test_pending_followups.py@@ -3,12 +3,17 @@ import uuidimport pytestfrom asgiref.sync import async_to_sync+from temporalio.exceptions import ApplicationErrorfrom products.tasks.backend.temporal.task_management.activities.pending_followups import (+ PENDING_FOLLOWUPS_GENERATION_STATE_KEY,PENDING_FOLLOWUPS_STATE_KEY,+ TASK_RUN_NOT_FOUND_ERROR_TYPE,PersistPendingFollowupsInput,+ PersistPendingFollowupsV2Input,ReadPendingFollowupsInput,persist_pending_followups,+ persist_pending_followups_v2,read_pending_followups,)@@ -62,6 +67,46 @@ class TestPersistPendingFollowups:{"message": "m", "artifact_ids": [], "source": "user"}]+ def test_older_generation_cannot_overwrite_newer_queue(self, activity_environment, test_task_run):+ run_id = str(test_task_run.id)+ first = [{"message": "first", "artifact_ids": [], "source": "user", "sequence": 1}]+ complete = [+ *first,+ {"message": "second", "artifact_ids": [], "source": "user", "sequence": 2},+ ]++ for generation, followups in [(1, first), (2, complete), (1, first)]:+ async_to_sync(activity_environment.run)(+ persist_pending_followups_v2,+ PersistPendingFollowupsV2Input(+ run_id=run_id,+ followups=followups,+ generation=generation,+ ),+ )+ async_to_sync(activity_environment.run)(+ persist_pending_followups,+ PersistPendingFollowupsInput(run_id=run_id, followups=first),+ )++ test_task_run.refresh_from_db()+ assert test_task_run.state[PENDING_FOLLOWUPS_STATE_KEY] == complete+ assert test_task_run.state[PENDING_FOLLOWUPS_GENERATION_STATE_KEY] == 2++ def test_missing_task_run_is_non_retryable(self, activity_environment):+ with pytest.raises(ApplicationError) as exc_info:+ async_to_sync(activity_environment.run)(+ persist_pending_followups_v2,+ PersistPendingFollowupsV2Input(+ run_id=str(uuid.uuid4()),+ followups=[],+ generation=1,+ ),+ )++ assert exc_info.value.type == TASK_RUN_NOT_FOUND_ERROR_TYPE+ assert exc_info.value.non_retryable is True+@pytest.mark.requires_secrets@pytest.mark.django_db(transaction=True)diff --git a/products/tasks/backend/temporal/task_management/tests/test_task_management_workflow.py b/products/tasks/backend/temporal/task_management/tests/test_task_management_workflow.pyindex 8c4982db76ce..fe905647914a 100644--- a/products/tasks/backend/temporal/task_management/tests/test_task_management_workflow.py+++ b/products/tasks/backend/temporal/task_management/tests/test_task_management_workflow.py@@ -3,6 +3,8 @@ from datetime import UTC, datetime, timedeltaimport pytestfrom unittest.mock import AsyncMock, Mock+from temporalio.exceptions import ApplicationError+from products.tasks.backend.temporal.constants import (ACK_TIMEOUT,DEFAULT_CI_MESSAGE,@@ -17,6 +19,7 @@ from products.tasks.backend.temporal.process_task.activities.get_pr_context impofrom products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContextfrom products.tasks.backend.temporal.task_management import workflow as task_management_workflow_modulefrom products.tasks.backend.temporal.task_management.workflow import (+ MAX_CONSECUTIVE_SANDBOX_REPLACEMENT_FAILURES,ChildAck,ChildCompletion,CIFollowUpDecision,@@ -560,11 +563,357 @@ class TestDrainExternalSignals:complete_mock.assert_not_awaited()assert workflow._pending_external_complete is None+ async def test_replacement_uses_deterministic_backoff(self, monkeypatch, silent_workflow_logger):+ workflow = TaskManagementWorkflow()+ workflow._run_id = "run-id"+ workflow._sandbox_workflow_id = "sandbox-wf"+ workflow._sandbox_alive = False+ workflow._consecutive_sandbox_replacement_failures = 3+ workflow._pending_external_followups.append(+ PendingExternalFollowup(message="retry me", artifact_ids=[], source="user")+ )++ sleep_mock = AsyncMock()+ bootstrap_mock = AsyncMock()+ signal_mock = AsyncMock(return_value=True)+ monkeypatch.setattr(task_management_workflow_module.workflow, "sleep", sleep_mock)+ monkeypatch.setattr(workflow, "_ensure_sandbox_workflow_started", bootstrap_mock)+ monkeypatch.setattr(workflow, "_signal_child_followup", signal_mock)+ monkeypatch.setattr(workflow, "_persist_pending_followups", AsyncMock())++ await workflow._drain_external_signals()++ sleep_mock.assert_awaited_once_with(4)+ bootstrap_mock.assert_awaited_once()+ signal_mock.assert_awaited_once()++ @pytest.mark.parametrize(("persist_patch_enabled", "persist_count"), [(False, 0), (True, 1)])+ async def test_replacement_budget_fails_before_starting_another_sandbox(+ self,+ monkeypatch,+ silent_workflow_logger,+ persist_patch_enabled: bool,+ persist_count: int,+ ):+ workflow = TaskManagementWorkflow()+ workflow._run_id = "run-id"+ workflow._sandbox_workflow_id = "sandbox-wf"+ workflow._sandbox_alive = False+ workflow._consecutive_sandbox_replacement_failures = MAX_CONSECUTIVE_SANDBOX_REPLACEMENT_FAILURES+ workflow._pending_external_followups.append(+ PendingExternalFollowup(message="park me", artifact_ids=[], source="user")+ )++ bootstrap_mock = AsyncMock()+ persist_mock = AsyncMock(return_value=True)+ monkeypatch.setattr(workflow, "_ensure_sandbox_workflow_started", bootstrap_mock)+ monkeypatch.setattr(workflow, "_persist_pending_followups", persist_mock)+ monkeypatch.setattr(+ task_management_workflow_module,+ "_patch_enabled",+ lambda patch_id: (+ persist_patch_enabled+ if patch_id == task_management_workflow_module._PATCH_ID_PERSIST_REPLACEMENT_BUDGET+ else False+ if patch_id+ in {+ task_management_workflow_module._PATCH_ID_DURABLE_REPLACEMENT_BUDGET_PERSISTENCE,+ task_management_workflow_module._PATCH_ID_TERMINAL_PENDING_FOLLOWUP_BARRIER,+ }+ else True+ ),+ )++ with pytest.raises(RuntimeError, match="before acknowledging a follow-up"):+ await workflow._drain_external_signals()++ assert persist_mock.await_count == persist_count+ bootstrap_mock.assert_not_awaited()+ assert workflow._pending_external_followups == [+ PendingExternalFollowup(message="park me", artifact_ids=[], source="user")+ ]++ async def test_replacement_budget_retries_only_persistence_when_storage_is_unavailable(+ self, monkeypatch, silent_workflow_logger+ ):+ workflow = TaskManagementWorkflow()+ workflow._run_id = "run-id"+ workflow._sandbox_workflow_id = "sandbox-wf"+ workflow._sandbox_alive = False+ workflow._consecutive_sandbox_replacement_failures = MAX_CONSECUTIVE_SANDBOX_REPLACEMENT_FAILURES+ workflow._pending_external_followups.append(+ PendingExternalFollowup(message="keep trying", artifact_ids=[], source="user")+ )++ persistence_options = []++ async def fail_persistence(_activity, _input, **kwargs):+ persistence_options.append(kwargs)+ raise RuntimeError("storage unavailable")++ sleep_mock = AsyncMock()+ bootstrap_mock = AsyncMock()+ signal_mock = AsyncMock(return_value=True)+ monkeypatch.setattr(task_management_workflow_module.workflow, "execute_activity", fail_persistence)+ monkeypatch.setattr(task_management_workflow_module.workflow, "sleep", sleep_mock)+ monkeypatch.setattr(workflow, "_ensure_sandbox_workflow_started", bootstrap_mock)+ monkeypatch.setattr(workflow, "_signal_child_followup", signal_mock)++ with pytest.raises(RuntimeError, match="storage unavailable"):+ await workflow._persist_pending_followups_until_stable()++ assert len(persistence_options) == 1+ assert persistence_options[0]["schedule_to_close_timeout"] == timedelta(minutes=5)+ assert persistence_options[0]["retry_policy"].maximum_attempts == 0+ assert persistence_options[0]["retry_policy"].non_retryable_error_types == [+ task_management_workflow_module.TASK_RUN_NOT_FOUND_ERROR_TYPE+ ]+ sleep_mock.assert_not_awaited()+ bootstrap_mock.assert_not_awaited()+ signal_mock.assert_not_awaited()++ async def test_existing_history_persists_before_replacement_budget_failure(+ self, monkeypatch, silent_workflow_logger+ ):+ workflow = TaskManagementWorkflow()+ workflow._run_id = "run-id"+ workflow._consecutive_sandbox_replacement_failures = MAX_CONSECUTIVE_SANDBOX_REPLACEMENT_FAILURES+ persist_mock = AsyncMock()+ monkeypatch.setattr(workflow, "_persist_pending_followups_until_stable", persist_mock)+ monkeypatch.setattr(+ task_management_workflow_module,+ "_patch_enabled",+ lambda patch_id: patch_id != task_management_workflow_module._PATCH_ID_TERMINAL_PENDING_FOLLOWUP_BARRIER,+ )++ with pytest.raises(RuntimeError, match="before acknowledging a follow-up"):+ await workflow._wait_before_replacement_sandbox()++ persist_mock.assert_awaited_once()+ assert workflow._persist_pending_followups_on_exit is False++ async def test_replacement_budget_persists_followups_arriving_during_terminal_snapshot(+ self, monkeypatch, silent_workflow_logger+ ):+ workflow = TaskManagementWorkflow()+ workflow._run_id = "run-id"+ workflow._sandbox_workflow_id = "sandbox-wf"+ workflow._sandbox_alive = False+ workflow._consecutive_sandbox_replacement_failures = MAX_CONSECUTIVE_SANDBOX_REPLACEMENT_FAILURES+ workflow._pending_external_followups.append(+ PendingExternalFollowup(message="first", artifact_ids=[], source="user", sequence=1)+ )++ persisted_payloads: list[list[dict]] = []++ async def capture_persistence(_activity, input_arg, **_kwargs):+ persisted_payloads.append(input_arg.followups)+ if len(persisted_payloads) == 1:+ workflow._pending_external_followups.append(+ PendingExternalFollowup(+ message="arrived during persist", artifact_ids=[], source="user", sequence=2+ )+ )++ bootstrap_mock = AsyncMock()+ monkeypatch.setattr(task_management_workflow_module.workflow, "execute_activity", capture_persistence)+ monkeypatch.setattr(workflow, "_ensure_sandbox_workflow_started", bootstrap_mock)++ await workflow._persist_pending_followups_until_stable()++ assert persisted_payloads == [+ [+ {+ "message": "first",+ "artifact_ids": [],+ "source": "user",+ "actor_user_id": None,+ "message_id": None,+ "context": {},+ "steer": False,+ "sequence": 1,+ }+ ],+ [+ {+ "message": "first",+ "artifact_ids": [],+ "source": "user",+ "actor_user_id": None,+ "message_id": None,+ "context": {},+ "steer": False,+ "sequence": 1,+ },+ {+ "message": "arrived during persist",+ "artifact_ids": [],+ "source": "user",+ "actor_user_id": None,+ "message_id": None,+ "context": {},+ "steer": False,+ "sequence": 2,+ },+ ],+ ]+ bootstrap_mock.assert_not_awaited()++ async def test_replacement_budget_persists_after_terminal_cleanup(self, monkeypatch, silent_workflow_logger):+ workflow = TaskManagementWorkflow()+ workflow._consecutive_sandbox_replacement_failures = MAX_CONSECUTIVE_SANDBOX_REPLACEMENT_FAILURES+ context = _build_context()+ order: list[str] = []+ slack_calls = 0++ async def get_context():+ return context++ async def track_event(*_args, **_kwargs):+ order.append("telemetry")++ async def post_slack_update(*_args, **_kwargs):+ nonlocal slack_calls+ slack_calls += 1+ order.append("initial-slack" if slack_calls == 1 else "final-slack")+ if slack_calls == 2:+ await workflow.send_followup_message("arrived during cleanup")++ async def fail_at_budget():+ await workflow._wait_before_replacement_sandbox()+ raise AssertionError("replacement budget should raise")++ async def wait_condition(predicate, **_kwargs):+ assert predicate is task_management_workflow_module.workflow.all_handlers_finished+ order.append("handlers-drained")++ async def persist_until_stable():+ order.append("persist")+ assert workflow._pending_external_followups == [+ PendingExternalFollowup(+ message="arrived during cleanup",+ artifact_ids=[],+ source="user",+ )+ ]++ monkeypatch.setattr(task_management_workflow_module.workflow, "info", lambda: Mock(workflow_id="wf-id"))+ monkeypatch.setattr(task_management_workflow_module.workflow, "wait_condition", wait_condition)+ monkeypatch.setattr(workflow, "_get_task_processing_context", get_context)+ monkeypatch.setattr(workflow, "_track_workflow_event", track_event)+ monkeypatch.setattr(workflow, "_post_slack_update", post_slack_update)+ monkeypatch.setattr(workflow, "_restore_pending_followups", AsyncMock())+ monkeypatch.setattr(workflow, "_ensure_sandbox_workflow_started", AsyncMock())+ monkeypatch.setattr(workflow, "_wait_for_event", fail_at_budget)+ monkeypatch.setattr(+ workflow, "_update_task_run_status", AsyncMock(side_effect=lambda *_args, **_kwargs: order.append("status"))+ )+ monkeypatch.setattr(workflow, "_persist_pending_followups_until_stable", persist_until_stable)++ result = await workflow.run(TaskRunManagementInput(run_id="run-id", slack_thread_context={"channel": "C1"}))++ assert result.success is False+ assert order[-4:] == ["status", "final-slack", "handlers-drained", "persist"]++ async def test_closed_child_clears_all_steers_and_rebootstraps_in_order(+ self, monkeypatch, fixed_now, silent_workflow_logger+ ):+ workflow = TaskManagementWorkflow()+ workflow._run_id = "run-id"+ workflow._sandbox_workflow_id = "sandbox-wf"+ workflow._sandbox_alive = True+ workflow._pending_external_followups.extend(+ [+ PendingExternalFollowup(+ message="retry me",+ artifact_ids=["artifact"],+ source="user",+ steer=True,+ sequence=4,+ ),+ PendingExternalFollowup(+ message="still queued",+ artifact_ids=[],+ source="user",+ steer=True,+ sequence=5,+ ),+ ]+ )++ handle = Mock()+ handle.signal = AsyncMock(+ side_effect=[+ ApplicationError(+ "child workflow closed",+ type="ExternalWorkflowExecutionNotFound",+ ),+ None,+ None,+ ]+ )+ monkeypatch.setattr(+ task_management_workflow_module.workflow,+ "get_external_workflow_handle",+ Mock(return_value=handle),+ )+ monkeypatch.setattr(+ task_management_workflow_module.workflow,+ "uuid4",+ Mock(side_effect=["closed-ack", "replacement-ack-1", "replacement-ack-2"]),+ )+ monkeypatch.setattr(task_management_workflow_module.workflow, "patched", lambda _patch_id: True)+ persist_mock = AsyncMock()+ monkeypatch.setattr(workflow, "_persist_pending_followups", persist_mock)++ await workflow._drain_external_signals()++ assert workflow._sandbox_alive is False+ assert workflow._pending_ack_slots == {}+ assert workflow._pending_external_followups == [+ PendingExternalFollowup(+ message="retry me",+ artifact_ids=["artifact"],+ source="user",+ sequence=4,+ ),+ PendingExternalFollowup(+ message="still queued",+ artifact_ids=[],+ source="user",+ sequence=5,+ ),+ ]++ async def mark_replacement_alive() -> None:+ workflow._sandbox_alive = True++ bootstrap_mock = AsyncMock(side_effect=mark_replacement_alive)+ monkeypatch.setattr(workflow, "_ensure_sandbox_workflow_started", bootstrap_mock)+ sleep_mock = AsyncMock()+ monkeypatch.setattr(task_management_workflow_module.workflow, "sleep", sleep_mock)++ await workflow._drain_external_signals()++ bootstrap_mock.assert_awaited_once()+ sleep_mock.assert_awaited_once_with(1)+ assert [call.args for call in handle.signal.await_args_list[-2:]] == [+ ("send_followup_message",),+ ("send_followup_message",),+ ]+ assert [call.kwargs for call in handle.signal.await_args_list[-2:]] == [+ {"args": ["replacement-ack-1", "retry me", ["artifact"], "user", None, None, {}]},+ {"args": ["replacement-ack-2", "still queued", [], "user", None, None, {}]},+ ]+ assert workflow._pending_external_followups == []+ assert persist_mock.await_count >= 2+class TestDrainChildSignals:async def test_matched_ack_clears_slot_and_logs(self, fixed_now, silent_workflow_logger):workflow = TaskManagementWorkflow()workflow._run_id = "run-id"+ workflow._consecutive_sandbox_replacement_failures = 2workflow._pending_ack_slots["ack-1"] = PendingAckSlot(signal_name="send_followup_message", sent_at=fixed_now.now)@@ -582,6 +931,7 @@ class TestDrainChildSignals:assert workflow._pending_ack_slots == {}assert workflow._child_acks == []+ assert workflow._consecutive_sandbox_replacement_failures == 0# Heartbeat flag is reset every drain so the wait condition can fire again.assert workflow._heartbeat_received is Falsesilent_workflow_logger.info.assert_called()@@ -634,6 +984,68 @@ class TestSignalChildFollowup:# can replay them — the child dedupes on ack_id so a replay is safe.assert slot.signal_args == ["ack-generated", "m", ["a"], "ci", None, None, {}]+ @pytest.mark.parametrize(("reset_patch_enabled", "expected_failures"), [(False, 5), (True, 1)])+ async def test_accepted_ack_resets_replacement_budget_before_closed_child_recovery(+ self,+ monkeypatch,+ fixed_now,+ silent_workflow_logger,+ reset_patch_enabled: bool,+ expected_failures: int,+ ):+ workflow = TaskManagementWorkflow()+ workflow._run_id = "run-id"+ workflow._sandbox_workflow_id = "sandbox-wf"+ workflow._sandbox_alive = True+ workflow._consecutive_sandbox_replacement_failures = 4+ workflow._pending_ack_slots["ack-accepted"] = PendingAckSlot(+ signal_name="send_followup_message",+ sent_at=fixed_now.now,+ signal_args=["ack-accepted", "accepted", [], "user"],+ sequence=1,+ )+ workflow._child_acks.append(+ ChildAck(+ signal_name="send_followup_message",+ ack_id="ack-accepted",+ accepted=True,+ detail=None,+ received_at=fixed_now.now,+ )+ )++ handle = Mock()+ handle.signal = AsyncMock(+ side_effect=ApplicationError(+ "child workflow closed",+ type="ExternalWorkflowExecutionNotFound",+ )+ )+ monkeypatch.setattr(+ task_management_workflow_module.workflow,+ "get_external_workflow_handle",+ Mock(return_value=handle),+ )+ monkeypatch.setattr(task_management_workflow_module.workflow, "uuid4", Mock(return_value="ack-closed"))+ monkeypatch.setattr(+ task_management_workflow_module,+ "_patch_enabled",+ lambda patch_id: (+ reset_patch_enabled+ if patch_id == task_management_workflow_module._PATCH_ID_ACCEPTED_ACK_RESETS_REPLACEMENT_BUDGET+ else True+ ),+ )+ monkeypatch.setattr(workflow, "_persist_pending_followups", AsyncMock())++ delivered = await workflow._signal_child_followup("retry", [], sequence=2)++ assert delivered is False+ assert workflow._consecutive_sandbox_replacement_failures == expected_failures+ assert workflow._pending_external_followups == [+ PendingExternalFollowup(message="retry", artifact_ids=[], source="user", sequence=2)+ ]+@pytest.mark.parametrize(("patch_enabled", "protocol_version", "expected_signal"),[@@ -731,6 +1143,56 @@ class TestSignalChildFollowup:assert slot.signal_args == ["ack-x", "m", [], "user", None, None, {}]assert slot.retry_count == 0+ @pytest.mark.parametrize("signal_path", ["followup", "completion", "ack_retry"])+ async def test_closed_child_failure_preserves_legacy_replay_commands(+ self,+ monkeypatch,+ fixed_now,+ silent_workflow_logger,+ signal_path: str,+ ):+ workflow = TaskManagementWorkflow()+ workflow._run_id = "run-id"+ workflow._sandbox_workflow_id = "sandbox-wf"+ workflow._sandbox_alive = True++ handle = Mock()+ handle.signal = AsyncMock(+ side_effect=ApplicationError(+ "child workflow closed",+ type="ExternalWorkflowExecutionNotFound",+ )+ )+ monkeypatch.setattr(+ task_management_workflow_module.workflow,+ "get_external_workflow_handle",+ Mock(return_value=handle),+ )+ monkeypatch.setattr(task_management_workflow_module.workflow, "uuid4", lambda: "historical-ack")+ monkeypatch.setattr(task_management_workflow_module.workflow, "in_workflow", lambda: True)+ monkeypatch.setattr(task_management_workflow_module.workflow, "patched", lambda _patch_id: False)+ persist_mock = AsyncMock()+ monkeypatch.setattr(workflow, "_persist_pending_followups", persist_mock)++ if signal_path == "followup":+ delivered = await workflow._signal_child_followup("historical", [], "user")+ assert delivered is True+ elif signal_path == "completion":+ await workflow._signal_child_complete("completed", None)+ else:+ workflow._pending_ack_slots["historical-ack"] = PendingAckSlot(+ signal_name="send_followup_message",+ sent_at=fixed_now.now,+ signal_args=["historical-ack", "historical", [], "user"],+ )+ fixed_now.advance(ACK_TIMEOUT + timedelta(seconds=1))+ await workflow._retry_stale_acks()++ assert workflow._sandbox_alive is True+ assert "historical-ack" in workflow._pending_ack_slots+ assert workflow._pending_external_followups == []+ persist_mock.assert_not_awaited()+class TestSignalChildComplete:async def test_skips_when_no_sandbox_id(self, monkeypatch):@@ -770,6 +1232,34 @@ class TestSignalChildComplete:assert slot.signal_name == "complete_task"assert slot.signal_args == ["ack-c", "failed", "boom"]+ async def test_closed_child_recovers_completion_slot(self, monkeypatch, fixed_now, silent_workflow_logger):+ workflow = TaskManagementWorkflow()+ workflow._run_id = "run-id"+ workflow._sandbox_workflow_id = "sandbox-wf"+ workflow._sandbox_alive = True++ handle = Mock()+ handle.signal = AsyncMock(+ side_effect=ApplicationError(+ "child workflow closed",+ type="ExternalWorkflowExecutionNotFound",+ )+ )+ monkeypatch.setattr(+ task_management_workflow_module.workflow,+ "get_external_workflow_handle",+ Mock(return_value=handle),+ )+ monkeypatch.setattr(task_management_workflow_module.workflow, "uuid4", lambda: "ack-c")+ persist_mock = AsyncMock()+ monkeypatch.setattr(workflow, "_persist_pending_followups", persist_mock)++ await workflow._signal_child_complete("completed", None)++ assert workflow._sandbox_alive is False+ assert workflow._pending_ack_slots == {}+ persist_mock.assert_awaited_once()+class TestNewAckId:def test_returns_uuid_string(self, monkeypatch):@@ -931,6 +1421,64 @@ class TestRetryStaleAcks:assert slot.sent_at == original_sentassert slot.retry_count == 0+ async def test_closed_child_requeues_stale_followups_in_arrival_order(+ self, monkeypatch, fixed_now, silent_workflow_logger+ ):+ workflow = TaskManagementWorkflow()+ workflow._run_id = "run-id"+ workflow._sandbox_workflow_id = "sandbox-wf"+ workflow._sandbox_alive = True+ workflow._child_steering_protocol_version = STEERING_PROTOCOL_VERSION+ workflow._pending_ack_slots["later"] = PendingAckSlot(+ signal_name=SEND_STEER_SIGNAL,+ sent_at=fixed_now.now,+ signal_args=["later", "second", [], "user"],+ sequence=2,+ )+ workflow._pending_ack_slots["earlier"] = PendingAckSlot(+ signal_name="send_followup_message",+ sent_at=fixed_now.now,+ signal_args=["earlier", "first", ["artifact"], "user"],+ sequence=1,+ )+ fixed_now.advance(ACK_TIMEOUT + timedelta(seconds=1))++ handle = Mock()+ handle.signal = AsyncMock(+ side_effect=ApplicationError(+ "child workflow closed",+ type="ExternalWorkflowExecutionNotFound",+ )+ )+ monkeypatch.setattr(+ task_management_workflow_module.workflow,+ "get_external_workflow_handle",+ Mock(return_value=handle),+ )+ persist_mock = AsyncMock()+ monkeypatch.setattr(workflow, "_persist_pending_followups", persist_mock)++ await workflow._retry_stale_acks()++ assert workflow._sandbox_alive is False+ assert workflow._child_steering_protocol_version == 0+ assert workflow._pending_ack_slots == {}+ assert workflow._pending_external_followups == [+ PendingExternalFollowup(+ message="first",+ artifact_ids=["artifact"],+ source="user",+ sequence=1,+ ),+ PendingExternalFollowup(+ message="second",+ artifact_ids=[],+ source="user",+ sequence=2,+ ),+ ]+ persist_mock.assert_awaited_once()+class TestWaitForAckRetry:"""The wait task sleeps until the *oldest* slot's ACK deadline."""@@ -1121,6 +1669,66 @@ class TestSandboxSessionCompletionReset:assert workflow._pending_external_followups == []+ async def test_existing_history_adopts_ack_first_ordering_for_a_new_sandbox_generation(+ self, monkeypatch, fixed_now, silent_workflow_logger+ ):+ workflow = TaskManagementWorkflow()+ workflow._context = _build_context()+ workflow._run_id = "run-id"+ workflow._sandbox_workflow_id = "sandbox-wf"+ workflow._ack_before_completion = False+ monkeypatch.setattr(+ task_management_workflow_module.workflow,+ "info",+ Mock(return_value=Mock(workflow_id="parent-wf")),+ )+ monkeypatch.setattr(+ task_management_workflow_module.workflow,+ "execute_activity",+ AsyncMock(return_value=0),+ )+ monkeypatch.setattr(+ task_management_workflow_module.workflow,+ "uuid4",+ Mock(side_effect=["historical-bootstrap-ack", "new-bootstrap-ack"]),+ )+ generation_patch = Mock(side_effect=[False, True])+ monkeypatch.setattr(+ task_management_workflow_module,+ "_ack_before_completion_for_sandbox_generation",+ generation_patch,+ )++ await workflow._ensure_sandbox_workflow_started()++ assert workflow._sandbox_generation == 1+ assert workflow._ack_before_completion is False++ await workflow._ensure_sandbox_workflow_started()++ assert workflow._sandbox_generation == 2+ assert [entry.args for entry in generation_patch.call_args_list] == [(1,), (2,)]++ workflow._child_completion = ChildCompletion(+ success=True,+ error=None,+ sandbox_id="sb-1",+ timed_out=False,+ )+ workflow._child_acks.append(+ ChildAck(+ signal_name="send_followup_message",+ ack_id="ack-delivered",+ accepted=True,+ detail=None,+ received_at=fixed_now.now,+ )+ )+ monkeypatch.setattr(task_management_workflow_module.workflow, "wait_condition", AsyncMock())++ assert await workflow._wait_for_signal() is TaskEvent.CHILD_FORWARDED+ assert workflow._ack_before_completion is True+async def test_session_completion_does_not_close_orchestrator(self, monkeypatch, fixed_now, silent_workflow_logger):# Hardest assertion to lose: after `_on_sandbox_session_completed`,# the workflow has *not* returned and is ready for more work.@@ -1194,6 +1802,19 @@ class TestSandboxSessionCompletionReset:42,{"actor_slack_user_id": "U123"},],+ sequence=1,+ )+ workflow._pending_external_followups.append(+ PendingExternalFollowup(+ message="still waiting",+ artifact_ids=[],+ source="user",+ actor_user_id=43,+ message_id="message-2",+ context={"actor_slack_user_id": "U456"},+ steer=True,+ sequence=2,+ ))monkeypatch.setattr(workflow, "_persist_pending_followups", AsyncMock())@@ -1208,7 +1829,18 @@ class TestSandboxSessionCompletionReset:message_id="message-1",context={"actor_slack_user_id": "U123"},steer=False,- )+ sequence=1,+ ),+ PendingExternalFollowup(+ message="still waiting",+ artifact_ids=[],+ source="user",+ actor_user_id=43,+ message_id="message-2",+ context={"actor_slack_user_id": "U456"},+ steer=False,+ sequence=2,+ ),]@@ -1259,7 +1891,7 @@ class TestPendingFollowupPersistence:async def test_persist_writes_current_queue(self, monkeypatch):from products.tasks.backend.temporal.task_management.activities.pending_followups import (- persist_pending_followups,+ persist_pending_followups_v2,)workflow = TaskManagementWorkflow()@@ -1271,7 +1903,7 @@ class TestPendingFollowupPersistence:captured: dict = {}async def fake_execute_activity(activity_fn, input_arg, *args, **kwargs):- assert activity_fn is persist_pending_followups+ assert activity_fn is persist_pending_followups_v2captured["input"] = input_argreturn None@@ -1292,3 +1924,4 @@ class TestPendingFollowupPersistence:"sequence": 0,}]+ assert captured["input"].generation > 0diff --git a/products/tasks/backend/temporal/task_management/workflow.py b/products/tasks/backend/temporal/task_management/workflow.pyindex e7c8d4d1e6b5..639e3e2c778a 100644--- a/products/tasks/backend/temporal/task_management/workflow.py+++ b/products/tasks/backend/temporal/task_management/workflow.py@@ -65,14 +65,34 @@ from products.tasks.backend.temporal.task_management.activities.ensure_execute_sensure_execute_sandbox_started,)from products.tasks.backend.temporal.task_management.activities.pending_followups import (+ TASK_RUN_NOT_FOUND_ERROR_TYPE,PersistPendingFollowupsInput,+ PersistPendingFollowupsV2Input,ReadPendingFollowupsInput,persist_pending_followups,+ persist_pending_followups_v2,read_pending_followups,)_PATCH_ID_CAPABILITY_GATED_STEERING = "tasks-capability-gated-steering-signal"_PATCH_ID_ACK_BEFORE_COMPLETION = "tasks-task-management-ack-before-completion"+_PATCH_ID_ACK_BEFORE_COMPLETION_SANDBOX_GENERATION = "tasks-task-management-ack-before-completion-sandbox-generation"+_PATCH_ID_CLOSED_CHILD_FOLLOWUP_RECOVERY = "tasks-task-management-closed-child-followup-recovery"+_PATCH_ID_CLOSED_CHILD_COMPLETION_RECOVERY = "tasks-task-management-closed-child-completion-recovery"+_PATCH_ID_CLOSED_CHILD_ACK_RETRY_RECOVERY = "tasks-task-management-closed-child-ack-retry-recovery"+_PATCH_ID_CLEAR_STEER_ON_SANDBOX_BOUNDARY = "tasks-task-management-clear-steer-on-sandbox-boundary"+_PATCH_ID_BOUNDED_SANDBOX_REPLACEMENT_RECOVERY = "tasks-task-management-bounded-sandbox-replacement-recovery"+_PATCH_ID_PERSIST_REPLACEMENT_BUDGET = "tasks-task-management-persist-replacement-budget"+_PATCH_ID_ACCEPTED_ACK_RESETS_REPLACEMENT_BUDGET = "tasks-task-management-accepted-ack-resets-replacement-budget"+_PATCH_ID_DURABLE_REPLACEMENT_BUDGET_PERSISTENCE = "tasks-task-management-durable-replacement-budget-persistence"+_PATCH_ID_TERMINAL_PENDING_FOLLOWUP_BARRIER = "tasks-task-management-terminal-pending-followup-barrier"+_PATCH_ID_GENERATION_SAFE_PENDING_FOLLOWUPS = "tasks-task-management-generation-safe-pending-followups"+_CHILD_SIGNAL_TERMINAL_ERROR_TYPES = {+ "ExternalWorkflowExecutionNotFound",+ "NamespaceNotFound",+}+MAX_CONSECUTIVE_SANDBOX_REPLACEMENT_FAILURES = 5+MAX_SANDBOX_REPLACEMENT_BACKOFF_SECONDS = 30def _ack_before_completion() -> bool:@@ -81,6 +101,24 @@ def _ack_before_completion() -> bool:return workflow.patched(_PATCH_ID_ACK_BEFORE_COMPLETION)+def _ack_before_completion_for_sandbox_generation(generation: int) -> bool:+ if not workflow.in_workflow():+ return True+ return workflow.patched(f"{_PATCH_ID_ACK_BEFORE_COMPLETION_SANDBOX_GENERATION}-{generation}")+++def _patch_enabled(patch_id: str) -> bool:+ if not workflow.in_workflow():+ return True+ return workflow.patched(patch_id)+++def _child_cannot_receive_signals(error: Exception) -> bool:+ return (+ isinstance(error, temporalio.exceptions.ApplicationError) and error.type in _CHILD_SIGNAL_TERMINAL_ERROR_TYPES+ )++@dataclassclass TaskRunManagementInput:run_id: str@@ -204,6 +242,8 @@ class TaskManagementWorkflow(PostHogWorkflow):# can skip the DB roundtrip when nothing changed (e.g., draining an# already-empty queue still triggers a persist call).self._last_persisted_followups: list[dict[str, Any]] = []+ self._last_persistence_generation: int = 0+ self._persist_pending_followups_on_exit: bool = False# Sandbox-side state.self._sandbox_workflow_id: Optional[str] = None@@ -211,12 +251,14 @@ class TaskManagementWorkflow(PostHogWorkflow):self._pending_ack_slots: dict[str, PendingAckSlot] = {}self._child_completion: Optional[ChildCompletion] = Noneself._ack_before_completion: bool = True+ self._sandbox_generation: int = 0# True between a successful `_ensure_sandbox_workflow_started` and# the next `PARENT_COMPLETED_SIGNAL`. The orchestrator lives for the# whole task run and spawns sandboxes lazily: when a follow-up arrives# while `_sandbox_alive=False`, we re-bootstrap before forwarding.self._sandbox_alive: bool = Falseself._child_steering_protocol_version: int = 0+ self._consecutive_sandbox_replacement_failures: int = 0# Activity tracking for CI follow-up timing. `_last_active_time` is# set when the sandbox workflow forwards a heartbeat with@@ -490,8 +532,13 @@ class TaskManagementWorkflow(PostHogWorkflow):)finally:- if self._slack_thread_context and self._context:- await self._post_slack_update(sandbox_cleaned=not self._sandbox_alive)+ try:+ if self._slack_thread_context and self._context:+ await self._post_slack_update(sandbox_cleaned=not self._sandbox_alive)+ finally:+ if self._persist_pending_followups_on_exit:+ await workflow.wait_condition(workflow.all_handlers_finished)+ await self._persist_pending_followups_until_stable()# ------------------------------------------------------------------# Event-wait loop@@ -584,6 +631,7 @@ class TaskManagementWorkflow(PostHogWorkflow):# nothing meaningful to complete when no sandbox is running.if not self._sandbox_alive:if self._pending_external_followups:+ await self._wait_before_replacement_sandbox()workflow.logger.info("task_management_rebootstrapping_for_followup",run_id=self._run_id,@@ -602,7 +650,7 @@ class TaskManagementWorkflow(PostHogWorkflow):# terminal and handled last so we don't drop in-flight messages.while self._pending_external_followups:followup = self._pending_external_followups.pop(0)- await self._signal_child_followup(+ delivered = await self._signal_child_followup(message=followup.message,artifact_ids=followup.artifact_ids,source=followup.source,@@ -612,6 +660,8 @@ class TaskManagementWorkflow(PostHogWorkflow):steer=followup.steer,sequence=followup.sequence,)+ if delivered is False:+ return# The persisted queue is the orchestrator's recovery buffer — keep# it in sync after every drain so a restart sees an accurate picture# rather than re-delivering work we already forwarded.@@ -647,6 +697,8 @@ class TaskManagementWorkflow(PostHogWorkflow):if followup is not None:requeued_followups.append(followup)continue+ if ack.accepted and slot.signal_name in {SEND_FOLLOWUP_SIGNAL, SEND_STEER_SIGNAL}:+ self._consecutive_sandbox_replacement_failures = 0workflow.logger.info("task_management_ack_received",run_id=self._run_id,@@ -660,6 +712,9 @@ class TaskManagementWorkflow(PostHogWorkflow):for followup in requeued_followups:self._insert_external_followup_in_arrival_order(followup)if requeued_followups:+ if _patch_enabled(_PATCH_ID_CLEAR_STEER_ON_SANDBOX_BOUNDARY):+ self._clear_pending_steer_intent()+ self._record_sandbox_replacement_failure()# Sync the recovery buffer to reflect the re-queue; otherwise an# orchestrator restart would forget about the rejected follow-up.await self._persist_pending_followups()@@ -707,6 +762,91 @@ class TaskManagementWorkflow(PostHogWorkflow):returnself._pending_external_followups.append(followup)+ def _clear_pending_steer_intent(self) -> None:+ for followup in self._pending_external_followups:+ followup.steer = False++ def _record_sandbox_replacement_failure(self) -> None:+ if _patch_enabled(_PATCH_ID_BOUNDED_SANDBOX_REPLACEMENT_RECOVERY):+ self._consecutive_sandbox_replacement_failures += 1++ async def _wait_before_replacement_sandbox(self) -> None:+ if not _patch_enabled(_PATCH_ID_BOUNDED_SANDBOX_REPLACEMENT_RECOVERY):+ return+ failures = self._consecutive_sandbox_replacement_failures+ if failures >= MAX_CONSECUTIVE_SANDBOX_REPLACEMENT_FAILURES:+ if _patch_enabled(_PATCH_ID_DURABLE_REPLACEMENT_BUDGET_PERSISTENCE):+ if _patch_enabled(_PATCH_ID_TERMINAL_PENDING_FOLLOWUP_BARRIER):+ self._persist_pending_followups_on_exit = True+ else:+ await self._persist_pending_followups_until_stable()+ raise RuntimeError(+ f"Sandbox replacement failed {failures} consecutive times before acknowledging a follow-up"+ )+ if not _patch_enabled(_PATCH_ID_PERSIST_REPLACEMENT_BUDGET):+ raise RuntimeError(+ f"Sandbox replacement failed {failures} consecutive times before acknowledging a follow-up"+ )+ if await self._persist_pending_followups():+ raise RuntimeError(+ f"Sandbox replacement failed {failures} consecutive times before acknowledging a follow-up"+ )+ workflow.logger.warning(+ "task_management_sandbox_replacement_budget_persist_failed",+ run_id=self._run_id,+ consecutive_failures=failures,+ )+ if failures == 0:+ return+ delay_seconds = min(2 ** (failures - 1), MAX_SANDBOX_REPLACEMENT_BACKOFF_SECONDS)+ workflow.logger.warning(+ "task_management_sandbox_replacement_backoff",+ run_id=self._run_id,+ consecutive_failures=failures,+ delay_seconds=delay_seconds,+ )+ await workflow.sleep(delay_seconds)++ async def _recover_closed_sandbox(self, error: Exception) -> None:+ child_acks_by_id = {ack.ack_id: ack for ack in self._child_acks}+ accepted_followup_ack = False+ requeued = 0+ for ack_id, slot in self._pending_ack_slots.items():+ ack = child_acks_by_id.get(ack_id)+ if ack is not None:+ if ack.accepted:+ if slot.signal_name in {SEND_FOLLOWUP_SIGNAL, SEND_STEER_SIGNAL}:+ accepted_followup_ack = True+ continue+ if ack.detail != SHUTDOWN_REJECTION_DETAIL:+ continue+ if slot.signal_name not in {SEND_FOLLOWUP_SIGNAL, SEND_STEER_SIGNAL} or slot.signal_args is None:+ continue+ self._insert_external_followup_in_arrival_order(self._external_followup_from_slot(slot))+ requeued += 1++ if accepted_followup_ack and _patch_enabled(_PATCH_ID_ACCEPTED_ACK_RESETS_REPLACEMENT_BUDGET):+ self._consecutive_sandbox_replacement_failures = 0+ self._clear_pending_steer_intent()+ if requeued:+ self._record_sandbox_replacement_failure()+ workflow.logger.warning(+ "task_management_closed_sandbox_recovered",+ run_id=self._run_id,+ requeued=requeued,+ error=str(error),+ )+ self._pending_ack_slots.clear()+ self._child_acks.clear()+ self._child_completion = None+ self._sandbox_alive = False+ self._child_steering_protocol_version = 0+ self._ci_repetitions = 0+ self._pr_fingerprint = None+ self._heartbeat_received = False+ self._last_active_time = None+ await self._persist_pending_followups()+# ------------------------------------------------------------------# Sandbox session lifecycle (multiple sessions per orchestrator)# ------------------------------------------------------------------@@ -746,6 +886,10 @@ class TaskManagementWorkflow(PostHogWorkflow):run_id=self._run_id,count=requeued,)+ self._record_sandbox_replacement_failure()++ if _patch_enabled(_PATCH_ID_CLEAR_STEER_ON_SANDBOX_BOUNDARY):+ self._clear_pending_steer_intent()# Hard-reset per-session state. The next session starts clean —# CI counters, fingerprint, heartbeat all belong to the previous@@ -813,7 +957,7 @@ class TaskManagementWorkflow(PostHogWorkflow):count=len(result.followups),)- async def _persist_pending_followups(self) -> None:+ async def _persist_pending_followups(self) -> bool:"""Mirror the in-memory queue into `TaskRun.state`.Best-effort: failure here doesn't compromise the current execution,@@ -823,24 +967,85 @@ class TaskManagementWorkflow(PostHogWorkflow):and an empty-to-empty no-op would still take a row lock."""if self._run_id is None:- return+ return Falsepayload = [asdict(f) for f in self._pending_external_followups]if payload == self._last_persisted_followups:- return+ return Truetry:- await workflow.execute_activity(- persist_pending_followups,- PersistPendingFollowupsInput(run_id=self._run_id, followups=payload),- start_to_close_timeout=timedelta(seconds=30),- retry_policy=RetryPolicy(maximum_attempts=3),- )+ if _patch_enabled(_PATCH_ID_GENERATION_SAFE_PENDING_FOLLOWUPS):+ await workflow.execute_activity(+ persist_pending_followups_v2,+ PersistPendingFollowupsV2Input(+ run_id=self._run_id,+ followups=payload,+ generation=self._new_persistence_generation(),+ ),+ start_to_close_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ else:+ await workflow.execute_activity(+ persist_pending_followups,+ PersistPendingFollowupsInput(run_id=self._run_id, followups=payload),+ start_to_close_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )self._last_persisted_followups = payload+ return Trueexcept Exception as e:workflow.logger.warning("task_management_persist_pending_failed",run_id=self._run_id,error=str(e),)+ return False++ async def _persist_pending_followups_until_stable(self) -> None:+ """Durably park the complete queue before exhausting recovery.++ Signals can append follow-ups while the persistence activity is+ running. Keep writing snapshots until the completed write still+ matches the in-memory queue. The schedule-to-close deadline bounds+ permanent storage failures without provisioning more sandboxes.+ """+ if self._run_id is None:+ raise RuntimeError("Cannot persist pending follow-ups without a run id")+ while True:+ payload = [asdict(followup) for followup in self._pending_external_followups]+ if _patch_enabled(_PATCH_ID_GENERATION_SAFE_PENDING_FOLLOWUPS):+ await workflow.execute_activity(+ persist_pending_followups_v2,+ PersistPendingFollowupsV2Input(+ run_id=self._run_id,+ followups=payload,+ generation=self._new_persistence_generation(),+ ),+ schedule_to_close_timeout=timedelta(minutes=5),+ start_to_close_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(+ maximum_attempts=0,+ non_retryable_error_types=[TASK_RUN_NOT_FOUND_ERROR_TYPE],+ ),+ )+ else:+ await workflow.execute_activity(+ persist_pending_followups,+ PersistPendingFollowupsInput(run_id=self._run_id, followups=payload),+ start_to_close_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=0),+ )+ self._last_persisted_followups = payload+ if payload == [asdict(followup) for followup in self._pending_external_followups]:+ return++ def _new_persistence_generation(self) -> int:+ now = workflow.now() if workflow.in_workflow() else datetime.now()+ timestamp_generation = int(now.timestamp() * 1_000_000)+ self._last_persistence_generation = max(+ self._last_persistence_generation + 1,+ timestamp_generation,+ )+ return self._last_persistence_generation# ------------------------------------------------------------------# Sandbox workflow management@@ -879,6 +1084,13 @@ class TaskManagementWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(maximum_attempts=3),)self._child_steering_protocol_version = protocol_version if isinstance(protocol_version, int) else 0+ self._sandbox_generation += 1+ # The startup patch is memoized for the workflow lifetime. A distinct+ # marker per sandbox lets an old replay keep its recorded ordering,+ # then adopt ACK-first handling when a later sandbox starts live.+ self._ack_before_completion = self._ack_before_completion or _ack_before_completion_for_sandbox_generation(+ self._sandbox_generation+ )# Activity success means Signal-With-Start landed — either delivered# to an already-running execution or kicked off a fresh one. Either# way, a sandbox session is now in-flight.@@ -898,14 +1110,14 @@ class TaskManagementWorkflow(PostHogWorkflow):message_context: dict[str, Any] | None = None,steer: bool = False,sequence: int | None = None,- ) -> None:+ ) -> bool | None:if self._sandbox_workflow_id is None:workflow.logger.warning("task_management_followup_dropped_no_sandbox",run_id=self._run_id,source=source,)- return+ return Noneack_id = self._new_ack_id()if sequence is None:sequence = self._next_followup_sequence@@ -937,6 +1149,9 @@ class TaskManagementWorkflow(PostHogWorkflow):try:await self._sandbox_handle().signal(signal_name, args=signal_args)except Exception as e:+ if _child_cannot_receive_signals(e) and _patch_enabled(_PATCH_ID_CLOSED_CHILD_FOLLOWUP_RECOVERY):+ await self._recover_closed_sandbox(e)+ return False# Keep the slot — `_retry_stale_acks` will try again after# ACK_TIMEOUT. This is the "child is dead, parent retries"# branch the design relies on.@@ -946,6 +1161,7 @@ class TaskManagementWorkflow(PostHogWorkflow):source=source,error=str(e),)+ return Trueasync def _signal_child_complete(self, status: str, error_message: Optional[str]) -> None:if self._sandbox_workflow_id is None or not self._sandbox_alive:@@ -963,6 +1179,9 @@ class TaskManagementWorkflow(PostHogWorkflow):try:await self._sandbox_handle().signal(COMPLETE_TASK_SIGNAL, args=signal_args)except Exception as e:+ if _child_cannot_receive_signals(e) and _patch_enabled(_PATCH_ID_CLOSED_CHILD_COMPLETION_RECOVERY):+ await self._recover_closed_sandbox(e)+ returnworkflow.logger.warning("task_management_signal_complete_failed",run_id=self._run_id,@@ -1013,6 +1232,9 @@ class TaskManagementWorkflow(PostHogWorkflow):retry_count=slot.retry_count,)except Exception as e:+ if _child_cannot_receive_signals(e) and _patch_enabled(_PATCH_ID_CLOSED_CHILD_ACK_RETRY_RECOVERY):+ await self._recover_closed_sandbox(e)+ return# Don't advance sent_at on failure — we want to retry again# at the next deadline rather than push it out by ACK_TIMEOUT.workflow.logger.warning(