: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): recover durable ci budget checkpoints (#108429)
Alessandro Pogliaghi53c62d996b9f
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.mdindex d5ab411bdf7b..d00892d39355 100644--- a/docs/internal/sandboxes-setup-guide.md+++ b/docs/internal/sandboxes-setup-guide.md@@ -77,6 +77,10 @@ The separate `task-management` implementation is not registered with the worker.It stops polling closed or merged PRs and caps background runs at two idle checks; pending CI and merge-queue checks do not consume that budget.Pending CI and merge queues have a separate limit of 96 waiting checks (24 hours at the normal cadence).Follow-ups and sandbox-session boundaries reset both budgets, and the counters persist in server-owned `TaskRun.state` across orchestrator restarts.+With the `tasks-task-management-durable-ci-checkpoints` Temporal patch, queue and budget changes are staged in a generation-protected checkpoint before application.+Startup applies any unfinished checkpoint before restoring the queue and counters. Follow-ups wait for their reset and queued message to persist before delivery.+Exhausted persistence retries stop the orchestrator instead of continuing with an unsaved budget; a new execution can recover a staged checkpoint. A failure before staging does not create a recoverable database checkpoint.+With `tasks-task-management-checkpoint-recovery-status`, checkpoint read or write failures leave the task run non-terminal so recovery can reattach to its sandbox. `tasks-execute-sandbox-reopen-parent-delivery` resumes sandbox acknowledgements when the restarted orchestrator attaches.The `process-task` workflow defined in`products/tasks/backend/temporal/process_task/workflow.py` provisions a sandbox,diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 5c6a6364293f..899a65dff4ab 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -2670,6 +2670,7 @@ _PROTECTED_RUN_STATE_KEYS = frozenset("cancel_fallback_cleanup_complete","pending_external_followups","pending_external_followups_generation",+ "pending_external_followups_checkpoint","task_management_ci_idle_skips","task_management_ci_wait_checks",# Terminal reason markers owned by the workflow (see the note above). Spelled as literalsdiff --git a/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py b/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.pyindex bc5e7f01d7b7..6d753c4d7376 100644--- a/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py+++ b/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py@@ -170,12 +170,20 @@ class TestParseInputs:class TestSignalHandlers:- async def test_parent_attached_sets_parent_id_and_queues_ack(self, silent_workflow_logger):+ @pytest.mark.parametrize("patched", [True, False])+ @pytest.mark.parametrize("delivery_closed", [True, False])+ async def test_parent_attached_sets_parent_id_and_queues_ack(+ self, monkeypatch, silent_workflow_logger, patched: bool, delivery_closed: bool+ ) -> None:workflow = ExecuteSandboxWorkflow()+ workflow._parent_signal_delivery_closed = delivery_closed+ monkeypatch.setattr(execute_sandbox_workflow_module.workflow, "in_workflow", lambda: True)+ monkeypatch.setattr(execute_sandbox_workflow_module.workflow, "patched", lambda _: patched)await workflow.parent_attached("ack-1", "parent-wf-id")assert workflow._parent_workflow_id == "parent-wf-id"+ assert workflow._parent_signal_delivery_closed is (delivery_closed and not patched)assert workflow._pending_outbound == [OutboundSignal(target_signal=PARENT_ACK_SIGNAL,diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.pyindex 87a786693f5f..bd8b8697968c 100644--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py@@ -229,6 +229,7 @@ class SandboxEvent(StrEnum):_PATCH_ID_CONCURRENT_FOLLOWUP_STEERING = "tasks-execute-sandbox-concurrent-followup-steering"_PATCH_ID_ORDERED_OUTBOUND_DELIVERY = "tasks-execute-sandbox-ordered-outbound-delivery"+_PATCH_ID_REOPEN_PARENT_DELIVERY = "tasks-execute-sandbox-reopen-parent-delivery"_PATCH_ID_BOUNDED_FINAL_OUTBOUND_DELIVERY = "tasks-execute-sandbox-bounded-final-outbound-delivery"_PARENT_SIGNAL_TERMINAL_ERROR_TYPES = {"ExternalWorkflowExecutionNotFound",@@ -711,6 +712,8 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):if self._is_duplicate_signal(PARENT_ATTACHED_SIGNAL, ack_id):returnself._parent_workflow_id = parent_workflow_id+ if not workflow.in_workflow() or workflow.patched(_PATCH_ID_REOPEN_PARENT_DELIVERY):+ self._parent_signal_delivery_closed = Falseself._enqueue_ack(signal_name=PARENT_ATTACHED_SIGNAL, ack_id=ack_id)@workflow.signal(name=COMPLETE_TASK_SIGNAL)diff --git a/products/tasks/backend/temporal/task_management/activities/__init__.py b/products/tasks/backend/temporal/task_management/activities/__init__.pyindex 0d9e34fa44ea..8e672a297d2c 100644--- a/products/tasks/backend/temporal/task_management/activities/__init__.py+++ b/products/tasks/backend/temporal/task_management/activities/__init__.py@@ -6,6 +6,7 @@ from .pending_followups import (ReadPendingFollowupsResult,persist_pending_followups,persist_pending_followups_v2,+ persist_pending_followups_v3,read_pending_followups,)@@ -18,5 +19,6 @@ __all__ = ["ensure_execute_sandbox_started","persist_pending_followups","persist_pending_followups_v2",+ "persist_pending_followups_v3","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 0653e49b356b..a9444f0c0b44 100644--- a/products/tasks/backend/temporal/task_management/activities/pending_followups.py+++ b/products/tasks/backend/temporal/task_management/activities/pending_followups.py@@ -14,7 +14,7 @@ Activities here are deliberately small: the orchestrator decides *when* topersist; this module only knows how."""-from dataclasses import dataclass+from dataclasses import asdict, dataclassfrom typing import Anyfrom temporalio import activity@@ -25,6 +25,7 @@ from posthog.temporal.common.utils import asyncifyfrom products.tasks.backend.models import TaskRunfrom products.tasks.backend.temporal.observability import log_activity_execution+PENDING_FOLLOWUPS_CHECKPOINT_STATE_KEY = "pending_external_followups_checkpoint"PENDING_FOLLOWUPS_STATE_KEY = "pending_external_followups"PENDING_FOLLOWUPS_GENERATION_STATE_KEY = "pending_external_followups_generation"CI_IDLE_SKIPS_STATE_KEY = "task_management_ci_idle_skips"@@ -50,9 +51,10 @@ class PersistPendingFollowupsV2Input:ci_wait_checks: int | None = None-@dataclass+@dataclass(frozen=False)class ReadPendingFollowupsInput:run_id: str+ recover_checkpoint: bool = False@dataclass(frozen=False)@@ -90,25 +92,26 @@ def persist_pending_followups(input: PersistPendingFollowupsInput) -> None:TaskRun.mutate_state_atomic(input.run_id, _persist_if_unversioned)+def _apply_pending_followups_snapshot(state: dict[str, Any], input: PersistPendingFollowupsV2Input) -> 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.generation+ if input.ci_idle_skips is not None:+ state[CI_IDLE_SKIPS_STATE_KEY] = input.ci_idle_skips+ if input.ci_wait_checks is not None:+ state[CI_WAIT_CHECKS_STATE_KEY] = input.ci_wait_checks+ if input.followups:+ state[PENDING_FOLLOWUPS_STATE_KEY] = input.followups+ else:+ state.pop(PENDING_FOLLOWUPS_STATE_KEY, None)++@activity.defn@asyncifydef 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.generation- if input.ci_idle_skips is not None:- state[CI_IDLE_SKIPS_STATE_KEY] = input.ci_idle_skips- if input.ci_wait_checks is not None:- state[CI_WAIT_CHECKS_STATE_KEY] = input.ci_wait_checks- if input.followups:- state[PENDING_FOLLOWUPS_STATE_KEY] = input.followups- else:- state.pop(PENDING_FOLLOWUPS_STATE_KEY, None)-with log_activity_execution("persist_pending_followups_v2",run_id=input.run_id,@@ -116,7 +119,41 @@ def persist_pending_followups_v2(input: PersistPendingFollowupsV2Input) -> None:generation=input.generation,):try:- TaskRun.mutate_state_atomic(input.run_id, _persist_if_newer)+ TaskRun.mutate_state_atomic(input.run_id, lambda state: _apply_pending_followups_snapshot(state, input))+ 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+++def _commit_pending_followups_checkpoint(state: dict[str, Any]) -> None:+ checkpoint = state.get(PENDING_FOLLOWUPS_CHECKPOINT_STATE_KEY)+ if checkpoint is None:+ return+ _apply_pending_followups_snapshot(state, PersistPendingFollowupsV2Input(**checkpoint))+ state.pop(PENDING_FOLLOWUPS_CHECKPOINT_STATE_KEY)+++@asyncify+def persist_pending_followups_v3(input: PersistPendingFollowupsV2Input) -> None:+ def stage_checkpoint(state: dict[str, Any]) -> None:+ committed_generation = state.get(PENDING_FOLLOWUPS_GENERATION_STATE_KEY, 0)+ pending_generation = (state.get(PENDING_FOLLOWUPS_CHECKPOINT_STATE_KEY) or {}).get("generation", 0)+ if not isinstance(committed_generation, int):+ committed_generation = 0+ if input.generation <= max(committed_generation, pending_generation):+ return+ state[PENDING_FOLLOWUPS_CHECKPOINT_STATE_KEY] = asdict(input)++ with log_activity_execution(+ "persist_pending_followups_v3", run_id=input.run_id, count=len(input.followups), generation=input.generation+ ):+ try:+ TaskRun.mutate_state_atomic(input.run_id, stage_checkpoint)+ TaskRun.mutate_state_atomic(input.run_id, _commit_pending_followups_checkpoint)except TaskRun.DoesNotExist as error:raise ApplicationError(f"Task run {input.run_id} no longer exists",@@ -139,6 +176,8 @@ def read_pending_followups(input: ReadPendingFollowupsInput) -> ReadPendingFollorun_id=input.run_id,):try:+ if input.recover_checkpoint:+ TaskRun.mutate_state_atomic(input.run_id, _commit_pending_followups_checkpoint)task_run = TaskRun.objects.only("state").get(id=input.run_id)except TaskRun.DoesNotExist:return ReadPendingFollowupsResult(followups=[])diff --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 fae43ab9bc05..771f22fb5189 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@@ -1,13 +1,18 @@import uuidimport pytest+from unittest.mock import patch++from django.db import OperationalErrorfrom asgiref.sync import async_to_syncfrom temporalio.exceptions import ApplicationError+from products.tasks.backend.temporal.task_management.activities import pending_followups as pending_modulefrom products.tasks.backend.temporal.task_management.activities.pending_followups import (CI_IDLE_SKIPS_STATE_KEY,CI_WAIT_CHECKS_STATE_KEY,+ PENDING_FOLLOWUPS_CHECKPOINT_STATE_KEY,PENDING_FOLLOWUPS_GENERATION_STATE_KEY,PENDING_FOLLOWUPS_STATE_KEY,TASK_RUN_NOT_FOUND_ERROR_TYPE,@@ -16,6 +21,7 @@ from products.tasks.backend.temporal.task_management.activities.pending_followupReadPendingFollowupsInput,persist_pending_followups,persist_pending_followups_v2,+ persist_pending_followups_v3,read_pending_followups,)@@ -69,7 +75,8 @@ class TestPersistPendingFollowups:{"message": "m", "artifact_ids": [], "source": "user"}]- def test_older_generation_cannot_overwrite_newer_queue(self, activity_environment, test_task_run):+ @pytest.mark.parametrize("persist", [persist_pending_followups_v2, persist_pending_followups_v3])+ def test_older_generation_cannot_overwrite_newer_queue(self, activity_environment, test_task_run, persist):run_id = str(test_task_run.id)first = [{"message": "first", "artifact_ids": [], "source": "user", "sequence": 1}]complete = [@@ -79,7 +86,7 @@ class TestPersistPendingFollowups:for generation, followups in [(1, first), (2, complete), (1, first)]:async_to_sync(activity_environment.run)(- persist_pending_followups_v2,+ persist,PersistPendingFollowupsV2Input(run_id=run_id,followups=followups,@@ -102,10 +109,11 @@ class TestPersistPendingFollowups:assert restored.ci_idle_skips == 2assert restored.ci_wait_checks == 2- def test_missing_task_run_is_non_retryable(self, activity_environment):+ @pytest.mark.parametrize("persist", [persist_pending_followups_v2, persist_pending_followups_v3])+ def test_missing_task_run_is_non_retryable(self, activity_environment, persist):with pytest.raises(ApplicationError) as exc_info:async_to_sync(activity_environment.run)(- persist_pending_followups_v2,+ persist,PersistPendingFollowupsV2Input(run_id=str(uuid.uuid4()),followups=[],@@ -116,6 +124,60 @@ class TestPersistPendingFollowups:assert exc_info.value.type == TASK_RUN_NOT_FOUND_ERROR_TYPEassert exc_info.value.non_retryable is True+ @pytest.mark.parametrize("before,after", [((2, 96), (0, 0)), ((1, 95), (2, 96))])+ @pytest.mark.parametrize("newer_write", [None, persist_pending_followups_v2, persist_pending_followups_v3])+ def test_recovers_staged_counters_and_queue_after_failed_apply(+ self, activity_environment, test_task_run, before, after, newer_write+ ):+ test_task_run.state = {+ CI_IDLE_SKIPS_STATE_KEY: before[0],+ CI_WAIT_CHECKS_STATE_KEY: before[1],+ PENDING_FOLLOWUPS_GENERATION_STATE_KEY: 1,+ "mode": "background",+ }+ test_task_run.save(update_fields=["state"])+ followups = [{"message": "retry queued work", "artifact_ids": [], "source": "user"}] if after == (0, 0) else []+ snapshot = PersistPendingFollowupsV2Input(+ run_id=str(test_task_run.id),+ followups=followups,+ generation=2,+ ci_idle_skips=after[0],+ ci_wait_checks=after[1],+ )+ with patch.object(+ pending_module, "_commit_pending_followups_checkpoint", side_effect=OperationalError("apply unavailable")+ ):+ for _ in range(3):+ with pytest.raises(OperationalError, match="apply unavailable"):+ async_to_sync(activity_environment.run)(persist_pending_followups_v3, snapshot)++ legacy_read = async_to_sync(activity_environment.run)(+ read_pending_followups, ReadPendingFollowupsInput(run_id=str(test_task_run.id))+ )+ assert (legacy_read.ci_idle_skips, legacy_read.ci_wait_checks) == before+ test_task_run.refresh_from_db()+ assert test_task_run.state[PENDING_FOLLOWUPS_CHECKPOINT_STATE_KEY]["generation"] == 2++ if newer_write:+ async_to_sync(activity_environment.run)(+ newer_write,+ PersistPendingFollowupsV2Input(+ run_id=str(test_task_run.id), followups=[], generation=3, ci_idle_skips=1, ci_wait_checks=4+ ),+ )+ restored = async_to_sync(activity_environment.run)(+ read_pending_followups, ReadPendingFollowupsInput(run_id=str(test_task_run.id), recover_checkpoint=True)+ )+ assert (restored.ci_idle_skips, restored.ci_wait_checks) == ((1, 4) if newer_write else after)+ assert restored.followups == ([] if newer_write else followups)+ test_task_run.refresh_from_db()+ assert PENDING_FOLLOWUPS_CHECKPOINT_STATE_KEY not in test_task_run.state+ assert test_task_run.state["mode"] == "background"+ async_to_sync(activity_environment.run)(persist_pending_followups_v3, snapshot)+ test_task_run.refresh_from_db()+ assert test_task_run.state[CI_IDLE_SKIPS_STATE_KEY] == restored.ci_idle_skips+ assert test_task_run.state[CI_WAIT_CHECKS_STATE_KEY] == restored.ci_wait_checks+@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 ec9228349613..26396cb6871a 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@@ -1,10 +1,11 @@+import asynciofrom dataclasses import replacefrom datetime import UTC, datetime, timedeltaimport pytestfrom unittest.mock import AsyncMock, Mock-from temporalio.exceptions import ApplicationError+from temporalio.exceptions import ActivityError, ApplicationError, CancelledErrorfrom products.tasks.backend.temporal.constants import (ACK_TIMEOUT,@@ -20,7 +21,11 @@ from products.tasks.backend.temporal.execute_sandbox.workflow import PARENT_ATTAfrom products.tasks.backend.temporal.process_task.activities.get_pr_context import GetPrContextOutput, get_pr_contextfrom 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_module-from products.tasks.backend.temporal.task_management.activities.pending_followups import ReadPendingFollowupsResult+from products.tasks.backend.temporal.task_management.activities.pending_followups import (+ ReadPendingFollowupsResult,+ persist_pending_followups_v2,+ persist_pending_followups_v3,+)from products.tasks.backend.temporal.task_management.workflow import (MAX_CI_WAIT_CHECKS,MAX_CONSECUTIVE_SANDBOX_REPLACEMENT_FAILURES,@@ -35,6 +40,21 @@ from products.tasks.backend.temporal.task_management.workflow import ()[email protected](params=[True, False])+def durable_ci_patch(request, monkeypatch) -> bool:+ original = task_management_workflow_module._patch_enabled+ monkeypatch.setattr(+ task_management_workflow_module,+ "_patch_enabled",+ lambda patch_id: (+ request.param+ if patch_id == task_management_workflow_module._PATCH_ID_DURABLE_CI_CHECKPOINTS+ else original(patch_id)+ ),+ )+ return request.param++def _build_context(*,create_pr: bool = True,@@ -523,7 +543,7 @@ class TestMaybeDispatchCIFollowUp:persisted = execute_activity.await_args_list[-1].args[1]assert persisted.ci_idle_skips == MAX_CI_IDLE_SKIPS- async def test_fire_dispatches_and_increments_repetitions(self, monkeypatch, fixed_now):+ async def test_fire_dispatches_and_increments_repetitions(self, monkeypatch, fixed_now, durable_ci_patch):# `_dispatch_ci_follow_up` increments repetitions, sets last_active so# _wait_for_ci_follow_up sleeps a full window, and forwards via the# signal-child-followup machinery.@@ -533,6 +553,7 @@ class TestMaybeDispatchCIFollowUp:workflow._ci_wait_checks = 1monkeypatch.setattr(task_management_workflow_module.workflow, "execute_activity", AsyncMock())workflow._run_id = "run-id"+ workflow._sandbox_alive = Trueworkflow._sandbox_workflow_id = "sandbox-wf"monkeypatch.setattr(workflow, "_should_run_ci_follow_up", AsyncMock(return_value=CIFollowUpDecision.FIRE))@@ -545,12 +566,18 @@ class TestMaybeDispatchCIFollowUp:assert workflow._ci_idle_skips == 0assert workflow._ci_wait_checks == 0assert workflow._last_active_time == fixed_now.now- signal_mock.assert_awaited_once_with(message="custom prompt", artifact_ids=[], source="ci")+ signal_mock.assert_awaited_once()+ assert signal_mock.await_args is not None+ assert signal_mock.await_args.kwargs["message"] == "custom prompt"+ assert signal_mock.await_args.kwargs["source"] == "ci"+ assert workflow._pending_external_followups == []- async def test_fire_falls_back_to_default_ci_message(self, monkeypatch, fixed_now):+ async def test_fire_falls_back_to_default_ci_message(self, monkeypatch, fixed_now, durable_ci_patch):workflow = TaskManagementWorkflow()workflow._context = _build_context(ci_prompt=None)workflow._run_id = "run-id"+ workflow._sandbox_alive = True+ monkeypatch.setattr(task_management_workflow_module.workflow, "execute_activity", AsyncMock())monkeypatch.setattr(workflow, "_should_run_ci_follow_up", AsyncMock(return_value=CIFollowUpDecision.FIRE))signal_mock = AsyncMock()@@ -558,7 +585,11 @@ class TestMaybeDispatchCIFollowUp:await workflow._maybe_dispatch_ci_follow_up()- signal_mock.assert_awaited_once_with(message=DEFAULT_CI_MESSAGE, artifact_ids=[], source="ci")+ signal_mock.assert_awaited_once()+ assert signal_mock.await_args is not None+ assert signal_mock.await_args.kwargs["message"] == DEFAULT_CI_MESSAGE+ assert signal_mock.await_args.kwargs["source"] == "ci"+ assert workflow._pending_external_followups == []@pytest.mark.parametrize("decision", [CIFollowUpDecision.NO_PR, CIFollowUpDecision.TERMINAL])async def test_terminal_decision_disables_ci_loop(self, monkeypatch, silent_workflow_logger, decision):@@ -600,6 +631,35 @@ class TestMaybeDispatchCIFollowUp:class TestDrainExternalSignals:+ async def test_followups_arriving_during_checkpoint_are_saved_before_delivery(self, monkeypatch, fixed_now):+ workflow = TaskManagementWorkflow()+ workflow._run_id = "run-id"+ workflow._sandbox_alive = True+ workflow._pending_external_followups.append(+ PendingExternalFollowup(message="first", artifact_ids=[], source="user")+ )+ saved_messages: list[str] = []+ delivered_messages: list[str] = []++ async def save_snapshot(_activity, input, **_kwargs):+ saved_messages[:] = [item["message"] for item in input.followups]+ if saved_messages == ["first"]:+ workflow._pending_external_followups.append(+ PendingExternalFollowup(message="second", artifact_ids=[], source="user", sequence=1)+ )++ async def deliver(*, message, **_kwargs):+ assert message in saved_messages+ delivered_messages.append(message)++ monkeypatch.setattr(task_management_workflow_module.workflow, "execute_activity", save_snapshot)+ monkeypatch.setattr(workflow, "_signal_child_followup", deliver)++ await workflow._drain_external_signals()++ assert delivered_messages == ["first", "second"]+ assert saved_messages == []+async def test_followups_drained_before_completion(self, monkeypatch):# complete_task is terminal for a session — if we processed it first,# any pending follow-up messages would be dropped on the floor.@@ -1647,7 +1707,8 @@ class TestShutdownRejectionHandling:the orchestrator re-queues the message so it stays visible in workflowstate for the next orchestrator execution to drain."""- async def test_followup_rejection_requeues_to_external_queue(self, fixed_now, silent_workflow_logger):+ async def test_followup_rejection_requeues_to_external_queue(self, monkeypatch, fixed_now, silent_workflow_logger):+ monkeypatch.setattr(task_management_workflow_module.workflow, "execute_activity", AsyncMock())workflow = TaskManagementWorkflow()workflow._run_id = "run-id"workflow._pending_ack_slots["ack-shut"] = PendingAckSlot(@@ -1676,7 +1737,10 @@ class TestShutdownRejectionHandling:]silent_workflow_logger.warning.assert_called()- async def test_steer_rejections_preserve_arrival_order_as_normal_followups(self, fixed_now, silent_workflow_logger):+ async def test_steer_rejections_preserve_arrival_order_as_normal_followups(+ self, monkeypatch, fixed_now, silent_workflow_logger+ ):+ monkeypatch.setattr(task_management_workflow_module.workflow, "execute_activity", AsyncMock())workflow = TaskManagementWorkflow()workflow._run_id = "run-id"workflow._pending_ack_slots["ack-steer-1"] = PendingAckSlot(@@ -1965,6 +2029,69 @@ class TestSandboxSessionCompletionReset:class TestPendingFollowupPersistence:+ @pytest.mark.parametrize("patched", [True, False])+ @pytest.mark.parametrize(+ "activity_type", ["read_pending_followups", "persist_pending_followups_v3", "get_task_processing_context"]+ )+ async def test_checkpoint_failure_preserves_recoverable_run_status(+ self, monkeypatch, silent_workflow_logger, patched: bool, activity_type: str+ ) -> None:+ workflow = TaskManagementWorkflow()+ workflow._pending_external_followups.append(+ PendingExternalFollowup(message="queued work", artifact_ids=[], source="user")+ )+ workflow._sandbox_alive = True+ error = ActivityError(+ "storage unavailable",+ scheduled_event_id=1,+ started_event_id=2,+ identity="worker",+ activity_type=activity_type,+ activity_id="activity-1",+ retry_state=None,+ )+ original_patch = task_management_workflow_module._patch_enabled+ monkeypatch.setattr(+ task_management_workflow_module,+ "_patch_enabled",+ lambda patch_id: (+ patched+ if patch_id == task_management_workflow_module._PATCH_ID_CHECKPOINT_RECOVERY_STATUS+ else original_patch(patch_id)+ ),+ )+ monkeypatch.setattr(task_management_workflow_module.workflow, "info", lambda: Mock(workflow_id="wf-id"))++ async def execute_activity(activity_fn, *_args, **_kwargs):+ if activity_fn.__name__ == activity_type:+ raise error+ return ReadPendingFollowupsResult(followups=[])++ monkeypatch.setattr(task_management_workflow_module.workflow, "execute_activity", execute_activity)+ monkeypatch.setattr(+ workflow,+ "_get_task_processing_context",+ AsyncMock(side_effect=error)+ if activity_type == "get_task_processing_context"+ else AsyncMock(return_value=_build_context()),+ )+ monkeypatch.setattr(workflow, "_track_workflow_event", AsyncMock())+ monkeypatch.setattr(workflow, "_post_slack_update", AsyncMock())+ monkeypatch.setattr(workflow, "_ensure_sandbox_workflow_started", AsyncMock())+ monkeypatch.setattr(workflow, "_wait_for_event", AsyncMock(return_value=TaskEvent.EXTERNAL_SIGNAL))+ status_update = AsyncMock()+ monkeypatch.setattr(workflow, "_update_task_run_status", status_update)++ result = await workflow.run(TaskRunManagementInput(run_id="run-id"))++ assert result.success is False+ if patched and activity_type != "get_task_processing_context":+ status_update.assert_not_awaited()+ else:+ status_update.assert_awaited_once_with(+ "failed", error_message="storage unavailable", error_type="ActivityError"+ )+@pytest.mark.parametrize("patched", [True, False])@pytest.mark.parametrize("wait_cap", [False, True])async def test_restart_preserves_ci_caps_with_no_pending_followups(@@ -1990,6 +2117,41 @@ class TestPendingFollowupPersistence:assert await workflow._persist_pending_followups()assert execute_activity.await_count == 1+ @pytest.mark.parametrize("source", ["user", "ci"])+ async def test_failed_checkpoint_keeps_followup_queued_before_delivery(+ self, monkeypatch, fixed_now, silent_workflow_logger, durable_ci_patch, source+ ) -> None:+ workflow = TaskManagementWorkflow()+ workflow._context = _build_context(ci_prompt="queued work")+ workflow._run_id = "run-id"+ workflow._sandbox_alive = True+ workflow._sandbox_workflow_id = "sandbox-wf"+ workflow._ci_idle_skips = MAX_CI_IDLE_SKIPS+ workflow._ci_wait_checks = MAX_CI_WAIT_CHECKS+ monkeypatch.setattr(+ task_management_workflow_module.workflow,+ "execute_activity",+ AsyncMock(side_effect=RuntimeError("storage unavailable")),+ )+ deliver = AsyncMock()+ monkeypatch.setattr(workflow, "_signal_child_followup", deliver)+ if source == "user":+ workflow._pending_external_followups.append(+ PendingExternalFollowup(message="queued work", artifact_ids=[], source=source)+ )+ transition = workflow._drain_external_signals+ else:+ transition = workflow._dispatch_ci_follow_up+ if durable_ci_patch:+ with pytest.raises(RuntimeError, match="storage unavailable"):+ await transition()+ deliver.assert_not_awaited()+ assert [f.message for f in workflow._pending_external_followups] == ["queued work"]+ assert workflow._last_persisted_ci_idle_skips == 0+ else:+ await transition()+ deliver.assert_awaited_once()+async def test_restore_pending_seeds_in_memory_queue(self, monkeypatch, silent_workflow_logger):# An orchestrator that restarts must rebuild its queue from# TaskRun.state so user messages that landed against the previous@@ -2020,7 +2182,7 @@ class TestPendingFollowupPersistence:PendingExternalFollowup(message="queued-2", artifact_ids=["a1"], source="user", sequence=1),]- async def test_restore_swallows_read_error(self, monkeypatch, silent_workflow_logger):+ async def test_restore_error_requires_recovery(self, monkeypatch, silent_workflow_logger, durable_ci_patch):workflow = TaskManagementWorkflow()workflow._run_id = "run-id"@@ -2029,15 +2191,43 @@ class TestPendingFollowupPersistence:monkeypatch.setattr(task_management_workflow_module.workflow, "execute_activity", boom)+ if durable_ci_patch:+ with pytest.raises(RuntimeError, match="db down"):+ await workflow._restore_pending_followups()+ returnawait workflow._restore_pending_followups()assert workflow._pending_external_followups == []silent_workflow_logger.warning.assert_called()- async def test_persist_writes_current_queue(self, monkeypatch):- from products.tasks.backend.temporal.task_management.activities.pending_followups import (- persist_pending_followups_v2,- )+ @pytest.mark.parametrize("operation", ["_restore_pending_followups", "_persist_pending_followups"])+ async def test_checkpoint_cancellation_stays_cancelled(+ self, monkeypatch, silent_workflow_logger, durable_ci_patch, operation: str+ ) -> None:+ workflow = TaskManagementWorkflow()+ workflow._run_id = "run-id"+ workflow._pending_external_followups.append(+ PendingExternalFollowup(message="queued work", artifact_ids=[], source="user")+ )+ error = ActivityError(+ "Activity cancelled",+ scheduled_event_id=1,+ started_event_id=2,+ identity="worker",+ activity_type="checkpoint",+ activity_id="checkpoint-1",+ retry_state=None,+ )+ error.__cause__ = CancelledError()+ monkeypatch.setattr(task_management_workflow_module.workflow, "execute_activity", AsyncMock(side_effect=error))++ if durable_ci_patch:+ with pytest.raises(asyncio.CancelledError):+ await getattr(workflow, operation)()+ else:+ await getattr(workflow, operation)()++ async def test_persist_writes_current_queue(self, monkeypatch, durable_ci_patch):workflow = TaskManagementWorkflow()workflow._run_id = "run-id"@@ -2048,7 +2238,7 @@ class TestPendingFollowupPersistence:captured: dict = {}async def fake_execute_activity(activity_fn, input_arg, *args, **kwargs):- assert activity_fn is persist_pending_followups_v2+ assert activity_fn is (persist_pending_followups_v3 if durable_ci_patch else persist_pending_followups_v2)captured["input"] = input_argreturn Nonediff --git a/products/tasks/backend/temporal/task_management/workflow.py b/products/tasks/backend/temporal/task_management/workflow.pyindex 8411ae742977..590e1b40f928 100644--- a/products/tasks/backend/temporal/task_management/workflow.py+++ b/products/tasks/backend/temporal/task_management/workflow.py@@ -8,6 +8,7 @@ from typing import Any, Optionalimport temporaliofrom temporalio import workflowfrom temporalio.common import RetryPolicy+from temporalio.exceptions import is_cancelled_exceptionfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.oauth import PosthogMcpScopes@@ -72,6 +73,7 @@ from products.tasks.backend.temporal.task_management.activities.pending_followupReadPendingFollowupsInput,persist_pending_followups,persist_pending_followups_v2,+ persist_pending_followups_v3,read_pending_followups,)@@ -92,6 +94,8 @@ _PATCH_ID_GENERATION_SAFE_PENDING_FOLLOWUPS = "tasks-task-management-generation-_PATCH_ID_CI_TERMINAL_PR = "tasks-task-management-ci-terminal-pr"_PATCH_ID_CI_WAIT = "tasks-task-management-ci-wait"_PATCH_ID_CI_IDLE_SKIP_CAP = "tasks-task-management-ci-idle-skip-cap"+_PATCH_ID_DURABLE_CI_CHECKPOINTS = "tasks-task-management-durable-ci-checkpoints"+_PATCH_ID_CHECKPOINT_RECOVERY_STATUS = "tasks-task-management-checkpoint-recovery-status"_PATCH_ID_CI_WAIT_CAP = "tasks-task-management-ci-wait-cap"MAX_CI_WAIT_CHECKS = 96_CHILD_SIGNAL_TERMINAL_ERROR_TYPES = {@@ -537,7 +541,13 @@ class TaskManagementWorkflow(PostHogWorkflow):"error_message": error_message,},)- await self._update_task_run_status("failed", error_message=error_message, error_type=type(e).__name__)+ checkpoint_recovery = (+ _patch_enabled(_PATCH_ID_CHECKPOINT_RECOVERY_STATUS)+ and isinstance(e, temporalio.exceptions.ActivityError)+ and e.activity_type in {"persist_pending_followups_v3", "read_pending_followups"}+ )+ if not checkpoint_recovery:+ await self._update_task_run_status("failed", error_message=error_message, error_type=type(e).__name__)return TaskRunManagementOutput(success=False,error=error_message,@@ -648,9 +658,14 @@ class TaskManagementWorkflow(PostHogWorkflow):# follow-ups to deliver, spin up a fresh sandbox first. A standalone# `complete_task` arriving without follow-ups is dropped — there's# nothing meaningful to complete when no sandbox is running.+ if self._pending_external_followups and _patch_enabled(_PATCH_ID_DURABLE_CI_CHECKPOINTS):+ self._ci_idle_skips = 0+ self._ci_wait_checks = 0if not self._sandbox_alive:if self._pending_external_followups:await self._wait_before_replacement_sandbox()+ if _patch_enabled(_PATCH_ID_DURABLE_CI_CHECKPOINTS):+ await self._persist_pending_followups()workflow.logger.info("task_management_rebootstrapping_for_followup",extra={"run_id": self._run_id, "pending": len(self._pending_external_followups)},@@ -664,6 +679,8 @@ class TaskManagementWorkflow(PostHogWorkflow):# Forward all pending external follow-ups first; complete_task is# terminal and handled last so we don't drop in-flight messages.while self._pending_external_followups:+ if _patch_enabled(_PATCH_ID_DURABLE_CI_CHECKPOINTS):+ await self._persist_pending_followups()followup = self._pending_external_followups.pop(0)delivered = await self._signal_child_followup(message=followup.message,@@ -927,11 +944,17 @@ class TaskManagementWorkflow(PostHogWorkflow):try:result = await workflow.execute_activity(read_pending_followups,- ReadPendingFollowupsInput(run_id=self._run_id),+ ReadPendingFollowupsInput(+ run_id=self._run_id, recover_checkpoint=_patch_enabled(_PATCH_ID_DURABLE_CI_CHECKPOINTS)+ ),start_to_close_timeout=timedelta(seconds=30),retry_policy=RetryPolicy(maximum_attempts=3),)except Exception as e:+ if _patch_enabled(_PATCH_ID_DURABLE_CI_CHECKPOINTS):+ if is_cancelled_exception(e):+ raise asyncio.CancelledError from e+ raiseworkflow.logger.warning("task_management_restore_pending_failed", extra={"run_id": self._run_id, "error": str(e)})@@ -974,14 +997,6 @@ class TaskManagementWorkflow(PostHogWorkflow):)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,- only the recovery picture if we later restart. Logged so we notice- sustained failures. Skips the activity when the payload hasn't- changed since the last write — drain paths fire this every iteration- and an empty-to-empty no-op would still take a row lock.- """if self._run_id is None:return Falsepayload = [asdict(f) for f in self._pending_external_followups]@@ -1000,9 +1015,12 @@ class TaskManagementWorkflow(PostHogWorkflow):_patch_enabled(_PATCH_ID_GENERATION_SAFE_PENDING_FOLLOWUPS)or persist_ci_idle_skipsor persist_ci_wait_checks+ or _patch_enabled(_PATCH_ID_DURABLE_CI_CHECKPOINTS)):await workflow.execute_activity(- persist_pending_followups_v2,+ persist_pending_followups_v3+ if _patch_enabled(_PATCH_ID_DURABLE_CI_CHECKPOINTS)+ else persist_pending_followups_v2,PersistPendingFollowupsV2Input(run_id=self._run_id,followups=payload,@@ -1027,6 +1045,10 @@ class TaskManagementWorkflow(PostHogWorkflow):self._last_persisted_ci_wait_checks = ci_wait_checksreturn Trueexcept Exception as e:+ if _patch_enabled(_PATCH_ID_DURABLE_CI_CHECKPOINTS):+ if is_cancelled_exception(e):+ raise asyncio.CancelledError from e+ raiseworkflow.logger.warning("task_management_persist_pending_failed", extra={"run_id": self._run_id, "error": str(e)})@@ -1052,9 +1074,12 @@ class TaskManagementWorkflow(PostHogWorkflow):_patch_enabled(_PATCH_ID_GENERATION_SAFE_PENDING_FOLLOWUPS)or persist_ci_idle_skipsor persist_ci_wait_checks+ or _patch_enabled(_PATCH_ID_DURABLE_CI_CHECKPOINTS)):await workflow.execute_activity(- persist_pending_followups_v2,+ persist_pending_followups_v3+ if _patch_enabled(_PATCH_ID_DURABLE_CI_CHECKPOINTS)+ else persist_pending_followups_v2,PersistPendingFollowupsV2Input(run_id=self._run_id,followups=payload,@@ -1384,6 +1409,18 @@ class TaskManagementWorkflow(PostHogWorkflow):self._ci_wait_checks = 0ci_message = (self._context.ci_prompt if self._context else None) or DEFAULT_CI_MESSAGEself._last_active_time = workflow.now()+ if _patch_enabled(_PATCH_ID_DURABLE_CI_CHECKPOINTS):+ self._pending_external_followups.append(+ PendingExternalFollowup(+ message=ci_message,+ artifact_ids=[],+ source=FOLLOWUP_SOURCE_CI,+ sequence=self._next_followup_sequence,+ )+ )+ self._next_followup_sequence += 1+ await self._drain_external_signals()+ returnawait self._signal_child_followup(message=ci_message, artifact_ids=[], source=FOLLOWUP_SOURCE_CI)if _patch_enabled(_PATCH_ID_CI_IDLE_SKIP_CAP) or _patch_enabled(_PATCH_ID_CI_WAIT_CAP):await self._persist_pending_followups()diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 622267d8fd9b..50d1ced21370 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -6852,6 +6852,7 @@ class TestTaskRunAPI(BaseTaskAPITest):"pending_external_followups_generation": 7,"task_management_ci_idle_skips": 1,"task_management_ci_wait_checks": 10,+ "pending_external_followups_checkpoint": {"generation": 8},"sandbox_gone": False,"ai_stage": "research","ai_agent_name": "signals-scout-errors",@@ -6934,6 +6935,7 @@ class TestTaskRunAPI(BaseTaskAPITest):"pending_external_followups_generation": 999,"task_management_ci_idle_skips": 0,"task_management_ci_wait_checks": 0,+ "pending_external_followups_checkpoint": {"generation": 99},"timed_out_inactivity": True,"timed_out_wall_clock": True,"sandbox_gone": True,@@ -7008,6 +7010,7 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["pending_external_followups_generation"] == 7assert run.state["task_management_ci_idle_skips"] == 1assert run.state["task_management_ci_wait_checks"] == 10+ assert run.state["pending_external_followups_checkpoint"] == {"generation": 8}assert "timed_out_inactivity" not in run.state # caller cannot forge a timeout reasonassert "timed_out_wall_clock" not in run.stateassert run.state["sandbox_gone"] is False@@ -7067,6 +7070,7 @@ class TestTaskRunAPI(BaseTaskAPITest):"pending_external_followups_generation","task_management_ci_idle_skips","task_management_ci_wait_checks",+ "pending_external_followups_checkpoint","sandbox_gone","runtime_adapter","provider",@@ -7119,6 +7123,7 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["pending_external_followups_generation"] == 7assert run.state["task_management_ci_idle_skips"] == 1assert run.state["task_management_ci_wait_checks"] == 10+ assert run.state["pending_external_followups_checkpoint"] == {"generation": 8}assert run.state["sandbox_gone"] is False # protected key survives removal# Dropping the model posture is as good as repointing it: the processing context reads these# back with .get(), so an absent key silently falls back to the runtime's default rather than@@ -7151,6 +7156,7 @@ class TestTaskRunAPI(BaseTaskAPITest):"systemPrompt": "Caller-controlled instructions","task_management_ci_idle_skips": 0,"task_management_ci_wait_checks": 0,+ "pending_external_followups_checkpoint": {"generation": 99},"scratch": "ok",}},@@ -7162,6 +7168,7 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["scratch"] == ["ok"]assert run.state["task_management_ci_idle_skips"] == 1assert run.state["task_management_ci_wait_checks"] == 10+ assert run.state["pending_external_followups_checkpoint"] == {"generation": 8}@patch("products.tasks.backend.facade.api.signal_workflow_completion")def test_update_run_status_to_completed_signals_workflow(self, mock_signal):