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 sandbox gateway errors as retryable, not issues (#100421)

posthog[bot]316a42ca8107
diff --git a/posthog/temporal/common/posthog_client.py b/posthog/temporal/common/posthog_client.py
index 4f4c8331ead0..8e9bb9bb207d 100644
--- a/posthog/temporal/common/posthog_client.py
+++ b/posthog/temporal/common/posthog_client.py
@@ -34,7 +34,14 @@ logger = get_write_only_logger()
# "AIFeaturesCloudOnly" is raised by the AI observability guard on non-cloud deployments (see
# posthog/temporal/ai_observability/llm_endpoint.py). It reflects the deployment, not a defect.
EXPECTED_CONTROL_FLOW_ERROR_TYPES = frozenset(
- {"trace_not_settled", "TransientRepartitionError", "EmbeddingServiceUnavailable", "AIFeaturesCloudOnly"}
+ {
+ "trace_not_settled",
+ "TransientRepartitionError",
+ "EmbeddingServiceUnavailable",
+ "AIFeaturesCloudOnly",
+ "SandboxRateLimitedError",
+ "SandboxControlPlaneUnavailableError",
+ }
)
diff --git a/products/tasks/backend/exceptions.py b/products/tasks/backend/exceptions.py
index e36573e91507..b4a8df8ccfba 100644
--- a/products/tasks/backend/exceptions.py
+++ b/products/tasks/backend/exceptions.py
@@ -144,11 +144,16 @@ class SandboxExecutionError(ProcessTaskTransientError):
pass
-class SandboxRateLimitedError(SandboxExecutionError):
- """The egress proxy in front of the sandbox control plane shed the call."""
+class SandboxControlPlaneError(SandboxExecutionError):
+ """The sandbox control plane refused or failed a call, before the sandbox itself saw it.
- def __init__(self, message: str, context: dict[str, Any]):
- attempt = activity.info().attempt if activity.in_activity() else 1
+ The fault belongs to the control plane, not to the run, so these stay retryable and are
+ never captured to error tracking. Capturing one mints an issue nobody can act on, and a
+ fresh one per provider message: the cause is constructed rather than raised, so every
+ occurrence carries its own synthesized traceback and none of them group.
+ """
+
+ def __init__(self, message: str, context: dict[str, Any], retry_delay: Optional[timedelta] = None):
ProcessTaskError.__init__(
self,
message,
@@ -156,10 +161,29 @@ class SandboxRateLimitedError(SandboxExecutionError):
None,
capture=False,
non_retryable=False,
- next_retry_delay=timedelta(seconds=sandbox_rate_limit_retry_delay(attempt)),
+ next_retry_delay=retry_delay,
)
+class SandboxRateLimitedError(SandboxControlPlaneError):
+ """The egress proxy in front of the sandbox control plane shed the call.
+
+ Backs off past the limit window so the retry lands after it rather than inside it.
+ """
+
+ def __init__(self, message: str, context: dict[str, Any]):
+ attempt = activity.info().attempt if activity.in_activity() else 1
+ super().__init__(message, context, retry_delay=timedelta(seconds=sandbox_rate_limit_retry_delay(attempt)))
+
+
+class SandboxControlPlaneUnavailableError(SandboxControlPlaneError):
+ """The sandbox control plane answered a call with a gateway status (5xx).
+
+ The activity's own retry policy is the right backoff here. Unlike a rate limit there is
+ no window to wait out, so this does not set a delay of its own.
+ """
+
+
class SandboxMissingRepositoryError(ProcessTaskFatalError):
"""The repository directory the agent-server needs as its cwd is absent from the sandbox.
diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.py
index 57eb1e13b7b9..fee2483aa626 100644
--- a/products/tasks/backend/logic/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import re
import json
import time
import uuid
@@ -13,9 +14,10 @@ import threading
from collections.abc import Iterable
from dataclasses import dataclass
from functools import lru_cache
+from http import HTTPStatus
from io import StringIO
from pathlib import Path
-from typing import Any, NoReturn, cast
+from typing import Any, Literal, NoReturn, cast
from django.conf import settings
@@ -44,6 +46,8 @@ from products.tasks.backend.constants import (
)
from products.tasks.backend.exceptions import (
SandboxCleanupError,
+ SandboxControlPlaneError,
+ SandboxControlPlaneUnavailableError,
SandboxExecutionError,
SandboxNetworkPolicyError,
SandboxNotFoundError,
@@ -139,35 +143,85 @@ TRANSIENT_SNAPSHOT_ERRORS: tuple[type[BaseException], ...] = (
DIRECTORY_SNAPSHOT_TIMEOUT_SECONDS = 240
-PROXY_RATE_LIMIT_MARKERS = ("429", "too many requests")
+PROXY_RATE_LIMIT_MARKERS = ("too many requests",)
+PROXY_UNAVAILABLE_MARKERS = ("bad gateway", "service unavailable", "gateway timeout")
PROXY_ERROR_TYPES: tuple[type[BaseException], ...] = (SocksProxyError, requests.exceptions.ProxyError)
_MAX_PROXY_ERROR_CHAIN_DEPTH = 10
+# The proxy answers a refused CONNECT with a bare status line ("502 Bad gateway"), which
+# python_socks re-raises verbatim. This runs against every exception in the chain, not just the
+# proxy types, because the wrapper a gateway status arrives in is not guaranteed to be one of
+# them. To make that safe it matches the whole message and bounds the reason phrase to the three
+# words a real one takes at most, so provider prose that merely opens with a number ("500 lines
+# of output were truncated") is not read as a control-plane failure. A status buried inside a
+# longer message is left to `error_code` or the markers below.
+_PROXY_STATUS_LINE = re.compile(r"\s*(\d{3})\s+[A-Za-z]+(?: [A-Za-z]+){0,2}\s*")
+# A proxy error wraps the CONNECT reply in its own prose ("Tunnel connection failed: 500
+# Internal Server Error"), so the status has to be read out of the middle of the message.
+_EMBEDDED_PROXY_STATUS = re.compile(r"\b([45]\d{2})\b")
+
+ControlPlaneFailure = Literal["rate_limited", "unavailable"]
RUNNING_STATUS_CACHE_SECONDS = 10.0
-def _is_proxy_rate_limit(error: BaseException) -> bool:
+def _classify_control_plane_failure(error: BaseException) -> ControlPlaneFailure | None:
+ """Classify one error as a refusal by the control plane, reading its status where it has one.
+
+ python_socks re-raises a non-200 CONNECT reply as ``ProxyError(error_code=<status>)``, so
+ the status is structured. ``requests`` proxy errors carry it in the message only.
+ """
+ message = str(error)
+ status = getattr(error, "error_code", None)
+ if not isinstance(status, int) and isinstance(error, PROXY_ERROR_TYPES):
+ status_line = _PROXY_STATUS_LINE.fullmatch(message)
+ status = int(status_line.group(1)) if status_line else None
+ # A proxy error only ever wraps a CONNECT reply, never command output, so its message is
+ # safe to search for a status the wrapper did not expose structurally.
+ if status is None and isinstance(error, PROXY_ERROR_TYPES):
+ embedded = _EMBEDDED_PROXY_STATUS.search(message)
+ status = int(embedded.group(1)) if embedded else None
+
+ if status == HTTPStatus.TOO_MANY_REQUESTS:
+ return "rate_limited"
+ if status is not None and 500 <= status < 600:
+ return "unavailable"
+ # A proxy that names the reason but not the status.
+ if isinstance(error, PROXY_ERROR_TYPES):
+ folded = message.casefold()
+ if any(marker in folded for marker in PROXY_RATE_LIMIT_MARKERS):
+ return "rate_limited"
+ if any(marker in folded for marker in PROXY_UNAVAILABLE_MARKERS):
+ return "unavailable"
+ return None
+
+
+def _classify_control_plane_failure_chain(error: BaseException) -> ControlPlaneFailure | None:
seen: set[int] = set()
current: BaseException | None = error
for _ in range(_MAX_PROXY_ERROR_CHAIN_DEPTH):
if current is None or id(current) in seen:
- return False
+ return None
seen.add(id(current))
- if isinstance(current, PROXY_ERROR_TYPES):
- message = str(current).casefold()
- if any(marker in message for marker in PROXY_RATE_LIMIT_MARKERS):
- return True
+ failure = _classify_control_plane_failure(current)
+ if failure is not None:
+ return failure
current = current.__cause__ or current.__context__
- return False
+ return None
+
+def _raise_if_proxy_failure(error: BaseException, sandbox_id: str | None, operation: str) -> None:
+ """Re-raise a control-plane refusal as the matching retryable, uncaptured error.
-def _raise_if_proxy_rate_limited(error: BaseException, sandbox_id: str | None, operation: str) -> None:
- if not _is_proxy_rate_limit(error):
+ Returns without raising when the failure is not the control plane's, so the caller's own
+ classification still runs.
+ """
+ failure = _classify_control_plane_failure_chain(error)
+ if failure is None:
return
- raise SandboxRateLimitedError(
- "Sandbox control plane is rate limited",
- {"sandbox_id": sandbox_id, "operation": operation},
- ) from error
+ context = {"sandbox_id": sandbox_id, "operation": operation}
+ if failure == "rate_limited":
+ raise SandboxRateLimitedError("Sandbox control plane is rate limited", context) from error
+ raise SandboxControlPlaneUnavailableError("Sandbox control plane is unavailable", context) from error
# Heavy, reproducible directories to prune before retrying a snapshot that hit Modal's
@@ -733,12 +787,13 @@ class ModalSandbox(AgentServerLaunchMixin):
@classmethod
def create(cls, config: SandboxConfig) -> ModalSandbox:
+ sb: modal.Sandbox | None = None
try:
modal.enable_output()
try:
app = cls._get_app_for_config(config)
except Exception as e:
- _raise_if_proxy_rate_limited(e, None, "lookup")
+ _raise_if_proxy_failure(e, None, "lookup")
raise
base_image = _get_template_image(config.template)
custom_image_bare: modal.Image | None = None
@@ -959,7 +1014,14 @@ class ModalSandbox(AgentServerLaunchMixin):
return sandbox
- except (SandboxNetworkPolicyError, SandboxRateLimitedError):
+ except SandboxControlPlaneError:
+ if sb is not None:
+ try:
+ sb.terminate()
+ except Exception as e:
+ logger.warning(f"Failed to terminate sandbox {sb.object_id} after control-plane failure: {e}")
+ raise
+ except SandboxNetworkPolicyError:
raise
except Exception as e:
logger.exception(f"Failed to create sandbox: {e}")
@@ -988,7 +1050,7 @@ class ModalSandbox(AgentServerLaunchMixin):
with capture_modal_output_if_debug() as modal_output:
sb = modal.Sandbox.create(**attempt_kwargs) # type: ignore[arg-type]
except Exception as e:
- _raise_if_proxy_rate_limited(e, None, "create")
+ _raise_if_proxy_failure(e, None, "create")
if config.outbound_domain_allowlist is not None and _is_modal_network_policy_rejection(e):
raise SandboxNetworkPolicyError(
"Modal rejected the requested sandbox network policy.",
@@ -1030,7 +1092,7 @@ class ModalSandbox(AgentServerLaunchMixin):
return False
time.sleep(1)
except Exception as e:
- _raise_if_proxy_rate_limited(e, sb.object_id, "restore_probe")
+ _raise_if_proxy_failure(e, sb.object_id, "restore_probe")
logger.warning(f"Post-restore health probe errored for sandbox {sb.object_id}: {e}")
return False
if returncode != 0:
@@ -1056,7 +1118,7 @@ class ModalSandbox(AgentServerLaunchMixin):
return ModalSandbox(sandbox=sb, config=config)
except Exception as e:
- _raise_if_proxy_rate_limited(e, sandbox_id, "lookup")
+ _raise_if_proxy_failure(e, sandbox_id, "lookup")
logger.exception(f"Failed to retrieve sandbox {sandbox_id}: {e}")
raise SandboxNotFoundError(
f"Sandbox {sandbox_id} not found", {"sandbox_id": sandbox_id, "error": str(e)}, cause=e
@@ -1068,7 +1130,7 @@ class ModalSandbox(AgentServerLaunchMixin):
try:
poll_result = self._sandbox.poll()
except Exception as e:
- _raise_if_proxy_rate_limited(e, self.id, "poll")
+ _raise_if_proxy_failure(e, self.id, "poll")
raise
return SandboxStatus.SHUTDOWN if poll_result is not None else SandboxStatus.RUNNING
@@ -1102,7 +1164,7 @@ class ModalSandbox(AgentServerLaunchMixin):
cause=error,
)
- _raise_if_proxy_rate_limited(error, self.id, "exec")
+ _raise_if_proxy_failure(error, self.id, "exec")
redacted_error = redact_sandbox_command(str(error))
# Provider exceptions can echo the shell command, so avoid exc_info here.
logger.error( # noqa: TRY400
@@ -1181,7 +1243,7 @@ class ModalSandbox(AgentServerLaunchMixin):
self._stdout_buffer.append(output)
yield output
except Exception as e:
- _raise_if_proxy_rate_limited(e, self._sandbox_id, "exec")
+ _raise_if_proxy_failure(e, self._sandbox_id, "exec")
raise
def wait(self) -> ExecutionResult:
@@ -1196,7 +1258,7 @@ class ModalSandbox(AgentServerLaunchMixin):
stderr = self._process.stderr.read()
stderr_text = stderr.decode("utf-8") if isinstance(stderr, bytes) else stderr
except Exception as e:
- _raise_if_proxy_rate_limited(e, self._sandbox_id, "exec")
+ _raise_if_proxy_failure(e, self._sandbox_id, "exec")
raise
return ExecutionResult(
stdout=stdout_text,
@@ -1223,7 +1285,7 @@ class ModalSandbox(AgentServerLaunchMixin):
try:
self._sandbox.filesystem.write_bytes(payload, temp_path)
except Exception as filesystem_error:
- _raise_if_proxy_rate_limited(filesystem_error, self.id, "filesystem_write")
+ _raise_if_proxy_failure(filesystem_error, self.id, "filesystem_write")
logger.warning(
"sandbox_filesystem_write_fallback",
extra={
@@ -1255,7 +1317,7 @@ class ModalSandbox(AgentServerLaunchMixin):
result.error = "exec_write"
self._remove_temp_file(temp_path, step_timeout)
return result
- except SandboxRateLimitedError:
+ except SandboxControlPlaneError:
raise
except Exception as e:
self._remove_temp_file(temp_path, step_timeout)
@@ -1328,7 +1390,7 @@ class ModalSandbox(AgentServerLaunchMixin):
credentials = self._sandbox.create_connect_token()
except Exception as e:
- _raise_if_proxy_rate_limited(e, self.id, "create_connect_token")
+ _raise_if_proxy_failure(e, self.id, "create_connect_token")
raise
self._sandbox_url = credentials.url
@@ -1523,7 +1585,7 @@ class ModalSandbox(AgentServerLaunchMixin):
self._running_status_expires_at = 0.0
logger.info(f"Destroyed sandbox {self.id}")
except Exception as e:
- _raise_if_proxy_rate_limited(e, self.id, "terminate")
+ _raise_if_proxy_failure(e, self.id, "terminate")
logger.exception(f"Failed to destroy sandbox: {e}")
raise SandboxCleanupError(
f"Failed to destroy sandbox: {e}", {"sandbox_id": self.id, "error": str(e)}, cause=e
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 6eb5361530ad..bd2804159c08 100644
--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
@@ -28,6 +28,8 @@ from requests.exceptions import (
from products.tasks.backend.constants import DEFAULT_SANDBOX_WORKING_DIR, SNAPSHOT_KIND_DIRECTORY
from products.tasks.backend.exceptions import (
+ SandboxControlPlaneError,
+ SandboxControlPlaneUnavailableError,
SandboxExecutionError,
SandboxNetworkPolicyError,
SandboxNotFoundError,
@@ -1986,7 +1988,7 @@ class TestModalSandboxCreateImageFallback:
assert error.next_retry_delay is not None
assert len(images_tried) == (0 if shed_call == "app_lookup" else 1)
- def test_proxy_rate_limit_in_the_restore_probe_keeps_the_restored_sandbox(self):
+ def test_proxy_rate_limit_in_the_restore_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()
@@ -2002,7 +2004,7 @@ class TestModalSandboxCreateImageFallback:
assert error.context["operation"] == "restore_probe"
assert len(images_tried) == 1
- restored.terminate.assert_not_called()
+ restored.terminate.assert_called_once()
class TestLaunchDevStackBootstrap:
@@ -2379,6 +2381,35 @@ def _modal_wrapped_rate_limit() -> Exception:
RATE_LIMIT_ERRORS = [_socks_rate_limit, _requests_rate_limit, _modal_wrapped_rate_limit]
+def _socks_gateway_error() -> Exception:
+ # What python_socks raises for a non-200 CONNECT reply: the bare status line, plus the
+ # status as a structured `error_code`.
+ return SocksProxyError("502 Bad gateway", error_code=502)
+
+
+def _requests_gateway_error() -> Exception:
+ return RequestsProxyError("Tunnel connection failed: 503 Service Unavailable")
+
+
+def _requests_embedded_gateway_error() -> Exception:
+ # A status the marker phrases do not name, buried in the proxy's own prose.
+ return RequestsProxyError("Tunnel connection failed: 500 Internal Server Error")
+
+
+def _modal_wrapped_gateway_error() -> Exception:
+ error = ModalConnectionError("failed to connect to the modal control plane")
+ error.__cause__ = SocksProxyError("502 Bad gateway", error_code=502)
+ return error
+
+
+GATEWAY_ERRORS = [
+ _socks_gateway_error,
+ _requests_gateway_error,
+ _requests_embedded_gateway_error,
+ _modal_wrapped_gateway_error,
+]
+
+
def _running_process(exit_code: int = 0) -> Any:
process = MagicMock(returncode=exit_code)
process.wait.return_value = exit_code
@@ -2419,13 +2450,56 @@ class TestModalSandboxProxyRateLimit:
assert exc.value.non_retryable is False
assert exc.value.next_retry_delay is not None
- def test_non_rate_limited_proxy_error_stays_generic(self, mock_sandbox: Any):
- mock_sandbox._sandbox.exec.side_effect = RequestsProxyError("Tunnel connection failed: 502 Bad Gateway")
+ @pytest.mark.parametrize("make_error", GATEWAY_ERRORS)
+ @pytest.mark.parametrize("operation", ["poll", "exec"])
+ def test_control_plane_gateway_error_raises_retryable_error(
+ self, make_error: Any, operation: str, mock_sandbox: Any
+ ):
+ if operation == "poll":
+ mock_sandbox._sandbox.poll.side_effect = make_error()
+ else:
+ mock_sandbox._sandbox.exec.side_effect = make_error()
+
+ with pytest.raises(SandboxControlPlaneUnavailableError) as exc:
+ mock_sandbox.get_status() if operation == "poll" else mock_sandbox.execute("echo hi")
+
+ assert exc.value.context["operation"] == operation
+ assert exc.value.context["sandbox_id"] == "test-sandbox-id"
+ assert exc.value.non_retryable is False
+
+ def test_gateway_error_is_not_captured_to_error_tracking(self, mock_sandbox: Any):
+ mock_sandbox._sandbox.exec.side_effect = _socks_gateway_error()
+
+ with patch("products.tasks.backend.exceptions.capture_exception") as capture:
+ with pytest.raises(SandboxControlPlaneUnavailableError):
+ mock_sandbox.execute("echo hi")
+
+ capture.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "message",
+ [
+ "500 lines of output were truncated",
+ # A bare status line, but from an exception that never wraps a CONNECT reply —
+ # must not be read as a control-plane status just because it fullmatches one.
+ "500 Internal Server Error",
+ ],
+ )
+ def test_provider_error_that_merely_opens_with_a_number_stays_generic(self, message: str, mock_sandbox: Any):
+ mock_sandbox._sandbox.exec.side_effect = RuntimeError(message)
+
+ with pytest.raises(SandboxExecutionError) as exc:
+ mock_sandbox.execute("echo hi")
+
+ assert not isinstance(exc.value, SandboxControlPlaneError)
+
+ def test_non_gateway_proxy_error_stays_generic(self, mock_sandbox: Any):
+ mock_sandbox._sandbox.exec.side_effect = RequestsProxyError("Tunnel connection failed: 407 Proxy Auth Required")
with pytest.raises(SandboxExecutionError) as exc:
mock_sandbox.execute("echo hi")
- assert not isinstance(exc.value, SandboxRateLimitedError)
+ assert not isinstance(exc.value, SandboxControlPlaneError)
def test_get_by_id_rate_limit_is_not_reported_as_missing_sandbox(self):
with patch(
diff --git a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
index 615ae5d17882..b0c632181056 100644
--- a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
@@ -8,10 +8,10 @@ from posthog.temporal.common.utils import asyncify, retry_on_db_connection_drop
from products.tasks.backend.exceptions import (
CredentialUnavailableError,
+ SandboxControlPlaneError,
SandboxExecutionError,
SandboxNotFoundError,
SandboxNotRunningError,
- SandboxRateLimitedError,
)
from products.tasks.backend.logic.services.sandbox import SandboxBase, get_sandbox_class_for_sandbox_id
from products.tasks.backend.models import TASK_OWNERSHIP_VERSION_STATE_KEY, Task, TaskRun
@@ -230,7 +230,7 @@ def refresh_sandbox_credentials(input: RefreshSandboxCredentialsInput) -> Refres
increment_credential_refresh(credential.kind, "orphaned")
orphaned_kinds.append(credential.kind)
continue
- except SandboxRateLimitedError:
+ except SandboxControlPlaneError:
raise
except SandboxExecutionError as error:
if "path" in error.context and ctx.sandbox_backend == "modal":
diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
index 76a1371c80cb..4a8677e0a8a6 100644
--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
@@ -25,9 +25,9 @@ from products.tasks.backend.exceptions import (
OAuthTokenError,
ProcessTaskError,
ProcessTaskFatalError,
+ SandboxControlPlaneError,
SandboxExecutionError,
SandboxMissingRepositoryError,
- SandboxRateLimitedError,
)
from products.tasks.backend.logic.services.connection_token import create_sandbox_event_ingest_token
from products.tasks.backend.logic.services.sandbox import (
@@ -572,7 +572,7 @@ def _invoke_start_agent_server(
)
return health_duration_ms if isinstance(health_duration_ms, int) else None
- except SandboxRateLimitedError:
+ except SandboxControlPlaneError:
raise
except ProcessTaskError:
if params.agentsh_domains is not None:
@@ -955,7 +955,7 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOu
origin_product=ctx.origin_product,
runtime=runtime,
)
- if not isinstance(error, SandboxRateLimitedError):
+ if not isinstance(error, SandboxControlPlaneError):
if agentsh_domains is not None:
_emit_agentsh_log_tail(ctx, sandbox)
_emit_agent_server_log_tail(ctx, sandbox)
diff --git a/products/tasks/backend/tests/test_exceptions.py b/products/tasks/backend/tests/test_exceptions.py
index 59b74dee2986..2bc89bb82ba9 100644
--- a/products/tasks/backend/tests/test_exceptions.py
+++ b/products/tasks/backend/tests/test_exceptions.py
@@ -6,7 +6,13 @@ import pytest
from temporalio import activity
from temporalio.testing import ActivityEnvironment
-from products.tasks.backend.exceptions import SandboxNotRunningError, SandboxRateLimitedError
+from posthog.temporal.common.posthog_client import is_expected_activity_failure
+
+from products.tasks.backend.exceptions import (
+ SandboxControlPlaneUnavailableError,
+ SandboxNotRunningError,
+ SandboxRateLimitedError,
+)
@activity.defn
@@ -20,6 +26,11 @@ def test_temporal_failure_type_defaults_to_class_name():
assert not error.non_retryable
[email protected]("error", [SandboxRateLimitedError("x", {}), SandboxControlPlaneUnavailableError("x", {})])
+def test_control_plane_errors_are_expected_activity_failures(error: Exception):
+ assert is_expected_activity_failure(error) is True
+
+
@pytest.mark.parametrize(
"attempt,expected_floor,expected_ceiling",
[