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(cloud-agent): fail closed on sandbox image digest resolution (#58985)

Alessandro Pogliaghiea9e76d23270
diff --git a/products/tasks/backend/services/modal_sandbox.py b/products/tasks/backend/services/modal_sandbox.py
index a07afd32a97a..acd8862ab013 100644
--- a/products/tasks/backend/services/modal_sandbox.py
+++ b/products/tasks/backend/services/modal_sandbox.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
+import time
import uuid
import shlex
import shutil
@@ -97,44 +98,91 @@ _image_ref_cache: TTLCache = TTLCache(maxsize=2, ttl=300)
_image_ref_lock = threading.Lock()
+# Modal caches images by reference indefinitely. Falling back to the mutable
+# `:master` tag therefore lets Modal keep serving a stale or broken image
+# (e.g. one missing /scripts/node_modules/.bin/agent-server) forever, so we
+# retry transient GHCR failures and otherwise fail closed.
+_GHCR_RESOLVE_MAX_ATTEMPTS = 4
+_GHCR_RESOLVE_BACKOFF_BASE_SECONDS = 1.0
+
+
+class _ImageDigestResolutionError(Exception):
+ """A single attempt to resolve the GHCR digest failed."""
+
+
+def _resolve_image_digest_once(image: str) -> str:
+ """Resolve ``image:master`` to an immutable ``image@sha256:...`` reference.
+
+ Raises ``_ImageDigestResolutionError`` for non-200 responses or missing
+ fields; network-level exceptions (``ConnectionError``, ``Timeout``, etc.)
+ propagate as-is. The caller catches ``Exception`` in all cases, so we never
+ fall back to the mutable ``:master`` tag.
+ """
+ image_repo = image.replace("ghcr.io/", "")
+
+ token_resp = requests.get(
+ f"https://ghcr.io/token?service=ghcr.io&scope=repository:{image_repo}:pull",
+ timeout=10,
+ )
+ if token_resp.status_code != 200:
+ raise _ImageDigestResolutionError(f"GHCR token request failed: status={token_resp.status_code}")
+
+ token = token_resp.json().get("token")
+ if not token:
+ raise _ImageDigestResolutionError("GHCR token response missing token field")
+
+ manifest_resp = requests.get(
+ f"https://ghcr.io/v2/{image_repo}/manifests/master",
+ headers={
+ "Accept": "application/vnd.oci.image.index.v1+json",
+ "Authorization": f"Bearer {token}",
+ },
+ timeout=10,
+ )
+ if manifest_resp.status_code != 200:
+ raise _ImageDigestResolutionError(f"GHCR manifest request failed: status={manifest_resp.status_code}")
+
+ digest = manifest_resp.headers.get("Docker-Content-Digest")
+ if not digest:
+ raise _ImageDigestResolutionError("GHCR manifest response missing Docker-Content-Digest header")
+
+ return f"{image}@{digest}"
+
+
@cached(cache=_image_ref_cache, lock=_image_ref_lock)
def _get_sandbox_image_reference(image: str = SANDBOX_IMAGE) -> str:
- """Modal caches sandbox images indefinitely. This function resolves the digest of the master tag
- so Modal fetches the correct version. Re-resolves from GHCR every ~5 minutes.
+ """Resolve the sandbox image to an immutable digest pin.
+
+ Modal caches sandbox images by reference indefinitely, so a mutable
+ ``:master`` tag would let Modal keep serving a stale or broken image. We
+ therefore retry transient GHCR failures with exponential backoff and, if
+ resolution still fails, fail closed by raising ``SandboxProvisionError``
+ (transient — the provisioning activity retries) rather than ever returning
+ the floating tag. Successful resolutions are cached for ~5 minutes;
+ failures are not cached and re-resolve on the next call.
"""
- image_repo = image.replace("ghcr.io/", "")
- try:
- token_resp = requests.get(
- f"https://ghcr.io/token?service=ghcr.io&scope=repository:{image_repo}:pull",
- timeout=10,
- )
- if token_resp.status_code != 200:
- logger.warning(f"Failed to get GHCR token: status={token_resp.status_code}")
- return f"{image}:master"
-
- token = token_resp.json().get("token")
- if not token:
- logger.warning("GHCR token response missing token field")
- return f"{image}:master"
-
- manifest_resp = requests.get(
- f"https://ghcr.io/v2/{image_repo}/manifests/master",
- headers={
- "Accept": "application/vnd.oci.image.index.v1+json",
- "Authorization": f"Bearer {token}",
- },
- timeout=10,
- )
- if manifest_resp.status_code == 200:
- digest = manifest_resp.headers.get("Docker-Content-Digest")
- if digest:
- logger.info(f"Resolved sandbox image digest for {image_repo}: {digest}")
- return f"{image}@{digest}"
- logger.warning(f"Failed to get sandbox image digest: status={manifest_resp.status_code}")
- except Exception as e:
- logger.warning(f"Failed to fetch sandbox image digest: {e}")
-
- return f"{image}:master"
+ last_error: Exception | None = None
+ for attempt in range(1, _GHCR_RESOLVE_MAX_ATTEMPTS + 1):
+ try:
+ reference = _resolve_image_digest_once(image)
+ logger.info(f"Resolved sandbox image digest for {image} on attempt {attempt}: {reference}")
+ return reference
+ except Exception as e:
+ last_error = e
+ logger.warning(
+ f"Failed to resolve sandbox image digest for {image} "
+ f"(attempt {attempt}/{_GHCR_RESOLVE_MAX_ATTEMPTS}): {e}"
+ )
+ if attempt < _GHCR_RESOLVE_MAX_ATTEMPTS:
+ time.sleep(_GHCR_RESOLVE_BACKOFF_BASE_SECONDS * (2 ** (attempt - 1)))
+
+ raise SandboxProvisionError(
+ f"Could not resolve an immutable digest for {image}:master after "
+ f"{_GHCR_RESOLVE_MAX_ATTEMPTS} attempts; refusing to fall back to the mutable "
+ f":master tag because Modal caches images by reference indefinitely",
+ {"image": image},
+ cause=last_error if last_error is not None else RuntimeError("digest resolution failed"),
+ )
def _attach_local_package_mounts(image: modal.Image, template: SandboxTemplate) -> modal.Image:
diff --git a/products/tasks/backend/services/tests/test_modal_sandbox.py b/products/tasks/backend/services/tests/test_modal_sandbox.py
index 9bad62cbf72f..66f3ee8275f0 100644
--- a/products/tasks/backend/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/services/tests/test_modal_sandbox.py
@@ -10,6 +10,7 @@ from products.tasks.backend.services.modal_provision_diagnostics import (
summarize_modal_output,
)
from products.tasks.backend.services.modal_sandbox import (
+ _GHCR_RESOLVE_MAX_ATTEMPTS,
AGENT_SERVER_PORT,
DEFAULT_MODAL_REGION,
SANDBOX_IMAGE,
@@ -19,7 +20,7 @@ from products.tasks.backend.services.modal_sandbox import (
_image_ref_cache,
)
from products.tasks.backend.services.sandbox import AgentServerResult, ExecutionResult, SandboxConfig
-from products.tasks.backend.temporal.exceptions import SandboxExecutionError
+from products.tasks.backend.temporal.exceptions import SandboxExecutionError, SandboxProvisionError
def _mock_token_response(status_code: int = 200, token: str | None = "test-token"):
@@ -36,10 +37,38 @@ def _mock_manifest_response(status_code: int = 200, digest: str | None = "sha256
return resp
+def _ghcr_side_effect(
+ token_resp: Any = None,
+ manifest_resp: Any = None,
+ token_exc: Exception | None = None,
+ manifest_exc: Exception | None = None,
+):
+ """Build a `requests.get` side effect that answers token vs manifest calls
+ consistently no matter how many times it is called, so the test stays valid
+ regardless of the (bounded) `_GHCR_RESOLVE_MAX_ATTEMPTS` retry cap.
+ """
+
+ def _side(url: str, *args: Any, **kwargs: Any) -> Any:
+ if "/token" in url:
+ if token_exc is not None:
+ raise token_exc
+ return token_resp
+ if manifest_exc is not None:
+ raise manifest_exc
+ return manifest_resp
+
+ return _side
+
+
class TestGetSandboxImageReference:
def setup_method(self):
_image_ref_cache.clear()
+ @pytest.fixture(autouse=True)
+ def _no_backoff_sleep(self):
+ with patch("products.tasks.backend.services.modal_sandbox.time.sleep"):
+ yield
+
def test_returns_digest_reference_on_success(self):
with patch(
"products.tasks.backend.services.modal_sandbox.requests.get",
@@ -50,42 +79,46 @@ class TestGetSandboxImageReference:
assert result == f"{SANDBOX_IMAGE}@sha256:abc123"
@pytest.mark.parametrize("status_code", [401, 403, 404, 500, 502, 503])
- def test_falls_back_to_master_on_token_request_failure(self, status_code: int):
+ def test_fails_closed_on_token_request_failure(self, status_code: int):
with patch(
"products.tasks.backend.services.modal_sandbox.requests.get",
return_value=_mock_token_response(status_code=status_code),
- ):
- result = _get_sandbox_image_reference()
+ ) as mock_get:
+ with pytest.raises(SandboxProvisionError, match="refusing to fall back to the mutable"):
+ _get_sandbox_image_reference()
- assert result == f"{SANDBOX_IMAGE}:master"
+ assert mock_get.call_count == _GHCR_RESOLVE_MAX_ATTEMPTS
- def test_falls_back_to_master_when_token_missing(self):
+ def test_fails_closed_when_token_missing(self):
with patch(
"products.tasks.backend.services.modal_sandbox.requests.get",
return_value=_mock_token_response(token=None),
):
- result = _get_sandbox_image_reference()
-
- assert result == f"{SANDBOX_IMAGE}:master"
+ with pytest.raises(SandboxProvisionError):
+ _get_sandbox_image_reference()
@pytest.mark.parametrize("status_code", [401, 403, 404, 500, 502, 503])
- def test_falls_back_to_master_on_manifest_request_failure(self, status_code: int):
+ def test_fails_closed_on_manifest_request_failure(self, status_code: int):
with patch(
"products.tasks.backend.services.modal_sandbox.requests.get",
- side_effect=[_mock_token_response(), _mock_manifest_response(status_code=status_code)],
+ side_effect=_ghcr_side_effect(
+ token_resp=_mock_token_response(),
+ manifest_resp=_mock_manifest_response(status_code=status_code),
+ ),
):
- result = _get_sandbox_image_reference()
+ with pytest.raises(SandboxProvisionError):
+ _get_sandbox_image_reference()
- assert result == f"{SANDBOX_IMAGE}:master"
-
- def test_falls_back_to_master_when_digest_header_missing(self):
+ def test_fails_closed_when_digest_header_missing(self):
with patch(
"products.tasks.backend.services.modal_sandbox.requests.get",
- side_effect=[_mock_token_response(), _mock_manifest_response(digest=None)],
+ side_effect=_ghcr_side_effect(
+ token_resp=_mock_token_response(),
+ manifest_resp=_mock_manifest_response(digest=None),
+ ),
):
- result = _get_sandbox_image_reference()
-
- assert result == f"{SANDBOX_IMAGE}:master"
+ with pytest.raises(SandboxProvisionError):
+ _get_sandbox_image_reference()
@pytest.mark.parametrize(
"exception",
@@ -95,14 +128,50 @@ class TestGetSandboxImageReference:
Exception("Unknown error"),
],
)
- def test_falls_back_to_master_on_request_exception(self, exception: Exception):
+ def test_fails_closed_on_request_exception(self, exception: Exception):
with patch(
"products.tasks.backend.services.modal_sandbox.requests.get",
side_effect=exception,
+ ):
+ with pytest.raises(SandboxProvisionError):
+ _get_sandbox_image_reference()
+
+ def test_retries_transient_failure_then_succeeds(self):
+ attempts = {"token": 0}
+
+ def _side(url: str, *args: Any, **kwargs: Any) -> Any:
+ if "/token" in url:
+ attempts["token"] += 1
+ if attempts["token"] == 1:
+ return _mock_token_response(status_code=503)
+ return _mock_token_response()
+ return _mock_manifest_response(digest="sha256:recovered")
+
+ with patch(
+ "products.tasks.backend.services.modal_sandbox.requests.get",
+ side_effect=_side,
+ ):
+ result = _get_sandbox_image_reference()
+
+ assert result == f"{SANDBOX_IMAGE}@sha256:recovered"
+ assert attempts["token"] == 2 # failed once, succeeded on retry
+
+ def test_failure_is_not_cached(self):
+ """A failed resolution must re-attempt on the next call (never cache the failure)."""
+ with patch(
+ "products.tasks.backend.services.modal_sandbox.requests.get",
+ return_value=_mock_token_response(status_code=503),
+ ):
+ with pytest.raises(SandboxProvisionError):
+ _get_sandbox_image_reference()
+
+ with patch(
+ "products.tasks.backend.services.modal_sandbox.requests.get",
+ side_effect=[_mock_token_response(), _mock_manifest_response(digest="sha256:after")],
):
result = _get_sandbox_image_reference()
- assert result == f"{SANDBOX_IMAGE}:master"
+ assert result == f"{SANDBOX_IMAGE}@sha256:after"
def test_caches_result_across_calls(self):
with patch(