: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): preserve snapshots during CI follow-ups (#82531)
Alessandro Pogliaghi86010f9c1b09
diff --git a/products/posthog_ai/backend/message_routing.py b/products/posthog_ai/backend/message_routing.pyindex 3c370a9b8a91..9ddccf1277d7 100644--- a/products/posthog_ai/backend/message_routing.py+++ b/products/posthog_ai/backend/message_routing.py@@ -462,10 +462,7 @@ class SandboxSession(BaseSandboxService):"initial_permission_mode": initial_permission_mode,"inactivity_timeout_seconds": SANDBOX_INACTIVITY_TIMEOUT_SECONDS,}- # Carry the prior Run's snapshot forward so the resume reuses its filesystem.- snapshot_external_id = (run.state or {}).get("snapshot_external_id")- if snapshot_external_id:- extra_state["snapshot_external_id"] = snapshot_external_id+ extra_state.update(tasks_facade.get_resume_snapshot_carry_state(run.state))new_run = task.create_run(mode="interactive", extra_state=extra_state)diff --git a/products/posthog_ai/backend/tests/test_message_routing.py b/products/posthog_ai/backend/tests/test_message_routing.pyindex 78f5b068c89d..8bdb871812de 100644--- a/products/posthog_ai/backend/tests/test_message_routing.py+++ b/products/posthog_ai/backend/tests/test_message_routing.py@@ -253,7 +253,12 @@ class TestOpenSandboxMessage(APIBaseTest):def test_terminal_followup_creates_new_run_with_resume(self):task, run = self._stub_task()run.status = TaskRun.Status.COMPLETED- run.state = {**(run.state or {}), "snapshot_external_id": "snap-9"}+ run.state = {+ **(run.state or {}),+ "snapshot_external_id": "snap-9",+ "snapshot_kind": "directory",+ "snapshot_mount_path": "/tmp/workspace",+ }run.save(update_fields=["status", "state"])self._attach_task(task)@@ -273,6 +278,8 @@ class TestOpenSandboxMessage(APIBaseTest):assert str(new_run.id) != str(run.id)assert new_run.state["resume_from_run_id"] == str(run.id)assert new_run.state["snapshot_external_id"] == "snap-9"+ assert new_run.state["snapshot_kind"] == "directory"+ assert new_run.state["snapshot_mount_path"] == "/tmp/workspace"assert new_run.state["interaction_origin"] == POSTHOG_AI_INTERACTION_ORIGINassert new_run.state["systemPrompt"] == SYS_PROMPTassert new_run.state["initial_permission_mode"] == "auto"diff --git a/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.py b/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.pyindex f432e9feef26..6a5e620c9531 100644--- a/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.py+++ b/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.py@@ -20,6 +20,7 @@ from products.tasks.backend.exceptions import (from products.tasks.backend.logic.services.sandbox import get_sandbox_classfrom products.tasks.backend.models import TaskRunfrom products.tasks.backend.temporal.metrics import increment_snapshot_create, record_snapshot_create_latency_ms+from products.tasks.backend.temporal.observability import emit_agent_loglogger = structlog.get_logger(__name__)@@ -43,6 +44,8 @@ class CreateResumeSnapshotInput:run_id: struse_directory_snapshot: bool = Falsesnapshot_mount_path: str = DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH+ reason: str = "teardown"+ allow_pruning: bool = True@dataclass@@ -51,6 +54,7 @@ class CreateResumeSnapshotOutput:snapshot_kind: SnapshotKind | None = Nonesnapshot_mount_path: str | None = Noneerror: str | None = None+ duration_ms: int | None = None@activity.defn@@ -65,26 +69,59 @@ def create_resume_snapshot(input: CreateResumeSnapshotInput) -> CreateResumeSnapsnapshot_kind: SnapshotKind = SNAPSHOT_KIND_DIRECTORY if input.use_directory_snapshot else SNAPSHOT_KIND_FILESYSTEMsnapshot_mount_path = input.snapshot_mount_path or DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH- logger.info("create_resume_snapshot_started", sandbox_id=input.sandbox_id, run_id=input.run_id)+ logger.info(+ "create_resume_snapshot_started",+ sandbox_id=input.sandbox_id,+ run_id=input.run_id,+ reason=input.reason,+ snapshot_kind=snapshot_kind,+ )started_at = time.perf_counter()try:sandbox = SandboxClass.get_by_id(input.sandbox_id)except Exception as e:- logger.warning("create_resume_snapshot_sandbox_not_found", sandbox_id=input.sandbox_id, error=str(e))+ duration_ms = int((time.perf_counter() - started_at) * 1000)+ logger.warning(+ "create_resume_snapshot_sandbox_not_found",+ sandbox_id=input.sandbox_id,+ run_id=input.run_id,+ reason=input.reason,+ snapshot_kind=snapshot_kind,+ duration_ms=duration_ms,+ error=str(e),+ )outcome = "sandbox_not_found"increment_snapshot_create(snapshot_kind, outcome)- record_snapshot_create_latency_ms(snapshot_kind, outcome, int((time.perf_counter() - started_at) * 1000))+ record_snapshot_create_latency_ms(snapshot_kind, outcome, duration_ms)+ emit_agent_log(input.run_id, "debug", f"Resume snapshot failed ({input.reason}): sandbox not found")return CreateResumeSnapshotOutput(- external_id=None, snapshot_kind=snapshot_kind, error=f"Sandbox not found: {e}"+ external_id=None,+ snapshot_kind=snapshot_kind,+ error=f"Sandbox not found: {e}",+ duration_ms=duration_ms,)if not sandbox.is_running():+ duration_ms = int((time.perf_counter() - started_at) * 1000)outcome = "sandbox_not_running"- logger.warning("create_resume_snapshot_sandbox_not_running", sandbox_id=input.sandbox_id, run_id=input.run_id)+ logger.warning(+ "create_resume_snapshot_sandbox_not_running",+ sandbox_id=input.sandbox_id,+ run_id=input.run_id,+ reason=input.reason,+ snapshot_kind=snapshot_kind,+ duration_ms=duration_ms,+ )increment_snapshot_create(snapshot_kind, outcome)- record_snapshot_create_latency_ms(snapshot_kind, outcome, int((time.perf_counter() - started_at) * 1000))- return CreateResumeSnapshotOutput(external_id=None, snapshot_kind=snapshot_kind, error="Sandbox not running")+ record_snapshot_create_latency_ms(snapshot_kind, outcome, duration_ms)+ emit_agent_log(input.run_id, "debug", f"Resume snapshot failed ({input.reason}): sandbox not running")+ return CreateResumeSnapshotOutput(+ external_id=None,+ snapshot_kind=snapshot_kind,+ error="Sandbox not running",+ duration_ms=duration_ms,+ )outcome = "created"try:@@ -96,12 +133,27 @@ def create_resume_snapshot(input: CreateResumeSnapshotInput) -> CreateResumeSnap# Modal caps snapshots at 1M files and a directory snapshot of the workspace can exceed it# once install trees and caches pile up. Only the directory snapshot has a mount path to# shrink; a full filesystem snapshot does not, so it degrades to a fresh start.- if snapshot_kind != SNAPSHOT_KIND_DIRECTORY:+ if snapshot_kind != SNAPSHOT_KIND_DIRECTORY or not input.allow_pruning:outcome = "file_limit_exceeded"- logger.warning("create_resume_snapshot_file_limit_exceeded", sandbox_id=input.sandbox_id, error=str(e))+ duration_ms = int((time.perf_counter() - started_at) * 1000)+ logger.warning(+ "create_resume_snapshot_file_limit_exceeded",+ sandbox_id=input.sandbox_id,+ run_id=input.run_id,+ reason=input.reason,+ snapshot_kind=snapshot_kind,+ duration_ms=duration_ms,+ error=str(e),+ )increment_snapshot_create(snapshot_kind, outcome)- record_snapshot_create_latency_ms(snapshot_kind, outcome, int((time.perf_counter() - started_at) * 1000))- return CreateResumeSnapshotOutput(external_id=None, snapshot_kind=snapshot_kind, error=str(e))+ record_snapshot_create_latency_ms(snapshot_kind, outcome, duration_ms)+ emit_agent_log(input.run_id, "debug", f"Resume snapshot failed ({input.reason}): file limit exceeded")+ return CreateResumeSnapshotOutput(+ external_id=None,+ snapshot_kind=snapshot_kind,+ error=str(e),+ duration_ms=duration_ms,+ )# Prune the reproducible trees (node_modules, virtualenvs, caches) in the live sandbox,# then let Temporal retry the whole activity: the next attempt snapshots the now-smaller@@ -111,14 +163,19 @@ def create_resume_snapshot(input: CreateResumeSnapshotInput) -> CreateResumeSnap# the cap, retries exhaust and both callers treat the failed snapshot as non-fatal (the run# starts fresh). The resume sandbox reinstalls the pruned trees, so this costs a reinstall.outcome = "file_limit_exceeded_pruned"+ duration_ms = int((time.perf_counter() - started_at) * 1000)logger.warning("create_resume_snapshot_file_limit_exceeded_pruning",sandbox_id=input.sandbox_id,+ run_id=input.run_id,+ reason=input.reason,+ snapshot_kind=snapshot_kind,+ duration_ms=duration_ms,error=str(e),)sandbox.prune_snapshot_heavy_dirs(snapshot_mount_path)increment_snapshot_create(snapshot_kind, outcome)- record_snapshot_create_latency_ms(snapshot_kind, outcome, int((time.perf_counter() - started_at) * 1000))+ record_snapshot_create_latency_ms(snapshot_kind, outcome, duration_ms)# capture=False: the original SnapshotFileLimitExceededError already carried the signal;# this transient wrapper only drives the Temporal retry.raise SnapshotTimeoutError(@@ -129,31 +186,61 @@ def create_resume_snapshot(input: CreateResumeSnapshotInput) -> CreateResumeSnap)except SnapshotTimeoutError as e:outcome = "transient_error"- logger.warning("create_resume_snapshot_transient_error", sandbox_id=input.sandbox_id, error=str(e))+ duration_ms = int((time.perf_counter() - started_at) * 1000)+ logger.warning(+ "create_resume_snapshot_transient_error",+ sandbox_id=input.sandbox_id,+ run_id=input.run_id,+ reason=input.reason,+ snapshot_kind=snapshot_kind,+ duration_ms=duration_ms,+ error=str(e),+ )increment_snapshot_create(snapshot_kind, outcome)- record_snapshot_create_latency_ms(snapshot_kind, outcome, int((time.perf_counter() - started_at) * 1000))+ record_snapshot_create_latency_ms(snapshot_kind, outcome, duration_ms)raiseexcept SandboxNotRunningError as e:outcome = "sandbox_not_running"+ duration_ms = int((time.perf_counter() - started_at) * 1000)logger.warning("create_resume_snapshot_sandbox_not_running",sandbox_id=input.sandbox_id,run_id=input.run_id,+ reason=input.reason,+ snapshot_kind=snapshot_kind,+ duration_ms=duration_ms,error=str(e),)increment_snapshot_create(snapshot_kind, outcome)- record_snapshot_create_latency_ms(snapshot_kind, outcome, int((time.perf_counter() - started_at) * 1000))- return CreateResumeSnapshotOutput(external_id=None, snapshot_kind=snapshot_kind, error=str(e))+ record_snapshot_create_latency_ms(snapshot_kind, outcome, duration_ms)+ emit_agent_log(input.run_id, "debug", f"Resume snapshot failed ({input.reason}): sandbox not running")+ return CreateResumeSnapshotOutput(+ external_id=None,+ snapshot_kind=snapshot_kind,+ error=str(e),+ duration_ms=duration_ms,+ )except Exception as e:outcome = "failed"- logger.warning("create_resume_snapshot_snapshot_failed", sandbox_id=input.sandbox_id, error=str(e))- increment_snapshot_create(snapshot_kind, outcome)- record_snapshot_create_latency_ms(snapshot_kind, outcome, int((time.perf_counter() - started_at) * 1000))- return CreateResumeSnapshotOutput(external_id=None, snapshot_kind=snapshot_kind, error=str(e))- else:+ duration_ms = int((time.perf_counter() - started_at) * 1000)+ logger.warning(+ "create_resume_snapshot_snapshot_failed",+ sandbox_id=input.sandbox_id,+ run_id=input.run_id,+ reason=input.reason,+ snapshot_kind=snapshot_kind,+ duration_ms=duration_ms,+ error=str(e),+ )increment_snapshot_create(snapshot_kind, outcome)- record_snapshot_create_latency_ms(snapshot_kind, outcome, int((time.perf_counter() - started_at) * 1000))-+ record_snapshot_create_latency_ms(snapshot_kind, outcome, duration_ms)+ emit_agent_log(input.run_id, "debug", f"Resume snapshot failed ({input.reason}): {e}")+ return CreateResumeSnapshotOutput(+ external_id=None,+ snapshot_kind=snapshot_kind,+ error=str(e),+ duration_ms=duration_ms,+ )# Persist snapshot external ID on TaskRun statetry:updates = {@@ -167,11 +254,46 @@ def create_resume_snapshot(input: CreateResumeSnapshotInput) -> CreateResumeSnapremove_keys.append("snapshot_mount_path")TaskRun.update_state_atomic(input.run_id, updates=updates, remove_keys=remove_keys)except Exception as e:- logger.warning("create_resume_snapshot_persist_failed", run_id=input.run_id, error=str(e))+ outcome = "persist_failed"+ duration_ms = int((time.perf_counter() - started_at) * 1000)+ logger.warning(+ "create_resume_snapshot_persist_failed",+ sandbox_id=input.sandbox_id,+ run_id=input.run_id,+ reason=input.reason,+ snapshot_kind=snapshot_kind,+ snapshot_external_id=external_id,+ duration_ms=duration_ms,+ error=str(e),+ )+ increment_snapshot_create(snapshot_kind, outcome)+ record_snapshot_create_latency_ms(snapshot_kind, outcome, duration_ms)+ emit_agent_log(input.run_id, "debug", f"Resume snapshot failed ({input.reason}): state could not be saved")+ return CreateResumeSnapshotOutput(+ external_id=None,+ snapshot_kind=snapshot_kind,+ error=f"Snapshot state could not be saved: {e}",+ duration_ms=duration_ms,+ )++ duration_ms = int((time.perf_counter() - started_at) * 1000)+ increment_snapshot_create(snapshot_kind, outcome)+ record_snapshot_create_latency_ms(snapshot_kind, outcome, duration_ms)- activity.logger.info(f"Created resume snapshot {external_id} for sandbox {input.sandbox_id}")+ logger.info(+ "create_resume_snapshot_created",+ sandbox_id=input.sandbox_id,+ run_id=input.run_id,+ reason=input.reason,+ snapshot_kind=snapshot_kind,+ snapshot_external_id=external_id,+ snapshot_mount_path=snapshot_mount_path if snapshot_kind == SNAPSHOT_KIND_DIRECTORY else None,+ duration_ms=duration_ms,+ )+ emit_agent_log(input.run_id, "debug", f"Resume snapshot created ({input.reason}): {external_id}")return CreateResumeSnapshotOutput(external_id=external_id,snapshot_kind=snapshot_kind,snapshot_mount_path=snapshot_mount_path if snapshot_kind == SNAPSHOT_KIND_DIRECTORY else None,+ duration_ms=duration_ms,)diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_create_resume_snapshot.py b/products/tasks/backend/temporal/process_task/activities/tests/test_create_resume_snapshot.pyindex 50924ec5cd8d..95047dbcfca8 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_create_resume_snapshot.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_create_resume_snapshot.py@@ -87,6 +87,37 @@ def _file_limit_error() -> SnapshotFileLimitExceededError:)+def test_directory_file_limit_does_not_prune_live_sandbox(activity_environment, mocker) -> None:+ sandbox = mocker.Mock()+ sandbox.is_running.return_value = True+ sandbox.create_directory_snapshot.side_effect = _file_limit_error()+ SandboxClass = mocker.Mock()+ SandboxClass.get_by_id.return_value = sandbox++ mocker.patch(+ "products.tasks.backend.temporal.process_task.activities.create_resume_snapshot.get_sandbox_class",+ return_value=SandboxClass,+ )+ update_state = mocker.patch.object(TaskRun, "update_state_atomic")++ output = async_to_sync(activity_environment.run)(+ create_resume_snapshot,+ CreateResumeSnapshotInput(+ sandbox_id="sandbox-1",+ run_id="run-1",+ use_directory_snapshot=True,+ reason="ci_follow_up",+ allow_pruning=False,+ ),+ )++ assert output.external_id is None+ assert output.error is not None+ sandbox.prune_snapshot_heavy_dirs.assert_not_called()+ update_state.assert_not_called()++@pytest.mark.django_dbdef test_directory_file_limit_prunes_and_retries_via_temporal(activity_environment, mocker) -> None:# A directory snapshot over the cap prunes the live sandbox and re-raises a transient error sodiff --git a/products/tasks/backend/temporal/process_task/tests/test_followup.py b/products/tasks/backend/temporal/process_task/tests/test_followup.pyindex 3977998a8511..842f3a04e1d7 100644--- a/products/tasks/backend/temporal/process_task/tests/test_followup.py+++ b/products/tasks/backend/temporal/process_task/tests/test_followup.py@@ -10,6 +10,10 @@ from temporalio.common import RetryPolicyfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker+from products.tasks.backend.temporal.process_task.activities.create_resume_snapshot import (+ CreateResumeSnapshotInput,+ CreateResumeSnapshotOutput,+)from products.tasks.backend.temporal.process_task.activities.get_pr_context import GetPrContextOutputfrom products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContextfrom products.tasks.backend.temporal.process_task.activities.provision_sandbox import (@@ -170,6 +174,8 @@ class TestFollowupDeliveryFailure:_ci_context_overrides: dict = {}_ci_followup_calls: list[str] = []_pr_context_overrides: dict = {}+_snapshot_events: list[str] = []+_snapshot_failures_remaining = 0@activity.defn(name="get_task_processing_context")@@ -186,6 +192,9 @@ def _mock_get_context_configurable(_input) -> TaskProcessingContext:create_pr=_ci_context_overrides.get("create_pr", True),pr_loop_enabled=_ci_context_overrides.get("pr_loop_enabled", True),ci_prompt=_ci_context_overrides.get("ci_prompt"),+ use_modal_resume_snapshots=_ci_context_overrides.get("use_modal_resume_snapshots", False),+ use_modal_directory_resume_snapshots=_ci_context_overrides.get("use_modal_directory_resume_snapshots", False),+ state=_ci_context_overrides.get("state"),)@@ -193,6 +202,22 @@ def _mock_get_context_configurable(_input) -> TaskProcessingContext:def _mock_send_followup_records(input: SendFollowupToSandboxInput) -> None:if input.message is not None:_ci_followup_calls.append(input.message)+ _snapshot_events.append("followup")++[email protected](name="create_resume_snapshot")+def _mock_create_resume_snapshot(input: CreateResumeSnapshotInput) -> CreateResumeSnapshotOutput:+ global _snapshot_failures_remaining+ _snapshot_events.append(f"{input.reason}:{input.allow_pruning}")+ if input.reason == "ci_follow_up" and _snapshot_failures_remaining > 0:+ _snapshot_failures_remaining -= 1+ return CreateResumeSnapshotOutput(external_id=None, error="snapshot failed", duration_ms=10)+ return CreateResumeSnapshotOutput(+ external_id=f"snapshot-{len(_snapshot_events)}",+ snapshot_kind="directory",+ snapshot_mount_path="/tmp/workspace",+ duration_ms=10,+ )@activity.defn(name="get_pr_context")@@ -261,6 +286,7 @@ def _make_worker(env, task_queue: str) -> Worker:_mock_read_logs,_mock_cleanup,_mock_get_pr_context,+ _mock_create_resume_snapshot,],workflow_runner=UnsandboxedWorkflowRunner(),activity_executor=ThreadPoolExecutor(max_workers=5),@@ -270,15 +296,20 @@ def _make_worker(env, task_queue: str) -> Worker:class TestCIFollowUpLoop:@pytest.fixture(autouse=True)def _reset_state(self):+ global _snapshot_failures_remaining_ci_context_overrides.clear()_ci_followup_calls.clear()_status_updates.clear()_pr_context_overrides.clear()+ _snapshot_events.clear()+ _snapshot_failures_remaining = 0yield_ci_context_overrides.clear()_ci_followup_calls.clear()_status_updates.clear()_pr_context_overrides.clear()+ _snapshot_events.clear()+ _snapshot_failures_remaining = 0@pytest.mark.timeout(60, func_only=True)async def test_runs_to_inactivity_timeout_after_max_ci_repetitions(self):@@ -302,6 +333,65 @@ class TestCIFollowUpLoop:assert timeout_updates, f"expected an inactivity-timeout completion, got {_status_updates}"assert timeout_updates == [("completed", None)]+ @pytest.mark.timeout(60, func_only=True)+ async def test_snapshots_idle_sandbox_before_ci_follow_up(self):+ global _snapshot_failures_remaining+ _ci_context_overrides["state"] = {"mode": "interactive"}+ _ci_context_overrides["use_modal_resume_snapshots"] = True+ _ci_context_overrides["use_modal_directory_resume_snapshots"] = True+ _pr_context_overrides["behavior"] = "unchanged"+ _snapshot_failures_remaining = 1++ async with await WorkflowEnvironment.start_time_skipping() as env:+ task_queue = f"test-{uuid.uuid4()}"+ async with _make_worker(env, task_queue):+ handle = await env.client.start_workflow(+ ProcessTaskWorkflow.run,+ ProcessTaskInput(run_id="run-1"),+ id=f"test-{uuid.uuid4()}",+ task_queue=task_queue,+ retry_policy=RetryPolicy(maximum_attempts=1),+ execution_timeout=timedelta(hours=2),+ )+ await env.sleep(CI_FOLLOW_UP_DELAY.total_seconds() * 3 + 10)+ await handle.signal(ProcessTaskWorkflow.complete_task, args=["completed", None])+ await handle.result()++ assert _snapshot_events[0:2] == ["ci_follow_up:False", "followup"]+ assert _snapshot_events.count("ci_follow_up:False") == 2+ assert _snapshot_events[-1] == "teardown:True"++ @pytest.mark.timeout(60, func_only=True)+ async def test_refreshes_ci_snapshot_after_follow_up(self):+ _ci_context_overrides["state"] = {"mode": "interactive"}+ _ci_context_overrides["use_modal_resume_snapshots"] = True+ _ci_context_overrides["use_modal_directory_resume_snapshots"] = True+ _pr_context_overrides["behavior"] = "unchanged"++ async with await WorkflowEnvironment.start_time_skipping() as env:+ task_queue = f"test-{uuid.uuid4()}"+ async with _make_worker(env, task_queue):+ handle = await env.client.start_workflow(+ ProcessTaskWorkflow.run,+ ProcessTaskInput(run_id="run-1"),+ id=f"test-{uuid.uuid4()}",+ task_queue=task_queue,+ retry_policy=RetryPolicy(maximum_attempts=1),+ execution_timeout=timedelta(hours=2),+ )+ for _ in range(5):+ await env.sleep(CI_FOLLOW_UP_DELAY.total_seconds() + 10)+ if "followup" in _snapshot_events:+ followup_index = _snapshot_events.index("followup")+ if "ci_follow_up:False" in _snapshot_events[followup_index + 1 :]:+ break+ await handle.signal(ProcessTaskWorkflow.complete_task, args=["completed", None])+ await handle.result()++ followup_index = _snapshot_events.index("followup")+ assert "ci_follow_up:False" in _snapshot_events[followup_index + 1 :]+ assert _snapshot_events[-1] == "teardown:True"+@pytest.mark.timeout(60, func_only=True)async def test_uses_ci_prompt_override_when_set(self):custom_prompt = "Custom CI prompt: please re-run the failed unit tests."@@ -440,15 +530,20 @@ class TestCIFollowUpLoop:class TestFollowupGuards:@pytest.fixture(autouse=True)def _reset_state(self):+ global _snapshot_failures_remaining_ci_context_overrides.clear()_ci_followup_calls.clear()_status_updates.clear()_pr_context_overrides.clear()+ _snapshot_events.clear()+ _snapshot_failures_remaining = 0yield_ci_context_overrides.clear()_ci_followup_calls.clear()_status_updates.clear()_pr_context_overrides.clear()+ _snapshot_events.clear()+ _snapshot_failures_remaining = 0@pytest.mark.parametrize("message,artifact_ids,expected",diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex 68bea2710fc6..b2ebefb98311 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -2206,7 +2206,7 @@ class TestProcessTaskWorkflowUnit:cleanup_sandbox_mock.assert_awaited_once_with("sandbox-123", complete_stream=True)if expect_resume_snapshot_call:- create_resume_snapshot_mock.assert_awaited_once_with("sandbox-123")+ create_resume_snapshot_mock.assert_awaited_once_with("sandbox-123", reason="teardown", allow_pruning=True)else:create_resume_snapshot_mock.assert_not_awaited()@@ -2301,6 +2301,7 @@ class TestContinueAsNew:wf._ci_repetitions = 2wf._pr_fingerprint = "fp-1"wf._pr_progress_emitted = True+ wf._ci_resume_snapshot_created = Truewf._first_user_message_received = Truewf._is_agent_design_enabled = Truewf._last_active_time = datetime(2026, 7, 16, 10, 30, tzinfo=UTC)@@ -2322,6 +2323,7 @@ class TestContinueAsNew:assert restored._ci_repetitions == 2assert restored._pr_fingerprint == "fp-1"assert restored._pr_progress_emitted is True+ assert restored._ci_resume_snapshot_created is Trueassert restored._first_user_message_received is Trueassert restored._is_agent_design_enabled is True# The datetime survives the ISO round-trip.@@ -2333,6 +2335,7 @@ class TestContinueAsNew:second_hop = restored._build_resumed_input(ProcessTaskInput(run_id="run-id"), sandbox_id="sb-2")assert second_hop.resumed_sandbox is not Noneassert second_hop.resumed_sandbox.chain_started_at == chain_start.isoformat()+ assert second_hop.resumed_sandbox.ci_resume_snapshot_created is True@parameterized.expand([diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 204934b8a0af..71f01105167b 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -153,6 +153,7 @@ class ResumedSandboxState:last_active_time: Optional[str] # ISO8601, or None if never active# Defaulted so continue_as_new payloads from pre-rollout runs deserialize.pr_unresolved_threads: int = 0+ ci_resume_snapshot_created: bool = Falseaccepted_message_ids: list[str] = field(default_factory=list)# ISO8601 start of the whole continue_as_new chain, so the wall-clock cap is not# reset by a continuation. None on payloads written before this field existed.@@ -314,6 +315,8 @@ _PATCH_ID_COMPLETE_STREAM_AFTER_CLEANUP_FAILURE = "tasks-complete-stream-after-c# Same two-step deprecate-then-delete cleanup lifecycle as the patches above._PATCH_ID_RUN_LIFECYCLE_BOUNDS = "tasks-run-lifecycle-bounds"+_PATCH_ID_SNAPSHOT_BEFORE_CI_FOLLOW_UP = "tasks-snapshot-before-ci-follow-up"+# `Task.OriginProduct.ONBOARDING`, mirrored as a literal so workflow code stays free of# Django model imports._ONBOARDING_ORIGIN_PRODUCT = "onboarding"@@ -387,6 +390,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):# Emit the "PR opened / keeping CI green" progress once, the first time we observe a PR — the# agent opens it mid-run and then keeps it green, so without this the UI dead-ends at "Started agent".self._pr_progress_emitted: bool = False+ self._ci_resume_snapshot_created: bool = False# Decided once at workflow start; gates the placeholder skip + relay spawn.self._is_agent_design_enabled: bool = False# Deadline-based so heartbeats waking the event loop don't keep resetting the timer.@@ -906,9 +910,22 @@ class ProcessTaskWorkflow(PostHogWorkflow):)_deprecate_ci_follow_up_pr_context_patch()follow_up_result = await self._should_run_ci_follow_up()+ if (+ not self._ci_resume_snapshot_created+ and follow_up_result != CIFollowUpDecision.NO_PR+ and self.context.mode == "interactive"+ and self.context.use_modal_resume_snapshots+ and workflow.patched(_PATCH_ID_SNAPSHOT_BEFORE_CI_FOLLOW_UP)+ ):+ self._ci_resume_snapshot_created = await self._create_resume_snapshot(+ sandbox_id,+ reason="ci_follow_up",+ allow_pruning=False,+ )match follow_up_result:case CIFollowUpDecision.FIRE:workflow.set_current_details("🔁 Re-checking the PR's CI and nudging the agent.")+ self._ci_resume_snapshot_created = Falseawait self._dispatch_ci_follow_up()case CIFollowUpDecision.NO_PR:# No PR will ever appear — stop the CI loop entirely.@@ -1173,7 +1190,11 @@ class ProcessTaskWorkflow(PostHogWorkflow):and self._context.mode == "interactive"and self._context.use_modal_resume_snapshots):- await self._create_resume_snapshot(cleanup_sandbox_id)+ await self._create_resume_snapshot(+ cleanup_sandbox_id,+ reason="teardown",+ allow_pruning=True,+ )await self._read_sandbox_logs(cleanup_sandbox_id)await self._cleanup_sandbox(@@ -1313,6 +1334,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):pr_fingerprint=self._pr_fingerprint,pr_unresolved_threads=self._pr_unresolved_threads,pr_progress_emitted=self._pr_progress_emitted,+ ci_resume_snapshot_created=self._ci_resume_snapshot_created,first_user_message_received=self._first_user_message_received,is_agent_design_enabled=self._is_agent_design_enabled,last_active_time=self._last_active_time.isoformat() if self._last_active_time else None,@@ -1337,6 +1359,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._pr_fingerprint = resumed.pr_fingerprintself._pr_unresolved_threads = resumed.pr_unresolved_threadsself._pr_progress_emitted = resumed.pr_progress_emitted+ self._ci_resume_snapshot_created = resumed.ci_resume_snapshot_createdself._first_user_message_received = resumed.first_user_message_receivedself._accepted_message_ids = resumed.accepted_message_idsself._accepted_message_id_set = set(resumed.accepted_message_ids)@@ -2187,7 +2210,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):except (asyncio.CancelledError, Exception):pass- async def _create_resume_snapshot(self, sandbox_id: str) -> None:+ async def _create_resume_snapshot(self, sandbox_id: str, *, reason: str, allow_pruning: bool) -> bool:"""Create a snapshot for interactive sandbox resume."""try:result = await workflow.execute_activity(@@ -2196,16 +2219,49 @@ class ProcessTaskWorkflow(PostHogWorkflow):sandbox_id=sandbox_id,run_id=self.context.run_id,use_directory_snapshot=self.context.use_modal_directory_resume_snapshots,+ reason=reason,+ allow_pruning=allow_pruning,),start_to_close_timeout=timedelta(minutes=5),retry_policy=RetryPolicy(maximum_attempts=3),)if result.external_id:- workflow.logger.info(f"Resume snapshot created: {result.external_id} for sandbox {sandbox_id}")+ workflow.logger.info(+ "resume_snapshot_created",+ extra={+ "run_id": self.context.run_id,+ "sandbox_id": sandbox_id,+ "reason": reason,+ "snapshot_external_id": result.external_id,+ "snapshot_kind": result.snapshot_kind,+ "duration_ms": result.duration_ms,+ },+ )+ return Trueelif result.error:- workflow.logger.warning(f"Resume snapshot skipped: {result.error}")+ workflow.logger.warning(+ "resume_snapshot_skipped",+ extra={+ "run_id": self.context.run_id,+ "sandbox_id": sandbox_id,+ "reason": reason,+ "snapshot_kind": result.snapshot_kind,+ "duration_ms": result.duration_ms,+ "error": result.error,+ },+ )+ return Falseexcept Exception as e:- workflow.logger.warning(f"Resume snapshot failed (non-fatal): {e}")+ workflow.logger.warning(+ "resume_snapshot_failed_non_fatal",+ extra={+ "run_id": self.context.run_id,+ "sandbox_id": sandbox_id,+ "reason": reason,+ "error": str(e),+ },+ )+ return Falseasync def _trigger_snapshot_workflow(self) -> None:github_integration_id = self.context.github_integration_id