: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): mount directory resume snapshots at the workspace only (#67716)
Alessandro Pogliaghicbd837b91a2a
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex 729ce8a343c8..4146afeb76a6 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -12,8 +12,14 @@ 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+# Directory resume snapshots capture a directory and re-mount it into the next sandbox. The mount+# REPLACES the target directory in the running sandbox, so only the quiescent workspace dir is safe:+# mounting over a live system directory (the old "/tmp" default) rips scratch space and sockets out+# from under Modal's in-sandbox helpers and kills the sandbox on its first filesystem operation.+# A snapshot's content layout matches the path it was captured from, so snapshots created for a+# path outside this allowlist cannot be remapped — they must be invalidated on resume instead.+DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH = DEFAULT_SANDBOX_WORKING_DIR+ALLOWED_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATHS: frozenset[str] = frozenset({DEFAULT_SANDBOX_WORKING_DIR})ClaudePermissionMode = Literal["default", "acceptEdits", "plan", "bypassPermissions", "auto"]CodexPermissionMode = Literal["auto", "read-only", "full-access"]diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex b1430078b12f..ba6427ea2ee7 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -3331,7 +3331,10 @@ 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)- if prev_state.snapshot_external_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_idextra_state["snapshot_kind"] = prev_state.resume_snapshot_kind()snapshot_mount_path = prev_state.resume_snapshot_mount_path()diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.pyindex b61d8fccac47..c92ca377d6fb 100644--- a/products/tasks/backend/logic/services/modal_sandbox.py+++ b/products/tasks/backend/logic/services/modal_sandbox.py@@ -33,7 +33,7 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.settings import CLOUD_DEPLOYMENTfrom products.tasks.backend.constants import (- DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH,+ ALLOWED_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATHS,SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS,SNAPSHOT_KIND_DIRECTORY,SNAPSHOT_KIND_FILESYSTEM,@@ -407,7 +407,10 @@ class ModalSandbox(SandboxBase):config.snapshot_restored = Falsesnapshot_external_id: str | None = Nonesnapshot_kind = _normalize_snapshot_kind(config.snapshot_kind)- snapshot_mount_path = config.snapshot_mount_path or DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH+ # No default-fill: a directory snapshot must arrive with an explicit allowed mount+ # path, or the mount below is refused. Defaulting here would silently re-target a+ # snapshot that upstream validation invalidated (mount path stripped).+ snapshot_mount_path: str | None = config.snapshot_mount_pathsnapshot_image: modal.Image | None = Noneused_snapshot_image = False@@ -483,7 +486,19 @@ class ModalSandbox(SandboxBase):config.snapshot_restored = Falseif snapshot_kind == SNAPSHOT_KIND_DIRECTORY and snapshot_image is not None:- if not hasattr(sb, "mount_image"):+ # The mount REPLACES the target directory in the running sandbox — over a live+ # system path (the legacy "/tmp" default) that kills Modal's in-sandbox helpers,+ # and a snapshot's content only fits the path it was captured from. Last-line+ # guard for snapshot rows whose stored mount path bypassed normalization.+ if snapshot_mount_path not in ALLOWED_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATHS:+ logger.warning(+ "Refusing to mount directory snapshot at unsupported path; falling back to base image",+ extra={+ "snapshot_external_id": snapshot_external_id,+ "snapshot_mount_path": snapshot_mount_path,+ },+ )+ elif not hasattr(sb, "mount_image"):logger.warning("Modal sandbox does not support directory snapshot restore; falling back to base image",extra={diff --git a/products/tasks/backend/logic/services/test_modal_sandbox.py b/products/tasks/backend/logic/services/test_modal_sandbox.pyindex 08641dcb5083..3fe3d8d81ff0 100644--- a/products/tasks/backend/logic/services/test_modal_sandbox.py+++ b/products/tasks/backend/logic/services/test_modal_sandbox.py@@ -1,6 +1,7 @@import pytestfrom unittest.mock import MagicMock+from products.tasks.backend.constants import DEFAULT_SANDBOX_WORKING_DIR, SNAPSHOT_KIND_DIRECTORYfrom products.tasks.backend.logic.services.modal_sandbox import ModalSandboxfrom products.tasks.backend.logic.services.sandbox import SandboxConfig, SandboxTemplate@@ -37,3 +38,39 @@ class TestModalSandboxVmRuntime:assert "experimental_options" not in kwargselse:assert kwargs["experimental_options"] == expected_experimental_options+++class TestModalSandboxDirectorySnapshotMount:+ @pytest.mark.parametrize(+ "mount_path, expect_mounted",+ [+ (DEFAULT_SANDBOX_WORKING_DIR, True),+ # Legacy captures of the system temp dir: re-mounting replaces the live /tmp and+ # kills Modal's in-sandbox helpers — must never reach mount_image again.+ ("/tmp", False),+ # Upstream validation strips a disallowed path; the missing path must not be+ # re-defaulted into a mount of mismatched content.+ (None, False),+ ],+ )+ def test_directory_snapshot_mount_guard(self, patched_modal, mocker, mount_path, expect_mounted):+ snapshot_image = MagicMock()+ mocker.patch("modal.Image.from_id", return_value=snapshot_image)+ fake_sandbox = patched_modal.return_value++ sandbox = ModalSandbox.create(+ SandboxConfig(+ name="test",+ template=SandboxTemplate.DEFAULT_BASE,+ snapshot_external_id="im-dir",+ snapshot_kind=SNAPSHOT_KIND_DIRECTORY,+ snapshot_mount_path=mount_path,+ )+ )++ if expect_mounted:+ fake_sandbox.mount_image.assert_called_once_with(mount_path, snapshot_image)+ assert sandbox.config.snapshot_restored is True+ else:+ fake_sandbox.mount_image.assert_not_called()+ assert sandbox.config.snapshot_restored is Falsediff --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 1bc3e951d270..47f544267099 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@@ -123,10 +123,14 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandboused_snapshot = snapshot is not Nonesnapshot_lookup_timer.set_used_snapshot(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_path+ if not snapshot_metadata.is_usable:+ snapshot = None+ used_snapshot = False+ else:+ snapshot_source = "repository"+ 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")@@ -221,10 +225,18 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandbo# Check for resume snapshot (takes priority over integration-level snapshots)resume_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()+ if not run_state.resume_snapshot_is_usable():+ emit_agent_log(+ ctx.run_id,+ "debug",+ "Previous session snapshot is unusable; resuming with a fresh sandbox",+ )+ resume_snapshot_ext_id = None+ else:+ 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(diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex b402c8eed256..3ccb77aff35d 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -305,10 +305,14 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> Pused_snapshot = snapshot is not Nonesnapshot_lookup_timer.set_used_snapshot(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_path+ if not snapshot_metadata.is_usable:+ snapshot = None+ used_snapshot = False+ else:+ snapshot_source = "repository"+ 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")@@ -356,10 +360,18 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> P# 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()+ if not run_state.resume_snapshot_is_usable():+ emit_agent_log(+ ctx.run_id,+ "debug",+ "Previous session snapshot is unusable; resuming with a fresh sandbox",+ )+ resume_snapshot_external_id = None+ else:+ 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",diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.pyindex bd7dca2d96e8..f524bf46659e 100644--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py@@ -37,10 +37,18 @@ class TestRunStateSnapshotPaths(TestCase):{"snapshot_kind": SNAPSHOT_KIND_DIRECTORY, "snapshot_mount_path": DEFAULT_SANDBOX_WORKING_DIR},DEFAULT_SANDBOX_WORKING_DIR,),+ # A disallowed stored path invalidates the snapshot (None) — it must NOT be remapped+ # to the default: the snapshot's content layout only fits the path it was captured+ # from. "/tmp" is the legacy default whose re-mount killed the sandbox.+ (+ "legacy_tmp_directory_snapshot",+ {"snapshot_kind": SNAPSHOT_KIND_DIRECTORY, "snapshot_mount_path": "/tmp"},+ None,+ ),("unsupported_directory_snapshot_path",{"snapshot_kind": SNAPSHOT_KIND_DIRECTORY, "snapshot_mount_path": "/tmp/agent-env"},- DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH,+ None,),("filesystem_snapshot", {"snapshot_kind": "filesystem"}, None),]diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex 7c185491743b..72c5cc93b29a 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -16,8 +16,8 @@ from posthog.temporal.oauth import TOKEN_EXPIRATION_SECONDS, PosthogMcpScopes, hfrom products.mcp_store.backend.facade.api import get_active_installationsfrom products.tasks.backend.constants import (+ ALLOWED_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATHS,DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH,- DEFAULT_SANDBOX_WORKING_DIR,SNAPSHOT_KIND_DIRECTORY,SNAPSHOT_KIND_FILESYSTEM,InitialPermissionMode,@@ -33,13 +33,6 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)-_ALLOWED_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATHS = frozenset(- {- DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH,- DEFAULT_SANDBOX_WORKING_DIR,- }-)-class PrAuthorshipMode(StrEnum):USER = "user"@@ -224,17 +217,24 @@ def get_reasoning_effort_error()-def normalize_directory_resume_snapshot_mount_path(snapshot_mount_path: object) -> str:+def normalize_directory_resume_snapshot_mount_path(snapshot_mount_path: object) -> str | None:+ """Resolve where a directory resume snapshot may be mounted; ``None`` means "don't use it".++ A snapshot's content layout matches the path it was captured from, so a stored path outside+ the allowlist (notably the legacy "/tmp" default, whose mount replaced the live system temp+ dir and killed the sandbox) cannot be remapped to a safe path — the snapshot is unusable and+ the resume must fall back to a fresh sandbox.+ """if not snapshot_mount_path:return DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH- if isinstance(snapshot_mount_path, str) and snapshot_mount_path in _ALLOWED_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATHS:+ if isinstance(snapshot_mount_path, str) and snapshot_mount_path in ALLOWED_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATHS:return snapshot_mount_pathlogger.warning(- "Ignoring unsupported directory resume snapshot mount path",+ "Directory resume snapshot has an unsupported mount path; invalidating the snapshot",extra={"snapshot_mount_path": snapshot_mount_path},)- return DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH+ return Noneclass RunState(BaseModel, extra="allow"):@@ -275,6 +275,13 @@ class RunState(BaseModel, extra="allow"):return Nonereturn 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+ )+def parse_run_state(state: dict[str, Any] | None) -> RunState:return RunState.model_validate(state or {})@@ -285,6 +292,11 @@ class SnapshotMetadata:kind: SnapshotKindmount_path: str | None+ @property+ def 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)+def get_sandbox_snapshot_metadata(snapshot: SandboxSnapshot) -> SnapshotMetadata:kind: SnapshotKind = (diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex 43c6376a145b..27b9fdb50d48 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -221,6 +221,50 @@ class TestFacadeReadsAndMappers(TestCase):self.assertEqual(stale.status, TaskRun.Status.FAILED.value)self.assertEqual(stale.error_message, "boom")+ @parameterized.expand(+ [+ # A directory snapshot captured at a still-allowed path is carried into the new run.+ ("workspace_path", "/tmp/workspace", True),+ # A legacy "/tmp" capture is unusable (its content only fits that path, and mounting+ # over the live /tmp killed sandboxes) — resuming must drop it, not carry it forward+ # with the path stripped, or downstream defaulting would remount mismatched content.+ ("legacy_tmp_path", "/tmp", False),+ ]+ )+ def test_run_task_resume_carries_only_usable_directory_snapshots(+ self, _name: str, prior_mount_path: str, expect_carried: bool+ ):+ task = self._make_task()+ previous_run = TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.COMPLETED,+ state={+ "snapshot_external_id": "im-dir",+ "snapshot_kind": "directory",+ "snapshot_mount_path": prior_mount_path,+ },+ )++ with patch("products.tasks.backend.facade.api._trigger_task_processing_workflow"):+ result = facade.run_task(+ task.id,+ self.team.id,+ self.user.id,+ validated_data={"mode": "interactive", "resume_from_run_id": str(previous_run.id)},+ )++ assert result is not None and result.error is None+ new_run = task.runs.exclude(id=previous_run.id).get()+ if expect_carried:+ self.assertEqual(new_run.state.get("snapshot_external_id"), "im-dir")+ self.assertEqual(new_run.state.get("snapshot_kind"), "directory")+ self.assertEqual(new_run.state.get("snapshot_mount_path"), prior_mount_path)+ else:+ self.assertNotIn("snapshot_external_id", new_run.state)+ self.assertNotIn("snapshot_kind", new_run.state)+ self.assertNotIn("snapshot_mount_path", new_run.state)+def test_stale_queued_created_at_hard_cap(self):task = self._make_task()now = django_timezone.now()