: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): carry full snapshot metadata when resuming task runs (#68274)
Alessandro Pogliaghi38d0bc6e8abd
diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.pyindex 58696e5c6a32..777a01768337 100644--- a/posthog/temporal/ai/slack_app/activities/task_creation.py+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py@@ -807,9 +807,7 @@ def _resume_task_with_new_run(if previous_state.get("slack_thread_url"):extra_state["slack_thread_url"] = previous_state["slack_thread_url"]- snapshot_ext_id = previous_state.get("snapshot_external_id")- if snapshot_ext_id:- extra_state["snapshot_external_id"] = snapshot_ext_id+ extra_state.update(tasks_facade.get_resume_snapshot_carry_state(previous_state))extra_state["resume_from_run_id"] = str(previous_run.id)previous_pr_url = (previous_run.output or {}).get("pr_url")diff --git a/products/tasks/backend/exceptions.py b/products/tasks/backend/exceptions.pyindex 056735c8550c..f7092f8ea628 100644--- a/products/tasks/backend/exceptions.py+++ b/products/tasks/backend/exceptions.py@@ -18,6 +18,8 @@ class ProcessTaskError(ApplicationError):if cause is not None and capture:capture_exception(cause, self.context)+ # Retry policies match non_retryable_error_types against this type; the SDK omits it unless set.+ kwargs.setdefault("type", type(self).__name__)super().__init__(message, self.context, **kwargs)diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex ba6427ea2ee7..0026a558345f 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -123,6 +123,7 @@ __all__ = ["get_conversation_task_dtos","get_latest_pr_url_by_task","get_latest_run_by_task",+ "get_resume_snapshot_carry_state","get_sandbox_environment","get_sandbox_snapshot","get_stale_prewarmed_queued_task_run_ids",@@ -415,6 +416,16 @@ def _sandbox_snapshot_to_dto(snapshot: SandboxSnapshot) -> contracts.SandboxSnap# --- Reads ---+def get_resume_snapshot_carry_state(run_state: dict[str, Any] | None) -> dict[str, Any]:+ """State keys a successor run must merge (whole dict, never ``snapshot_external_id`` alone)+ to resume from a prior run's sandbox snapshot; empty when there is no usable snapshot."""+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import path+ parse_run_state,+ )++ return parse_run_state(run_state).resume_snapshot_carry_state()++def get_task_run(run_id: str | UUID, team_id: int | None = None) -> contracts.TaskRunDTO | None:"""Fetch a single task run as a DTO, optionally scoped to a team."""qs = TaskRun.objects.select_related("task", "task__created_by")@@ -3331,15 +3342,7 @@ def run_task(prev_state = parse_run_state(previous_run.state)extra_state = extra_state or {}extra_state["resume_from_run_id"] = str(resume_from_run_id)- # An unusable directory snapshot (see RunState.resume_snapshot_is_usable) must not be- # carried into the new run's state — the stripped mount path would get re-defaulted- # downstream and mount mismatched content.- if prev_state.snapshot_external_id and prev_state.resume_snapshot_is_usable():- extra_state["snapshot_external_id"] = prev_state.snapshot_external_id- extra_state["snapshot_kind"] = prev_state.resume_snapshot_kind()- snapshot_mount_path = prev_state.resume_snapshot_mount_path()- if snapshot_mount_path is not None:- extra_state["snapshot_mount_path"] = snapshot_mount_path+ extra_state.update(prev_state.resume_snapshot_carry_state())if prev_state.sandbox_environment_id and sandbox_environment_id is None:sandbox_environment_id = prev_state.sandbox_environment_iddiff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.pyindex 082035dd8b6f..fe535852c9a0 100644--- a/products/tasks/backend/logic/services/modal_sandbox.py+++ b/products/tasks/backend/logic/services/modal_sandbox.py@@ -99,6 +99,7 @@ SANDBOX_STREAMLIT_IMAGE = "ghcr.io/posthog/posthog-sandbox-streamlit"SANDBOX_IMAGE = SANDBOX_BASE_IMAGEAGENT_SERVER_PORT = 8080 # Modal connect tokens require port 8080AGENT_SERVER_HEALTH_MAX_ATTEMPTS = 240+POST_RESTORE_PROBE_TIMEOUT_SECONDS = 45# Recoverable infra errors Modal surfaces when filesystem snapshotting times out or loses its# connection (e.g. the command router's "Deadline exceeded"). These usually succeed on retry, so@@ -520,6 +521,26 @@ class ModalSandbox(SandboxBase):)capture_exception(e)+ # A restored sandbox can come up dead with every RPC succeeding; probe before use.+ if config.snapshot_restored and not cls._is_healthy_after_restore(sb):+ logger.warning(+ "Snapshot-restored sandbox is not executing processes; recreating from base image",+ extra={+ "sandbox_id": sb.object_id,+ "snapshot_external_id": snapshot_external_id,+ "snapshot_kind": snapshot_kind,+ "snapshot_mount_path": snapshot_mount_path,+ },+ )+ try:+ sb.terminate()+ except Exception as e:+ logger.warning(f"Failed to terminate wedged sandbox {sb.object_id}: {e}")+ create_kwargs["image"] = base_image+ with capture_modal_output_if_debug() as modal_output:+ sb = modal.Sandbox.create(**create_kwargs) # type: ignore[arg-type]+ config.snapshot_restored = False+if config.metadata:sb.set_tags(config.metadata)@@ -537,6 +558,34 @@ class ModalSandbox(SandboxBase):"Failed to create sandbox", {"config_name": config.name, "error": str(e)}, cause=e)+ @staticmethod+ def _is_healthy_after_restore(sb: modal.Sandbox) -> bool:+ """Whether the sandbox executes processes after a snapshot restore (image or mount)."""+ try:+ process = sb.exec("true", timeout=30)+ # ContainerProcess.wait() has no timeout and can hang on a wedged container.+ deadline = time.monotonic() + POST_RESTORE_PROBE_TIMEOUT_SECONDS+ while (returncode := process.poll()) is None:+ if time.monotonic() >= deadline:+ logger.warning(f"Post-restore health probe timed out for sandbox {sb.object_id}")+ return False+ time.sleep(1)+ except Exception as e:+ logger.warning(f"Post-restore health probe errored for sandbox {sb.object_id}: {e}")+ return False+ if returncode != 0:+ poll_result: int | str | None+ try:+ poll_result = sb.poll()+ except Exception:+ poll_result = "unavailable"+ logger.warning(+ "Post-restore health probe exited non-zero",+ extra={"sandbox_id": sb.object_id, "returncode": returncode, "sandbox_poll": str(poll_result)},+ )+ return False+ return True+@staticmethoddef get_by_id(sandbox_id: str) -> ModalSandbox:try:diff --git a/products/tasks/backend/logic/services/test_modal_sandbox.py b/products/tasks/backend/logic/services/test_modal_sandbox.pyindex 3fe3d8d81ff0..7ce4b6804d9d 100644--- a/products/tasks/backend/logic/services/test_modal_sandbox.py+++ b/products/tasks/backend/logic/services/test_modal_sandbox.py@@ -1,7 +1,11 @@import pytestfrom unittest.mock import MagicMock-from products.tasks.backend.constants import DEFAULT_SANDBOX_WORKING_DIR, SNAPSHOT_KIND_DIRECTORY+from products.tasks.backend.constants import (+ DEFAULT_SANDBOX_WORKING_DIR,+ SNAPSHOT_KIND_DIRECTORY,+ SNAPSHOT_KIND_FILESYSTEM,+)from products.tasks.backend.logic.services.modal_sandbox import ModalSandboxfrom products.tasks.backend.logic.services.sandbox import SandboxConfig, SandboxTemplate@@ -57,6 +61,7 @@ class TestModalSandboxDirectorySnapshotMount:snapshot_image = MagicMock()mocker.patch("modal.Image.from_id", return_value=snapshot_image)fake_sandbox = patched_modal.return_value+ fake_sandbox.exec.return_value.poll.return_value = 0sandbox = ModalSandbox.create(SandboxConfig(@@ -74,3 +79,32 @@ class TestModalSandboxDirectorySnapshotMount:else:fake_sandbox.mount_image.assert_not_called()assert sandbox.config.snapshot_restored is False++ @pytest.mark.parametrize("snapshot_kind", [SNAPSHOT_KIND_DIRECTORY, SNAPSHOT_KIND_FILESYSTEM])+ def test_wedged_restore_falls_back_to_base_image(self, patched_modal, mocker, snapshot_kind):+ snapshot_image = MagicMock()+ mocker.patch("modal.Image.from_id", return_value=snapshot_image)+ wedged = MagicMock()+ wedged.object_id = "sb-wedged"+ wedged.exec.return_value.poll.return_value = 137+ fresh = MagicMock()+ fresh.object_id = "sb-fresh"+ patched_modal.side_effect = [wedged, fresh]++ sandbox = ModalSandbox.create(+ SandboxConfig(+ name="test",+ template=SandboxTemplate.DEFAULT_BASE,+ snapshot_external_id="im-snap",+ snapshot_kind=snapshot_kind,+ snapshot_mount_path=DEFAULT_SANDBOX_WORKING_DIR if snapshot_kind == SNAPSHOT_KIND_DIRECTORY else None,+ )+ )++ if snapshot_kind == SNAPSHOT_KIND_DIRECTORY:+ wedged.mount_image.assert_called_once_with(DEFAULT_SANDBOX_WORKING_DIR, snapshot_image)+ else:+ wedged.mount_image.assert_not_called()+ wedged.terminate.assert_called_once()+ assert sandbox.id == "sb-fresh"+ assert sandbox.config.snapshot_restored is Falsediff --git a/products/tasks/backend/logic/services/warm.py b/products/tasks/backend/logic/services/warm.pyindex a889b5e55147..5873a8944fcb 100644--- a/products/tasks/backend/logic/services/warm.py+++ b/products/tasks/backend/logic/services/warm.py@@ -27,6 +27,7 @@ from posthog.models.user import Userfrom products.tasks.backend.models import Task, TaskRunfrom products.tasks.backend.temporal.client import execute_task_processing_workflow+from products.tasks.backend.temporal.process_task.utils import parse_run_statefrom ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limited@@ -164,15 +165,7 @@ class SandboxWarmer:if existing is not None:# Latest Run is terminal — resume into a successor so the warm session reuses its filesystem.run_state["resume_from_run_id"] = str(existing.id)- snapshot_external_id = (existing.state or {}).get("snapshot_external_id")- if snapshot_external_id:- run_state["snapshot_external_id"] = snapshot_external_id- snapshot_kind = (existing.state or {}).get("snapshot_kind")- if snapshot_kind:- run_state["snapshot_kind"] = snapshot_kind- snapshot_mount_path = (existing.state or {}).get("snapshot_mount_path")- if snapshot_mount_path:- run_state["snapshot_mount_path"] = snapshot_mount_path+ run_state.update(parse_run_state(existing.state).resume_snapshot_carry_state())new_run = locked.create_run(mode=mode, extra_state=run_state, branch=run_state.get("branch"))diff --git a/products/tasks/backend/temporal/__init__.py b/products/tasks/backend/temporal/__init__.pyindex 56cf04d02ad7..840be77687cb 100644--- a/products/tasks/backend/temporal/__init__.py+++ b/products/tasks/backend/temporal/__init__.py@@ -27,6 +27,7 @@ from .process_task.activities import (get_sandbox_for_repository,get_task_processing_context,inject_fresh_tokens_on_resume,+ invalidate_resume_snapshot,launch_agent_server,mark_repo_ready,post_slack_update,@@ -67,6 +68,7 @@ ACTIVITIES = [prepare_sandbox_for_repository,create_sandbox_for_repository,inject_fresh_tokens_on_resume,+ invalidate_resume_snapshot,refresh_sandbox_credentials,clone_repository_in_sandbox,checkout_branch_in_sandbox,diff --git a/products/tasks/backend/temporal/process_task/activities/__init__.py b/products/tasks/backend/temporal/process_task/activities/__init__.pyindex b73f679354e9..247178c56f04 100644--- a/products/tasks/backend/temporal/process_task/activities/__init__.py+++ b/products/tasks/backend/temporal/process_task/activities/__init__.py@@ -16,12 +16,14 @@ from .provision_sandbox import (CreateSandboxForRepositoryInput,CreateSandboxForRepositoryOutput,InjectFreshTokensOnResumeInput,+ InvalidateResumeSnapshotInput,PrepareSandboxForRepositoryInput,PrepareSandboxForRepositoryOutput,checkout_branch_in_sandbox,clone_repository_in_sandbox,create_sandbox_for_repository,inject_fresh_tokens_on_resume,+ invalidate_resume_snapshot,prepare_sandbox_for_repository,)from .read_sandbox_logs import ReadSandboxLogsInput, read_sandbox_logs@@ -59,6 +61,7 @@ __all__ = ["CreateSandboxForRepositoryInput","CreateSandboxForRepositoryOutput","InjectFreshTokensOnResumeInput",+ "InvalidateResumeSnapshotInput","PostSlackUpdateInput","PrepareSandboxForRepositoryInput","PrepareSandboxForRepositoryOutput",@@ -85,6 +88,7 @@ __all__ = ["get_sandbox_for_repository","get_task_processing_context","inject_fresh_tokens_on_resume",+ "invalidate_resume_snapshot","post_slack_update","prepare_sandbox_for_repository","read_sandbox_logs",diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex 3ccb77aff35d..e8bc7dce5c82 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -112,6 +112,12 @@ class InjectFreshTokensOnResumeInput:repository: str | None+@dataclass+class InvalidateResumeSnapshotInput:+ run_id: str+ snapshot_external_id: str | None = None++def _is_covered_by_wildcard(host: str, wildcard_bases: set[str]) -> bool:base = host[2:] if host.startswith("*.") else hostfor wildcard_base in wildcard_bases:@@ -685,3 +691,20 @@ def inject_fresh_tokens_on_resume(input: InjectFreshTokensOnResumeInput) -> None)emit_agent_log(ctx.run_id, "debug", "Refreshed sandbox credentials after resume")+++@asyncify+def invalidate_resume_snapshot(input: InvalidateResumeSnapshotInput) -> None:+ """Drop the resume snapshot from the run state after a failed restore, so retries and+ future runs of the task (which carry the previous run's snapshot) stop resuming from it."""+ with log_activity_execution(+ "invalidate_resume_snapshot",+ run_id=input.run_id,+ snapshot_external_id=input.snapshot_external_id,+ ):+ TaskRun.update_state_atomic(+ input.run_id,+ remove_keys=["snapshot_external_id", "snapshot_kind", "snapshot_mount_path"],+ )+ emit_agent_log(input.run_id, "debug", "Previous session snapshot could not be restored; discarded it")diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.pyindex f524bf46659e..d583693b5c0e 100644--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py@@ -56,6 +56,66 @@ class TestRunStateSnapshotPaths(TestCase):def test_resume_snapshot_mount_path(self, _name: str, state: dict[str, str], expected_path: str | None) -> None:assert RunState.model_validate(state).resume_snapshot_mount_path() == expected_path+ @parameterized.expand(+ [+ (+ "directory_workspace_path",+ {"snapshot_kind": SNAPSHOT_KIND_DIRECTORY, "snapshot_mount_path": DEFAULT_SANDBOX_WORKING_DIR},+ True,+ ),+ ("directory_no_path", {"snapshot_kind": SNAPSHOT_KIND_DIRECTORY}, True),+ (+ "directory_legacy_tmp_path",+ {"snapshot_kind": SNAPSHOT_KIND_DIRECTORY, "snapshot_mount_path": "/tmp"},+ False,+ ),+ ("filesystem", {"snapshot_kind": "filesystem"}, True),+ ("no_kind", {}, True),+ ]+ )+ def test_resume_snapshot_is_usable(self, _name: str, state: dict[str, str], expected: bool) -> None:+ assert RunState.model_validate(state).resume_snapshot_is_usable() is expected++ @parameterized.expand(+ [+ (+ "directory_full_triple",+ {+ "snapshot_external_id": "im-dir",+ "snapshot_kind": SNAPSHOT_KIND_DIRECTORY,+ "snapshot_mount_path": DEFAULT_SANDBOX_WORKING_DIR,+ },+ {+ "snapshot_external_id": "im-dir",+ "snapshot_kind": SNAPSHOT_KIND_DIRECTORY,+ "snapshot_mount_path": DEFAULT_SANDBOX_WORKING_DIR,+ },+ ),+ (+ "filesystem_no_mount_path",+ {"snapshot_external_id": "im-fs", "snapshot_kind": "filesystem"},+ {"snapshot_external_id": "im-fs", "snapshot_kind": "filesystem"},+ ),+ (+ "legacy_no_kind",+ {"snapshot_external_id": "im-old"},+ {"snapshot_external_id": "im-old", "snapshot_kind": "filesystem"},+ ),+ (+ "unusable_directory",+ {+ "snapshot_external_id": "im-dir",+ "snapshot_kind": SNAPSHOT_KIND_DIRECTORY,+ "snapshot_mount_path": "/tmp",+ },+ {},+ ),+ ("no_snapshot", {}, {}),+ ]+ )+ def test_resume_snapshot_carry_state(self, _name: str, state: dict[str, str], expected: dict[str, str]) -> None:+ assert RunState.model_validate(state).resume_snapshot_carry_state() == expected+class TestGetSandboxMcpConfigs(TestCase):TOKEN = "phx_test_token"diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex d483de707df1..4d3d7906fd81 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -13,7 +13,7 @@ from django.conf import settingsfrom asgiref.sync import sync_to_asyncfrom temporalio.common import RetryPolicy-from temporalio.exceptions import ActivityError, RetryState+from temporalio.exceptions import ActivityError, ApplicationError, RetryStatefrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker@@ -22,8 +22,11 @@ from products.tasks.backend.models import SandboxSnapshotfrom products.tasks.backend.temporal.constants import INACTIVITY_TIMEOUT_USER_SECONDS, WARM_IDLE_TIMEOUTfrom products.tasks.backend.temporal.process_task import workflow as process_task_workflow_modulefrom products.tasks.backend.temporal.process_task.activities import (+ CleanupSandboxInput,+ CreateSandboxForRepositoryInput,CreateSandboxForRepositoryOutput,GetSandboxForRepositoryOutput,+ InvalidateResumeSnapshotInput,PrepareSandboxForRepositoryOutput,StartAgentServerOutput,TaskProcessingContext,@@ -35,6 +38,7 @@ from products.tasks.backend.temporal.process_task.activities import (forward_pending_user_message,get_task_processing_context,inject_fresh_tokens_on_resume,+ invalidate_resume_snapshot,prepare_sandbox_for_repository,read_sandbox_logs,start_agent_server,@@ -463,6 +467,39 @@ class TestProcessTaskWorkflowUnit:track_workflow_event_mock.assert_not_awaited()post_slack_update_mock.assert_not_awaited()+ async def test_run_persists_activity_failure_cause_not_the_wrapper(self, monkeypatch):+ workflow = ProcessTaskWorkflow()+ error = ActivityError(+ "Activity task failed",+ scheduled_event_id=10,+ started_event_id=11,+ identity="worker-1",+ activity_type="inject_fresh_tokens_on_resume",+ activity_id="activity-1",+ retry_state=RetryState.MAXIMUM_ATTEMPTS_REACHED,+ )+ error.__cause__ = ApplicationError("Sandbox not in running state.", type="SandboxNotRunningError")+ update_task_run_status_mock = AsyncMock()++ monkeypatch.setattr(+ workflow, "_get_task_processing_context", AsyncMock(return_value=_build_context(github_integration_id=123))+ )+ monkeypatch.setattr(workflow, "_update_task_run_status", update_task_run_status_mock)+ monkeypatch.setattr(workflow, "_track_workflow_event", AsyncMock())+ monkeypatch.setattr(workflow, "_post_slack_update", AsyncMock())+ monkeypatch.setattr(workflow, "_emit_progress", AsyncMock())+ monkeypatch.setattr(workflow, "_get_sandbox_for_repository", AsyncMock(side_effect=error))++ result = await workflow.run(ProcessTaskInput(run_id="run-id"))++ assert result.success is False+ assert result.error == "Sandbox not in running state."+ update_task_run_status_mock.assert_awaited_with(+ "failed",+ error_message="Sandbox not in running state.",+ run_id="run-id",+ )+async def test_run_skips_relay_when_sandbox_event_ingest_is_enabled(self, monkeypatch):workflow = ProcessTaskWorkflow()context = _build_context(github_integration_id=123, sandbox_event_ingest_enabled=True)@@ -773,6 +810,127 @@ class TestProcessTaskWorkflowUnit:assert inject_fresh_tokens_on_resume not in activity_calls+ async def test_get_sandbox_for_repository_falls_back_to_fresh_sandbox_when_resume_injection_fails(+ self, monkeypatch+ ):+ workflow = ProcessTaskWorkflow()+ workflow._context = _build_context(+ github_integration_id=123,+ state={"snapshot_external_id": "im-abc123", "resume_from_run_id": "previous-run-id"},+ )++ prepared = PrepareSandboxForRepositoryOutput(+ sandbox_name="sandbox-name",+ repository="posthog/posthog-js",+ github_token="ghs_fresh",+ branch=None,+ environment_variables={},+ snapshot_id=None,+ snapshot_external_id="im-abc123",+ used_snapshot=True,+ should_create_snapshot=False,+ shallow_clone=True,+ image_source="resume_snapshot",+ image_source_label="resume snapshot im-abc123",+ )+ created_dead = CreateSandboxForRepositoryOutput(+ sandbox_id="sandbox-dead",+ sandbox_url="https://sandbox.example",+ connect_token="connect-token",+ )+ created_fresh = CreateSandboxForRepositoryOutput(+ sandbox_id="sandbox-fresh",+ sandbox_url="https://sandbox.example",+ connect_token="connect-token",+ )+ activity_calls: list[object] = []+ create_inputs: list[CreateSandboxForRepositoryInput] = []+ invalidate_inputs: list[InvalidateResumeSnapshotInput] = []+ cleanup_inputs: list[CleanupSandboxInput] = []++ async def fake_execute_activity(activity_fn, *args, **kwargs):+ activity_calls.append(activity_fn)+ if activity_fn is prepare_sandbox_for_repository:+ return prepared+ if activity_fn is create_sandbox_for_repository:+ create_inputs.append(args[0])+ return created_dead if len(create_inputs) == 1 else created_fresh+ if activity_fn is inject_fresh_tokens_on_resume:+ raise ApplicationError("Sandbox not in running state.", type="SandboxNotRunningError")+ if activity_fn is invalidate_resume_snapshot:+ invalidate_inputs.append(args[0])+ return None+ if activity_fn is cleanup_sandbox:+ cleanup_inputs.append(args[0])+ return None+ if activity_fn in (clone_repository_in_sandbox, emit_progress_activity):+ return None+ raise AssertionError(f"Unexpected activity call: {activity_fn}")++ monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", fake_execute_activity)+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())++ result = await workflow._get_sandbox_for_repository()++ assert result.sandbox_id == "sandbox-fresh"+ assert result.used_snapshot is False+ assert [i.run_id for i in invalidate_inputs] == ["run-id"]+ assert [i.sandbox_id for i in cleanup_inputs] == ["sandbox-dead"]+ assert len(create_inputs) == 2+ fresh_prepared = create_inputs[1].prepared+ assert fresh_prepared.snapshot_external_id is None+ assert fresh_prepared.used_snapshot is False+ assert fresh_prepared.should_create_snapshot is True+ assert clone_repository_in_sandbox in activity_calls++ async def test_get_sandbox_for_repository_propagates_non_dead_sandbox_failures(self, monkeypatch):+ workflow = ProcessTaskWorkflow()+ workflow._context = _build_context(+ github_integration_id=123,+ state={"snapshot_external_id": "im-abc123", "resume_from_run_id": "previous-run-id"},+ )++ prepared = PrepareSandboxForRepositoryOutput(+ sandbox_name="sandbox-name",+ repository="posthog/posthog-js",+ github_token="ghs_fresh",+ branch=None,+ environment_variables={},+ snapshot_id=None,+ snapshot_external_id="im-abc123",+ used_snapshot=True,+ should_create_snapshot=False,+ shallow_clone=True,+ image_source="resume_snapshot",+ image_source_label="resume snapshot im-abc123",+ )+ created = CreateSandboxForRepositoryOutput(+ sandbox_id="sandbox-live",+ sandbox_url="https://sandbox.example",+ connect_token="connect-token",+ )+ activity_calls: list[object] = []++ async def fake_execute_activity(activity_fn, *args, **kwargs):+ activity_calls.append(activity_fn)+ if activity_fn is prepare_sandbox_for_repository:+ return prepared+ if activity_fn is create_sandbox_for_repository:+ return created+ if activity_fn is inject_fresh_tokens_on_resume:+ raise ApplicationError("Failed to refresh GitHub token", type="GitHubAuthenticationError")+ if activity_fn is emit_progress_activity:+ return None+ raise AssertionError(f"Unexpected activity call: {activity_fn}")++ monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", fake_execute_activity)++ with pytest.raises(ApplicationError, match="Failed to refresh GitHub token"):+ await workflow._get_sandbox_for_repository()++ assert invalidate_resume_snapshot not in activity_calls+ assert cleanup_sandbox not in activity_calls+@pytest.mark.parametrize("mode, use_modal_resume_snapshots, expect_resume_snapshot_call",[diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex 72c5cc93b29a..026ed6dec30f 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -237,6 +237,12 @@ def normalize_directory_resume_snapshot_mount_path(snapshot_mount_path: object)return None+def is_resume_snapshot_usable(kind: SnapshotKind, mount_path: str | None) -> bool:+ """Whether a stored snapshot may be restored into a new sandbox; False falls back to a fresh one.+ A directory snapshot whose stored mount path was invalidated (legacy "/tmp" captures) can't be restored."""+ return not (kind == SNAPSHOT_KIND_DIRECTORY and mount_path is None)++class RunState(BaseModel, extra="allow"):pr_authorship_mode: PrAuthorshipMode | None = Nonegithub_credential_source: GitHubCredentialSource | None = None@@ -276,11 +282,22 @@ class RunState(BaseModel, extra="allow"):return normalize_directory_resume_snapshot_mount_path(self.snapshot_mount_path)def resume_snapshot_is_usable(self) -> bool:- """A directory snapshot whose stored mount path was invalidated (e.g. legacy "/tmp"- captures) can't be restored anywhere — callers must provision fresh instead."""- return not (- self.resume_snapshot_kind() == SNAPSHOT_KIND_DIRECTORY and self.resume_snapshot_mount_path() is None- )+ """See ``is_resume_snapshot_usable`` — callers must provision fresh when False."""+ return is_resume_snapshot_usable(self.resume_snapshot_kind(), self.resume_snapshot_mount_path())++ def resume_snapshot_carry_state(self) -> dict[str, Any]:+ """State keys a successor run must copy (always the full set, never the external ID+ alone) to resume from this run's snapshot; ``{}`` when there is no usable snapshot."""+ if not self.snapshot_external_id or not self.resume_snapshot_is_usable():+ return {}+ carried: dict[str, Any] = {+ "snapshot_external_id": self.snapshot_external_id,+ "snapshot_kind": self.resume_snapshot_kind(),+ }+ mount_path = self.resume_snapshot_mount_path()+ if mount_path is not None:+ carried["snapshot_mount_path"] = mount_path+ return carrieddef parse_run_state(state: dict[str, Any] | None) -> RunState:@@ -294,8 +311,8 @@ class SnapshotMetadata:@propertydef is_usable(self) -> bool:- """See ``RunState.resume_snapshot_is_usable`` — same invalidation rule."""- return not (self.kind == SNAPSHOT_KIND_DIRECTORY and self.mount_path is None)+ """See ``is_resume_snapshot_usable`` — same invalidation rule."""+ return is_resume_snapshot_usable(self.kind, self.mount_path)def get_sandbox_snapshot_metadata(snapshot: SandboxSnapshot) -> SnapshotMetadata:diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex d5d848d22122..5c709aba73ee 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -1,6 +1,6 @@import jsonimport asyncio-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom datetime import datetime, timedeltafrom enum import StrEnumfrom typing import Any, Optional@@ -8,6 +8,7 @@ from typing import Any, Optionalfrom django.conf import settingsimport temporalio+import temporalio.exceptionsfrom temporalio import workflowfrom temporalio.common import RetryPolicyfrom temporalio.workflow import ParentClosePolicy@@ -15,6 +16,7 @@ from temporalio.workflow import ParentClosePolicyfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.oauth import PosthogMcpScopes+from products.tasks.backend.constants import SNAPSHOT_KIND_FILESYSTEMfrom products.tasks.backend.logic.services.sandbox import is_public_sandbox_repofrom products.tasks.backend.temporal.create_snapshot.workflow import CreateSnapshotForRepositoryInputfrom products.tasks.backend.temporal.process_task.activities.get_pr_context import GetPrContextInput, get_pr_context@@ -40,11 +42,13 @@ from .activities.provision_sandbox import (CloneRepositoryInSandboxInput,CreateSandboxForRepositoryInput,InjectFreshTokensOnResumeInput,+ InvalidateResumeSnapshotInput,PrepareSandboxForRepositoryInput,checkout_branch_in_sandbox,clone_repository_in_sandbox,create_sandbox_for_repository,inject_fresh_tokens_on_resume,+ invalidate_resume_snapshot,prepare_sandbox_for_repository,)from .activities.read_sandbox_logs import ReadSandboxLogsInput, read_sandbox_logs@@ -69,6 +73,13 @@ from .activities.update_task_run_status import UpdateTaskRunStatusInput, update_from .credential_refresh import SANDBOX_GONE_ERROR_MESSAGE, CredentialRefreshExitReason, run_credential_refresh_loopfrom .slack_agent_design_relay import SlackAgentDesignRelayInput, SlackAgentDesignRelayWorkflow+DEAD_SANDBOX_ERROR_TYPES = ("SandboxNotRunningError", "SandboxNotFoundError")+++def _is_dead_sandbox_failure(error: BaseException) -> bool:+ cause = error.cause if isinstance(error, temporalio.exceptions.ActivityError) else error+ return isinstance(cause, temporalio.exceptions.ApplicationError) and cause.type in DEAD_SANDBOX_ERROR_TYPES+@dataclassclass ProcessTaskInput:@@ -668,7 +679,11 @@ class ProcessTaskWorkflow(PostHogWorkflow):except Exception as e:current_sandbox_id = sandbox_id or self._sandbox_id_for_cleanup- error_message = str(e)[:500]+ # str(ActivityError) is Temporal's opaque "Activity task failed" wrapper; Slack and+ # the UI show the persisted message, so surface the cause instead.+ cause = e.cause if isinstance(e, temporalio.exceptions.ActivityError) else None+ cause_message = getattr(cause, "message", None) or (str(cause) if cause is not None else None)+ error_message = (cause_message or str(e))[:500]if self._context:if self._current_progress_step is not None:failed_step, failed_label, failed_group = self._current_progress_step@@ -694,7 +709,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):"model": self.context.model,"reasoning_effort": self.context.reasoning_effort,"error_type": type(e).__name__,- "error_message": error_message,+ "error_message": str(e)[:500],"sandbox_id": current_sandbox_id,**self._activity_error_properties(e),},@@ -766,16 +781,77 @@ class ProcessTaskWorkflow(PostHogWorkflow):# credentials baked into .git/config and any agentsh env file — refresh# them before any sandbox command (diagnostics, fetch, checkout) runs.if used_snapshot and prepared.snapshot_external_id:- await workflow.execute_activity(- inject_fresh_tokens_on_resume,- InjectFreshTokensOnResumeInput(- context=self.context,- sandbox_id=created.sandbox_id,- repository=prepared.repository,- ),- start_to_close_timeout=timedelta(minutes=2),- retry_policy=RetryPolicy(maximum_attempts=3),- )+ try:+ await workflow.execute_activity(+ inject_fresh_tokens_on_resume,+ InjectFreshTokensOnResumeInput(+ context=self.context,+ sandbox_id=created.sandbox_id,+ repository=prepared.repository,+ ),+ start_to_close_timeout=timedelta(minutes=2),+ # A dead sandbox won't come back; fail fast into the fallback below.+ retry_policy=RetryPolicy(+ maximum_attempts=3,+ non_retryable_error_types=list(DEAD_SANDBOX_ERROR_TYPES),+ ),+ )+ except Exception as e:+ # Only a dead restored sandbox falls back: drop the poison snapshot, discard the+ # sandbox, and provision fresh (the agent resumes from run-log history, not the+ # filesystem). Anything else — e.g. credential failures — would hit a fresh+ # sandbox too, so let it fail the run without trashing a valid snapshot.+ if not _is_dead_sandbox_failure(e):+ raise+ workflow.logger.warning(+ "resume_restore_failed_falling_back_to_fresh_sandbox",+ extra={+ "run_id": self.context.run_id,+ "sandbox_id": created.sandbox_id,+ "snapshot_external_id": prepared.snapshot_external_id,+ "error": str(e),+ **self._activity_error_properties(e),+ },+ )+ await workflow.execute_activity(+ invalidate_resume_snapshot,+ InvalidateResumeSnapshotInput(+ run_id=self.context.run_id,+ snapshot_external_id=prepared.snapshot_external_id,+ ),+ start_to_close_timeout=timedelta(minutes=1),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ await self._cleanup_sandbox(created.sandbox_id)+ self._sandbox_id_for_cleanup = None+ prepared = replace(+ prepared,+ snapshot_id=None,+ snapshot_external_id=None,+ used_snapshot=False,+ should_create_snapshot=True,+ snapshot_kind=SNAPSHOT_KIND_FILESYSTEM,+ snapshot_mount_path=None,+ snapshot_source="none",+ image_source="base_image",+ image_source_label="published sandbox base image",+ )+ await self._emit_progress(+ "sandbox",+ "in_progress",+ "Setting up sandbox",+ "setup",+ detail="Previous session could not be restored; starting fresh",+ )+ created = await workflow.execute_activity(+ create_sandbox_for_repository,+ CreateSandboxForRepositoryInput(context=self.context, prepared=prepared),+ start_to_close_timeout=timedelta(minutes=5),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ self._sandbox_id_for_cleanup = created.sandbox_id+ used_snapshot = False+ await self._emit_progress("sandbox", "completed", "Set up sandbox", "setup")can_clone_without_integration = is_public_sandbox_repo(prepared.repository)has_clone_credentials = self.context.has_github_credentials or can_clone_without_integrationdiff --git a/products/tasks/backend/tests/test_exceptions.py b/products/tasks/backend/tests/test_exceptions.pynew file mode 100644index 000000000000..8e6e775f4065--- /dev/null+++ b/products/tasks/backend/tests/test_exceptions.py@@ -0,0 +1,7 @@+from products.tasks.backend.exceptions import SandboxNotRunningError+++def test_temporal_failure_type_defaults_to_class_name():+ error = SandboxNotRunningError("boom", {}, cause=RuntimeError("x"), capture=False)+ assert error.type == "SandboxNotRunningError"+ assert not error.non_retryable