: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
chore(sandbox): Add TTL to sandbox image digest cache (#57611)
Vojta Bartoš3921f3ceab9a
diff --git a/products/tasks/backend/services/modal_sandbox.py b/products/tasks/backend/services/modal_sandbox.pyindex 9e5c973114bc..197cbcc25ee0 100644--- a/products/tasks/backend/services/modal_sandbox.py+++ b/products/tasks/backend/services/modal_sandbox.py@@ -6,6 +6,7 @@ import shleximport shutilimport loggingimport tempfile+import threadingfrom collections.abc import Iterablefrom functools import lru_cachefrom io import StringIO@@ -14,6 +15,8 @@ from typing import TYPE_CHECKING, Any, castfrom django.conf import settings+from cachetools import TTLCache, cached+if TYPE_CHECKING:from products.tasks.backend.temporal.process_task.utils import McpServerConfig@@ -90,10 +93,14 @@ LOCAL_MODAL_DOCKERFILES = {LOCAL_MODAL_INSTALL_SKILLS_SCRIPT = Path("products/tasks/backend/sandbox/images/install-skills.sh")-@lru_cache(maxsize=2)+_image_ref_cache: TTLCache = TTLCache(maxsize=2, ttl=300)+_image_ref_lock = threading.Lock()+++@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. Queries GHCR once per deployment.+ so Modal fetches the correct version. Re-resolves from GHCR every ~5 minutes."""image_repo = image.replace("ghcr.io/", "")try:@@ -152,7 +159,11 @@ def _attach_local_package_mounts(image: modal.Image, template: SandboxTemplate)return image-@lru_cache(maxsize=2)+_template_image_cache: TTLCache = TTLCache(maxsize=2, ttl=300)+_template_image_lock = threading.Lock()+++@cached(cache=_template_image_cache, lock=_template_image_lock)def _get_template_image(template: SandboxTemplate) -> modal.Image:registry_image = {SandboxTemplate.DEFAULT_BASE: SANDBOX_BASE_IMAGE,diff --git a/products/tasks/backend/services/tests/test_modal_sandbox.py b/products/tasks/backend/services/tests/test_modal_sandbox.pyindex df519dafc931..4594cb4b6cfc 100644--- a/products/tasks/backend/services/tests/test_modal_sandbox.py+++ b/products/tasks/backend/services/tests/test_modal_sandbox.py@@ -16,6 +16,7 @@ from products.tasks.backend.services.modal_sandbox import (ModalSandbox,_get_modal_region,_get_sandbox_image_reference,+ _image_ref_cache,)from products.tasks.backend.services.sandbox import AgentServerResult, ExecutionResult, SandboxConfigfrom products.tasks.backend.temporal.exceptions import SandboxExecutionError@@ -37,7 +38,7 @@ def _mock_manifest_response(status_code: int = 200, digest: str | None = "sha256class TestGetSandboxImageReference:def setup_method(self):- _get_sandbox_image_reference.cache_clear()+ _image_ref_cache.clear()def test_returns_digest_reference_on_success(self):with patch(@@ -115,10 +116,31 @@ class TestGetSandboxImageReference:assert result1 == result2 == result3 == f"{SANDBOX_IMAGE}@sha256:cached123"assert mock_get.call_count == 2 # token + manifest, called only once due to cache+ def test_re_resolves_after_cache_expiry(self):+ """After TTL expiry (simulated via clear), a fresh GHCR query picks up the new digest."""+ with patch(+ "products.tasks.backend.services.modal_sandbox.requests.get",+ side_effect=[+ _mock_token_response(),+ _mock_manifest_response(digest="sha256:old"),+ _mock_token_response(),+ _mock_manifest_response(digest="sha256:new"),+ ],+ ) as mock_get:+ result1 = _get_sandbox_image_reference()+ assert result1 == f"{SANDBOX_IMAGE}@sha256:old"+ assert mock_get.call_count == 2++ _image_ref_cache.clear()++ result2 = _get_sandbox_image_reference()+ assert result2 == f"{SANDBOX_IMAGE}@sha256:new"+ assert mock_get.call_count == 4+class TestGetSandboxImageReferenceIntegration:def setup_method(self):- _get_sandbox_image_reference.cache_clear()+ _image_ref_cache.clear()@pytest.mark.xfail(reason="Flaky: depends on GHCR availability. Remove this mark when we've figured out a less flaky approach"