: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
feat(tasks): add directory resume snapshots (#66956)
Alessandro Pogliaghi3f0044c4d2e4
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex ba1492b2b76f..ac2465e0d556 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -53,10 +53,10 @@ SANDBOX_MCP_URL: str | None = get_from_env("SANDBOX_MCP_URL", None, optional=Tru# run and the token carries the wizard's scope ceiling. Empty disables cloud wizard runs.WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID: str = get_from_env("WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID", "")-# When True, cloud-to-cloud resume boots from a Modal filesystem snapshot taken at-# end-of-run. When False, no Modal snapshot is taken and resume relies on the-# git-checkpoint mechanism in the agent server (same path as local-to-cloud handoff).-# Modal image storage is not EU-compliant, so this is forced off in EU.+# When True, cloud-to-cloud resume can create legacy Modal filesystem snapshots+# at end-of-run. Modal filesystem image storage is not EU-compliant, so this is+# forced off in EU. Directory snapshots are controlled separately by feature flag+# and may still be created when this setting is False.TASKS_USE_MODAL_RESUME_SNAPSHOTS: bool = get_from_env("TASKS_USE_MODAL_RESUME_SNAPSHOTS",CLOUD_DEPLOYMENT != "EU",diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex 7efaa7eea47c..50c11caf942d 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -3,9 +3,17 @@ from typing import Literal, get_argsSANDBOX_EVENT_INGEST_FEATURE_FLAG = "tasks-cloud-runs-sandbox-event-ingest"MODAL_VM_SANDBOX_FEATURE_FLAG = "tasks-modal-vm-sandbox"MODAL_NETWORK_ALLOWLIST_FEATURE_FLAG = "tasks-modal-network-allowlist"+MODAL_DIRECTORY_RESUME_SNAPSHOTS_FEATURE_FLAG = "tasks-modal-directory-resume-snapshots"STREAM_VIA_PROXY_FEATURE_FLAG = "tasks-stream-via-proxy"OVERLAP_CLONE_BOOT_FEATURE_FLAG = "tasks-overlap-clone-boot"+SnapshotKind = Literal["filesystem", "directory"]+SNAPSHOT_KIND_FILESYSTEM: SnapshotKind = "filesystem"+SNAPSHOT_KIND_DIRECTORY: SnapshotKind = "directory"+DEFAULT_SANDBOX_WORKING_DIR = "/tmp/workspace"+DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH = "/tmp"+DEFAULT_RESUME_SNAPSHOT_MOUNT_PATH = DEFAULT_SANDBOX_WORKING_DIR+ClaudePermissionMode = Literal["default", "acceptEdits", "plan", "bypassPermissions", "auto"]CodexPermissionMode = Literal["auto", "read-only", "full-access"]InitialPermissionMode = ClaudePermissionMode | CodexPermissionModediff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 9466070a7b53..ae37ccec7002 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -1198,7 +1198,9 @@ def _sync_automation_schedule(automation: TaskAutomation) -> None:# - sandbox_cpu_cores / sandbox_memory_gb / sandbox_ttl_seconds / inactivity_timeout_seconds set# the run's compute and lifetime at creation; a caller could otherwise PATCH a queued run to# provision an oversized or long-lived sandbox beyond what they're entitled to.-# All are written only server-side (run creation + the temporal workflow), never via PATCH.+# - use_modal_directory_resume_snapshots is the server-side directory snapshot rollout decision;+# a caller could otherwise force directory snapshot creation while the feature flag is off.+# These keys are reserved for server-owned run state, never PATCH input._PROTECTED_RUN_STATE_KEYS = frozenset({"github_credential_source",@@ -1209,6 +1211,7 @@ _PROTECTED_RUN_STATE_KEYS = frozenset("sandbox_ttl_seconds","inactivity_timeout_seconds","wizard_config",+ "use_modal_directory_resume_snapshots",})@@ -2375,8 +2378,6 @@ def resume_task_run_in_cloud(``"already_active"`` (400), ``"auth_error:<detail>"`` (400, github auth), ``"workflow_failed"``(502), or ``"resumed"`` (run_dto set). Mirrors ``TaskRunViewSet.resume_in_cloud``."""- from django.conf import settings # noqa: PLC0415-from products.tasks.backend.temporal.client import ( # noqa: PLC0415 — keep temporalio off the api import pathresume_task_in_cloud_workflow,)@@ -2398,7 +2399,8 @@ def resume_task_run_in_cloud("prior_environment": run.environment,"prior_state_keys": sorted((run.state or {}).keys()),"prior_snapshot_external_id": (run.state or {}).get("snapshot_external_id"),- "use_modal_resume_snapshots": settings.TASKS_USE_MODAL_RESUME_SNAPSHOTS,+ "prior_snapshot_kind": (run.state or {}).get("snapshot_kind"),+ "prior_snapshot_mount_path": (run.state or {}).get("snapshot_mount_path"),},)@@ -3300,6 +3302,10 @@ def run_task(extra_state["resume_from_run_id"] = str(resume_from_run_id)if prev_state.snapshot_external_id: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_pathif 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/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.pyindex 312457042dff..f915754fc7f6 100644--- a/products/tasks/backend/logic/services/docker_sandbox.py+++ b/products/tasks/backend/logic/services/docker_sandbox.py@@ -313,10 +313,12 @@ class DockerSandbox(SandboxBase):@staticmethoddef _get_image(config: SandboxConfig) -> str:"""Get the image to use, checking for snapshots first."""+ config.snapshot_restored = Falseif config.snapshot_external_id:snapshot_image = f"posthog-sandbox-snapshot:{config.snapshot_external_id}"result = DockerSandbox._run(["docker", "images", "-q", snapshot_image])if result.stdout.strip():+ config.snapshot_restored = Truereturn snapshot_imagelogger.warning(f"Resume snapshot image {snapshot_image} not found locally, using base image")@@ -327,6 +329,7 @@ class DockerSandbox(SandboxBase):snapshot_image = f"posthog-sandbox-snapshot:{snapshot.external_id}"result = DockerSandbox._run(["docker", "images", "-q", snapshot_image])if result.stdout.strip():+ config.snapshot_restored = Truereturn snapshot_imagelogger.warning(f"Snapshot image {snapshot_image} not found locally, using base image")except SandboxSnapshot.DoesNotExist:@@ -1013,6 +1016,9 @@ class DockerSandbox(SandboxBase):cause=e,)+ def create_directory_snapshot(self, path: str) -> str:+ return self.create_snapshot()+@staticmethoddef delete_snapshot(external_id: str) -> None:logger.info(f"Deleting snapshot {external_id}")diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.pyindex c1cc9bd1a9b5..87111c6a0e00 100644--- a/products/tasks/backend/logic/services/modal_sandbox.py+++ b/products/tasks/backend/logic/services/modal_sandbox.py@@ -32,7 +32,13 @@ from modal.exception import (from posthog.exceptions_capture import capture_exceptionfrom posthog.settings import CLOUD_DEPLOYMENT-from products.tasks.backend.constants import SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS+from products.tasks.backend.constants import (+ DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH,+ SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS,+ SNAPSHOT_KIND_DIRECTORY,+ SNAPSHOT_KIND_FILESYSTEM,+ SnapshotKind,+)from products.tasks.backend.exceptions import (SandboxCleanupError,SandboxExecutionError,@@ -123,6 +129,12 @@ def _get_modal_region() -> str:return MODAL_REGION_BY_DEPLOYMENT.get(CLOUD_DEPLOYMENT, DEFAULT_MODAL_REGION)+def _normalize_snapshot_kind(value: object) -> SnapshotKind:+ if value == SNAPSHOT_KIND_DIRECTORY:+ return SNAPSHOT_KIND_DIRECTORY+ return SNAPSHOT_KIND_FILESYSTEM++def _resource_create_kwargs(config: SandboxConfig) -> dict[str, object]:"""Build the `cpu`/`memory` kwargs for ``modal.Sandbox.create``.@@ -392,23 +404,36 @@ class ModalSandbox(SandboxBase):app = cls._get_app_for_template(config.template)base_image = _get_template_image(config.template)image = base_image+ config.snapshot_restored = False+ snapshot_external_id: str | None = None+ snapshot_kind = _normalize_snapshot_kind(config.snapshot_kind)+ snapshot_mount_path = config.snapshot_mount_path or DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH+ snapshot_image: modal.Image | None = Noneused_snapshot_image = Falseif config.snapshot_external_id:+ snapshot_external_id = config.snapshot_external_idtry:- image = _attach_local_package_mounts(- modal.Image.from_id(config.snapshot_external_id), config.template- )- used_snapshot_image = True+ snapshot_image = modal.Image.from_id(config.snapshot_external_id)+ if snapshot_kind == SNAPSHOT_KIND_FILESYSTEM:+ image = _attach_local_package_mounts(snapshot_image, config.template)+ used_snapshot_image = Trueexcept Exception as e:logger.warning(f"Failed to load resume snapshot image {config.snapshot_external_id}: {e}")capture_exception(e)elif config.snapshot_id:snapshot = SandboxSnapshot.objects.get(id=config.snapshot_id)if snapshot.status == SandboxSnapshot.Status.COMPLETE:+ snapshot_external_id = snapshot.external_id+ snapshot_kind = _normalize_snapshot_kind(snapshot.metadata.get("snapshot_kind"))+ metadata_mount_path = snapshot.metadata.get("snapshot_mount_path")+ if isinstance(metadata_mount_path, str) and metadata_mount_path:+ snapshot_mount_path = metadata_mount_pathtry:- image = _attach_local_package_mounts(modal.Image.from_id(snapshot.external_id), config.template)- used_snapshot_image = True+ snapshot_image = modal.Image.from_id(snapshot.external_id)+ if snapshot_kind == SNAPSHOT_KIND_FILESYSTEM:+ image = _attach_local_package_mounts(snapshot_image, config.template)+ used_snapshot_image = Trueexcept Exception as e:logger.warning(f"Failed to load snapshot image {snapshot.external_id}: {e}")capture_exception(e)@@ -446,6 +471,7 @@ class ModalSandbox(SandboxBase):modal_output: StringIO | Nonewith capture_modal_output_if_debug() as modal_output:sb = modal.Sandbox.create(**create_kwargs) # type: ignore[arg-type]+ config.snapshot_restored = used_snapshot_imageexcept Exception as e:if not used_snapshot_image:raise@@ -454,6 +480,26 @@ class ModalSandbox(SandboxBase):create_kwargs["image"] = base_imagewith capture_modal_output_if_debug() as modal_output:sb = modal.Sandbox.create(**create_kwargs) # type: ignore[arg-type]+ config.snapshot_restored = False++ if snapshot_kind == SNAPSHOT_KIND_DIRECTORY and snapshot_image is not None:+ if not hasattr(sb, "mount_image"):+ logger.warning(+ "Modal sandbox does not support directory snapshot restore; falling back to base image",+ extra={+ "snapshot_external_id": snapshot_external_id,+ "snapshot_mount_path": snapshot_mount_path,+ },+ )+ else:+ try:+ sb.mount_image(snapshot_mount_path, snapshot_image)+ config.snapshot_restored = True+ except Exception as e:+ logger.warning(+ f"Failed to mount directory snapshot image {snapshot_external_id} at {snapshot_mount_path}: {e}"+ )+ capture_exception(e)if config.metadata:sb.set_tags(config.metadata)@@ -1002,6 +1048,49 @@ class ModalSandbox(SandboxBase):f"Failed to create snapshot: {e}", {"sandbox_id": self.id, "error": str(e)}, cause=e)+ def create_directory_snapshot(self, path: str) -> str:+ if not self.is_running():+ raise SandboxNotRunningError(+ f"Sandbox not in running state.",+ {"sandbox_id": self.id},+ cause=RuntimeError(f"Sandbox {self.id} is not running"),+ )++ snapshot_directory = getattr(self._sandbox, "snapshot_directory", None)+ if snapshot_directory is None:+ raise SnapshotCreationError(+ "Modal SDK does not support directory snapshots",+ {"sandbox_id": self.id, "path": path},+ cause=RuntimeError("modal.Sandbox.snapshot_directory is unavailable"),+ )++ try:+ quoted_path = shlex.quote(path)+ self._sandbox.exec("bash", "-c", f"mkdir -p {quoted_path} && test -d {quoted_path}", timeout=30).wait()+ image = snapshot_directory(path, ttl=None)+ snapshot_id = image.object_id++ logger.info(f"Created directory snapshot for sandbox {self.id}, path: {path}, snapshot ID: {snapshot_id}")++ return snapshot_id++ except TRANSIENT_SNAPSHOT_ERRORS as e:+ logger.warning(f"Transient error creating directory snapshot for sandbox {self.id}, will retry: {e}")+ raise SnapshotTimeoutError(+ f"Transient error creating directory snapshot: {e}",+ {"sandbox_id": self.id, "path": path, "error": str(e)},+ cause=e,+ capture=False,+ )++ except Exception as e:+ logger.exception(f"Failed to create directory snapshot: {e}")+ raise SnapshotCreationError(+ f"Failed to create directory snapshot: {e}",+ {"sandbox_id": self.id, "path": path, "error": str(e)},+ cause=e,+ )+@staticmethoddef delete_snapshot(external_id: str) -> None:logger.info(f"Deleting snapshot {external_id}")diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex 8a7ef324f184..575adc1411b1 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -27,6 +27,7 @@ from django.conf import settingsimport structlogfrom pydantic import BaseModel+from products.tasks.backend.constants import DEFAULT_SANDBOX_WORKING_DIR, SNAPSHOT_KIND_FILESYSTEM, SnapshotKindfrom products.tasks.backend.logic.services.sandbox_config import (BURSTABLE_REQUEST_CPU_CORES,BURSTABLE_REQUEST_MEMORY_MB,@@ -88,6 +89,10 @@ class SandboxConfig(BaseModel):environment_variables: dict[str, str] | None = Nonesnapshot_id: str | None = Nonesnapshot_external_id: str | None = None+ snapshot_kind: SnapshotKind = SNAPSHOT_KIND_FILESYSTEM+ snapshot_mount_path: str | None = None+ snapshot_source: str = "none"+ snapshot_restored: bool = Falsettl_seconds: int = SANDBOX_TTL_SECONDSmetadata: dict[str, str] | None = Nonememory_gb: float = 16@@ -109,7 +114,7 @@ class SandboxConfig(BaseModel):return self.vm_runtime or self.template == SandboxTemplate.VM_BASE-WORKING_DIR = "/tmp/workspace"+WORKING_DIR = DEFAULT_SANDBOX_WORKING_DIRREPO_READY_FILE = f"{WORKING_DIR}/.repo-ready"@@ -279,6 +284,9 @@ class SandboxBase(ABC):@abstractmethoddef create_snapshot(self) -> str: ...+ @abstractmethod+ def create_directory_snapshot(self, path: str) -> str: ...+@abstractmethoddef destroy(self) -> None: ...diff --git a/products/tasks/backend/logic/services/warm.py b/products/tasks/backend/logic/services/warm.pyindex 36f61833b0da..a889b5e55147 100644--- a/products/tasks/backend/logic/services/warm.py+++ b/products/tasks/backend/logic/services/warm.py@@ -132,7 +132,7 @@ class SandboxWarmer:- Idempotent: if the Task already has a non-terminal Run, return it without provisioning.- Fresh: a Task with no Runs gets a new warm Run; a Task whose latest Run is terminal gets a- successor that resumes from it (filesystem reuse via ``snapshot_external_id``).+ successor that resumes from it (snapshot reuse via ``snapshot_external_id``).- ``extra_state`` carries product-specific Run state the generic warmer can't know (e.g. PostHogAI's ``systemPrompt``, or a target ``branch``); it is merged into the warm Run's initial state.- ``create_pr`` is forwarded to the processing workflow; it defaults to ``False`` (PostHog AI warm@@ -167,6 +167,12 @@ class SandboxWarmer: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_pathnew_run = locked.create_run(mode=mode, extra_state=run_state, branch=run_state.get("branch"))diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 63fe17d36431..d7b19dc113c4 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -898,23 +898,21 @@ class TaskRun(models.Model):state = self.state or {}prior_snapshot_external_id = state.get("snapshot_external_id")+ prior_snapshot_kind = state.get("snapshot_kind")+ prior_snapshot_mount_path = state.get("snapshot_mount_path")state["handoff_resumed"] = Truestate["mode"] = "interactive"state.pop("pending_user_message", None)state.pop("pending_user_message_ts", None)- if not settings.TASKS_USE_MODAL_RESUME_SNAPSHOTS:- state.pop("snapshot_external_id", None)self.state = statelogger.info("prepare_for_cloud_handoff",run_id=str(self.id),task_id=str(self.task_id),- use_modal_resume_snapshots=settings.TASKS_USE_MODAL_RESUME_SNAPSHOTS,prior_snapshot_external_id=prior_snapshot_external_id,- stripped_snapshot_external_id=(- prior_snapshot_external_id is not None and not settings.TASKS_USE_MODAL_RESUME_SNAPSHOTS- ),+ prior_snapshot_kind=prior_snapshot_kind,+ prior_snapshot_mount_path=prior_snapshot_mount_path,)self.save(diff --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 310241228ec9..1c0a5bb1c0d9 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@@ -541,11 +541,24 @@ class TestRun:sandbox_id="sandbox-123",)- async def test_run_ends_session_without_failing_when_sandbox_gone(self, monkeypatch, silent_workflow_logger):+ @pytest.mark.parametrize(+ "use_modal_resume_snapshots, expect_resume_snapshot_call",+ [+ (True, True),+ (False, False),+ ],+ )+ async def test_run_ends_session_without_failing_when_sandbox_gone(+ self, monkeypatch, silent_workflow_logger, use_modal_resume_snapshots, expect_resume_snapshot_call+ ):workflow = ExecuteSandboxWorkflow()- context = _build_context(state={"mode": "interactive"}, use_modal_resume_snapshots=False)+ context = _build_context(+ state={"mode": "interactive"},+ use_modal_resume_snapshots=use_modal_resume_snapshots,+ )update_status_mock = AsyncMock()cleanup_sandbox_mock = AsyncMock()+ create_resume_snapshot_mock = AsyncMock()monkeypatch.setattr(workflow, "_reap_orphaned_sandbox", AsyncMock())monkeypatch.setattr(workflow, "_get_task_processing_context", AsyncMock(return_value=context))@@ -555,6 +568,7 @@ class TestRun:monkeypatch.setattr(workflow, "_persist_sandbox_id", AsyncMock())monkeypatch.setattr(workflow, "_read_sandbox_logs", AsyncMock())monkeypatch.setattr(workflow, "_cleanup_sandbox", cleanup_sandbox_mock)+ monkeypatch.setattr(workflow, "_create_resume_snapshot", create_resume_snapshot_mock)monkeypatch.setattr(workflow, "_clear_persisted_sandbox_id", AsyncMock())monkeypatch.setattr(workflow, "_flush_pending_outbound", AsyncMock())monkeypatch.setattr(workflow, "_relay_sandbox_events", AsyncMock())@@ -600,6 +614,10 @@ class TestRun:payload = completed_signals[0].args[0]assert isinstance(payload, ChildCompletionPayload)assert payload.success is True+ if expect_resume_snapshot_call:+ create_resume_snapshot_mock.assert_awaited_once_with("sandbox-123")+ else:+ create_resume_snapshot_mock.assert_not_awaited()async def test_context_load_failure_marks_run_failed(self, monkeypatch, silent_workflow_logger):workflow = ExecuteSandboxWorkflow()diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.pyindex 3757faa4979d..86881d61cb6f 100644--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py@@ -861,7 +861,8 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):)self._sandbox_id_for_cleanup = created.sandbox_id- if prepared.used_snapshot:+ used_snapshot = created.used_snapshot if created.used_snapshot is not None else prepared.used_snapshot+ if used_snapshot:await self._emit_progress("sandbox","completed",@@ -872,7 +873,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):else:await self._emit_progress("sandbox", "completed", "Set up sandbox", "setup")- if prepared.snapshot_external_id:+ if used_snapshot and prepared.snapshot_external_id:await workflow.execute_activity(inject_fresh_tokens_on_resume,InjectFreshTokensOnResumeInput(@@ -887,7 +888,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):can_clone_without_integration = is_public_sandbox_repo(prepared.repository)has_clone_credentials = self.context.has_github_credentials or can_clone_without_integration- will_clone = bool(prepared.repository and not prepared.used_snapshot and has_clone_credentials)+ will_clone = bool(prepared.repository and not used_snapshot and has_clone_credentials)will_checkout = bool(prepared.repository and prepared.branch and has_clone_credentials)if will_clone:@@ -921,7 +922,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):branch=prepared.branch,github_token=prepared.github_token,shallow_clone=prepared.shallow_clone,- used_snapshot=prepared.used_snapshot,+ used_snapshot=used_snapshot,),start_to_close_timeout=timedelta(minutes=5),retry_policy=RetryPolicy(maximum_attempts=3),@@ -932,8 +933,8 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):sandbox_id=created.sandbox_id,sandbox_url=created.sandbox_url,connect_token=created.connect_token,- used_snapshot=prepared.used_snapshot,- should_create_snapshot=prepared.should_create_snapshot,+ used_snapshot=used_snapshot,+ should_create_snapshot=not used_snapshot,)async def _cleanup_sandbox(self, sandbox_id: str) -> None:@@ -1155,7 +1156,11 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):async def _create_resume_snapshot(self, sandbox_id: str) -> None:result = await workflow.execute_activity(create_resume_snapshot,- CreateResumeSnapshotInput(sandbox_id=sandbox_id, run_id=self.context.run_id),+ CreateResumeSnapshotInput(+ sandbox_id=sandbox_id,+ run_id=self.context.run_id,+ use_directory_snapshot=self.context.use_modal_directory_resume_snapshots,+ ),start_to_close_timeout=timedelta(minutes=5),retry_policy=RetryPolicy(maximum_attempts=1),)diff --git a/products/tasks/backend/temporal/metrics.py b/products/tasks/backend/temporal/metrics.pyindex 818b93c108d8..7ef081dec2f1 100644--- a/products/tasks/backend/temporal/metrics.py+++ b/products/tasks/backend/temporal/metrics.py@@ -7,7 +7,7 @@ from temporalio.common import MetricMeterAttributes = dict[str, str | int | float | bool]-TASKS_LATENCY_HISTOGRAM_METRICS = ("tasks_process_sandbox_step_latency",)+TASKS_LATENCY_HISTOGRAM_METRICS = ("tasks_process_sandbox_step_latency", "tasks_process_snapshot_create_latency")TASKS_LATENCY_HISTOGRAM_BUCKETS = [100.0,250.0,@@ -42,12 +42,66 @@ def _bool_label(value: bool | None) -> str:return "true" if value else "false"-def increment_snapshot_usage(used_snapshot: bool) -> None:- meter = _metric_meter({"used_snapshot": _bool_label(used_snapshot)})- meter.create_counter(- "tasks_process_snapshot_usage",- "Number of process-task runs by snapshot usage",- ).add(1)+def increment_snapshot_usage(+ used_snapshot: bool,+ *,+ snapshot_source: str = "unknown",+ snapshot_kind: str = "unknown",+) -> None:+ try:+ meter = _metric_meter(+ {+ "used_snapshot": _bool_label(used_snapshot),+ "snapshot_source": snapshot_source,+ "snapshot_kind": snapshot_kind,+ }+ )+ meter.create_counter(+ "tasks_process_snapshot_usage",+ "Number of process-task runs by final snapshot usage",+ ).add(1)+ except Exception:+ pass+++def increment_snapshot_restore(snapshot_source: str, snapshot_kind: str, outcome: str) -> None:+ try:+ meter = _metric_meter(+ {+ "snapshot_source": snapshot_source,+ "snapshot_kind": snapshot_kind,+ "outcome": outcome,+ }+ )+ meter.create_counter(+ "tasks_process_snapshot_restore",+ "Snapshot restore outcomes for process-task sandbox creation",+ ).add(1)+ except Exception:+ pass+++def increment_snapshot_create(snapshot_kind: str, outcome: str) -> None:+ try:+ meter = _metric_meter({"snapshot_kind": snapshot_kind, "outcome": outcome})+ meter.create_counter(+ "tasks_process_snapshot_create",+ "Resume snapshot creation outcomes for process-task runs",+ ).add(1)+ except Exception:+ pass+++def record_snapshot_create_latency_ms(snapshot_kind: str, outcome: str, latency_ms: int) -> None:+ try:+ delta = dt.timedelta(milliseconds=latency_ms)+ _metric_meter({"snapshot_kind": snapshot_kind, "outcome": outcome}).create_histogram_timedelta(+ "tasks_process_snapshot_create_latency",+ "Resume snapshot creation latency for process-task runs",+ unit="ms",+ ).record(delta)+ except Exception:+ passdef increment_credential_refresh(kind: str, outcome: str) -> None: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 0e1beadade34..3b19e8bf0b31 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@@ -1,3 +1,4 @@+import timefrom dataclasses import dataclassimport structlog@@ -5,56 +6,103 @@ from temporalio import activityfrom posthog.temporal.common.utils import asyncify+from products.tasks.backend.constants import (+ DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH,+ SNAPSHOT_KIND_DIRECTORY,+ SNAPSHOT_KIND_FILESYSTEM,+ SnapshotKind,+)from products.tasks.backend.logic.services.sandbox import get_sandbox_classfrom products.tasks.backend.models import TaskRun+from products.tasks.backend.temporal.metrics import increment_snapshot_create, record_snapshot_create_latency_mslogger = structlog.get_logger(__name__)+PENDING_USER_STATE_KEYS = ["pending_user_message", "pending_user_artifact_ids", "pending_user_message_ts"]+@dataclassclass CreateResumeSnapshotInput:sandbox_id: strrun_id: str+ use_directory_snapshot: bool = False+ snapshot_mount_path: str = DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH@dataclassclass CreateResumeSnapshotOutput:external_id: str | None+ snapshot_kind: SnapshotKind | None = None+ snapshot_mount_path: str | None = Noneerror: str | None = None@activity.defn@asyncifydef create_resume_snapshot(input: CreateResumeSnapshotInput) -> CreateResumeSnapshotOutput:- """Create a filesystem snapshot of the sandbox for later resume.+ """Create a snapshot of the sandbox for later resume.Stores the snapshot external ID on the TaskRun state so the conversationAPI can look it up when resuming."""SandboxClass = get_sandbox_class()+ snapshot_kind: SnapshotKind = SNAPSHOT_KIND_DIRECTORY if input.use_directory_snapshot else SNAPSHOT_KIND_FILESYSTEM+ snapshot_mount_path = input.snapshot_mount_path or DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATHlogger.info("create_resume_snapshot_started", sandbox_id=input.sandbox_id, run_id=input.run_id)+ 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))- return CreateResumeSnapshotOutput(external_id=None, error=f"Sandbox not found: {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))+ return CreateResumeSnapshotOutput(+ external_id=None, snapshot_kind=snapshot_kind, error=f"Sandbox not found: {e}"+ )if not sandbox.is_running():- return CreateResumeSnapshotOutput(external_id=None, error="Sandbox not running")+ outcome = "sandbox_not_running"+ 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")+ outcome = "created"try:- external_id = sandbox.create_snapshot()+ if snapshot_kind == SNAPSHOT_KIND_DIRECTORY:+ external_id = sandbox.create_directory_snapshot(snapshot_mount_path)+ else:+ external_id = sandbox.create_snapshot()except Exception as e:+ outcome = "failed"logger.warning("create_resume_snapshot_snapshot_failed", sandbox_id=input.sandbox_id, error=str(e))- return CreateResumeSnapshotOutput(external_id=None, 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:+ increment_snapshot_create(snapshot_kind, outcome)+ record_snapshot_create_latency_ms(snapshot_kind, outcome, int((time.perf_counter() - started_at) * 1000))# Persist snapshot external ID on TaskRun statetry:- TaskRun.update_state_atomic(input.run_id, updates={"snapshot_external_id": external_id})+ updates = {+ "snapshot_external_id": external_id,+ "snapshot_kind": snapshot_kind,+ }+ remove_keys: list[str] = [*PENDING_USER_STATE_KEYS]+ if snapshot_kind == SNAPSHOT_KIND_DIRECTORY:+ updates["snapshot_mount_path"] = snapshot_mount_path+ else:+ remove_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))activity.logger.info(f"Created resume snapshot {external_id} for sandbox {input.sandbox_id}")- return CreateResumeSnapshotOutput(external_id=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,+ )diff --git a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.pyindex 634097eccf73..1bc3e951d270 100644--- a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py+++ b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py@@ -8,7 +8,7 @@ from temporalio import activityfrom posthog.temporal.common.utils import asyncify-from products.tasks.backend.constants import filter_user_sandbox_env_vars+from products.tasks.backend.constants import SNAPSHOT_KIND_FILESYSTEM, filter_user_sandbox_env_varsfrom products.tasks.backend.exceptions import GitHubAuthenticationError, OAuthTokenError, TaskNotFoundErrorfrom products.tasks.backend.logic.services.connection_token import (SANDBOX_JWT_STATE_KID_KEY,@@ -22,7 +22,7 @@ from products.tasks.backend.logic.services.sandbox import (parse_sandbox_repo_mount_map,)from products.tasks.backend.models import SandboxSnapshot, Task, TaskRun-from products.tasks.backend.temporal.metrics import StepTimer, increment_snapshot_usage+from products.tasks.backend.temporal.metrics import StepTimer, increment_snapshot_restore, increment_snapshot_usagefrom products.tasks.backend.temporal.oauth import create_oauth_access_tokenfrom products.tasks.backend.temporal.observability import emit_agent_log, log_activity_executionfrom products.tasks.backend.temporal.process_task.utils import (@@ -30,6 +30,7 @@ from products.tasks.backend.temporal.process_task.utils import (get_sandbox_api_url,get_sandbox_github_token,get_sandbox_name_for_task,+ get_sandbox_snapshot_metadata,parse_run_state,)@@ -112,13 +113,20 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandbosnapshot = Noneused_snapshot = False+ snapshot_source = "none"+ snapshot_kind = SNAPSHOT_KIND_FILESYSTEM+ snapshot_mount_path: str | None = Noneif has_repo and github_integration_id is not None:assert repository is not Nonewith StepTimer("snapshot_lookup") as snapshot_lookup_timer:snapshot = SandboxSnapshot.get_latest_snapshot_with_repos(github_integration_id, [repository])used_snapshot = snapshot is not Nonesnapshot_lookup_timer.set_used_snapshot(used_snapshot)- increment_snapshot_usage(used_snapshot)+ if snapshot is not None:+ snapshot_source = "repository"+ snapshot_metadata = get_sandbox_snapshot_metadata(snapshot)+ snapshot_kind = snapshot_metadata.kind+ snapshot_mount_path = snapshot_metadata.mount_pathelif not has_repo:emit_agent_log(ctx.run_id, "debug", "Creating environment without repository")@@ -214,6 +222,9 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandboresume_snapshot_ext_id = run_state.snapshot_external_idif resume_snapshot_ext_id:used_snapshot = True+ snapshot_source = "resume"+ snapshot_kind = run_state.resume_snapshot_kind()+ snapshot_mount_path = run_state.resume_snapshot_mount_path()provider = getattr(settings, "SANDBOX_PROVIDER", None)image_source_label = _get_image_source_label(@@ -237,6 +248,9 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandbotemplate=SandboxTemplate.DEFAULT_BASE,environment_variables=environment_variables,snapshot_external_id=resume_snapshot_ext_id,+ snapshot_kind=snapshot_kind,+ snapshot_mount_path=snapshot_mount_path,+ snapshot_source=snapshot_source,snapshot_id=str(snapshot.id) if snapshot and not resume_snapshot_ext_id else None,metadata={"task_id": ctx.task_id},**ctx.sandbox_resource_overrides(),@@ -247,8 +261,14 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandbo"debug",f"Provisioning sandbox from {image_source_label} (image build may take a few minutes on first run)",)- with StepTimer("sandbox_creation", used_snapshot=used_snapshot):+ with StepTimer("sandbox_creation", used_snapshot=used_snapshot) as sandbox_creation_timer:sandbox = Sandbox.create(config)+ used_snapshot = bool((resume_snapshot_ext_id or snapshot) and sandbox.config.snapshot_restored)+ sandbox_creation_timer.set_used_snapshot(used_snapshot)+ snapshot_outcome = "used" if used_snapshot else "fresh" if snapshot_source == "none" else "fallback"+ metrics_snapshot_kind = snapshot_kind if snapshot_source != "none" else "none"+ increment_snapshot_usage(used_snapshot, snapshot_source=snapshot_source, snapshot_kind=metrics_snapshot_kind)+ increment_snapshot_restore(snapshot_source, metrics_snapshot_kind, snapshot_outcome)_emit_provisioning_diagnostics(ctx, sandbox)emit_agent_log(ctx.run_id, "debug", f"Sandbox provisioned: {sandbox.id}")diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.pyindex bf84810c7ff2..dd97bea21c1f 100644--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py@@ -12,6 +12,7 @@ from posthog.models import Teamfrom posthog.temporal.common.utils import asyncify, close_db_connectionsfrom products.tasks.backend.constants import (+ MODAL_DIRECTORY_RESUME_SNAPSHOTS_FEATURE_FLAG,MODAL_NETWORK_ALLOWLIST_FEATURE_FLAG,MODAL_VM_SANDBOX_FEATURE_FLAG,OVERLAP_CLONE_BOOT_FEATURE_FLAG,@@ -66,9 +67,11 @@ class TaskProcessingContext:allowed_domains: list[str] | None = Nonejson_schema: dict | None = Noneci_prompt: str | None = None- # Captured at workflow start so a flag flip mid-run can't introduce- # nondeterminism (the workflow consults this in its finally block).+ # Captured at workflow start so snapshot creation is deterministic across+ # activity retries. This means "create any Modal resume snapshot"; filesystem+ # snapshots are guarded by the legacy setting, directory snapshots by feature flag.use_modal_resume_snapshots: bool = True+ use_modal_directory_resume_snapshots: bool = False# Captured at workflow start so the sandbox event transport branch is# deterministic for the full run.sandbox_event_ingest_enabled: bool = False@@ -415,6 +418,35 @@ def _is_modal_network_allowlist_enabled(return enabled+def _is_modal_directory_resume_snapshots_enabled(+ *,+ distinct_id: str,+ organization_id: str,+ run_id: str,+) -> bool:+ try:+ enabled = bool(+ posthoganalytics.feature_enabled(+ MODAL_DIRECTORY_RESUME_SNAPSHOTS_FEATURE_FLAG,+ distinct_id=distinct_id,+ groups={"organization": organization_id},+ group_properties={"organization": {"id": organization_id}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+ except Exception as e:+ log_with_activity_context("modal_directory_resume_snapshots_flag_check_failed", run_id=run_id, error=str(e))+ return False++ log_with_activity_context(+ "modal_directory_resume_snapshots_flag_checked",+ run_id=run_id,+ use_modal_directory_resume_snapshots=enabled,+ )+ return enabled++@activity.defn@asyncify@close_db_connections@@ -567,6 +599,16 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro"debug",f"overlap_clone_boot_enabled: {overlap_clone_boot_enabled} for this task run",)+ use_modal_directory_resume_snapshots = _is_modal_directory_resume_snapshots_enabled(+ distinct_id=distinct_id,+ organization_id=organization_id,+ run_id=run_id,+ )+ emit_agent_log(+ run_id,+ "debug",+ f"use_modal_directory_resume_snapshots: {use_modal_directory_resume_snapshots} for this task run",+ )user_github_integration_id = str(task.github_user_integration_id) if task.github_user_integration_id else Noneif user_github_integration_id is None and get_pr_authorship_mode(task, state).value == "user":user_github_integration = resolve_user_github_integration_for_task(task, allow_refresh=False)@@ -594,7 +636,8 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskProallowed_domains=allowed_domains,json_schema=task.json_schema,ci_prompt=task.ci_prompt,- use_modal_resume_snapshots=settings.TASKS_USE_MODAL_RESUME_SNAPSHOTS,+ use_modal_resume_snapshots=settings.TASKS_USE_MODAL_RESUME_SNAPSHOTS or use_modal_directory_resume_snapshots,+ use_modal_directory_resume_snapshots=use_modal_directory_resume_snapshots,sandbox_event_ingest_enabled=sandbox_event_ingest_enabled,use_modal_vm_sandbox=use_modal_vm_sandbox,use_modal_network_allowlist=use_modal_network_allowlist,diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex f019e13dc9a3..b402c8eed256 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -8,7 +8,7 @@ from temporalio import activityfrom posthog.temporal.common.utils import asyncify-from products.tasks.backend.constants import filter_user_sandbox_env_vars+from products.tasks.backend.constants import SNAPSHOT_KIND_FILESYSTEM, filter_user_sandbox_env_varsfrom products.tasks.backend.exceptions import GitHubAuthenticationError, OAuthTokenError, TaskNotFoundErrorfrom products.tasks.backend.logic.services.agentsh import ENV_FILE, INFRASTRUCTURE_DOMAINS, _get_debug_only_domainsfrom products.tasks.backend.logic.services.connection_token import (@@ -18,7 +18,12 @@ from products.tasks.backend.logic.services.connection_token import ()from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxConfig, SandboxTemplatefrom products.tasks.backend.models import SandboxSnapshot, Task, TaskRun-from products.tasks.backend.temporal.metrics import StepTimer, increment_sandbox_created, increment_snapshot_usage+from products.tasks.backend.temporal.metrics import (+ StepTimer,+ increment_sandbox_created,+ increment_snapshot_restore,+ increment_snapshot_usage,+)from products.tasks.backend.temporal.oauth import create_oauth_access_token, create_wizard_oauth_access_tokenfrom products.tasks.backend.temporal.observability import emit_agent_log, log_activity_executionfrom products.tasks.backend.temporal.process_task.sandbox_credentials import set_git_remote_token@@ -27,6 +32,7 @@ from products.tasks.backend.temporal.process_task.utils import (get_sandbox_api_url,get_sandbox_github_token,get_sandbox_name_for_task,+ get_sandbox_snapshot_metadata,parse_run_state,)@@ -60,6 +66,9 @@ class PrepareSandboxForRepositoryOutput:shallow_clone: boolimage_source: strimage_source_label: str+ snapshot_kind: str = SNAPSHOT_KIND_FILESYSTEM+ snapshot_mount_path: str | None = None+ snapshot_source: str = "none"@dataclass@@ -73,6 +82,7 @@ class CreateSandboxForRepositoryOutput:sandbox_id: strsandbox_url: strconnect_token: str | None+ used_snapshot: bool | None = None@dataclass@@ -285,13 +295,20 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> Psnapshot = Noneused_snapshot = False+ snapshot_source = "none"+ snapshot_kind = SNAPSHOT_KIND_FILESYSTEM+ snapshot_mount_path: str | None = Noneif has_repo and ctx.github_integration_id is not None:assert repository is not Nonewith StepTimer("snapshot_lookup") as snapshot_lookup_timer:snapshot = SandboxSnapshot.get_latest_snapshot_with_repos(ctx.github_integration_id, [repository])used_snapshot = snapshot is not Nonesnapshot_lookup_timer.set_used_snapshot(used_snapshot)- increment_snapshot_usage(used_snapshot)+ if snapshot is not None:+ snapshot_source = "repository"+ snapshot_metadata = get_sandbox_snapshot_metadata(snapshot)+ snapshot_kind = snapshot_metadata.kind+ snapshot_mount_path = snapshot_metadata.mount_pathelif not has_repo:emit_agent_log(ctx.run_id, "debug", "Creating environment without repository")@@ -334,23 +351,25 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> Penvironment_variables = _build_environment_variables(ctx, task, github_token, access_token)run_state = parse_run_state(ctx.state)- # VM and gVisor both resume from filesystem snapshots. A run's resume- # snapshot is taken from the same task's sandbox, so its base image- # matches the runtime provisioned here (the earlier disable was for- # gVisor memory snapshots, which cannot restore into the VM runtime).- resume_snapshot_external_id = (- run_state.snapshot_external_id if settings.TASKS_USE_MODAL_RESUME_SNAPSHOTS else None- )+ # VM and gVisor both resume from snapshots. A run's stored snapshot kind+ # determines the restore mechanism; the rollout flag only chooses the+ # kind of new snapshot created after this run.+ resume_snapshot_external_id = run_state.snapshot_external_idif resume_snapshot_external_id:used_snapshot = True+ snapshot_source = "resume"+ snapshot_kind = run_state.resume_snapshot_kind()+ snapshot_mount_path = run_state.resume_snapshot_mount_path()activity.logger.info("resume_decision",extra={"run_id": ctx.run_id,- "use_modal_resume_snapshots": settings.TASKS_USE_MODAL_RESUME_SNAPSHOTS,"state_snapshot_external_id": run_state.snapshot_external_id,+ "state_snapshot_kind": run_state.snapshot_kind,"effective_snapshot_external_id": resume_snapshot_external_id,+ "effective_snapshot_kind": snapshot_kind,+ "effective_snapshot_mount_path": snapshot_mount_path,"handoff_resumed": run_state.handoff_resumed,"resume_from_run_id": run_state.resume_from_run_id,"posthog_resume_run_id_set": "POSTHOG_RESUME_RUN_ID" in environment_variables,@@ -387,6 +406,9 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> Pshallow_clone=shallow_clone,image_source=image_source,image_source_label=image_source_label,+ snapshot_kind=snapshot_kind,+ snapshot_mount_path=snapshot_mount_path,+ snapshot_source=snapshot_source,)@@ -417,6 +439,9 @@ def create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Creenvironment_variables=prepared.environment_variables,snapshot_id=prepared.snapshot_id,snapshot_external_id=prepared.snapshot_external_id,+ snapshot_kind=prepared.snapshot_kind,+ snapshot_mount_path=prepared.snapshot_mount_path,+ snapshot_source=prepared.snapshot_source,metadata=_build_sandbox_tags(ctx, prepared, use_vm_sandbox),vm_runtime=use_vm_sandbox,**ctx.sandbox_resource_overrides(),@@ -445,8 +470,22 @@ def create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cref"Using Modal outbound_domain_allowlist ({len(config.outbound_domain_allowlist)} domains) instead of agentsh",)- with StepTimer("sandbox_creation", used_snapshot=prepared.used_snapshot):+ with StepTimer("sandbox_creation", used_snapshot=prepared.used_snapshot) as sandbox_creation_timer:sandbox = Sandbox.create(config)+ actual_used_snapshot = bool(+ (prepared.snapshot_external_id or prepared.snapshot_id) and sandbox.config.snapshot_restored+ )+ sandbox_creation_timer.set_used_snapshot(actual_used_snapshot)+ snapshot_outcome = (+ "used" if actual_used_snapshot else "fresh" if prepared.snapshot_source == "none" else "fallback"+ )+ metrics_snapshot_kind = prepared.snapshot_kind if prepared.snapshot_source != "none" else "none"+ increment_snapshot_usage(+ actual_used_snapshot,+ snapshot_source=prepared.snapshot_source,+ snapshot_kind=metrics_snapshot_kind,+ )+ increment_snapshot_restore(prepared.snapshot_source, metrics_snapshot_kind, snapshot_outcome)increment_sandbox_created("vm" if use_vm_sandbox else "gvisor")@@ -466,12 +505,13 @@ def create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Creraiseemit_agent_log(ctx.run_id, "debug", f"Sandbox provisioned: {sandbox.id}")- activity.logger.info(f"Created sandbox {sandbox.id} (used_snapshot={prepared.used_snapshot})")+ activity.logger.info(f"Created sandbox {sandbox.id} (used_snapshot={actual_used_snapshot})")return CreateSandboxForRepositoryOutput(sandbox_id=sandbox.id,sandbox_url=credentials.url,connect_token=credentials.token,+ used_snapshot=actual_used_snapshot,)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.pynew file mode 100644index 000000000000..23e67efea8cb--- /dev/null+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_create_resume_snapshot.py@@ -0,0 +1,45 @@+import pytest++from asgiref.sync import async_to_sync++from products.tasks.backend.constants import DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH, SNAPSHOT_KIND_DIRECTORY+from products.tasks.backend.models import TaskRun+from products.tasks.backend.temporal.process_task.activities.create_resume_snapshot import (+ CreateResumeSnapshotInput,+ create_resume_snapshot,+)+++def test_create_directory_resume_snapshot_uses_tmp_mount_path(activity_environment, mocker) -> None:+ sandbox = mocker.Mock()+ sandbox.is_running.return_value = True+ sandbox.create_directory_snapshot.return_value = "im-dir"+ 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),+ )++ sandbox.create_directory_snapshot.assert_called_once_with(DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH)+ sandbox.create_snapshot.assert_not_called()+ update_state.assert_called_once_with(+ "run-1",+ updates={+ "snapshot_external_id": "im-dir",+ "snapshot_kind": SNAPSHOT_KIND_DIRECTORY,+ "snapshot_mount_path": DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH,+ },+ remove_keys=["pending_user_message", "pending_user_artifact_ids", "pending_user_message_ts"],+ )+ assert output.external_id == "im-dir"+ assert output.snapshot_kind == SNAPSHOT_KIND_DIRECTORY+ assert output.snapshot_mount_path == DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATHdiff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_sandbox_for_repository.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_sandbox_for_repository.pyindex e705a54b5db9..60dac2ac1b9d 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_sandbox_for_repository.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_sandbox_for_repository.py@@ -33,7 +33,7 @@ class TestGetSandboxForRepositoryActivity:)@pytest.mark.django_db(transaction=True)- def test_get_sandbox_with_existing_snapshot(+ def test_get_sandbox_with_unavailable_snapshot_falls_back(self, activity_environment, github_integration, test_task, test_task_run):snapshot = SandboxSnapshot.objects.create(@@ -51,8 +51,8 @@ class TestGetSandboxForRepositoryActivity:result = async_to_sync(activity_environment.run)(get_sandbox_for_repository, input_data)assert result.sandbox_id is not None- assert result.used_snapshot is True- assert result.should_create_snapshot is False+ assert result.used_snapshot is False+ assert result.should_create_snapshot is Truesandbox_id = result.sandbox_iddiff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.pyindex 9056835bf32b..ceeca634d98f 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py@@ -2,13 +2,18 @@ import pytestfrom unittest.mock import patchfrom django.core.exceptions import ValidationError+from django.test import override_settingsfrom asgiref.sync import async_to_syncfrom posthog.models import OrganizationMembership, Userfrom posthog.models.user_integration import UserIntegration-from products.tasks.backend.constants import MODAL_VM_SANDBOX_FEATURE_FLAG, SANDBOX_EVENT_INGEST_FEATURE_FLAG+from products.tasks.backend.constants import (+ MODAL_DIRECTORY_RESUME_SNAPSHOTS_FEATURE_FLAG,+ MODAL_VM_SANDBOX_FEATURE_FLAG,+ SANDBOX_EVENT_INGEST_FEATURE_FLAG,+)from products.tasks.backend.exceptions import TaskInvalidStateError, TaskRunNotReadyErrorfrom products.tasks.backend.models import SandboxEnvironment, Taskfrom products.tasks.backend.temporal.process_task.activities.get_task_processing_context import (@@ -541,6 +546,46 @@ class TestGetTaskProcessingContextActivity:assert result.sandbox_event_ingest_enabled is True+ @pytest.mark.django_db(transaction=True)+ @pytest.mark.parametrize(+ "legacy_resume_snapshots, directory_resume_snapshots, run_state, expected_resume_snapshots",+ [+ (True, False, {}, True),+ (False, True, {}, True),+ (False, False, {}, False),+ (False, False, {"use_modal_directory_resume_snapshots": True}, False),+ (False, True, {"use_modal_directory_resume_snapshots": False}, True),+ ],+ )+ def test_get_task_processing_context_combines_legacy_and_directory_resume_snapshot_flags(+ self,+ activity_environment,+ test_task,+ legacy_resume_snapshots,+ directory_resume_snapshots,+ run_state,+ expected_resume_snapshots,+ ):+ task_run = test_task.create_run(extra_state=run_state)+ input_data = GetTaskProcessingContextInput(run_id=str(task_run.id))++ def feature_enabled(flag_key, *args, **kwargs):+ if flag_key == MODAL_DIRECTORY_RESUME_SNAPSHOTS_FEATURE_FLAG:+ return directory_resume_snapshots+ return False++ with (+ override_settings(TASKS_USE_MODAL_RESUME_SNAPSHOTS=legacy_resume_snapshots),+ patch(+ "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",+ side_effect=feature_enabled,+ ),+ ):+ result = async_to_sync(activity_environment.run)(get_task_processing_context, input_data)++ assert result.use_modal_resume_snapshots is expected_resume_snapshots+ assert result.use_modal_directory_resume_snapshots is directory_resume_snapshots+@pytest.mark.django_db(transaction=True)def test_get_task_processing_context_exposes_ci_prompt(self, activity_environment, test_task):custom_prompt = "Re-run the failed mypy checks and push a fix."diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.pyindex 6d662ed8aebf..6f49426afd1a 100644--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py@@ -5,10 +5,16 @@ from django.test import TestCasefrom parameterized import parameterizedfrom products.mcp_store.backend.facade.contracts import ActiveInstallationInfo+from products.tasks.backend.constants import (+ DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH,+ DEFAULT_SANDBOX_WORKING_DIR,+ SNAPSHOT_KIND_DIRECTORY,+)from products.tasks.backend.models import Taskfrom products.tasks.backend.temporal.process_task.utils import (GitHubCredentialSource,McpServerConfig,+ RunState,get_git_identity_env_vars,get_github_credential_source,get_sandbox_github_token,@@ -18,6 +24,26 @@ from products.tasks.backend.temporal.process_task.utils import ()+class TestRunStateSnapshotPaths(TestCase):+ @parameterized.expand(+ [+ (+ "new_directory_snapshot",+ {"snapshot_kind": SNAPSHOT_KIND_DIRECTORY},+ DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH,+ ),+ (+ "stored_directory_snapshot_path",+ {"snapshot_kind": SNAPSHOT_KIND_DIRECTORY, "snapshot_mount_path": DEFAULT_SANDBOX_WORKING_DIR},+ DEFAULT_SANDBOX_WORKING_DIR,+ ),+ ("filesystem_snapshot", {"snapshot_kind": "filesystem"}, None),+ ]+ )+ 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++class TestGetSandboxMcpConfigs(TestCase):TOKEN = "phx_test_token"PROJECT_ID = 42diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex 15c622f87893..1326582952da 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -744,24 +744,16 @@ class TestProcessTaskWorkflowUnit:assert inject_fresh_tokens_on_resume not in activity_calls@pytest.mark.parametrize(- "use_modal_resume_snapshots, mode, expect_resume_snapshot_call",+ "mode, use_modal_resume_snapshots, expect_resume_snapshot_call",[- (True, "interactive", True),- (False, "interactive", False),- (True, "background", False),- (False, "background", False),+ ("interactive", True, True),+ ("interactive", False, False),+ ("background", True, False),],)- async def test_finally_block_resume_snapshot_gating(- self, monkeypatch, use_modal_resume_snapshots, mode, expect_resume_snapshot_call+ async def test_finally_block_creates_resume_snapshot_for_interactive_runs(+ self, monkeypatch, mode, use_modal_resume_snapshots, expect_resume_snapshot_call):- """`_create_resume_snapshot` runs only when interactive AND flag is on.-- Disabling the Modal-snapshot flag (e.g. for EU compliance) must skip the- snapshot creation activity in the workflow's finally block, regardless of- mode. The flag value is set on the context (captured at workflow start)- so a mid-run flip can't introduce replay nondeterminism.- """workflow = ProcessTaskWorkflow()get_task_processing_context_mock = AsyncMock(return_value=_build_context(@@ -802,40 +794,28 @@ class TestProcessTaskWorkflowUnit:create_resume_snapshot_mock.assert_not_awaited()@pytest.mark.parametrize(- "use_modal_resume_snapshots, prior_snapshot_external_id, expect_used_snapshot, expect_inject_tokens",+ "use_modal_resume_snapshots",[- # Flag on: a stale snapshot id propagated via state still gets used,- # and the post-resume token-injection activity runs to refresh the- # snapshotted .git/config.- (True, "im-abc123", True, True),- # Flag off: snapshot id is ignored even if state still carries it,- # and the token-injection activity is skipped (no snapshotted creds).- (False, "im-abc123", False, False),+ True,+ False,],)- async def test_get_sandbox_respects_modal_resume_flag(+ async def test_get_sandbox_uses_stored_snapshot_regardless_of_legacy_modal_resume_flag(self,monkeypatch,use_modal_resume_snapshots,- prior_snapshot_external_id,- expect_used_snapshot,- expect_inject_tokens,):- """`_get_sandbox_for_repository` honors TASKS_USE_MODAL_RESUME_SNAPSHOTS.-- Verified via the prepared-output the workflow receives: when the flag is- off, the workflow doesn't see a `snapshot_external_id` and therefore- doesn't schedule the `inject_fresh_tokens_on_resume` activity.- """- monkeypatch.setattr(settings, "TASKS_USE_MODAL_RESUME_SNAPSHOTS", use_modal_resume_snapshots)+ """Stored snapshot IDs are restored even if the legacy context field is false."""+ prior_snapshot_external_id = "im-abc123"workflow = ProcessTaskWorkflow()workflow._context = _build_context(github_integration_id=123,state={"snapshot_external_id": prior_snapshot_external_id, "resume_from_run_id": "previous-run-id"},+ use_modal_resume_snapshots=use_modal_resume_snapshots,)- # Mirror what `prepare_sandbox_for_repository` would produce given the flag.+ # Mirror what `prepare_sandbox_for_repository` produces from stored snapshot state.prepared = PrepareSandboxForRepositoryOutput(sandbox_name="sandbox-name",repository="posthog/posthog-js",@@ -843,17 +823,18 @@ class TestProcessTaskWorkflowUnit:branch=None,environment_variables={},snapshot_id=None,- snapshot_external_id=prior_snapshot_external_id if expect_used_snapshot else None,- used_snapshot=expect_used_snapshot,- should_create_snapshot=not expect_used_snapshot,+ snapshot_external_id=prior_snapshot_external_id,+ used_snapshot=True,+ should_create_snapshot=False,shallow_clone=True,- image_source="resume_snapshot" if expect_used_snapshot else "base_image",- image_source_label="resume snapshot" if expect_used_snapshot else "published sandbox base image",+ image_source="resume_snapshot",+ image_source_label="resume snapshot",)created = CreateSandboxForRepositoryOutput(sandbox_id="sandbox-123",sandbox_url="https://sandbox.example",connect_token="connect-token",+ used_snapshot=True,)activity_calls: list[object] = []@@ -877,7 +858,4 @@ class TestProcessTaskWorkflowUnit:await workflow._get_sandbox_for_repository()- if expect_inject_tokens:- assert inject_fresh_tokens_on_resume in activity_calls- else:- assert inject_fresh_tokens_on_resume not in activity_calls+ assert inject_fresh_tokens_on_resume in activity_callsdiff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex da789dd98b91..62f1b9797621 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -15,13 +15,20 @@ from posthog.models.user_integration import ReauthorizationRequired, UserGitHubIfrom posthog.temporal.oauth import TOKEN_EXPIRATION_SECONDS, PosthogMcpScopes, has_write_scopesfrom products.mcp_store.backend.facade.api import get_active_installations-from products.tasks.backend.constants import InitialPermissionMode, filter_user_sandbox_env_vars+from products.tasks.backend.constants import (+ DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH,+ SNAPSHOT_KIND_DIRECTORY,+ SNAPSHOT_KIND_FILESYSTEM,+ InitialPermissionMode,+ SnapshotKind,+ filter_user_sandbox_env_vars,+)from products.tasks.backend.redis import get_tasks_cacheif TYPE_CHECKING:from posthog.models.user import User- from products.tasks.backend.models import Task+ from products.tasks.backend.models import SandboxSnapshot, Tasklogger = logging.getLogger(__name__)@@ -218,6 +225,8 @@ class RunState(BaseModel, extra="allow"):resume_from_run_id: str | None = Nonehandoff_resumed: bool = Falsesnapshot_external_id: str | None = None+ snapshot_kind: str | None = None+ snapshot_mount_path: str | None = Nonesandbox_id: str | None = Nonesandbox_url: str | None = Nonesandbox_connect_token: str | None = None@@ -230,11 +239,38 @@ class RunState(BaseModel, extra="allow"):interaction_origin: str | None = Noneslack_sent_relay_ids: list[str] | None = None+ def resume_snapshot_kind(self) -> SnapshotKind:+ if self.snapshot_kind == SNAPSHOT_KIND_DIRECTORY:+ return SNAPSHOT_KIND_DIRECTORY+ return SNAPSHOT_KIND_FILESYSTEM++ def resume_snapshot_mount_path(self) -> str | None:+ if self.resume_snapshot_kind() != SNAPSHOT_KIND_DIRECTORY:+ return None+ return self.snapshot_mount_path or DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH+def parse_run_state(state: dict[str, Any] | None) -> RunState:return RunState.model_validate(state or {})+@dataclass(frozen=True)+class SnapshotMetadata:+ kind: SnapshotKind+ mount_path: str | None+++def get_sandbox_snapshot_metadata(snapshot: SandboxSnapshot) -> SnapshotMetadata:+ kind: SnapshotKind = (+ SNAPSHOT_KIND_DIRECTORY+ if snapshot.metadata.get("snapshot_kind") == SNAPSHOT_KIND_DIRECTORY+ else SNAPSHOT_KIND_FILESYSTEM+ )+ metadata_mount_path = snapshot.metadata.get("snapshot_mount_path")+ mount_path = metadata_mount_path if isinstance(metadata_mount_path, str) and metadata_mount_path else None+ return SnapshotMetadata(kind=kind, mount_path=mount_path)++# TTL for the per-run GitHub user token cache. Kept for backward-compat with callers# (notably the PostHog Code CLI) that still pass ``github_user_token`` on the run request.# The server-side identity flow should be preferred going forward.diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex ec9b3fdcd830..1a2f5a0ac732 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -692,10 +692,6 @@ class ProcessTaskWorkflow(PostHogWorkflow):cleanup_sandbox_id = sandbox_id or self._sandbox_id_for_cleanupif cleanup_sandbox_id:- # When `use_modal_resume_snapshots` is off, resume relies on the- # agent server's git-checkpoint mechanism instead. Read from- # context (captured at workflow start) so replay is deterministic- # against env-var flips.if self._context and self._context.mode == "interactive" and self._context.use_modal_resume_snapshots:await self._create_resume_snapshot(cleanup_sandbox_id)@@ -730,7 +726,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(maximum_attempts=3),)self._sandbox_id_for_cleanup = created.sandbox_id- if prepared.used_snapshot:+ used_snapshot = created.used_snapshot if created.used_snapshot is not None else prepared.used_snapshot+ if used_snapshot:await self._emit_progress("sandbox","completed",@@ -744,7 +741,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):# Resuming from a filesystem snapshot carries the previous run's# credentials baked into .git/config and any agentsh env file — refresh# them before any sandbox command (diagnostics, fetch, checkout) runs.- if prepared.snapshot_external_id:+ if used_snapshot and prepared.snapshot_external_id:await workflow.execute_activity(inject_fresh_tokens_on_resume,InjectFreshTokensOnResumeInput(@@ -759,7 +756,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):can_clone_without_integration = is_public_sandbox_repo(prepared.repository)has_clone_credentials = self.context.has_github_credentials or can_clone_without_integration- will_clone = bool(prepared.repository and not prepared.used_snapshot and has_clone_credentials)+ will_clone = bool(prepared.repository and not used_snapshot and has_clone_credentials)will_checkout = bool(prepared.repository and prepared.branch and has_clone_credentials)overlap = bool(self.context.overlap_clone_boot_enabled and will_clone)@@ -798,7 +795,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):branch=prepared.branch,github_token=prepared.github_token,shallow_clone=prepared.shallow_clone,- used_snapshot=prepared.used_snapshot,+ used_snapshot=used_snapshot,),start_to_close_timeout=timedelta(minutes=5),retry_policy=RetryPolicy(maximum_attempts=3),@@ -812,8 +809,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):sandbox_id=created.sandbox_id,sandbox_url=created.sandbox_url,connect_token=created.connect_token,- used_snapshot=prepared.used_snapshot,- should_create_snapshot=prepared.should_create_snapshot,+ used_snapshot=used_snapshot,+ should_create_snapshot=not used_snapshot,agent_server_launched=overlap,)@@ -1075,11 +1072,15 @@ class ProcessTaskWorkflow(PostHogWorkflow):passasync def _create_resume_snapshot(self, sandbox_id: str) -> None:- """Create a filesystem snapshot for interactive sandbox resume."""+ """Create a snapshot for interactive sandbox resume."""try:result = await workflow.execute_activity(create_resume_snapshot,- CreateResumeSnapshotInput(sandbox_id=sandbox_id, run_id=self.context.run_id),+ CreateResumeSnapshotInput(+ sandbox_id=sandbox_id,+ run_id=self.context.run_id,+ use_directory_snapshot=self.context.use_modal_directory_resume_snapshots,+ ),start_to_close_timeout=timedelta(minutes=5),retry_policy=RetryPolicy(maximum_attempts=1),)diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 11ff33d52568..56ca091bd222 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -3342,13 +3342,15 @@ class TestTaskRunAPI(BaseTaskAPITest):"sandbox_memory_gb": 8,"sandbox_ttl_seconds": 1800,"inactivity_timeout_seconds": 600,+ "use_modal_directory_resume_snapshots": True,},)# A caller cannot escalate to the creator's integration, flip authorship, repoint the# credential-propagation target at a sandbox they control, inflate the run's compute /# lifetime to provision an oversized, long-lived sandbox, or turn the run into a wizard run- # (which would mint a write-scoped wizard token into the sandbox). Non-protected keys merge.+ # (which would mint a write-scoped wizard token into the sandbox), or change rollout+ # decisions. Non-protected keys still merge.response = self.client.patch(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/",{@@ -3361,6 +3363,7 @@ class TestTaskRunAPI(BaseTaskAPITest):"sandbox_ttl_seconds": 86400,"inactivity_timeout_seconds": 86400,"wizard_config": {},+ "use_modal_directory_resume_snapshots": False,"scratch": "ok",}},@@ -3376,18 +3379,28 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["sandbox_ttl_seconds"] == 1800assert run.state["inactivity_timeout_seconds"] == 600assert "wizard_config" not in run.state # caller cannot mark a run as a wizard run+ assert run.state["use_modal_directory_resume_snapshots"] is Trueassert run.state["scratch"] == "ok" # non-protected keys still merge# Nor can a caller remove a protected key to force a fallback or unguarded path.response = self.client.patch(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/",- {"state": {}, "state_remove_keys": ["github_credential_source", "sandbox_id", "scratch"]},+ {+ "state": {},+ "state_remove_keys": [+ "github_credential_source",+ "sandbox_id",+ "use_modal_directory_resume_snapshots",+ "scratch",+ ],+ },format="json",)self.assertEqual(response.status_code, status.HTTP_200_OK)run.refresh_from_db()assert run.state["github_credential_source"] == "caller_token" # protected key survives removalassert run.state["sandbox_id"] == "sb-real" # protected key survives removal+ assert run.state["use_modal_directory_resume_snapshots"] is True # protected key survives removalassert "scratch" not in run.state # non-protected key removed@patch("products.tasks.backend.facade.api.signal_workflow_completion")