: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): implement Modal readiness probe (#98054)
Charles Vieneb4bc4999eef
diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.mdindex 0caf5af022e2..e747a4b76531 100644--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md@@ -440,6 +440,19 @@ container traffic because their network paths differ.The `use_modal_vm_sandbox` run-state key force-selects the VM runtime for trusted server-created runs(image builders) and is never accepted from client input.+### Sandbox readiness++Every Modal sandbox is created with a [readiness probe](https://modal.com/docs/guide/sandboxes#readiness-probes) that runs `true` inside the sandbox until it exits 0.+Provisioning waits on that probe before it runs anything else in the sandbox, because a sandbox can come up dead with every RPC succeeding.+That happens most often after a filesystem snapshot restore: a resume snapshot, or the prebaked dev-stack image, which is itself a snapshot.+A sandbox whose probe has not passed within `READINESS_PROBE_TIMEOUT_SECONDS` (`products/tasks/backend/logic/services/modal_sandbox.py`) is terminated and recreated from the next image candidate in the downgrade chain: resume snapshot, then custom or dev-stack image, then the plain base.+Termination is retried, and provisioning fails when it still does not complete: the run stores only the id of the sandbox that `create()` returned, so a sandbox left running here is invisible to every later cleanup path.+A directory resume snapshot is mounted into the sandbox after the probe has passed, and Modal stops the probe at its first success.+Provisioning therefore runs one more `true` after that mount, and recreates the sandbox without the mount when it fails.+The run log records the full downgrade chain as "Sandbox image downgraded: ...", one entry per recreation.+The application log keeps a warning for every recreation.+When no candidate remains, provisioning fails with a transient error and Temporal retries the activity.+### Network accessNetwork access is configured per-team via `SandboxEnvironment`:diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.pyindex 073d422bf73e..e393e60a98e6 100644--- a/products/tasks/backend/logic/services/modal_sandbox.py+++ b/products/tasks/backend/logic/services/modal_sandbox.py@@ -135,7 +135,11 @@ SANDBOX_IMAGE = SANDBOX_BASE_IMAGE# which both mirror).SANDBOX_SLIM_NODE_MAJOR = 24SANDBOX_SLIM_UV_IMAGE = "ghcr.io/astral-sh/uv:0.12.13"-POST_RESTORE_PROBE_TIMEOUT_SECONDS = 45+READINESS_PROBE_INTERVAL_MS = 250+READINESS_PROBE_TIMEOUT_SECONDS = 45+POST_MOUNT_PROBE_TIMEOUT_SECONDS = 45+UNREADY_TERMINATE_MAX_ATTEMPTS = 3+UNREADY_TERMINATE_BACKOFF_BASE_SECONDS = 1.0# Recoverable infra errors Modal surfaces when filesystem snapshotting times out or loses its# connection (e.g. the command router's "Deadline exceeded"). These usually succeed on retry, so@@ -293,6 +297,13 @@ MODAL_REGION_BY_DEPLOYMENT: dict[str | None, str] = {DEFAULT_MODAL_REGION = "us-east"+def _sandbox_poll_result(sb: modal.Sandbox) -> str:+ try:+ return str(sb.poll())+ except Exception:+ return "unavailable"++def _get_modal_region() -> str:return MODAL_REGION_BY_DEPLOYMENT.get(CLOUD_DEPLOYMENT, DEFAULT_MODAL_REGION)@@ -448,10 +459,6 @@ class ImageCandidate:label: strrestored_from_snapshot: bool = Falsehas_dev_stack: bool = False- # The image is a Modal sandbox filesystem snapshot (a resume snapshot or the- # published dev-stack image), so a boot from it needs the post-create health probe —- # snapshot restores can come up dead with every RPC succeeding.- snapshot_derived: bool = Falsedef _merge_runtime_dependency_specs(name: str, existing: str, candidate: str) -> str:@@ -942,7 +949,6 @@ class ModalSandbox(AgentServerLaunchMixin):overlaid_snapshot,f"snapshot image {snapshot_external_id} with local package overlay",restored_from_snapshot=True,- snapshot_derived=True,has_dev_stack=requested_dev_stack,))@@ -951,21 +957,15 @@ class ModalSandbox(AgentServerLaunchMixin):snapshot_image,f"snapshot image {snapshot_external_id}",restored_from_snapshot=True,- snapshot_derived=True,has_dev_stack=requested_dev_stack,))if custom_image is not None and custom_image_bare is not None:- # The published dev-stack image is itself a sandbox filesystem snapshot- # (dockerd cannot run in the gVisor image builder), so booting it is the- # same restore the health probe guards; user custom images are spec-built.- custom_is_snapshot = config.custom_image_name == DEV_STACK_IMAGE_NAMEif custom_image is not custom_image_bare:candidates.append(ImageCandidate(custom_image,f"custom image {config.custom_image_name} with local package overlay",- snapshot_derived=custom_is_snapshot,has_dev_stack=requested_dev_stack,))@@ -973,7 +973,6 @@ class ModalSandbox(AgentServerLaunchMixin):ImageCandidate(custom_image_bare,f"custom image {config.custom_image_name}",- snapshot_derived=custom_is_snapshot,has_dev_stack=requested_dev_stack,))@@ -996,6 +995,7 @@ class ModalSandbox(AgentServerLaunchMixin):**_resource_create_kwargs(config),"region": region,"verbose": True,+ "readiness_probe": modal.Probe.with_exec("true", interval_ms=READINESS_PROBE_INTERVAL_MS),}if config.is_vm:@@ -1012,6 +1012,7 @@ class ModalSandbox(AgentServerLaunchMixin):sb, modal_output, winner = cls._create_from_image_candidates(create_kwargs, candidates, config)+ directory_mount_applied = Falseif snapshot_kind == SNAPSHOT_KIND_DIRECTORY and snapshot_image is not None:# 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,@@ -1037,21 +1038,21 @@ class ModalSandbox(AgentServerLaunchMixin):try:sb.mount_image(snapshot_mount_path, snapshot_image)config.snapshot_restored = True+ directory_mount_applied = Trueexcept Exception as e:logger.warning(f"Failed to mount directory snapshot image {snapshot_external_id} at {snapshot_mount_path}: {e}")capture_exception(e)- # A sandbox whose filesystem came out of a Modal snapshot restore can come up- # dead with every RPC succeeding — probe before use. That covers resume- # snapshots (image or directory mount) and the published dev-stack image,- # which is itself a sandbox filesystem snapshot; spec-built images boot- # normally and skip the probe. Loops because a recovery can land on another- # snapshot-derived tier (resume snapshot -> dev-stack image -> base).- while (config.snapshot_restored or winner.snapshot_derived) and not cls._is_healthy_after_restore(sb):+ # A sandbox can come up dead with every RPC succeeding, most often after a+ # filesystem snapshot restore: a resume snapshot, or the published dev-stack+ # image, which is itself a snapshot because dockerd cannot run in the gVisor+ # image builder. Loops because a recovery can land on another snapshot-derived+ # tier (resume snapshot -> dev-stack image -> base).+ while not cls._is_ready(sb, after_directory_mount=directory_mount_applied):logger.warning(- "Snapshot-restored sandbox is not executing processes; recreating from the remaining image candidates",+ "Sandbox never became ready; recreating from the remaining image candidates",extra={"sandbox_id": sb.object_id,"winner_label": winner.label,@@ -1060,11 +1061,8 @@ class ModalSandbox(AgentServerLaunchMixin):"snapshot_mount_path": snapshot_mount_path,},)- try:- sb.terminate()- except Exception as e:- logger.warning(f"Failed to terminate wedged sandbox {sb.object_id}: {e}")- if config.snapshot_restored and not winner.restored_from_snapshot:+ cls._terminate_unready_sandbox(sb, config)+ if directory_mount_applied:# The directory resume mount (not the image) wedged the sandbox:# recreate on the same chain and leave the mount off. The run loses# its resume state — exactly what the fallback message must say,@@ -1075,12 +1073,26 @@ class ModalSandbox(AgentServerLaunchMixin):)remaining = [c for c in candidates if not c.restored_from_snapshot]else:- # The winning image itself restored wedged: drop it and every tier+ # The winning image itself came up unready: drop it and every tier# above it, along with any resume-snapshot candidates.- wedged = f"{winner.label} (unresponsive after restore)"+ wedged = f"{winner.label} (never became ready)"remaining = [c for c in candidates[candidates.index(winner) + 1 :] if not c.restored_from_snapshot]+ if not remaining:+ raise SandboxProvisionError(+ "Sandbox never became ready and no image candidates remain",+ {"config_name": config.name, "sandbox_id": sb.object_id, "image": winner.label},+ cause=RuntimeError("readiness probe never passed"),+ )+ earlier_fallback: str | None = config.image_fallback+ # Cleared so the chain the recreate records for itself reads back+ # distinguishable: it names a tier this hop would otherwise skip over.+ config.image_fallback = Nonesb, modal_output, winner = cls._create_from_image_candidates(create_kwargs, remaining, config)- config.image_fallback = f"{wedged} -> {winner.label}"+ directory_mount_applied = False+ # Every hop stays in the string: the run log reads the field once, so an+ # overwrite would hide the dropped resume snapshot or package overlay.+ hop = f"{wedged} -> {config.image_fallback or winner.label}"+ config.image_fallback = f"{earlier_fallback}; {hop}" if earlier_fallback else hopif config.metadata:sb.set_tags(config.metadata)@@ -1105,6 +1117,10 @@ class ModalSandbox(AgentServerLaunchMixin):raiseexcept SandboxNetworkPolicyError:raise+ except SandboxProvisionError:+ # Already carries the failing image and sandbox id, and already captured its+ # cause — the wrapper below would send a second event with less context.+ raiseexcept Exception as e:logger.exception(f"Failed to create sandbox: {e}")raise SandboxProvisionError(@@ -1162,30 +1178,90 @@ class ModalSandbox(AgentServerLaunchMixin):)@staticmethod- def _is_healthy_after_restore(sb: modal.Sandbox) -> bool:- """Whether the sandbox executes processes after a snapshot restore (image or mount)."""+ def _terminate_unready_sandbox(sb: modal.Sandbox, config: SandboxConfig) -> None:+ """Terminate a sandbox the readiness probe rejected, retrying before giving up.++ The caller replaces the sandbox and drops its id, and ``process-task`` only records+ an id once ``create()`` has returned, so a sandbox still running here is invisible+ to every later cleanup path. Failing the provision costs one retry; leaking it bills+ until Modal's own timeout.+ """+ for attempt in range(1, UNREADY_TERMINATE_MAX_ATTEMPTS + 1):+ try:+ sb.terminate()+ return+ except Exception as e:+ logger.warning(+ f"Failed to terminate unready sandbox {sb.object_id} "+ f"(attempt {attempt}/{UNREADY_TERMINATE_MAX_ATTEMPTS}): {e}"+ )+ if attempt == UNREADY_TERMINATE_MAX_ATTEMPTS:+ raise SandboxProvisionError(+ "Failed to terminate an unready sandbox",+ {"config_name": config.name, "sandbox_id": sb.object_id},+ cause=e,+ ) from e+ time.sleep(UNREADY_TERMINATE_BACKOFF_BASE_SECONDS * (2 ** (attempt - 1)))++ @classmethod+ def _is_ready(cls, sb: modal.Sandbox, *, after_directory_mount: bool) -> bool:+ if not cls._wait_until_ready(sb):+ return False+ if not after_directory_mount:+ return True+ # Modal stops the probe at its first success and returns that state to every later+ # wait, so it cannot see a directory mount — applied to the running sandbox after+ # the probe passed — that left the sandbox unable to run commands.+ return cls._executes_processes(sb)++ @staticmethod+ def _executes_processes(sb: modal.Sandbox) -> bool:+ """Whether the sandbox still runs commands after a directory snapshot mount."""try:process = sb.exec("true", timeout=30)# ContainerProcess.wait() has no timeout and can hang on a wedged container.- deadline = time.monotonic() + POST_RESTORE_PROBE_TIMEOUT_SECONDS+ deadline = time.monotonic() + POST_MOUNT_PROBE_TIMEOUT_SECONDSwhile (returncode := process.poll()) is None:if time.monotonic() >= deadline:- logger.warning(f"Post-restore health probe timed out for sandbox {sb.object_id}")+ logger.warning(f"Post-mount probe timed out for sandbox {sb.object_id}")return Falsetime.sleep(1)except Exception as e:- _raise_if_proxy_failure(e, sb.object_id, "restore_probe")- logger.warning(f"Post-restore health probe errored for sandbox {sb.object_id}: {e}")+ _raise_if_proxy_failure(e, sb.object_id, "mount_probe")+ logger.warning(f"Post-mount probe errored for sandbox {sb.object_id}: {e}")return Falseif returncode != 0:- poll_result: int | str | None- try:- poll_result = sb.poll()- except Exception:- poll_result = "unavailable"logger.warning(- "Post-restore health probe exited non-zero",- extra={"sandbox_id": sb.object_id, "returncode": returncode, "sandbox_poll": str(poll_result)},+ "Post-mount probe exited non-zero",+ extra={+ "sandbox_id": sb.object_id,+ "returncode": returncode,+ "sandbox_poll": _sandbox_poll_result(sb),+ },+ )+ return False+ return True++ @staticmethod+ def _wait_until_ready(sb: modal.Sandbox) -> bool:+ """Modal keeps an unready sandbox running after the probe times out, so the caller terminates it."""+ try:+ sb.wait_until_ready(timeout=READINESS_PROBE_TIMEOUT_SECONDS)+ except ModalTimeoutError:+ logger.warning(+ "Sandbox readiness probe timed out",+ extra={+ "sandbox_id": sb.object_id,+ "timeout_seconds": READINESS_PROBE_TIMEOUT_SECONDS,+ "sandbox_poll": _sandbox_poll_result(sb),+ },+ )+ return False+ except Exception as e:+ _raise_if_proxy_failure(e, sb.object_id, "readiness_probe")+ logger.warning(+ "Sandbox readiness probe errored",+ extra={"sandbox_id": sb.object_id, "error": str(e), "sandbox_poll": _sandbox_poll_result(sb)},)return Falsereturn Truediff --git a/products/tasks/backend/logic/services/test_modal_sandbox.py b/products/tasks/backend/logic/services/test_modal_sandbox.pyindex 2a59f53dcf23..806dded6d22d 100644--- a/products/tasks/backend/logic/services/test_modal_sandbox.py+++ b/products/tasks/backend/logic/services/test_modal_sandbox.py@@ -4,6 +4,8 @@ from pathlib import Pathimport pytestfrom unittest.mock import MagicMock, patch+from modal.exception import TimeoutError as ModalTimeoutError+from products.tasks.backend.constants import (DEFAULT_SANDBOX_WORKING_DIR,SNAPSHOT_KIND_DIRECTORY,@@ -220,6 +222,7 @@ class TestModalSandboxDirectorySnapshotMount:snapshot_image = MagicMock()mocker.patch("modal.Image.from_id", return_value=snapshot_image)fake_sandbox = patched_modal.return_value+ # The post-mount probe runs a command in the mounted sandbox; let it pass.fake_sandbox.exec.return_value.poll.return_value = 0sandbox = ModalSandbox.create(@@ -245,7 +248,7 @@ class TestModalSandboxDirectorySnapshotMount:mocker.patch("modal.Image.from_id", return_value=snapshot_image)wedged = MagicMock()wedged.object_id = "sb-wedged"- wedged.exec.return_value.poll.return_value = 137+ wedged.wait_until_ready.side_effect = ModalTimeoutError("readiness probe timed out")fresh = MagicMock()fresh.object_id = "sb-fresh"patched_modal.side_effect = [wedged, fresh]diff --git a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.pyindex aa358450b3dd..f7f0a73bec25 100644--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py@@ -11,6 +11,7 @@ from unittest.mock import MagicMock, patchfrom django.test import override_settings+from modal import Probefrom modal.exception import (ConnectionError as ModalConnectionError,InvalidError as ModalInvalidError,@@ -61,8 +62,11 @@ from products.tasks.backend.logic.services.modal_sandbox import (DIRECTORY_SNAPSHOT_TIMEOUT_SECONDS,FILESYSTEM_SNAPSHOT_TIMEOUT_SECONDS,PUBLISHED_IMAGE_SNAPSHOT_TIMEOUT_SECONDS,+ READINESS_PROBE_INTERVAL_MS,+ READINESS_PROBE_TIMEOUT_SECONDS,RUNNING_STATUS_CACHE_SECONDS,SANDBOX_IMAGE,+ UNREADY_TERMINATE_MAX_ATTEMPTS,ModalSandbox,_attach_local_package_mounts,_get_modal_region,@@ -1584,6 +1588,15 @@ class TestModalSandboxCreateAllowlist:assert mock_create.call_args.kwargs["experimental_options"] == {"vm_runtime": True}+ def test_create_attaches_an_exec_readiness_probe_and_waits_on_it(self):+ # Modal raises on wait_until_ready when no probe was attached, so the two must stay paired.+ mock_create = self._create_with_config(SandboxConfig(name="t"))++ assert mock_create.call_args.kwargs["readiness_probe"] == Probe.with_exec(+ "true", interval_ms=READINESS_PROBE_INTERVAL_MS+ )+ mock_create.return_value.wait_until_ready.assert_called_once_with(timeout=READINESS_PROBE_TIMEOUT_SECONDS)+class TestModalSandboxCreateImageFallback:"""A failed create with an overlaid image must downgrade one step at a time (bare@@ -1593,8 +1606,6 @@ class TestModalSandboxCreateImageFallback:def _create_failing_on(self, config: SandboxConfig, *, failing_image: Any, loaded_image: Any) -> tuple[Any, list]:mock_sb = MagicMock()mock_sb.object_id = "sb-created"- # A snapshot-restored sandbox is health-probed after create; make the probe pass.- mock_sb.exec.return_value.poll.return_value = 0images_tried: list[Any] = []def sandbox_create(**kwargs: Any) -> Any:@@ -1663,7 +1674,6 @@ class TestModalSandboxCreateImageFallback:return original_create(**kwargs)original_create.return_value.object_id = "sb-created"- original_create.return_value.exec.return_value.poll.return_value = 0with (patch("products.tasks.backend.logic.services.modal_sandbox.modal.enable_output"),patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock()),@@ -1746,7 +1756,7 @@ class TestModalSandboxCreateImageFallback:):ModalSandbox.create(config)- assert len(attempts) == 3+ assert len(attempts) == 2assert all(attempt["experimental_options"] == {"vm_runtime": True} for attempt in attempts)assert all(attempt["outbound_domain_allowlist"] == ["example.com", "*.posthog.com"] for attempt in attempts)@@ -1795,20 +1805,26 @@ class TestModalSandboxCreateImageFallback:assert attempts[0]["outbound_domain_allowlist"] == ["example.com"]assert attempts[0]["experimental_options"] == {"vm_runtime": True}- def _create_with_probe(+ def _create_with_readiness(self,config: SandboxConfig,*,- probe: Any,+ ready: list[bool],snapshot_image: Any,custom_image: Any,+ executes: list[bool] | None = None,) -> tuple[Any, list]:images_tried: list[Any] = []+ outcomes = iter(ready)+ exec_outcomes = iter(executes or [])def sandbox_create(**kwargs: Any) -> Any:images_tried.append(kwargs["image"])sb = MagicMock()sb.object_id = f"sb-{len(images_tried)}"+ if not next(outcomes, True):+ sb.wait_until_ready.side_effect = ModalTimeoutError("readiness probe timed out")+ sb.exec.return_value.poll.return_value = 0 if next(exec_outcomes, True) else 137return sbwith (@@ -1833,7 +1849,6 @@ class TestModalSandboxCreateImageFallback:patch("products.tasks.backend.logic.services.modal_sandbox.modal.Sandbox.create", side_effect=sandbox_create),- probe,):sandbox = ModalSandbox.create(config)return sandbox, images_tried@@ -1851,10 +1866,10 @@ class TestModalSandboxCreateImageFallback:snapshot_image = MagicMock(name="snapshot_image")custom_image = MagicMock(name="custom_image")- sandbox, images_tried = self._create_with_probe(+ sandbox, images_tried = self._create_with_readiness(config,- # Snapshot restore wedged; the recovered dev-stack boot probes healthy.- probe=patch.object(ModalSandbox, "_is_healthy_after_restore", side_effect=[False, True]),+ # Snapshot restore wedged; the recovered dev-stack boot becomes ready.+ ready=[False, True],snapshot_image=snapshot_image,custom_image=custom_image,)@@ -1862,7 +1877,7 @@ class TestModalSandboxCreateImageFallback:assert images_tried == [snapshot_image, custom_image]assert sandbox.config.snapshot_restored is Falseassert sandbox.config.image_fallback is not None- assert "snapshot image im-snap-1 (unresponsive after restore)" in sandbox.config.image_fallback+ assert "snapshot image im-snap-1 (never became ready)" in sandbox.config.image_fallbackassert "custom image posthog-dev-stack" in sandbox.config.image_fallbackdef test_wedged_dev_stack_boot_is_probed_and_falls_back_to_base(self):@@ -1872,9 +1887,9 @@ class TestModalSandboxCreateImageFallback:config = SandboxConfig(name="t", template=SandboxTemplate.VM_BASE, custom_image_name="posthog-dev-stack")custom_image = MagicMock(name="custom_image")- sandbox, images_tried = self._create_with_probe(+ sandbox, images_tried = self._create_with_readiness(config,- probe=patch.object(ModalSandbox, "_is_healthy_after_restore", side_effect=[False]),+ ready=[False],snapshot_image=MagicMock(name="unused_snapshot"),custom_image=custom_image,)@@ -1882,26 +1897,153 @@ class TestModalSandboxCreateImageFallback:assert len(images_tried) == 2 # dev-stack image, then baseassert images_tried[0] is custom_imageassert sandbox.config.image_fallback is not None- assert "custom image posthog-dev-stack (unresponsive after restore)" in sandbox.config.image_fallback+ assert "custom image posthog-dev-stack (never became ready)" in sandbox.config.image_fallbackassert "base image" in sandbox.config.image_fallback- def test_spec_built_custom_images_are_not_probed(self):- # User custom images are spec-built, not snapshot restores — probing them would- # add a health-check roundtrip (and its flake surface) to every custom-image run.+ def test_unready_spec_built_custom_image_falls_back_to_base(self):config = SandboxConfig(name="t", template=SandboxTemplate.VM_BASE, custom_image_name="posthog-sandbox-custom-2-abc:latest")- probe_mock = MagicMock()+ custom_image = MagicMock(name="custom_image")- _, images_tried = self._create_with_probe(+ sandbox, images_tried = self._create_with_readiness(config,- probe=patch.object(ModalSandbox, "_is_healthy_after_restore", probe_mock),+ ready=[False],snapshot_image=MagicMock(name="unused_snapshot"),+ custom_image=custom_image,+ )++ assert len(images_tried) == 2+ assert images_tried[0] is custom_image+ assert sandbox.config.image_fallback is not None+ assert "custom image posthog-sandbox-custom-2-abc:latest (never became ready)" in sandbox.config.image_fallback+ assert "base image" in sandbox.config.image_fallback++ def test_every_readiness_downgrade_stays_on_the_fallback_chain(self):+ # The run log reads image_fallback once, so a second downgrade that overwrote the+ # first would hide which snapshot or overlay the run lost.+ config = SandboxConfig(+ name="t",+ template=SandboxTemplate.VM_BASE,+ custom_image_name="posthog-dev-stack",+ snapshot_external_id="im-snap-1",+ )++ sandbox, images_tried = self._create_with_readiness(+ config,+ ready=[False, False, True],+ snapshot_image=MagicMock(name="snapshot_image"),custom_image=MagicMock(name="custom_image"),)- assert len(images_tried) == 1- probe_mock.assert_not_called()+ assert len(images_tried) == 3+ assert sandbox.config.image_fallback is not None+ assert "snapshot image im-snap-1 (never became ready) -> custom image posthog-dev-stack" in (+ sandbox.config.image_fallback+ )+ assert "custom image posthog-dev-stack (never became ready) -> base image" in sandbox.config.image_fallback++ def test_unready_base_image_is_terminated_and_provisioning_fails(self):+ mock_sb = MagicMock()+ mock_sb.object_id = "sb-dead"+ mock_sb.wait_until_ready.side_effect = ModalTimeoutError("readiness probe timed out")++ with (+ patch("products.tasks.backend.logic.services.modal_sandbox.modal.enable_output"),+ patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock()),+ patch("products.tasks.backend.logic.services.modal_sandbox._get_template_image", return_value=MagicMock()),+ patch("products.tasks.backend.logic.services.modal_sandbox.modal.Sandbox.create", return_value=mock_sb),+ patch("products.tasks.backend.exceptions.capture_exception"),+ ):+ with pytest.raises(SandboxProvisionError) as error:+ ModalSandbox.create(SandboxConfig(name="t"))++ mock_sb.terminate.assert_called_once()+ assert error.value.non_retryable is False++ def test_unready_sandbox_that_refuses_to_terminate_fails_the_provision(self):+ # process-task only records a sandbox id once create() has returned, so an unready+ # sandbox we could not terminate is invisible to every later cleanup path. Failing+ # beats recovering onto the next image and leaving the old one billing.+ mock_sb = MagicMock()+ mock_sb.object_id = "sb-stuck"+ mock_sb.wait_until_ready.side_effect = ModalTimeoutError("readiness probe timed out")+ mock_sb.terminate.side_effect = ModalServiceError("terminate failed")++ with (+ patch("products.tasks.backend.logic.services.modal_sandbox.modal.enable_output"),+ patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock()),+ patch("products.tasks.backend.logic.services.modal_sandbox._get_template_image", return_value=MagicMock()),+ patch(+ "products.tasks.backend.logic.services.modal_sandbox.modal.Image.from_name",+ return_value=MagicMock(name="custom_image"),+ ),+ patch(+ "products.tasks.backend.logic.services.modal_sandbox._attach_local_package_mounts",+ side_effect=lambda image, template, **kwargs: image,+ ),+ patch("products.tasks.backend.logic.services.modal_sandbox.modal.Sandbox.create", return_value=mock_sb),+ patch("products.tasks.backend.logic.services.modal_sandbox.time.sleep"),+ patch("products.tasks.backend.exceptions.capture_exception"),+ ):+ with pytest.raises(SandboxProvisionError) as error:+ ModalSandbox.create(+ SandboxConfig(name="t", template=SandboxTemplate.VM_BASE, custom_image_name="posthog-dev-stack")+ )++ assert mock_sb.terminate.call_count == UNREADY_TERMINATE_MAX_ATTEMPTS+ assert "Failed to terminate an unready sandbox" in str(error.value)++ def test_create_failure_inside_the_recovery_stays_on_the_fallback_chain(self):+ # The recovery re-enters the image chain, which records its own downgrade on+ # image_fallback. Overwriting that hides the tier the recovery tried and failed on,+ # leaving the run log naming a hop that never happened.+ config = SandboxConfig(+ name="t",+ template=SandboxTemplate.VM_BASE,+ custom_image_name="posthog-dev-stack",+ snapshot_external_id="im-snap-1",+ )+ snapshot_image = MagicMock(name="snapshot_image")+ custom_image = MagicMock(name="custom_image")+ base_image = MagicMock(name="base_image")+ images_tried: list[Any] = []++ def sandbox_create(**kwargs: Any) -> Any:+ images_tried.append(kwargs["image"])+ if len(images_tried) == 2:+ raise ModalServiceError("custom image unavailable")+ sb = MagicMock()+ sb.object_id = f"sb-{len(images_tried)}"+ if len(images_tried) == 1:+ sb.wait_until_ready.side_effect = ModalTimeoutError("readiness probe timed out")+ return sb++ with (+ patch("products.tasks.backend.logic.services.modal_sandbox.modal.enable_output"),+ patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock()),+ patch("products.tasks.backend.logic.services.modal_sandbox._get_template_image", return_value=base_image),+ patch(+ "products.tasks.backend.logic.services.modal_sandbox.modal.Image.from_name", return_value=custom_image+ ),+ patch(+ "products.tasks.backend.logic.services.modal_sandbox.modal.Image.from_id", return_value=snapshot_image+ ),+ patch(+ "products.tasks.backend.logic.services.modal_sandbox._attach_local_package_mounts",+ side_effect=lambda image, template, **kwargs: image,+ ),+ patch(+ "products.tasks.backend.logic.services.modal_sandbox.modal.Sandbox.create", side_effect=sandbox_create+ ),+ patch("products.tasks.backend.exceptions.capture_exception"),+ ):+ sandbox = ModalSandbox.create(config)++ assert images_tried == [snapshot_image, custom_image, base_image]+ assert sandbox.config.image_fallback == (+ "snapshot image im-snap-1 (never became ready) -> custom image posthog-dev-stack -> base image"+ )def test_wedged_directory_mount_recovers_on_same_image_and_names_the_mount(self):# A directory resume that wedges the sandbox never changed the boot image — the@@ -1917,10 +2059,10 @@ class TestModalSandboxCreateImageFallback:)custom_image = MagicMock(name="custom_image")- sandbox, images_tried = self._create_with_probe(+ sandbox, images_tried = self._create_with_readiness(config,- # Mounted sandbox wedged; the recreated (mount-free) one probes healthy.- probe=patch.object(ModalSandbox, "_is_healthy_after_restore", side_effect=[False, True]),+ # Mounted sandbox wedged; the recreated (mount-free) one becomes ready.+ ready=[False, True],snapshot_image=MagicMock(name="snapshot_image"),custom_image=custom_image,)@@ -1977,10 +2119,10 @@ class TestModalSandboxCreateImageFallback:assert error.next_retry_delay is not Noneassert len(images_tried) == (0 if shed_call == "app_lookup" else 1)- def test_proxy_rate_limit_in_the_restore_probe_terminates_the_restored_sandbox(self):+ def test_proxy_rate_limit_in_the_readiness_probe_terminates_the_restored_sandbox(self):config = SandboxConfig(name="t", snapshot_external_id="im-snap-1")restored = MagicMock(object_id="sb-restored")- restored.exec.side_effect = _socks_rate_limit()+ restored.wait_until_ready.side_effect = _socks_rate_limit()images_tried: list[Any] = []def sandbox_create(**kwargs: Any) -> Any:@@ -1991,10 +2133,37 @@ class TestModalSandboxCreateImageFallback:config, app_lookup=MagicMock(return_value=MagicMock()), sandbox_create=sandbox_create)- assert error.context["operation"] == "restore_probe"+ assert error.context["operation"] == "readiness_probe"assert len(images_tried) == 1restored.terminate.assert_called_once()+ def test_directory_mount_that_stops_execution_drops_the_mount(self):+ # Modal stops the readiness probe at its first success, so the probe reports on the+ # boot that came before the mount. Only a fresh exec sees a mount that wedged the+ # sandbox, which is the failure the mount fallback exists for.+ config = SandboxConfig(+ name="t",+ template=SandboxTemplate.VM_BASE,+ custom_image_name="posthog-dev-stack",+ snapshot_external_id="im-snap-1",+ snapshot_kind=SNAPSHOT_KIND_DIRECTORY,+ snapshot_mount_path=DEFAULT_SANDBOX_WORKING_DIR,+ )+ custom_image = MagicMock(name="custom_image")++ sandbox, images_tried = self._create_with_readiness(+ config,+ ready=[True, True],+ executes=[False, True],+ snapshot_image=MagicMock(name="snapshot_image"),+ custom_image=custom_image,+ )++ assert images_tried == [custom_image, custom_image]+ assert sandbox.config.snapshot_restored is False+ assert sandbox.config.image_fallback is not None+ assert "resume state dropped" in sandbox.config.image_fallback+class TestLaunchDevStackBootstrap:def _sandbox(