Skip to content

: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.

fix(tasks): classify Modal's 1M-file snapshot cap and prune-retry (#79345)

posthog[bot]2b5c47159465
diff --git a/products/tasks/backend/exceptions.py b/products/tasks/backend/exceptions.py
index e84415614b02..0b254b6b43b9 100644
--- a/products/tasks/backend/exceptions.py
+++ b/products/tasks/backend/exceptions.py
@@ -160,6 +160,22 @@ class SnapshotTimeoutError(ProcessTaskTransientError):
pass
+class SnapshotFileLimitExceededError(ProcessTaskFatalError):
+ """Modal refuses to snapshot a directory/filesystem holding more than its hard file-count
+ cap (1,000,000 files). This is a permanent limit, not a transient blip, so retrying the same
+ snapshot cannot succeed — the caller must shrink the tree (prune node_modules, virtualenvs,
+ and package caches) before it can snapshot.
+
+ Non-retryable and captured to error tracking: it is a named, classified condition (not the
+ generic mystery issue this replaced), and callers with no fallback — the dev-stack image bake,
+ the standalone snapshot activity — need it visible. The resume path recovers by pruning and
+ letting Temporal retry, so it converts this into a transient error itself rather than swallowing
+ the signal.
+ """
+
+ pass
+
+
class RepositoryCloneError(ProcessTaskTransientError):
"""Failed to clone repository."""
diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.py
index df108a9c879d..77e36016c597 100644
--- a/products/tasks/backend/logic/services/docker_sandbox.py
+++ b/products/tasks/backend/logic/services/docker_sandbox.py
@@ -1165,6 +1165,11 @@ class DockerSandbox(SandboxBase):
def create_directory_snapshot(self, path: str) -> str:
return self.create_snapshot()
+ def prune_snapshot_heavy_dirs(self, path: str) -> None:
+ # Docker snapshots the whole container image, not a directory subtree, so there is no
+ # targeted prune to do here (and local dev never approaches Modal's file-count cap).
+ return None
+
@staticmethod
def 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.py
index 62e1e06e2550..0d0cab00fa79 100644
--- a/products/tasks/backend/logic/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -28,6 +28,7 @@ import modal
import requests
from modal.exception import (
ConnectionError as ModalConnectionError,
+ ResourceExhaustedError as ModalResourceExhaustedError,
ServiceError as ModalServiceError,
TimeoutError as ModalTimeoutError,
)
@@ -52,6 +53,7 @@ from products.tasks.backend.exceptions import (
SandboxProvisionError,
SandboxTimeoutError,
SnapshotCreationError,
+ SnapshotFileLimitExceededError,
SnapshotTimeoutError,
)
from products.tasks.backend.logic.services.agentsh import (
@@ -133,6 +135,34 @@ TRANSIENT_SNAPSHOT_ERRORS: tuple[type[BaseException], ...] = (
DIRECTORY_SNAPSHOT_TIMEOUT_SECONDS = 240
+# Heavy, reproducible directories to prune before retrying a snapshot that hit Modal's
+# 1M-file cap. Each is a package cache or install tree the resume sandbox rebuilds, so
+# dropping them shrinks the file count without losing the run's own work.
+SNAPSHOT_PRUNE_DIR_NAMES = (
+ "node_modules",
+ ".venv",
+ "venv",
+ "__pycache__",
+ ".pnpm-store",
+ ".cache",
+ ".pytest_cache",
+ ".mypy_cache",
+)
+SNAPSHOT_PRUNE_TIMEOUT_SECONDS = 90
+
+
+def _is_snapshot_file_cap_error(error: BaseException) -> bool:
+ """Whether Modal's ``ResourceExhaustedError`` is the permanent >1M-file snapshot cap
+ rather than a generic (retryable) quota/rate-limit ``RESOURCE_EXHAUSTED``.
+
+ ``ResourceExhaustedError`` is Modal's generic gRPC RESOURCE_EXHAUSTED wrapper, so we
+ key on the file-count message ("... snapshot contains more than 1000000 files") to avoid
+ classifying a transient quota/rate-limit blip as a permanent, non-retryable failure.
+ """
+ message = str(error).lower()
+ return "snapshot" in message and "more than" in message and "file" in message
+
+
# Modal's snapshot_filesystem default timeout is 55s, which multi-GB sandbox filesystems
# routinely exceed. The default fits the standalone snapshot activity's 10-minute budget;
# resume snapshots run under a 5-minute activity budget and pass a tighter per-call
@@ -1507,6 +1537,27 @@ class ModalSandbox(SandboxBase):
logger.info(f"Created snapshot for sandbox {self.id}, snapshot ID: {image.object_id}")
return image.object_id
+ except ModalResourceExhaustedError as e:
+ if _is_snapshot_file_cap_error(e):
+ # Modal rejects a snapshot whose tree exceeds its hard 1M-file cap. Permanent, not
+ # transient: classify it separately so it neither retries forever nor mints a generic
+ # captured issue.
+ logger.warning(f"Filesystem snapshot for sandbox {self.id} exceeds Modal's file-count cap: {e}")
+ raise SnapshotFileLimitExceededError(
+ f"Filesystem snapshot exceeds Modal's file-count cap: {e}",
+ {**error_context, "error": str(e)},
+ cause=e,
+ )
+ # A generic RESOURCE_EXHAUSTED (server-side quota / rate limit) is transient — let the
+ # caller's retry recover it instead of failing permanently.
+ logger.warning(f"Transient resource-exhausted error creating snapshot for sandbox {self.id}: {e}")
+ raise SnapshotTimeoutError(
+ f"Transient resource-exhausted error creating snapshot: {e}",
+ {**error_context, "error": str(e)},
+ cause=e,
+ capture=False,
+ )
+
except TRANSIENT_SNAPSHOT_ERRORS as e:
# Transient Modal infra timeout — Temporal retries the activity, so log at warning and
# skip error-tracking capture to avoid a fresh issue for every recoverable deadline.
@@ -1527,6 +1578,22 @@ class ModalSandbox(SandboxBase):
timeout_seconds=timeout_seconds if timeout_seconds is not None else FILESYSTEM_SNAPSHOT_TIMEOUT_SECONDS
)
+ def prune_snapshot_heavy_dirs(self, path: str) -> None:
+ """Delete reproducible package/cache trees under ``path`` so a later snapshot fits under
+ Modal's file-count cap. Best-effort: a failure here must not crash the caller — a partial
+ prune may already have shrunk the tree enough, and the caller decides what to do next.
+ """
+ quoted_path = shlex.quote(path)
+ name_predicate = " -o ".join(f"-name {shlex.quote(name)}" for name in SNAPSHOT_PRUNE_DIR_NAMES)
+ prune_command = (
+ f"find {quoted_path} -type d \\( {name_predicate} \\) -prune -exec rm -rf {{}} + 2>/dev/null || true"
+ )
+ try:
+ self.execute(prune_command, timeout_seconds=SNAPSHOT_PRUNE_TIMEOUT_SECONDS)
+ logger.info(f"Pruned heavy directories under {path} for sandbox {self.id}")
+ except Exception as e:
+ logger.warning(f"Best-effort prune of heavy directories under {path} failed for sandbox {self.id}: {e}")
+
def create_directory_snapshot(self, path: str) -> str:
if not self.is_running():
raise SandboxNotRunningError(
@@ -1553,6 +1620,27 @@ class ModalSandbox(SandboxBase):
return snapshot_id
+ except ModalResourceExhaustedError as e:
+ if _is_snapshot_file_cap_error(e):
+ # Modal rejects a snapshot whose tree exceeds its hard 1M-file cap. This is permanent,
+ # not transient — retrying the same tree cannot succeed — so classify it separately
+ # (the caller prunes the tree and retries) instead of misclassifying it as a generic error.
+ logger.warning(f"Directory snapshot for sandbox {self.id} exceeds Modal's file-count cap: {e}")
+ raise SnapshotFileLimitExceededError(
+ f"Directory snapshot exceeds Modal's file-count cap: {e}",
+ {"sandbox_id": self.id, "path": path, "error": str(e)},
+ cause=e,
+ )
+ # A generic RESOURCE_EXHAUSTED (server-side quota / rate limit) is transient — let the
+ # caller's retry recover it instead of failing permanently.
+ logger.warning(f"Transient resource-exhausted error creating directory snapshot for sandbox {self.id}: {e}")
+ raise SnapshotTimeoutError(
+ f"Transient resource-exhausted error creating directory snapshot: {e}",
+ {"sandbox_id": self.id, "path": path, "error": str(e)},
+ cause=e,
+ capture=False,
+ )
+
except TRANSIENT_SNAPSHOT_ERRORS as e:
logger.warning(f"Transient error creating directory snapshot for sandbox {self.id}, will retry: {e}")
raise SnapshotTimeoutError(
diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.py
index 9343e3e9a858..c1f25cafa5cd 100644
--- a/products/tasks/backend/logic/services/sandbox.py
+++ b/products/tasks/backend/logic/services/sandbox.py
@@ -471,6 +471,9 @@ class SandboxBase(ABC):
@abstractmethod
def create_directory_snapshot(self, path: str) -> str: ...
+ @abstractmethod
+ def prune_snapshot_heavy_dirs(self, path: str) -> None: ...
+
@abstractmethod
def destroy(self) -> None: ...
diff --git a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
index c3c251da90f5..48bd456473b7 100644
--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
@@ -12,6 +12,7 @@ from django.test import override_settings
from modal.exception import (
ConnectionError as ModalConnectionError,
+ ResourceExhaustedError as ModalResourceExhaustedError,
ServiceError as ModalServiceError,
TimeoutError as ModalTimeoutError,
)
@@ -22,6 +23,7 @@ from products.tasks.backend.exceptions import (
SandboxExecutionError,
SandboxProvisionError,
SnapshotCreationError,
+ SnapshotFileLimitExceededError,
SnapshotTimeoutError,
)
from products.tasks.backend.logic.services.local_packages import LocalPackage
@@ -834,6 +836,52 @@ class TestModalSandboxAgentServer:
assert result == "snapshot-456"
mock_sandbox._sandbox.snapshot_filesystem.assert_called_once_with(timeout=240, ttl=None)
+ def _trigger_snapshot(self, mock_sandbox: Any, snapshot_method: str, error: Exception) -> None:
+ mock_sandbox._sandbox.snapshot_directory.side_effect = error
+ mock_sandbox._sandbox.snapshot_filesystem.side_effect = error
+ if snapshot_method == "create_directory_snapshot":
+ mock_sandbox.create_directory_snapshot(DEFAULT_SANDBOX_WORKING_DIR)
+ else:
+ mock_sandbox.create_snapshot()
+
+ @pytest.mark.parametrize("snapshot_method", ["create_directory_snapshot", "create_snapshot"])
+ def test_snapshot_over_file_cap_raises_classified_error(self, mock_sandbox: Any, snapshot_method: str) -> None:
+ # Modal's 1M-file cap is permanent, not transient: it must surface as the classified,
+ # non-retryable error rather than a generic captured SnapshotCreationError.
+ cap_error = ModalResourceExhaustedError("filesystem snapshot contains more than 1000000 files")
+
+ with pytest.raises(SnapshotFileLimitExceededError) as exc:
+ self._trigger_snapshot(mock_sandbox, snapshot_method, cap_error)
+
+ assert exc.value.non_retryable is True
+
+ @pytest.mark.parametrize("snapshot_method", ["create_directory_snapshot", "create_snapshot"])
+ def test_generic_resource_exhausted_is_transient_not_file_cap(
+ self, mock_sandbox: Any, snapshot_method: str
+ ) -> None:
+ # A generic quota/rate-limit RESOURCE_EXHAUSTED must stay retryable, not be misclassified
+ # as the permanent file-count cap.
+ quota_error = ModalResourceExhaustedError("resource quota exceeded, please try again later")
+
+ with pytest.raises(SnapshotTimeoutError):
+ self._trigger_snapshot(mock_sandbox, snapshot_method, quota_error)
+
+ def test_prune_snapshot_heavy_dirs_targets_reproducible_trees(self, mock_sandbox: Any) -> None:
+ with patch.object(ModalSandbox, "execute") as execute:
+ mock_sandbox.prune_snapshot_heavy_dirs(DEFAULT_SANDBOX_WORKING_DIR)
+
+ prune_command = execute.call_args_list[0].args[0]
+ assert "node_modules" in prune_command
+ assert ".venv" in prune_command
+ assert DEFAULT_SANDBOX_WORKING_DIR in prune_command
+
+ def test_prune_snapshot_heavy_dirs_is_best_effort(self, mock_sandbox: Any) -> None:
+ # A failed or timed-out prune must not raise — the caller decides what to do next.
+ with patch.object(
+ ModalSandbox, "execute", side_effect=SandboxExecutionError("prune timed out", {}, cause=RuntimeError())
+ ):
+ mock_sandbox.prune_snapshot_heavy_dirs(DEFAULT_SANDBOX_WORKING_DIR)
+
class TestModalSandboxProvisionDiagnostics:
@pytest.mark.parametrize(
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.py
index edf586c4eec7..f432e9feef26 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
@@ -12,7 +12,11 @@ from products.tasks.backend.constants import (
SNAPSHOT_KIND_FILESYSTEM,
SnapshotKind,
)
-from products.tasks.backend.exceptions import SandboxNotRunningError, SnapshotTimeoutError
+from products.tasks.backend.exceptions import (
+ SandboxNotRunningError,
+ SnapshotFileLimitExceededError,
+ SnapshotTimeoutError,
+)
from products.tasks.backend.logic.services.sandbox import get_sandbox_class
from products.tasks.backend.models import TaskRun
from products.tasks.backend.temporal.metrics import increment_snapshot_create, record_snapshot_create_latency_ms
@@ -88,6 +92,41 @@ def create_resume_snapshot(input: CreateResumeSnapshotInput) -> CreateResumeSnap
external_id = sandbox.create_directory_snapshot(snapshot_mount_path)
else:
external_id = sandbox.create_snapshot(timeout_seconds=RESUME_SNAPSHOT_TIMEOUT_SECONDS)
+ except SnapshotFileLimitExceededError as e:
+ # Modal caps snapshots at 1M files and a directory snapshot of the workspace can exceed it
+ # once install trees and caches pile up. Only the directory snapshot has a mount path to
+ # shrink; a full filesystem snapshot does not, so it degrades to a fresh start.
+ if snapshot_kind != SNAPSHOT_KIND_DIRECTORY:
+ outcome = "file_limit_exceeded"
+ logger.warning("create_resume_snapshot_file_limit_exceeded", sandbox_id=input.sandbox_id, error=str(e))
+ increment_snapshot_create(snapshot_kind, outcome)
+ record_snapshot_create_latency_ms(snapshot_kind, outcome, int((time.perf_counter() - started_at) * 1000))
+ return CreateResumeSnapshotOutput(external_id=None, snapshot_kind=snapshot_kind, error=str(e))
+
+ # Prune the reproducible trees (node_modules, virtualenvs, caches) in the live sandbox,
+ # then let Temporal retry the whole activity: the next attempt snapshots the now-smaller
+ # tree in a fresh 5-minute budget. Doing the prune here and re-raising a transient error —
+ # rather than snapshotting again inline — keeps each attempt to a single snapshot, so the
+ # activity's timeout can't pre-empt the recovery. If pruning does not bring the tree under
+ # the cap, retries exhaust and both callers treat the failed snapshot as non-fatal (the run
+ # starts fresh). The resume sandbox reinstalls the pruned trees, so this costs a reinstall.
+ outcome = "file_limit_exceeded_pruned"
+ logger.warning(
+ "create_resume_snapshot_file_limit_exceeded_pruning",
+ sandbox_id=input.sandbox_id,
+ error=str(e),
+ )
+ sandbox.prune_snapshot_heavy_dirs(snapshot_mount_path)
+ increment_snapshot_create(snapshot_kind, outcome)
+ record_snapshot_create_latency_ms(snapshot_kind, outcome, int((time.perf_counter() - started_at) * 1000))
+ # capture=False: the original SnapshotFileLimitExceededError already carried the signal;
+ # this transient wrapper only drives the Temporal retry.
+ raise SnapshotTimeoutError(
+ f"Pruned workspace over Modal's file-count cap; retrying snapshot: {e}",
+ {"sandbox_id": input.sandbox_id, "snapshot_mount_path": snapshot_mount_path},
+ cause=e,
+ capture=False,
+ )
except SnapshotTimeoutError as e:
outcome = "transient_error"
logger.warning("create_resume_snapshot_transient_error", sandbox_id=input.sandbox_id, error=str(e))
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.py
index 918895996add..50924ec5cd8d 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_create_resume_snapshot.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_create_resume_snapshot.py
@@ -3,7 +3,7 @@ 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.exceptions import SnapshotTimeoutError
+from products.tasks.backend.exceptions import SnapshotFileLimitExceededError, SnapshotTimeoutError
from products.tasks.backend.models import TaskRun
from products.tasks.backend.temporal.process_task.activities.create_resume_snapshot import (
CreateResumeSnapshotInput,
@@ -77,3 +77,69 @@ def test_transient_snapshot_error_propagates_so_temporal_retries(activity_enviro
)
update_state.assert_not_called()
+
+
+def _file_limit_error() -> SnapshotFileLimitExceededError:
+ return SnapshotFileLimitExceededError(
+ "Directory snapshot exceeds Modal's file-count cap",
+ {"sandbox_id": "sandbox-1", "path": DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH},
+ cause=RuntimeError("filesystem snapshot contains more than 1000000 files"),
+ )
+
+
+def test_directory_file_limit_prunes_and_retries_via_temporal(activity_environment, mocker) -> None:
+ # A directory snapshot over the cap prunes the live sandbox and re-raises a transient error so
+ # Temporal retries the whole activity on the shrunk tree — a single snapshot per attempt keeps
+ # the recovery inside the activity's timeout budget.
+ sandbox = mocker.Mock()
+ sandbox.is_running.return_value = True
+ sandbox.create_directory_snapshot.side_effect = _file_limit_error()
+ SandboxClass = mocker.Mock()
+ SandboxClass.get_by_id.return_value = sandbox
+
+ mocker.patch(
+ "products.tasks.backend.temporal.process_task.activities.create_resume_snapshot.get_sandbox_class",
+ return_value=SandboxClass,
+ )
+ update_state = mocker.patch.object(TaskRun, "update_state_atomic")
+
+ with pytest.raises(SnapshotTimeoutError):
+ async_to_sync(activity_environment.run)(
+ create_resume_snapshot,
+ CreateResumeSnapshotInput(sandbox_id="sandbox-1", run_id="run-1", use_directory_snapshot=True),
+ )
+
+ sandbox.prune_snapshot_heavy_dirs.assert_called_once_with(DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH)
+ update_state.assert_not_called()
+
+
+def test_filesystem_file_limit_degrades_to_fresh_start(activity_environment, mocker) -> None:
+ # A full filesystem snapshot has no mount path to prune, so it degrades gracefully rather than
+ # crashing or looping retries.
+ sandbox = mocker.Mock()
+ sandbox.is_running.return_value = True
+ sandbox.create_snapshot.side_effect = SnapshotFileLimitExceededError(
+ "Filesystem snapshot exceeds Modal's file-count cap",
+ {"sandbox_id": "sandbox-1"},
+ cause=RuntimeError("filesystem snapshot contains more than 1000000 files"),
+ )
+ 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=False),
+ )
+
+ assert output.external_id is None
+ assert output.error is not None
+ sandbox.prune_snapshot_heavy_dirs.assert_not_called()
+ update_state.assert_not_called()