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): stop transient Modal snapshot timeouts creating error issues (#65940)

posthog[bot]7c7238212c4b
diff --git a/products/tasks/backend/exceptions.py b/products/tasks/backend/exceptions.py
index b9b38084da48..8c81cac11e5b 100644
--- a/products/tasks/backend/exceptions.py
+++ b/products/tasks/backend/exceptions.py
@@ -6,12 +6,16 @@ from posthog.exceptions_capture import capture_exception
class ProcessTaskError(ApplicationError):
- def __init__(self, message: str, context: dict[str, Any], cause: Optional[Exception], **kwargs):
+ def __init__(
+ self, message: str, context: dict[str, Any], cause: Optional[BaseException], capture: bool = True, **kwargs
+ ):
self.context = context or {}
if "team" not in self.context:
self.context["team"] = "array"
- if cause is not None:
+ # `capture=False` skips error-tracking capture for expected, recoverable failures
+ # (e.g. transient infra timeouts that Temporal retries) so they don't create noisy issues.
+ if cause is not None and capture:
capture_exception(cause, self.context)
super().__init__(message, self.context, **kwargs)
@@ -27,7 +31,7 @@ class ProcessTaskFatalError(ProcessTaskError):
class ProcessTaskTransientError(ProcessTaskError):
"""Transient errors that may succeed on retry."""
- def __init__(self, message: str, context: dict[str, Any], cause: Exception, **kwargs):
+ def __init__(self, message: str, context: dict[str, Any], cause: BaseException, **kwargs):
super().__init__(message, context, cause, non_retryable=False, **kwargs)
@@ -93,6 +97,12 @@ class SnapshotCreationError(ProcessTaskTransientError):
pass
+class SnapshotTimeoutError(ProcessTaskTransientError):
+ """Transient timeout/connection error while creating a snapshot; safe to retry."""
+
+ pass
+
+
class RepositoryCloneError(ProcessTaskTransientError):
"""Failed to clone repository."""
diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.py
index 56a98208a6d3..c3cee1dad62c 100644
--- a/products/tasks/backend/logic/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -5,6 +5,7 @@ import time
import uuid
import shlex
import shutil
+import asyncio
import logging
import tempfile
import threading
@@ -23,6 +24,10 @@ if TYPE_CHECKING:
import modal
import requests
+from modal.exception import (
+ ConnectionError as ModalConnectionError,
+ TimeoutError as ModalTimeoutError,
+)
from posthog.exceptions_capture import capture_exception
from posthog.settings import CLOUD_DEPLOYMENT
@@ -35,6 +40,7 @@ from products.tasks.backend.exceptions import (
SandboxProvisionError,
SandboxTimeoutError,
SnapshotCreationError,
+ SnapshotTimeoutError,
)
from products.tasks.backend.logic.services.agentsh import (
AGENTSH_DAEMON_PORT,
@@ -86,6 +92,17 @@ SANDBOX_IMAGE = SANDBOX_BASE_IMAGE
AGENT_SERVER_PORT = 8080 # Modal connect tokens require port 8080
AGENT_SERVER_HEALTH_MAX_ATTEMPTS = 240
+# 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
+# Temporal should retry them rather than treating them as hard snapshot failures.
+TRANSIENT_SNAPSHOT_ERRORS: tuple[type[BaseException], ...] = (
+ ModalTimeoutError,
+ ModalConnectionError,
+ TimeoutError,
+ ConnectionError,
+ asyncio.CancelledError,
+)
+
SESSION_INIT_PROBE_HOSTS = (
"gateway.us.posthog.com",
"gateway.eu.posthog.com",
@@ -944,6 +961,17 @@ class ModalSandbox(SandboxBase):
return snapshot_id
+ 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.
+ logger.warning(f"Transient error creating snapshot for sandbox {self.id}, will retry: {e}")
+ raise SnapshotTimeoutError(
+ f"Transient error creating snapshot: {e}",
+ {"sandbox_id": self.id, "error": str(e)},
+ cause=e,
+ capture=False,
+ )
+
except Exception as e:
logger.exception(f"Failed to create snapshot: {e}")
raise SnapshotCreationError(
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 b7ef97024fbb..9a10c64cb8b9 100644
--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
@@ -1,11 +1,22 @@
+import asyncio
+import builtins
from typing import Any
import pytest
from unittest.mock import MagicMock, patch
+from modal.exception import (
+ ConnectionError as ModalConnectionError,
+ TimeoutError as ModalTimeoutError,
+)
from requests.exceptions import ConnectionError, Timeout
-from products.tasks.backend.exceptions import SandboxExecutionError, SandboxProvisionError
+from products.tasks.backend.exceptions import (
+ SandboxExecutionError,
+ SandboxProvisionError,
+ SnapshotCreationError,
+ SnapshotTimeoutError,
+)
from products.tasks.backend.logic.services.modal_provision_diagnostics import (
MAX_PROVISION_LOG_EXCERPT_LINES,
summarize_modal_output,
@@ -926,3 +937,57 @@ class TestResourceCreateKwargs:
kwargs = _resource_create_kwargs(config)
assert kwargs == {"cpu": (1.0, 1.0), "memory": (2048, 2048)}
+
+
+class TestModalSandboxCreateSnapshot:
+ @pytest.fixture
+ def mock_sandbox(self) -> Any:
+ mock_modal_sandbox = MagicMock()
+ mock_modal_sandbox.object_id = "test-sandbox-id"
+ mock_modal_sandbox.poll.return_value = None # None => still running
+
+ config = SandboxConfig(name="test-sandbox")
+ with patch.object(ModalSandbox, "_get_app_for_template", return_value=MagicMock()):
+ return ModalSandbox(sandbox=mock_modal_sandbox, config=config)
+
+ def test_create_snapshot_success(self, mock_sandbox: Any):
+ mock_sandbox._sandbox.snapshot_filesystem.return_value = MagicMock(object_id="im-123")
+
+ with patch("products.tasks.backend.exceptions.capture_exception") as capture_exception:
+ assert mock_sandbox.create_snapshot() == "im-123"
+
+ capture_exception.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "error",
+ [
+ ModalTimeoutError("Deadline exceeded"),
+ ModalConnectionError("connection reset"),
+ builtins.TimeoutError("timed out"),
+ builtins.ConnectionError("connection error"),
+ asyncio.CancelledError(),
+ ],
+ )
+ def test_transient_modal_errors_are_retryable_and_not_captured(self, mock_sandbox: Any, error: BaseException):
+ mock_sandbox._sandbox.snapshot_filesystem.side_effect = error
+
+ with (
+ patch("products.tasks.backend.exceptions.capture_exception") as capture_exception,
+ pytest.raises(SnapshotTimeoutError) as exc,
+ ):
+ mock_sandbox.create_snapshot()
+
+ # Transient timeouts must stay retryable (Temporal retries) and must not create error-tracking issues.
+ assert exc.value.non_retryable is False
+ capture_exception.assert_not_called()
+
+ def test_genuine_failure_raises_snapshot_creation_error_and_is_captured(self, mock_sandbox: Any):
+ mock_sandbox._sandbox.snapshot_filesystem.side_effect = RuntimeError("Failed to create image")
+
+ with (
+ patch("products.tasks.backend.exceptions.capture_exception") as capture_exception,
+ pytest.raises(SnapshotCreationError),
+ ):
+ mock_sandbox.create_snapshot()
+
+ capture_exception.assert_called_once()