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): retry sandbox launches past an egress proxy rate limit (#99981)

Alessandro Pogliaghid4b55c7a6f37
diff --git a/products/tasks/backend/exceptions.py b/products/tasks/backend/exceptions.py
index b9bd6ad39eb8..e36573e91507 100644
--- a/products/tasks/backend/exceptions.py
+++ b/products/tasks/backend/exceptions.py
@@ -1,12 +1,25 @@
+import random
from datetime import timedelta
from typing import Any, Optional
+from temporalio import activity
from temporalio.exceptions import ApplicationError
from posthog.exceptions_capture import capture_exception
from products.tasks.backend.facade.compute_quota import ComputeBillingLimitExceeded
+SANDBOX_RATE_LIMIT_BASE_DELAY_SECONDS = 45
+SANDBOX_RATE_LIMIT_MAX_DELAY_SECONDS = 300
+
+
+def sandbox_rate_limit_retry_delay(attempt: int) -> float:
+ ceiling = min(
+ SANDBOX_RATE_LIMIT_BASE_DELAY_SECONDS * 2 ** max(attempt - 1, 0),
+ SANDBOX_RATE_LIMIT_MAX_DELAY_SECONDS,
+ )
+ return random.uniform(ceiling / 2, ceiling)
+
class ProcessTaskError(ApplicationError):
def __init__(
@@ -131,6 +144,22 @@ class SandboxExecutionError(ProcessTaskTransientError):
pass
+class SandboxRateLimitedError(SandboxExecutionError):
+ """The egress proxy in front of the sandbox control plane shed the call."""
+
+ def __init__(self, message: str, context: dict[str, Any]):
+ attempt = activity.info().attempt if activity.in_activity() else 1
+ ProcessTaskError.__init__(
+ self,
+ message,
+ context,
+ None,
+ capture=False,
+ non_retryable=False,
+ next_retry_delay=timedelta(seconds=sandbox_rate_limit_retry_delay(attempt)),
+ )
+
+
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/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.py
index f850fd981490..7b69b872da6c 100644
--- a/products/tasks/backend/logic/services/docker_sandbox.py
+++ b/products/tasks/backend/logic/services/docker_sandbox.py
@@ -840,10 +840,14 @@ class DockerSandbox(SandboxBase):
# An empty payload still has to produce an empty file: with no chunks the temp path is
# never created and the mv below fails. Blanking a credential file is exactly this case.
chunks = [encoded_payload[start : start + chunk_size] for start in range(0, len(encoded_payload), chunk_size)]
- for index, chunk in enumerate(chunks or [""]):
+ prepared_chunks = chunks or [""]
+ last_index = len(prepared_chunks) - 1
+ for index, chunk in enumerate(prepared_chunks):
write_mode = "wb" if index == 0 else "ab"
+ prologue = f"umask 077 && rm -f {shlex.quote(path)}.tmp-* && " if index == 0 else ""
+ epilogue = f" && mv {shlex.quote(temp_path)} {shlex.quote(path)}" if index == last_index else ""
command = (
- "python3 - <<'EOF_SANDBOX_WRITE'\n"
+ f"{prologue}python3 - <<'EOF_SANDBOX_WRITE'{epilogue}\n"
"import base64\n"
"from pathlib import Path\n"
f"path = Path({json.dumps(temp_path)})\n"
@@ -861,15 +865,6 @@ class DockerSandbox(SandboxBase):
)
break
- if result.exit_code == 0:
- move_command = f"mv {shlex.quote(temp_path)} {shlex.quote(path)}"
- result = self.execute(move_command, timeout_seconds=step_timeout)
- if result.exit_code != 0:
- logger.warning(
- "sandbox_write_failed",
- extra={"stdout": result.stdout, "stderr": result.stderr, "sandbox_id": self.id},
- )
-
return result
def clone_repository(
diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.py
index 497f1431d517..80f5a319f449 100644
--- a/products/tasks/backend/logic/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -15,7 +15,7 @@ from dataclasses import dataclass
from functools import lru_cache
from io import StringIO
from pathlib import Path
-from typing import Any, cast
+from typing import Any, NoReturn, cast
from django.conf import settings
@@ -29,6 +29,7 @@ from modal.exception import (
ServiceError as ModalServiceError,
TimeoutError as ModalTimeoutError,
)
+from python_socks import ProxyError as SocksProxyError
from semantic_version import NpmSpec
from posthog.exceptions_capture import capture_exception
@@ -48,6 +49,7 @@ from products.tasks.backend.exceptions import (
SandboxNotFoundError,
SandboxNotRunningError,
SandboxProvisionError,
+ SandboxRateLimitedError,
SandboxTimeoutError,
SnapshotCreationError,
SnapshotFileLimitExceededError,
@@ -137,6 +139,37 @@ TRANSIENT_SNAPSHOT_ERRORS: tuple[type[BaseException], ...] = (
DIRECTORY_SNAPSHOT_TIMEOUT_SECONDS = 240
+PROXY_RATE_LIMIT_MARKERS = ("429", "too many requests")
+PROXY_ERROR_TYPES: tuple[type[BaseException], ...] = (SocksProxyError, requests.exceptions.ProxyError)
+_MAX_PROXY_ERROR_CHAIN_DEPTH = 10
+
+RUNNING_STATUS_CACHE_SECONDS = 10.0
+
+
+def _is_proxy_rate_limit(error: BaseException) -> bool:
+ 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
+ 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
+ current = current.__cause__ or current.__context__
+ return False
+
+
+def _raise_if_proxy_rate_limited(error: BaseException, sandbox_id: str | None, operation: str) -> None:
+ if not _is_proxy_rate_limit(error):
+ return
+ raise SandboxRateLimitedError(
+ "Sandbox control plane is rate limited",
+ {"sandbox_id": sandbox_id, "operation": operation},
+ ) from error
+
+
# Heavy, reproducible directories to prune before retrying a snapshot that hit Modal's
# 1M-file cap. Each is a package cache or install tree the resume sandbox rebuilds, so
# dropping them shrinks the file count without losing the run's own work.
@@ -644,6 +677,7 @@ class ModalSandbox(AgentServerLaunchMixin):
_sandbox: modal.Sandbox
_app: modal.App
_sandbox_url: str | None
+ _running_status_expires_at: float = 0.0
provision_diagnostics: SandboxProvisionDiagnostics | None
DEFAULT_APP_NAME = DEFAULT_MODAL_APP_NAME
NOTEBOOK_APP_NAME = NOTEBOOK_MODAL_APP_NAME
@@ -656,6 +690,7 @@ class ModalSandbox(AgentServerLaunchMixin):
self._sandbox = sandbox
self._app = type(self)._get_app_for_config(config)
self._sandbox_url = sandbox_url
+ self._running_status_expires_at = 0.0
self.provision_diagnostics = None
self._destroyed = False
@@ -695,7 +730,11 @@ class ModalSandbox(AgentServerLaunchMixin):
def create(cls, config: SandboxConfig) -> ModalSandbox:
try:
modal.enable_output()
- app = cls._get_app_for_config(config)
+ try:
+ app = cls._get_app_for_config(config)
+ except Exception as e:
+ _raise_if_proxy_rate_limited(e, None, "lookup")
+ raise
base_image = _get_template_image(config.template)
custom_image_bare: modal.Image | None = None
custom_image: modal.Image | None = None
@@ -915,7 +954,7 @@ class ModalSandbox(AgentServerLaunchMixin):
return sandbox
- except SandboxNetworkPolicyError:
+ except (SandboxNetworkPolicyError, SandboxRateLimitedError):
raise
except Exception as e:
logger.exception(f"Failed to create sandbox: {e}")
@@ -944,6 +983,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")
if config.outbound_domain_allowlist is not None and _is_modal_network_policy_rejection(e):
raise SandboxNetworkPolicyError(
"Modal rejected the requested sandbox network policy.",
@@ -985,6 +1025,7 @@ class ModalSandbox(AgentServerLaunchMixin):
return False
time.sleep(1)
except Exception as e:
+ _raise_if_proxy_rate_limited(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:
@@ -1010,20 +1051,32 @@ class ModalSandbox(AgentServerLaunchMixin):
return ModalSandbox(sandbox=sb, config=config)
except Exception as e:
+ _raise_if_proxy_rate_limited(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
)
def get_status(self) -> SandboxStatus:
- return SandboxStatus.SHUTDOWN if self._destroyed or self._sandbox.poll() is not None else SandboxStatus.RUNNING
-
- def execute(
- self,
- command: str,
- timeout_seconds: int | None = None,
- ) -> ExecutionResult:
- if not self.is_running():
+ if self._destroyed:
+ return SandboxStatus.SHUTDOWN
+ try:
+ poll_result = self._sandbox.poll()
+ except Exception as e:
+ _raise_if_proxy_rate_limited(e, self.id, "poll")
+ raise
+ return SandboxStatus.SHUTDOWN if poll_result is not None else SandboxStatus.RUNNING
+
+ def _is_running_cached(self) -> bool:
+ if time.monotonic() < self._running_status_expires_at:
+ return True
+ running = self.is_running()
+ if running:
+ self._running_status_expires_at = time.monotonic() + RUNNING_STATUS_CACHE_SECONDS
+ return running
+
+ def _prepare_command(self, command: str, timeout_seconds: int | None) -> tuple[str, int]:
+ if not self._is_running_cached():
raise SandboxNotRunningError(
f"Sandbox not in running state.",
{"sandbox_id": self.id},
@@ -1033,8 +1086,37 @@ class ModalSandbox(AgentServerLaunchMixin):
if timeout_seconds is None:
timeout_seconds = self.config.default_execution_timeout_seconds
+ return redact_sandbox_command(command), timeout_seconds
+
+ def _raise_command_failure(self, error: Exception, redacted_command: str, timeout_seconds: int) -> NoReturn:
+ if isinstance(error, TimeoutError):
+ capture_exception(error)
+ raise SandboxTimeoutError(
+ f"Execution timed out after {timeout_seconds} seconds",
+ {"sandbox_id": self.id, "timeout_seconds": timeout_seconds},
+ cause=error,
+ )
+
+ _raise_if_proxy_rate_limited(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
+ "Failed to execute command", extra={"sandbox_id": self.id, "redacted_error": redacted_error}
+ )
+ raise SandboxExecutionError(
+ "Failed to execute command",
+ {"sandbox_id": self.id, "command": redacted_command, "error": redacted_error},
+ cause=RuntimeError(redacted_error),
+ )
+
+ def execute(
+ self,
+ command: str,
+ timeout_seconds: int | None = None,
+ ) -> ExecutionResult:
+ redacted_command, timeout_seconds = self._prepare_command(command, timeout_seconds)
+
try:
- redacted_command = redact_sandbox_command(command)
process = self._sandbox.exec("bash", "-c", command, timeout=timeout_seconds)
process.wait()
@@ -1064,85 +1146,53 @@ class ModalSandbox(AgentServerLaunchMixin):
except SandboxTimeoutError:
raise
- except TimeoutError as e:
- capture_exception(e)
- raise SandboxTimeoutError(
- f"Execution timed out after {timeout_seconds} seconds",
- {"sandbox_id": self.id, "timeout_seconds": timeout_seconds},
- cause=e,
- )
except Exception as e:
- redacted_error = redact_sandbox_command(str(e))
- # Provider exceptions can echo the shell command, so avoid exc_info here.
- logger.error( # noqa: TRY400
- "Failed to execute command", extra={"sandbox_id": self.id, "redacted_error": redacted_error}
- )
- raise SandboxExecutionError(
- "Failed to execute command",
- {"sandbox_id": self.id, "command": redacted_command, "error": redacted_error},
- cause=RuntimeError(redacted_error),
- )
+ self._raise_command_failure(e, redacted_command, timeout_seconds)
def execute_stream(
self,
command: str,
timeout_seconds: int | None = None,
) -> ExecutionStream:
- if not self.is_running():
- raise SandboxNotRunningError(
- f"Sandbox not in running state.",
- {"sandbox_id": self.id},
- cause=RuntimeError(f"Sandbox {self.id} is not running"),
- )
-
- if timeout_seconds is None:
- timeout_seconds = self.config.default_execution_timeout_seconds
+ redacted_command, timeout_seconds = self._prepare_command(command, timeout_seconds)
try:
- redacted_command = redact_sandbox_command(command)
process = self._sandbox.exec("bash", "-c", command, timeout=timeout_seconds)
- except TimeoutError as e:
- capture_exception(e)
- raise SandboxTimeoutError(
- f"Execution timed out after {timeout_seconds} seconds",
- {"sandbox_id": self.id, "timeout_seconds": timeout_seconds},
- cause=e,
- )
except Exception as e:
- redacted_error = redact_sandbox_command(str(e))
- # Provider exceptions can echo the shell command, so avoid exc_info here.
- logger.error( # noqa: TRY400
- "Failed to execute command", extra={"sandbox_id": self.id, "redacted_error": redacted_error}
- )
- raise SandboxExecutionError(
- "Failed to execute command",
- {"sandbox_id": self.id, "command": redacted_command, "error": redacted_error},
- cause=RuntimeError(redacted_error),
- )
+ self._raise_command_failure(e, redacted_command, timeout_seconds)
class _ModalExecutionStream:
- def __init__(self, process: Any):
+ def __init__(self, process: Any, sandbox_id: str):
self._process = process
+ self._sandbox_id = sandbox_id
self._stdout_buffer: list[str] = []
self._stdout_iterated = False
def iter_stdout(self) -> Iterable[str]:
self._stdout_iterated = True
- for line in self._process.stdout:
- output = line.decode("utf-8") if isinstance(line, bytes) else line
- self._stdout_buffer.append(output)
- yield output
+ try:
+ for line in self._process.stdout:
+ output = line.decode("utf-8") if isinstance(line, bytes) else line
+ self._stdout_buffer.append(output)
+ yield output
+ except Exception as e:
+ _raise_if_proxy_rate_limited(e, self._sandbox_id, "exec")
+ raise
def wait(self) -> ExecutionResult:
- self._process.wait()
- if not self._stdout_iterated:
- stdout = self._process.stdout.read()
- stdout_text = stdout.decode("utf-8") if isinstance(stdout, bytes) else stdout
- else:
- stdout_text = "".join(self._stdout_buffer)
-
- stderr = self._process.stderr.read()
- stderr_text = stderr.decode("utf-8") if isinstance(stderr, bytes) else stderr
+ try:
+ self._process.wait()
+ if not self._stdout_iterated:
+ stdout = self._process.stdout.read()
+ stdout_text = stdout.decode("utf-8") if isinstance(stdout, bytes) else stdout
+ else:
+ stdout_text = "".join(self._stdout_buffer)
+
+ 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
return ExecutionResult(
stdout=stdout_text,
stderr=stderr_text,
@@ -1150,10 +1200,10 @@ class ModalSandbox(AgentServerLaunchMixin):
error=None,
)
- return _ModalExecutionStream(process)
+ return _ModalExecutionStream(process, self.id)
def write_file(self, path: str, payload: bytes, timeout_seconds: int | None = None) -> ExecutionResult:
- if not self.is_running():
+ if not self._is_running_cached():
raise SandboxNotRunningError(
"Sandbox not in running state.",
{"sandbox_id": self.id},
@@ -1163,12 +1213,12 @@ class ModalSandbox(AgentServerLaunchMixin):
temp_path = f"{path}.tmp-{uuid.uuid4().hex}"
step_timeout = timeout_seconds or self.config.default_execution_timeout_seconds
write_stage = "filesystem_write" if timeout_seconds is None else "exec_write"
- write_result: ExecutionResult | None = None
try:
if timeout_seconds is None:
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")
logger.warning(
"sandbox_filesystem_write_fallback",
extra={
@@ -1178,36 +1228,32 @@ class ModalSandbox(AgentServerLaunchMixin):
"error_type": type(filesystem_error).__name__,
},
)
- write_stage = "exec_write"
- write_result = self._write_file_with_exec(temp_path, payload, step_timeout)
- else:
- write_result = self._write_file_with_exec(temp_path, payload, step_timeout)
- if write_result is not None and write_result.exit_code != 0:
- write_result.error = "exec_write"
- try:
- self.execute(f"rm -f {shlex.quote(temp_path)}", timeout_seconds=min(step_timeout, 10))
- except Exception:
- pass
- return write_result
- write_stage = "atomic_move"
- mv_command = f"mv {shlex.quote(temp_path)} {shlex.quote(path)}"
- result = self.execute(mv_command, timeout_seconds=step_timeout)
+ else:
+ write_stage = "atomic_move"
+ mv_command = f"mv {shlex.quote(temp_path)} {shlex.quote(path)}"
+ result = self.execute(mv_command, timeout_seconds=step_timeout)
+ if result.exit_code != 0:
+ logger.warning(
+ "sandbox_write_failed",
+ extra={"stdout": result.stdout, "stderr": result.stderr, "sandbox_id": self.id},
+ )
+ result.error = "atomic_move"
+ self._remove_temp_file(temp_path, step_timeout)
+ return result
+ write_stage = "exec_write"
+ result = self._write_file_with_exec(path, temp_path, payload, step_timeout)
if result.exit_code != 0:
logger.warning(
"sandbox_write_failed",
extra={"stdout": result.stdout, "stderr": result.stderr, "sandbox_id": self.id},
)
- result.error = "atomic_move"
- try:
- self.execute(f"rm -f {shlex.quote(temp_path)}", timeout_seconds=min(step_timeout, 10))
- except Exception:
- pass
+ result.error = "exec_write"
+ self._remove_temp_file(temp_path, step_timeout)
return result
+ except SandboxRateLimitedError:
+ raise
except Exception as e:
- try:
- self.execute(f"rm -f {shlex.quote(temp_path)}", timeout_seconds=min(step_timeout, 10))
- except Exception:
- pass
+ self._remove_temp_file(temp_path, step_timeout)
capture_exception(e)
logger.exception(f"Failed to write file to sandbox: {e}")
raise SandboxExecutionError(
@@ -1216,18 +1262,28 @@ class ModalSandbox(AgentServerLaunchMixin):
cause=e,
)
- def _write_file_with_exec(self, temp_path: str, payload: bytes, timeout_seconds: int) -> ExecutionResult:
+ def _remove_temp_file(self, temp_path: str, step_timeout: int) -> None:
+ try:
+ self.execute(f"rm -f {shlex.quote(temp_path)}", timeout_seconds=min(step_timeout, 10))
+ except Exception:
+ pass
+
+ def _write_file_with_exec(self, path: str, temp_path: str, payload: bytes, timeout_seconds: int) -> ExecutionResult:
parent_path = str(Path(temp_path).parent)
chunk_starts = range(0, len(payload), 37_500) if payload else (0,)
+ last_index = len(chunk_starts) - 1
for index, start in enumerate(chunk_starts):
chunk = base64.b64encode(payload[start : start + 37_500]).decode("ascii")
- redirect = ">" if index == 0 else ">>"
- command = (
- f"mkdir -p {shlex.quote(parent_path)} && base64 -d {redirect} {shlex.quote(temp_path)} "
- "<<'POSTHOG_FILE_EOF'\n"
- f"{chunk}\n"
- "POSTHOG_FILE_EOF"
- )
+ if index == 0:
+ opener = (
+ f"umask 077 && mkdir -p {shlex.quote(parent_path)} && "
+ f"rm -f {shlex.quote(path)}.tmp-* && "
+ f"base64 -d > {shlex.quote(temp_path)}"
+ )
+ else:
+ opener = f"base64 -d >> {shlex.quote(temp_path)}"
+ move = f" && mv {shlex.quote(temp_path)} {shlex.quote(path)}" if index == last_index else ""
+ command = f"{opener} <<'POSTHOG_FILE_EOF'{move}\n{chunk}\nPOSTHOG_FILE_EOF"
result = self.execute(command, timeout_seconds=timeout_seconds)
if result.exit_code != 0:
return result
@@ -1238,7 +1294,7 @@ class ModalSandbox(AgentServerLaunchMixin):
return ExecutionResult(stdout="", stderr="", exit_code=0, error=None)
def is_git_clean(self, repository: str) -> tuple[bool, str]:
- if not self.is_running():
+ if not self._is_running_cached():
raise RuntimeError(f"Sandbox not in running state.")
org, repo = repository.lower().split("/")
@@ -1261,10 +1317,14 @@ class ModalSandbox(AgentServerLaunchMixin):
Modal connect tokens provide authenticated HTTP access to port 8080 in the sandbox.
Should be called after sandbox creation to get the URL and token needed for connection.
"""
- if not self.is_running():
- raise RuntimeError("Sandbox not in running state.")
+ try:
+ if not self.is_running():
+ raise RuntimeError("Sandbox not in running state.")
- credentials = self._sandbox.create_connect_token()
+ credentials = self._sandbox.create_connect_token()
+ except Exception as e:
+ _raise_if_proxy_rate_limited(e, self.id, "create_connect_token")
+ raise
self._sandbox_url = credentials.url
logger.info(f"Got connect credentials for sandbox {self.id}: {credentials.url}")
@@ -1455,8 +1515,10 @@ class ModalSandbox(AgentServerLaunchMixin):
try:
self._sandbox.terminate()
self._destroyed = True
+ 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")
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/test_modal_sandbox.py b/products/tasks/backend/logic/services/test_modal_sandbox.py
index 1abf4036d65f..9bec4f472742 100644
--- a/products/tasks/backend/logic/services/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/test_modal_sandbox.py
@@ -66,7 +66,7 @@ class TestModalSandboxWriteFile:
assert error.value.context["exit_code"] == "1"
assert error.value.context["write_stage"] == "atomic_move"
- def test_uses_exec_fallback_before_atomic_move(self, mocker):
+ def test_exec_fallback_moves_into_place_within_the_last_write_command(self, mocker):
handle = MagicMock(object_id="sb-test")
handle.poll.return_value = None
handle.filesystem.write_bytes.side_effect = RuntimeError("fs tool failed")
@@ -75,19 +75,19 @@ class TestModalSandboxWriteFile:
execute = mocker.patch.object(
sandbox,
"execute",
- side_effect=[
- ExecutionResult(stdout="", stderr="", exit_code=0),
- ExecutionResult(stdout="", stderr="", exit_code=0),
- ],
+ return_value=ExecutionResult(stdout="", stderr="", exit_code=0),
)
result = sandbox.write_file("/tmp/credentials", b"token=value\x00")
assert result.exit_code == 0
- assert execute.call_count == 2
- assert "base64 -d >" in execute.call_args_list[0].args[0]
- assert "dG9rZW49dmFsdWUA" in execute.call_args_list[0].args[0]
- assert execute.call_args_list[1].args[0].startswith("mv ")
+ assert execute.call_count == 1
+ command = execute.call_args_list[0].args[0]
+ assert "base64 -d >" in command
+ assert "dG9rZW49dmFsdWUA" in command
+ assert "umask 077 &&" in command
+ assert "rm -f /tmp/credentials.tmp-*" in command
+ assert " && mv /tmp/credentials.tmp-" in command
def test_uses_bounded_exec_path_when_timeout_is_set(self, mocker):
handle = MagicMock(object_id="sb-test")
@@ -122,8 +122,10 @@ class TestModalSandboxWriteFile:
sandbox.write_file("/tmp/output", b"x" * 100_000)
- write_commands = [call.args[0] for call in execute.call_args_list[:-1]]
+ write_commands = [call.args[0] for call in execute.call_args_list]
assert len(write_commands) == 3
+ assert " && mv /tmp/output.tmp-" in write_commands[-1]
+ assert all(" && mv " not in command for command in write_commands[:-1])
assert all(len(command) < 51_000 for command in write_commands)
assert [len(command.splitlines()[1]) for command in write_commands] == [50_000, 50_000, 33_336]
diff --git a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py b/products/tasks/backend/logic/services/tests/test_docker_sandbox.py
index 9aa6558d102d..6e4893a39930 100644
--- a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_docker_sandbox.py
@@ -154,4 +154,5 @@ def test_write_file_creates_the_temp_file_before_moving_it(_name: str, payload:
assert result.exit_code == 0
assert any("EOF_SANDBOX_WRITE" in command for command in commands), "temp file was never written"
- assert commands[-1].startswith("mv ")
+ assert commands[-1].startswith("umask 077 && rm -f /tmp/creds.env.tmp-* && ")
+ assert " && mv /tmp/creds.env.tmp-" in commands[-1]
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 6f4d5c8e7eff..6eb5361530ad 100644
--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
@@ -19,13 +19,20 @@ from modal.exception import (
TimeoutError as ModalTimeoutError,
)
from parameterized import parameterized
-from requests.exceptions import ConnectionError, Timeout
+from python_socks import ProxyError as SocksProxyError
+from requests.exceptions import (
+ ConnectionError,
+ ProxyError as RequestsProxyError,
+ Timeout,
+)
from products.tasks.backend.constants import DEFAULT_SANDBOX_WORKING_DIR, SNAPSHOT_KIND_DIRECTORY
from products.tasks.backend.exceptions import (
SandboxExecutionError,
SandboxNetworkPolicyError,
+ SandboxNotFoundError,
SandboxProvisionError,
+ SandboxRateLimitedError,
SandboxTimeoutError,
SnapshotCreationError,
SnapshotFileLimitExceededError,
@@ -52,6 +59,7 @@ from products.tasks.backend.logic.services.modal_sandbox import (
DIRECTORY_SNAPSHOT_TIMEOUT_SECONDS,
FILESYSTEM_SNAPSHOT_TIMEOUT_SECONDS,
PUBLISHED_IMAGE_SNAPSHOT_TIMEOUT_SECONDS,
+ RUNNING_STATUS_CACHE_SECONDS,
SANDBOX_IMAGE,
ModalSandbox,
_attach_local_package_mounts,
@@ -1933,6 +1941,69 @@ class TestModalSandboxCreateImageFallback:
assert "resume state dropped" in sandbox.config.image_fallback
assert not sandbox.config.image_fallback.startswith("snapshot image")
+ def _create_shed_by_the_proxy(self, config: SandboxConfig, *, app_lookup: Any, sandbox_create: Any) -> Any:
+ with (
+ patch("products.tasks.backend.logic.services.modal_sandbox.modal.enable_output"),
+ patch.object(ModalSandbox, "_get_app_for_config", app_lookup),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox._get_template_image",
+ return_value=MagicMock(name="base"),
+ ),
+ patch(
+ "products.tasks.backend.logic.services.modal_sandbox.modal.Image.from_id",
+ return_value=MagicMock(name="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.logic.services.modal_sandbox.capture_exception"),
+ ):
+ with pytest.raises(SandboxRateLimitedError) as error:
+ ModalSandbox.create(config)
+ return error.value
+
+ @pytest.mark.parametrize("shed_call,expected_operation", [("app_lookup", "lookup"), ("sandbox_create", "create")])
+ def test_proxy_rate_limit_never_downgrades_past_the_snapshot_candidate(
+ self, shed_call: str, expected_operation: str
+ ):
+ config = SandboxConfig(name="t", snapshot_external_id="im-snap-1")
+ images_tried: list[Any] = []
+ app_lookup = MagicMock(return_value=MagicMock())
+ if shed_call == "app_lookup":
+ app_lookup.side_effect = _modal_wrapped_rate_limit()
+
+ def sandbox_create(**kwargs: Any) -> Any:
+ images_tried.append(kwargs["image"])
+ raise _modal_wrapped_rate_limit()
+
+ error = self._create_shed_by_the_proxy(config, app_lookup=app_lookup, sandbox_create=sandbox_create)
+
+ assert error.context["operation"] == expected_operation
+ 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):
+ config = SandboxConfig(name="t", snapshot_external_id="im-snap-1")
+ restored = MagicMock(object_id="sb-restored")
+ restored.exec.side_effect = _socks_rate_limit()
+ images_tried: list[Any] = []
+
+ def sandbox_create(**kwargs: Any) -> Any:
+ images_tried.append(kwargs["image"])
+ return restored
+
+ error = self._create_shed_by_the_proxy(
+ config, app_lookup=MagicMock(return_value=MagicMock()), sandbox_create=sandbox_create
+ )
+
+ assert error.context["operation"] == "restore_probe"
+ assert len(images_tried) == 1
+ restored.terminate.assert_not_called()
+
class TestLaunchDevStackBootstrap:
def _sandbox(
@@ -2289,3 +2360,139 @@ class TestSessionInitProbeHosts:
def test_deduplicates_against_static_hosts_and_skips_unset(self):
hosts = _session_init_probe_hosts()
assert hosts.count("gateway.us.posthog.com") == 1
+
+
+def _socks_rate_limit() -> Exception:
+ return SocksProxyError("Proxy server unexpectedly closed: 429 Too Many Requests")
+
+
+def _requests_rate_limit() -> Exception:
+ return RequestsProxyError("Tunnel connection failed: 429 Too Many Requests")
+
+
+def _modal_wrapped_rate_limit() -> Exception:
+ error = ModalConnectionError("failed to connect to the modal control plane")
+ error.__cause__ = SocksProxyError("429 Too Many Requests")
+ return error
+
+
+RATE_LIMIT_ERRORS = [_socks_rate_limit, _requests_rate_limit, _modal_wrapped_rate_limit]
+
+
+def _running_process(exit_code: int = 0) -> Any:
+ process = MagicMock(returncode=exit_code)
+ process.wait.return_value = exit_code
+ process.stdout.read.return_value = ""
+ process.stderr.read.return_value = ""
+ return process
+
+
+class TestModalSandboxProxyRateLimit:
+ @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
+ mock_modal_sandbox.exec.return_value = _running_process()
+
+ credentials = MagicMock()
+ credentials.url = "https://test-sandbox.modal.run"
+ credentials.token = "test-connect-token"
+ mock_modal_sandbox.create_connect_token.return_value = credentials
+
+ with patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock()):
+ return ModalSandbox(sandbox=mock_modal_sandbox, config=SandboxConfig(name="test-sandbox"))
+
+ @pytest.mark.parametrize("make_error", RATE_LIMIT_ERRORS)
+ @pytest.mark.parametrize("operation", ["poll", "exec"])
+ def test_proxy_rate_limit_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(SandboxRateLimitedError) 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
+ 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")
+
+ with pytest.raises(SandboxExecutionError) as exc:
+ mock_sandbox.execute("echo hi")
+
+ assert not isinstance(exc.value, SandboxRateLimitedError)
+
+ def test_get_by_id_rate_limit_is_not_reported_as_missing_sandbox(self):
+ with patch(
+ "products.tasks.backend.logic.services.modal_sandbox.modal.Sandbox.from_id",
+ side_effect=_modal_wrapped_rate_limit(),
+ ):
+ with pytest.raises(SandboxRateLimitedError) as exc:
+ ModalSandbox.get_by_id("sb-123")
+
+ assert not isinstance(exc.value, SandboxNotFoundError)
+ assert exc.value.context["operation"] == "lookup"
+
+ def test_write_file_rate_limit_skips_exec_fallback(self, mock_sandbox: Any):
+ mock_sandbox._sandbox.filesystem.write_bytes.side_effect = _socks_rate_limit()
+
+ with pytest.raises(SandboxRateLimitedError) as exc:
+ mock_sandbox.write_file("/tmp/target", b"payload")
+
+ assert exc.value.context["operation"] == "filesystem_write"
+ mock_sandbox._sandbox.exec.assert_not_called()
+
+ def test_write_file_rate_limit_in_fallback_skips_cleanup(self, mock_sandbox: Any):
+ mock_sandbox._sandbox.filesystem.write_bytes.side_effect = RuntimeError("filesystem unavailable")
+ mock_sandbox._sandbox.exec.side_effect = _socks_rate_limit()
+
+ with pytest.raises(SandboxRateLimitedError):
+ mock_sandbox.write_file("/tmp/target", b"payload")
+
+ assert mock_sandbox._sandbox.exec.call_count == 1
+
+ @pytest.mark.parametrize("stage", ["wait", "iterate"])
+ def test_execute_stream_rate_limit_propagates(self, stage: str, mock_sandbox: Any):
+ process = _running_process()
+ if stage == "wait":
+ process.wait.side_effect = _socks_rate_limit()
+ else:
+ process.stdout.__iter__.side_effect = _socks_rate_limit()
+ mock_sandbox._sandbox.exec.return_value = process
+
+ stream = mock_sandbox.execute_stream("echo hi")
+
+ with pytest.raises(SandboxRateLimitedError) as exc:
+ stream.wait() if stage == "wait" else list(stream.iter_stdout())
+
+ assert exc.value.context["operation"] == "exec"
+
+ def test_get_connect_credentials_rate_limit(self, mock_sandbox: Any):
+ mock_sandbox._sandbox.create_connect_token.side_effect = _requests_rate_limit()
+
+ with pytest.raises(SandboxRateLimitedError) as exc:
+ mock_sandbox.get_connect_credentials()
+
+ assert exc.value.context["operation"] == "create_connect_token"
+
+ def test_consecutive_commands_reuse_one_liveness_poll(self, mock_sandbox: Any):
+ clock = {"now": 1000.0}
+
+ with patch(
+ "products.tasks.backend.logic.services.modal_sandbox.time.monotonic",
+ side_effect=lambda: clock["now"],
+ ):
+ mock_sandbox.execute("echo one")
+ mock_sandbox.execute("echo two")
+
+ assert mock_sandbox._sandbox.poll.call_count == 1
+
+ clock["now"] += RUNNING_STATUS_CACHE_SECONDS + 1
+ mock_sandbox.execute("echo three")
+
+ assert mock_sandbox._sandbox.poll.call_count == 2
diff --git a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
index 37c57d4604f7..0c3c8fc6dd41 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
@@ -18,11 +18,7 @@ from products.tasks.backend.exceptions import (
OAuthTokenError,
TaskNotFoundError,
)
-from products.tasks.backend.logic.services.connection_token import (
- SANDBOX_JWT_STATE_KID_KEY,
- get_primary_sandbox_jwt_kid,
- get_sandbox_jwt_public_key,
-)
+from products.tasks.backend.logic.services.connection_token import get_sandbox_jwt_public_key
from products.tasks.backend.logic.services.sandbox import (
Sandbox,
SandboxConfig,
@@ -30,11 +26,6 @@ from products.tasks.backend.logic.services.sandbox import (
parse_sandbox_repo_mount_map,
workload_for_origin_product,
)
-from products.tasks.backend.logic.services.sandbox_usage import (
- measure_sandbox_billed_cpu_usage,
- measure_sandbox_cpu_usage,
- open_sandbox_session,
-)
from products.tasks.backend.models import SandboxSnapshot, Task, TaskRun
from products.tasks.backend.temporal.metrics import (
StepTimer,
@@ -45,6 +36,7 @@ from products.tasks.backend.temporal.metrics import (
)
from products.tasks.backend.temporal.oauth import create_oauth_access_token_for_run
from products.tasks.backend.temporal.observability import emit_agent_log, log_activity_execution
+from products.tasks.backend.temporal.process_task.sandbox_connection import persist_sandbox_connection
from products.tasks.backend.temporal.process_task.utils import (
get_git_identity_env_vars,
get_sandbox_api_url,
@@ -431,25 +423,12 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandbo
credentials = sandbox.get_connect_credentials()
try:
- sandbox_state = {
- "sandbox_id": sandbox.id,
- "sandbox_url": credentials.url,
- SANDBOX_JWT_STATE_KID_KEY: get_primary_sandbox_jwt_kid(),
- }
- if credentials.token:
- sandbox_state["sandbox_connect_token"] = credentials.token
- TaskRun.update_state_atomic(ctx.run_id, updates=sandbox_state)
- cpu_usage_attribution_usec, cpu_usage_attribution_measured_at = measure_sandbox_cpu_usage(sandbox)
- billed_cpu_usage_attribution_usec = measure_sandbox_billed_cpu_usage(sandbox)
- open_sandbox_session(
+ persist_sandbox_connection(
run_id=ctx.run_id,
- sandbox_id=sandbox.id,
- config=sandbox.config,
+ sandbox=sandbox,
+ credentials=credentials,
sandbox_created_at=sandbox_created_at,
- cpu_usage_attribution_usec=cpu_usage_attribution_usec,
- billed_cpu_usage_attribution_usec=billed_cpu_usage_attribution_usec,
- cpu_usage_attribution_measured_at=cpu_usage_attribution_measured_at,
- required=ctx.task_runtime == "pi",
+ task_runtime=ctx.task_runtime,
)
except Exception:
try:
diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
index ecd92f93d063..5871c0b37988 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -41,11 +41,7 @@ from products.tasks.backend.logic.services.agentsh import (
enforced_egress_domains,
)
from products.tasks.backend.logic.services.compute_quota import get_compute_quota_denial_reason
-from products.tasks.backend.logic.services.connection_token import (
- SANDBOX_JWT_STATE_KID_KEY,
- get_primary_sandbox_jwt_kid,
- get_sandbox_jwt_public_key,
-)
+from products.tasks.backend.logic.services.connection_token import SANDBOX_JWT_STATE_KID_KEY, get_sandbox_jwt_public_key
from products.tasks.backend.logic.services.network_policy import (
EffectiveNetworkPolicy,
NetworkPolicyValidationError,
@@ -61,11 +57,6 @@ from products.tasks.backend.logic.services.sandbox import (
sandbox_repo_path,
workload_for_origin_product,
)
-from products.tasks.backend.logic.services.sandbox_usage import (
- measure_sandbox_billed_cpu_usage,
- measure_sandbox_cpu_usage,
- open_sandbox_session,
-)
from products.tasks.backend.models import TASK_OWNERSHIP_VERSION_STATE_KEY, SandboxSnapshot, Task, TaskRun
from products.tasks.backend.temporal.metrics import (
StepTimer,
@@ -84,6 +75,7 @@ from products.tasks.backend.temporal.observability import (
log_activity_execution,
log_with_activity_context,
)
+from products.tasks.backend.temporal.process_task.sandbox_connection import persist_sandbox_connection
from products.tasks.backend.temporal.process_task.sandbox_credentials import (
replace_sandbox_credentials,
set_git_remote_token,
@@ -867,72 +859,62 @@ def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cr
"sandbox_creation_with_policy_request", runtime, "modal_requested", "failure"
)
raise
- if config.outbound_domain_allowlist is not None:
- emit_agent_log(ctx.run_id, "debug", "Modal sandbox created with network policy requested")
- record_network_enforcement("sandbox_creation_with_policy_request", runtime, "modal_requested", "success")
- if not sandbox.start_cpu_billing_sampler():
- activity.logger.warning("Failed to start sandbox CPU billing sampler", extra={"sandbox_id": sandbox.id})
- if sandbox.config.image_fallback:
- emit_agent_log(
- ctx.run_id,
- "warn",
- f"Sandbox image downgraded: {sandbox.config.image_fallback}",
+ try:
+ if config.outbound_domain_allowlist is not None:
+ emit_agent_log(ctx.run_id, "debug", "Modal sandbox created with network policy requested")
+ record_network_enforcement(
+ "sandbox_creation_with_policy_request", runtime, "modal_requested", "success"
+ )
+ if not sandbox.start_cpu_billing_sampler():
+ activity.logger.warning("Failed to start sandbox CPU billing sampler", extra={"sandbox_id": sandbox.id})
+ if sandbox.config.image_fallback:
+ emit_agent_log(
+ ctx.run_id,
+ "warn",
+ f"Sandbox image downgraded: {sandbox.config.image_fallback}",
+ )
+ if sandbox.launch_dev_stack_bootstrap():
+ emit_agent_log(
+ ctx.run_id,
+ "debug",
+ "Warming the prebaked dev stack in the background (compose host aliases + dockerd)",
+ )
+ create_ms = sandbox_creation_timer.elapsed_ms
+ snapshot_outcome = (
+ "used" if actual_used_snapshot else "fresh" if prepared.snapshot_source == "none" else "fallback"
)
- if sandbox.launch_dev_stack_bootstrap():
- emit_agent_log(
- ctx.run_id,
- "debug",
- "Warming the prebaked dev stack in the background (compose host aliases + dockerd)",
+ metrics_snapshot_kind = prepared.snapshot_kind if prepared.snapshot_source != "none" else "none"
+ increment_snapshot_usage(
+ actual_used_snapshot,
+ snapshot_source=prepared.snapshot_source,
+ snapshot_kind=metrics_snapshot_kind,
)
- create_ms = sandbox_creation_timer.elapsed_ms
- snapshot_outcome = (
- "used" if actual_used_snapshot else "fresh" if prepared.snapshot_source == "none" else "fallback"
- )
- metrics_snapshot_kind = prepared.snapshot_kind if prepared.snapshot_source != "none" else "none"
- increment_snapshot_usage(
- actual_used_snapshot,
- snapshot_source=prepared.snapshot_source,
- snapshot_kind=metrics_snapshot_kind,
- )
- increment_snapshot_restore(prepared.snapshot_source, metrics_snapshot_kind, snapshot_outcome)
-
- record_sandbox_created(
- runtime,
- _sandbox_image_kind(prepared.image_source, config.custom_image_name),
- sandbox.config.image_fallback is not None,
- create_ms,
- sandbox_backend=sandbox_backend,
- )
+ increment_snapshot_restore(prepared.snapshot_source, metrics_snapshot_kind, snapshot_outcome)
- credentials = sandbox.get_connect_credentials()
+ record_sandbox_created(
+ runtime,
+ _sandbox_image_kind(prepared.image_source, config.custom_image_name),
+ sandbox.config.image_fallback is not None,
+ create_ms,
+ sandbox_backend=sandbox_backend,
+ )
- try:
- jwt_kid = get_primary_sandbox_jwt_kid()
- sandbox_state = {
- "sandbox_id": sandbox.id,
- "sandbox_url": credentials.url,
- SANDBOX_JWT_STATE_KID_KEY: jwt_kid,
- }
- if ctx.sandbox_backend != "modal":
- sandbox_state["sandbox_backend"] = ctx.sandbox_backend
- if credentials.token:
- sandbox_state["sandbox_connect_token"] = credentials.token
- TaskRun.update_state_atomic(ctx.run_id, updates=sandbox_state)
- cpu_usage_attribution_usec, cpu_usage_attribution_measured_at = measure_sandbox_cpu_usage(sandbox)
- billed_cpu_usage_attribution_usec = measure_sandbox_billed_cpu_usage(sandbox)
- open_sandbox_session(
+ credentials = sandbox.get_connect_credentials()
+ jwt_kid = persist_sandbox_connection(
run_id=ctx.run_id,
- sandbox_id=sandbox.id,
- config=sandbox.config,
+ sandbox=sandbox,
+ credentials=credentials,
sandbox_created_at=sandbox_created_at,
- cpu_usage_attribution_usec=cpu_usage_attribution_usec,
- billed_cpu_usage_attribution_usec=billed_cpu_usage_attribution_usec,
- cpu_usage_attribution_measured_at=cpu_usage_attribution_measured_at,
- required=ctx.task_runtime == "pi",
+ task_runtime=ctx.task_runtime,
+ sandbox_backend=ctx.sandbox_backend if ctx.sandbox_backend != "modal" else None,
)
except Exception:
try:
sandbox.destroy()
+ except Exception:
+ activity.logger.warning(
+ "Failed to destroy sandbox after provisioning failure", extra={"sandbox_id": sandbox.id}
+ )
finally:
TaskRun.clear_sandbox_connection_state_atomic(ctx.run_id, sandbox.id)
raise
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 ce3fd6e26f74..615ae5d17882 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
@@ -11,6 +11,7 @@ from products.tasks.backend.exceptions import (
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
@@ -229,6 +230,8 @@ def refresh_sandbox_credentials(input: RefreshSandboxCredentialsInput) -> Refres
increment_credential_refresh(credential.kind, "orphaned")
orphaned_kinds.append(credential.kind)
continue
+ except SandboxRateLimitedError:
+ raise
except SandboxExecutionError as error:
if "path" in error.context and ctx.sandbox_backend == "modal":
verdict, probe = _probe_sandbox_wedge(sandbox)
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 4a0e700c9828..76a1371c80cb 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
@@ -27,6 +27,7 @@ from products.tasks.backend.exceptions import (
ProcessTaskFatalError,
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 (
@@ -571,6 +572,8 @@ def _invoke_start_agent_server(
)
return health_duration_ms if isinstance(health_duration_ms, int) else None
+ except SandboxRateLimitedError:
+ raise
except ProcessTaskError:
if params.agentsh_domains is not None:
_emit_agentsh_log_tail(ctx, sandbox)
@@ -943,7 +946,7 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOu
),
)
_record_agent_server_launch(sandbox, ctx, params)
- except Exception:
+ except Exception as error:
if attempt > 1:
increment_agent_server_readiness_retry(
attempt,
@@ -952,9 +955,10 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOu
origin_product=ctx.origin_product,
runtime=runtime,
)
- if agentsh_domains is not None:
- _emit_agentsh_log_tail(ctx, sandbox)
- _emit_agent_server_log_tail(ctx, sandbox)
+ if not isinstance(error, SandboxRateLimitedError):
+ if agentsh_domains is not None:
+ _emit_agentsh_log_tail(ctx, sandbox)
+ _emit_agent_server_log_tail(ctx, sandbox)
raise
if attempt > 1:
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py
index 36131cd2bcf8..bcb2bdfd0a8b 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py
@@ -10,7 +10,7 @@ from django.test import override_settings
from asgiref.sync import async_to_sync
from products.tasks.backend.constants import SNAPSHOT_KIND_DIRECTORY, SNAPSHOT_KIND_FILESYSTEM
-from products.tasks.backend.exceptions import RepositoryCloneError
+from products.tasks.backend.exceptions import RepositoryCloneError, SandboxCleanupError, SandboxRateLimitedError
from products.tasks.backend.logic.services.docker_sandbox import DockerSandbox
from products.tasks.backend.logic.services.sandbox import ExecutionResult
from products.tasks.backend.models import Task
@@ -487,3 +487,76 @@ def test_clone_failure_records_failed_latency_and_captures_command_result(mocker
}
)
assert str(capture_exception.call_args.args[0]) == "clone output"
+
+
+def _prepared_for_create() -> PrepareSandboxForRepositoryOutput:
+ return PrepareSandboxForRepositoryOutput(
+ sandbox_name="sandbox-name",
+ repository="posthog/posthog",
+ github_token="github-token",
+ branch=None,
+ environment_variables={},
+ snapshot_id=None,
+ snapshot_external_id=None,
+ used_snapshot=False,
+ should_create_snapshot=False,
+ shallow_clone=True,
+ image_source="fresh",
+ image_source_label="fresh image",
+ )
+
+
+ "failing_step,destroy_fails",
+ [
+ ("get_connect_credentials", False),
+ ("get_connect_credentials", True),
+ ("start_cpu_billing_sampler", False),
+ ],
+)
+def test_a_failure_after_create_destroys_the_fresh_sandbox(mocker, failing_step: str, destroy_fails: bool):
+ context = TaskProcessingContext(
+ task_id="task-id",
+ run_id="run-id",
+ team_id=1,
+ team_uuid="team-uuid",
+ organization_id="organization-id",
+ github_integration_id=123,
+ repository="posthog/posthog",
+ distinct_id="distinct-id",
+ state={"await_user_message": True},
+ )
+ sandbox = mocker.Mock(id="sandbox-id")
+ sandbox.config.image_fallback = None
+ sandbox.config.snapshot_restored = False
+ sandbox.launch_dev_stack_bootstrap.return_value = False
+ sandbox.start_cpu_billing_sampler.return_value = True
+ getattr(sandbox, failing_step).side_effect = SandboxRateLimitedError(
+ "Sandbox control plane is rate limited", {"sandbox_id": "sandbox-id", "operation": "create_connect_token"}
+ )
+ if destroy_fails:
+ sandbox.destroy.side_effect = SandboxCleanupError(
+ "Failed to destroy sandbox", {"sandbox_id": "sandbox-id"}, cause=RuntimeError("terminate failed")
+ )
+
+ mocker.patch.object(
+ provision_sandbox_module,
+ "get_sandbox_class_for_run_backend",
+ return_value=mocker.Mock(create=mocker.Mock(return_value=sandbox)),
+ )
+ mocker.patch.object(provision_sandbox_module, "emit_agent_log")
+ mocker.patch.object(provision_sandbox_module, "_emit_image_source_log")
+ mocker.patch.object(provision_sandbox_module, "_apply_modal_network_policy")
+ mocker.patch.object(provision_sandbox_module, "_build_sandbox_tags", return_value={})
+ mocker.patch.object(provision_sandbox_module, "record_sandbox_created")
+ mocker.patch.object(provision_sandbox_module, "increment_snapshot_usage")
+ mocker.patch.object(provision_sandbox_module, "increment_snapshot_restore")
+ task_run = mocker.patch.object(provision_sandbox_module, "TaskRun")
+
+ with pytest.raises(SandboxRateLimitedError):
+ async_to_sync(provision_sandbox_module._create_sandbox_for_repository)(
+ CreateSandboxForRepositoryInput(context=context, prepared=_prepared_for_create())
+ )
+
+ sandbox.destroy.assert_called_once_with()
+ task_run.clear_sandbox_connection_state_atomic.assert_called_once_with("run-id", "sandbox-id")
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
index 1522000f84bd..649886506e2f 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
@@ -10,7 +10,12 @@ from asgiref.sync import async_to_sync
from posthog.models.integration import Integration
-from products.tasks.backend.exceptions import SandboxExecutionError, SandboxNotFoundError, SandboxNotRunningError
+from products.tasks.backend.exceptions import (
+ SandboxExecutionError,
+ SandboxNotFoundError,
+ SandboxNotRunningError,
+ SandboxRateLimitedError,
+)
from products.tasks.backend.logic.services.sandbox import ExecutionResult
from products.tasks.backend.models import TASK_OWNERSHIP_VERSION_STATE_KEY, Task, TaskRun
from products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials import (
@@ -415,6 +420,32 @@ class TestRefreshSandboxCredentialsActivity:
assert output.refreshed_kinds == []
increment.assert_called_once_with("github", "failed")
+ def test_proxy_rate_limit_reaches_temporal_instead_of_being_skipped(
+ self, activity_environment, task_context, test_task, sandbox
+ ):
+ sandbox.write_file.side_effect = SandboxRateLimitedError(
+ "Sandbox control plane is rate limited",
+ {"sandbox_id": "sandbox-abc", "operation": "filesystem_write"},
+ )
+ with (
+ patch(
+ "products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.get_sandbox_class_for_sandbox_id",
+ **{"return_value.get_by_id.return_value": sandbox},
+ ),
+ patch(
+ "products.tasks.backend.temporal.process_task.sandbox_credentials.get_sandbox_github_token",
+ return_value="ghs_fresh",
+ ),
+ patch("products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.track_event"),
+ ):
+ with pytest.raises(SandboxRateLimitedError) as error:
+ async_to_sync(activity_environment.run)(
+ refresh_sandbox_credentials,
+ RefreshSandboxCredentialsInput(context=task_context, sandbox_id="sandbox-abc"),
+ )
+
+ assert error.value.next_retry_delay is not None
+
def test_hogland_file_write_failure_does_not_run_modal_probe(
self, activity_environment, task_context, test_task, sandbox
):
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
index 2147fea70df8..27a58dff2f18 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
@@ -10,6 +10,7 @@ from products.tasks.backend.exceptions import (
ProcessTaskFatalError,
SandboxExecutionError,
SandboxMissingRepositoryError,
+ SandboxRateLimitedError,
SandboxTimeoutError,
)
from products.tasks.backend.logic.services.sandbox import ExecutionResult, sandbox_repo_path
@@ -200,6 +201,27 @@ def test_invoke_start_agent_server_preserves_process_task_error(mocker, error_ty
assert raised.value is error
+def test_invoke_start_agent_server_skips_log_tails_when_rate_limited(mocker) -> None:
+ error = SandboxRateLimitedError("Sandbox control plane is rate limited", {"sandbox_id": "sandbox-id"})
+ sandbox = mocker.Mock(id="sandbox-id")
+ sandbox.start_agent_server.side_effect = error
+ emit_agentsh = mocker.patch(
+ "products.tasks.backend.temporal.process_task.activities.start_agent_server._emit_agentsh_log_tail"
+ )
+ emit_agent_server = mocker.patch(
+ "products.tasks.backend.temporal.process_task.activities.start_agent_server._emit_agent_server_log_tail"
+ )
+
+ with pytest.raises(SandboxRateLimitedError) as raised:
+ _invoke_start_agent_server(
+ sandbox, _context(), mocker.Mock(agentsh_domains=["example.com"]), repo_ready_file=None
+ )
+
+ assert raised.value is error
+ emit_agentsh.assert_not_called()
+ emit_agent_server.assert_not_called()
+
+
@pytest.mark.parametrize(
("error", "expected_statuses"),
[
diff --git a/products/tasks/backend/temporal/process_task/sandbox_connection.py b/products/tasks/backend/temporal/process_task/sandbox_connection.py
new file mode 100644
index 000000000000..ad03e4967ef7
--- /dev/null
+++ b/products/tasks/backend/temporal/process_task/sandbox_connection.py
@@ -0,0 +1,51 @@
+from datetime import datetime
+from typing import Any
+
+from products.tasks.backend.logic.services.connection_token import (
+ SANDBOX_JWT_STATE_KID_KEY,
+ get_primary_sandbox_jwt_kid,
+)
+from products.tasks.backend.logic.services.sandbox import AgentServerResult, SandboxBase
+from products.tasks.backend.logic.services.sandbox_usage import (
+ measure_sandbox_billed_cpu_usage,
+ measure_sandbox_cpu_usage,
+ open_sandbox_session,
+)
+from products.tasks.backend.models import TaskRun
+
+
+def persist_sandbox_connection(
+ *,
+ run_id: str,
+ sandbox: SandboxBase,
+ credentials: AgentServerResult,
+ sandbox_created_at: datetime | None,
+ task_runtime: str | None,
+ sandbox_backend: str | None = None,
+) -> str:
+ jwt_kid = get_primary_sandbox_jwt_kid()
+ sandbox_state: dict[str, Any] = {
+ "sandbox_id": sandbox.id,
+ "sandbox_url": credentials.url,
+ SANDBOX_JWT_STATE_KID_KEY: jwt_kid,
+ }
+ if sandbox_backend is not None:
+ sandbox_state["sandbox_backend"] = sandbox_backend
+ if credentials.token:
+ sandbox_state["sandbox_connect_token"] = credentials.token
+
+ TaskRun.update_state_atomic(run_id, updates=sandbox_state)
+
+ cpu_usage_attribution_usec, cpu_usage_attribution_measured_at = measure_sandbox_cpu_usage(sandbox)
+ billed_cpu_usage_attribution_usec = measure_sandbox_billed_cpu_usage(sandbox)
+ open_sandbox_session(
+ run_id=run_id,
+ sandbox_id=sandbox.id,
+ config=sandbox.config,
+ sandbox_created_at=sandbox_created_at,
+ cpu_usage_attribution_usec=cpu_usage_attribution_usec,
+ billed_cpu_usage_attribution_usec=billed_cpu_usage_attribution_usec,
+ cpu_usage_attribution_measured_at=cpu_usage_attribution_measured_at,
+ required=task_runtime == "pi",
+ )
+ return jwt_kid
diff --git a/products/tasks/backend/tests/test_exceptions.py b/products/tasks/backend/tests/test_exceptions.py
index 8e6e775f4065..59b74dee2986 100644
--- a/products/tasks/backend/tests/test_exceptions.py
+++ b/products/tasks/backend/tests/test_exceptions.py
@@ -1,7 +1,41 @@
-from products.tasks.backend.exceptions import SandboxNotRunningError
+import dataclasses
+from datetime import timedelta
+
+import pytest
+
+from temporalio import activity
+from temporalio.testing import ActivityEnvironment
+
+from products.tasks.backend.exceptions import SandboxNotRunningError, SandboxRateLimitedError
+
+
+def _shed_by_the_proxy() -> None:
+ raise SandboxRateLimitedError("x", {})
def test_temporal_failure_type_defaults_to_class_name():
error = SandboxNotRunningError("boom", {}, cause=RuntimeError("x"), capture=False)
assert error.type == "SandboxNotRunningError"
assert not error.non_retryable
+
+
+ "attempt,expected_floor,expected_ceiling",
+ [
+ (1, 22.5, 45.0),
+ (2, 45.0, 90.0),
+ (3, 90.0, 180.0),
+ (6, 150.0, 300.0),
+ ],
+)
+def test_rate_limit_backoff_follows_the_activity_attempt(attempt: int, expected_floor: float, expected_ceiling: float):
+ environment = ActivityEnvironment()
+ environment.info = dataclasses.replace(environment.info, attempt=attempt)
+
+ with pytest.raises(SandboxRateLimitedError) as error:
+ environment.run(_shed_by_the_proxy)
+
+ assert error.value.non_retryable is False
+ assert error.value.next_retry_delay is not None
+ assert timedelta(seconds=expected_floor) <= error.value.next_retry_delay <= timedelta(seconds=expected_ceiling)