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): preserve sandbox credential refreshes (#95103)

Alessandro Pogliaghi87b41a2668e9
diff --git a/products/tasks/backend/logic/services/agent_server_launcher.py b/products/tasks/backend/logic/services/agent_server_launcher.py
index fa61e8a56df0..fcf0f7485c08 100644
--- a/products/tasks/backend/logic/services/agent_server_launcher.py
+++ b/products/tasks/backend/logic/services/agent_server_launcher.py
@@ -105,6 +105,21 @@ class AgentServerLaunchMixin(SandboxBase):
def supports_combined_agent_server_start_and_health(self) -> bool:
return True
+ def _write_required_file(self, path: str, payload: bytes) -> None:
+ result = self.write_file(path, payload)
+ if result.exit_code != 0:
+ write_stage = (result.error or "unknown")[:100]
+ raise SandboxExecutionError(
+ "Failed to write required sandbox file",
+ {
+ "sandbox_id": self.id,
+ "path": path,
+ "exit_code": str(result.exit_code),
+ "write_stage": write_stage,
+ },
+ cause=RuntimeError(f"write_file returned {result.exit_code} during {write_stage}"),
+ )
+
def _build_agent_server_command(
self,
repo_path: str | None,
@@ -303,11 +318,11 @@ class AgentServerLaunchMixin(SandboxBase):
org, repo = repository.lower().split("/")
repo_path = f"/tmp/workspace/repos/{org}/{repo}"
- self.write_file(BASH_ENV_SCRIPT, generate_bash_env_script().encode())
+ self._write_required_file(BASH_ENV_SCRIPT, generate_bash_env_script().encode())
# Install the gh shim at runtime too (see agentsh.GH_GUARD_INSTALL_PATH): a resume from a
# pre-shim filesystem snapshot — or any window where the base image lags this backend —
# would otherwise leave gh with no token once the frozen launch-env token is unset.
- self.write_file(GH_GUARD_INSTALL_PATH, read_gh_guard_script())
+ self._write_required_file(GH_GUARD_INSTALL_PATH, read_gh_guard_script())
self.execute(f"chmod +x {shlex.quote(GH_GUARD_INSTALL_PATH)}", timeout_seconds=30)
if allowed_domains is not None:
@@ -437,9 +452,9 @@ class AgentServerLaunchMixin(SandboxBase):
self.execute("pkill -f 'agentsh server' || true", timeout_seconds=5)
self.execute("mkdir -p /etc/agentsh/policies /var/log/agentsh /var/lib/agentsh/sessions", timeout_seconds=5)
- self.write_file("/etc/agentsh/config.yaml", config_yaml.encode())
- self.write_file("/etc/agentsh/policies/default.yaml", policy_yaml.encode())
- self.write_file(ENV_WRAPPER_SCRIPT, generate_env_wrapper().encode())
+ self._write_required_file("/etc/agentsh/config.yaml", config_yaml.encode())
+ self._write_required_file("/etc/agentsh/policies/default.yaml", policy_yaml.encode())
+ self._write_required_file(ENV_WRAPPER_SCRIPT, generate_env_wrapper().encode())
self.execute(f"chmod +x {ENV_WRAPPER_SCRIPT}", timeout_seconds=5)
setup_script = build_setup_script(workspace_path)
diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.py
index 8cb6027063b2..cd7dad79f819 100644
--- a/products/tasks/backend/logic/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -4,6 +4,7 @@ import json
import time
import uuid
import shlex
+import base64
import shutil
import asyncio
import logging
@@ -94,6 +95,7 @@ from .sandbox import (
logger = logging.getLogger(__name__)
+
DEFAULT_MODAL_APP_NAME = "posthog-sandbox-default"
NOTEBOOK_MODAL_APP_NAME = "posthog-sandbox-notebook"
STREAMLIT_MODAL_APP_NAME = "posthog-sandbox-streamlit"
@@ -1143,27 +1145,78 @@ 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:
- self._sandbox.filesystem.write_bytes(payload, temp_path)
+ if timeout_seconds is None:
+ try:
+ self._sandbox.filesystem.write_bytes(payload, temp_path)
+ except Exception as filesystem_error:
+ logger.warning(
+ "sandbox_filesystem_write_fallback",
+ extra={
+ "sandbox_id": self.id,
+ "path": path,
+ "error": str(filesystem_error),
+ "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=timeout_seconds or self.config.default_execution_timeout_seconds
- )
+ 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"
+ try:
+ self.execute(f"rm -f {shlex.quote(temp_path)}", timeout_seconds=min(step_timeout, 10))
+ except Exception:
+ pass
return result
except Exception as e:
+ try:
+ self.execute(f"rm -f {shlex.quote(temp_path)}", timeout_seconds=min(step_timeout, 10))
+ except Exception:
+ pass
capture_exception(e)
logger.exception(f"Failed to write file to sandbox: {e}")
raise SandboxExecutionError(
"Failed to write file",
- {"sandbox_id": self.id, "path": path, "error": str(e)},
+ {"sandbox_id": self.id, "path": path, "write_stage": write_stage, "error": str(e)},
cause=e,
)
+ def _write_file_with_exec(self, 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,)
+ 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"
+ )
+ result = self.execute(command, timeout_seconds=timeout_seconds)
+ if result.exit_code != 0:
+ return result
+ return result
+
def setup_repository(self, repository: str) -> ExecutionResult:
"""No-op: Repository setup is now handled by agent-server."""
return ExecutionResult(stdout="", stderr="", exit_code=0, error=None)
diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.py
index 3745549b03c9..6759d593712c 100644
--- a/products/tasks/backend/logic/services/sandbox.py
+++ b/products/tasks/backend/logic/services/sandbox.py
@@ -242,6 +242,9 @@ SENSITIVE_AGENT_RUNTIME_ENV_PATTERN = re.compile(
SENSITIVE_AGENT_RUNTIME_ARGUMENT_PATTERN = re.compile(
rf"(?P<name>--mcpServers)\s+(?P<value>{SHELL_ARGUMENT_VALUE_PATTERN})"
)
+SENSITIVE_FILE_HEREDOC_PATTERN = re.compile(
+ r"(?P<prefix><<'POSTHOG_FILE_EOF'\n).*?(?P<suffix>\nPOSTHOG_FILE_EOF)", re.DOTALL
+)
def is_public_sandbox_repo(repository: str | None) -> bool:
@@ -256,7 +259,8 @@ def sandbox_repo_path(repository: str) -> str:
def redact_sandbox_command(command: str) -> str:
redacted = SENSITIVE_AGENT_RUNTIME_ENV_PATTERN.sub(r"\g<name>=<redacted>", command)
- return SENSITIVE_AGENT_RUNTIME_ARGUMENT_PATTERN.sub(r"\g<name> <redacted>", redacted)
+ redacted = SENSITIVE_AGENT_RUNTIME_ARGUMENT_PATTERN.sub(r"\g<name> <redacted>", redacted)
+ return SENSITIVE_FILE_HEREDOC_PATTERN.sub(r"\g<prefix><redacted>\g<suffix>", redacted)
def build_agent_runtime_env_prefix(
diff --git a/products/tasks/backend/logic/services/test_docker_sandbox.py b/products/tasks/backend/logic/services/test_docker_sandbox.py
index 72c4b97b7a87..c6ea96494581 100644
--- a/products/tasks/backend/logic/services/test_docker_sandbox.py
+++ b/products/tasks/backend/logic/services/test_docker_sandbox.py
@@ -133,6 +133,14 @@ class TestDockerSandboxUnit:
assert redacted == "agent-server --mcpServers <redacted> --port 8080"
+ def test_redact_sandbox_command_hides_file_heredoc(self):
+ command = "base64 -d > /tmp/value <<'POSTHOG_FILE_EOF'\nc2VjcmV0\nPOSTHOG_FILE_EOF"
+
+ redacted = redact_sandbox_command(command)
+
+ assert "c2VjcmV0" not in redacted
+ assert "<redacted>" in redacted
+
@pytest.mark.parametrize(
"input_url,expected_url",
[
diff --git a/products/tasks/backend/logic/services/test_modal_sandbox.py b/products/tasks/backend/logic/services/test_modal_sandbox.py
index 79f60b65ce9a..1abf4036d65f 100644
--- a/products/tasks/backend/logic/services/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/test_modal_sandbox.py
@@ -9,6 +9,7 @@ from products.tasks.backend.constants import (
SNAPSHOT_KIND_DIRECTORY,
SNAPSHOT_KIND_FILESYSTEM,
)
+from products.tasks.backend.exceptions import SandboxExecutionError
from products.tasks.backend.logic.services.modal_sandbox import (
DEFAULT_MODAL_APP_NAME,
LOCAL_MODAL_AGENT_SHADOW_DIR,
@@ -22,6 +23,7 @@ from products.tasks.backend.logic.services.modal_sandbox import (
)
from products.tasks.backend.logic.services.sandbox import (
SELF_DRIVING_ORIGIN_PRODUCTS,
+ ExecutionResult,
SandboxConfig,
SandboxStatus,
SandboxTemplate,
@@ -44,6 +46,124 @@ def test_destroy_updates_status_before_modal_termination_settles(mocker):
handle.terminate.assert_called_once_with()
+class TestModalSandboxWriteFile:
+ def test_required_file_write_failure_raises(self, mocker):
+ handle = MagicMock(object_id="sb-test")
+ handle.poll.return_value = None
+ mocker.patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock())
+ sandbox = ModalSandbox(handle, SandboxConfig(name="test"))
+ mocker.patch.object(
+ sandbox,
+ "write_file",
+ return_value=ExecutionResult(stdout="", stderr="", exit_code=1, error="atomic_move"),
+ )
+
+ with pytest.raises(SandboxExecutionError, match="Failed to write required sandbox file") as error:
+ sandbox._write_required_file("/etc/agentsh/config.yaml", b"config")
+
+ assert error.value.context["sandbox_id"] == "sb-test"
+ assert error.value.context["path"] == "/etc/agentsh/config.yaml"
+ 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):
+ handle = MagicMock(object_id="sb-test")
+ handle.poll.return_value = None
+ handle.filesystem.write_bytes.side_effect = RuntimeError("fs tool failed")
+ mocker.patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock())
+ sandbox = ModalSandbox(handle, SandboxConfig(name="test"))
+ execute = mocker.patch.object(
+ sandbox,
+ "execute",
+ side_effect=[
+ ExecutionResult(stdout="", stderr="", exit_code=0),
+ 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 ")
+
+ def test_uses_bounded_exec_path_when_timeout_is_set(self, mocker):
+ handle = MagicMock(object_id="sb-test")
+ handle.poll.return_value = None
+ mocker.patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock())
+ sandbox = ModalSandbox(handle, SandboxConfig(name="test"))
+ execute = mocker.patch.object(
+ sandbox,
+ "execute",
+ side_effect=[
+ ExecutionResult(stdout="", stderr="", exit_code=0),
+ ExecutionResult(stdout="", stderr="", exit_code=0),
+ ],
+ )
+
+ sandbox.write_file("/tmp/credentials", b"token=value\x00", timeout_seconds=15)
+
+ handle.filesystem.write_bytes.assert_not_called()
+ assert all(call.kwargs["timeout_seconds"] == 15 for call in execute.call_args_list)
+
+ def test_chunks_large_exec_fallback_payloads(self, mocker):
+ handle = MagicMock(object_id="sb-test")
+ handle.poll.return_value = None
+ handle.filesystem.write_bytes.side_effect = RuntimeError("fs tool failed")
+ mocker.patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock())
+ sandbox = ModalSandbox(handle, SandboxConfig(name="test"))
+ execute = mocker.patch.object(
+ sandbox,
+ "execute",
+ return_value=ExecutionResult(stdout="", stderr="", exit_code=0),
+ )
+
+ sandbox.write_file("/tmp/output", b"x" * 100_000)
+
+ write_commands = [call.args[0] for call in execute.call_args_list[:-1]]
+ assert len(write_commands) == 3
+ 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]
+
+ def test_returns_exec_fallback_failure(self, mocker):
+ handle = MagicMock(object_id="sb-test")
+ handle.poll.return_value = None
+ handle.filesystem.write_bytes.side_effect = RuntimeError("fs tool failed")
+ mocker.patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock())
+ sandbox = ModalSandbox(handle, SandboxConfig(name="test"))
+ mocker.patch.object(
+ sandbox,
+ "execute",
+ return_value=ExecutionResult(stdout="", stderr="write failed", exit_code=1),
+ )
+
+ result = sandbox.write_file("/tmp/credentials", b"token=value\x00")
+
+ assert result.exit_code == 1
+ assert result.error == "exec_write"
+
+ def test_returns_atomic_move_failure(self, mocker):
+ handle = MagicMock(object_id="sb-test")
+ handle.poll.return_value = None
+ mocker.patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock())
+ sandbox = ModalSandbox(handle, SandboxConfig(name="test"))
+ mocker.patch.object(
+ sandbox,
+ "execute",
+ side_effect=[
+ ExecutionResult(stdout="", stderr="move failed", exit_code=1),
+ ExecutionResult(stdout="", stderr="", exit_code=0),
+ ],
+ )
+
+ result = sandbox.write_file("/tmp/credentials", b"token=value\x00")
+
+ assert result.exit_code == 1
+ assert result.error == "atomic_move"
+
+
@pytest.fixture
def patched_modal(mocker):
fake_sandbox = MagicMock()
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 f5039240ac8d..5a44fbc39acb 100644
--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
@@ -734,6 +734,9 @@ class TestModalSandboxAgentServer:
)
def test_start_agent_server_raises_on_start_failure(self, mock_sandbox: Any):
+ mock_sandbox.write_file = MagicMock(
+ return_value=ExecutionResult(stdout="", stderr="", exit_code=0, error=None),
+ )
mock_sandbox.execute = MagicMock(
return_value=ExecutionResult(stdout="", stderr="npx: command not found", exit_code=127, error=None)
)
diff --git a/products/tasks/backend/temporal/metrics.py b/products/tasks/backend/temporal/metrics.py
index d66c8d541684..a43615eeadae 100644
--- a/products/tasks/backend/temporal/metrics.py
+++ b/products/tasks/backend/temporal/metrics.py
@@ -275,6 +275,17 @@ def increment_credential_refresh(kind: str, outcome: str) -> None:
pass
+def increment_sandbox_wedge_probe(verdict: str, write_stage: str) -> None:
+ try:
+ meter = _metric_meter({"verdict": verdict, "write_stage": write_stage})
+ meter.create_counter(
+ "tasks_sandbox_wedge_probe",
+ "Sandbox pressure probe results after credential file write failures",
+ ).add(1)
+ except Exception:
+ pass
+
+
def increment_pr_babysit_decision(decision: str) -> None:
try:
meter = workflow.metric_meter().with_additional_attributes({"decision": decision})
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 54562972365e..ce3fd6e26f74 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
@@ -6,10 +6,15 @@ from temporalio import activity
from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.utils import asyncify, retry_on_db_connection_drop
-from products.tasks.backend.exceptions import CredentialUnavailableError, SandboxNotFoundError, SandboxNotRunningError
-from products.tasks.backend.logic.services.sandbox import get_sandbox_class_for_sandbox_id
+from products.tasks.backend.exceptions import (
+ CredentialUnavailableError,
+ SandboxExecutionError,
+ SandboxNotFoundError,
+ SandboxNotRunningError,
+)
+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
-from products.tasks.backend.temporal.metrics import increment_credential_refresh
+from products.tasks.backend.temporal.metrics import increment_credential_refresh, increment_sandbox_wedge_probe
from products.tasks.backend.temporal.observability import log_activity_execution, track_event
from products.tasks.backend.temporal.process_task.sandbox_credentials import (
DEFAULT_REFRESH_INTERVAL_SECONDS,
@@ -20,6 +25,47 @@ from .get_task_processing_context import TaskProcessingContext
logger = get_logger(__name__)
+_SANDBOX_WEDGE_PROBE_COMMAND = """
+printf 'memory_current='; cat /sys/fs/cgroup/memory.current 2>/dev/null || printf 'unavailable\n'
+printf 'memory_max='; cat /sys/fs/cgroup/memory.max 2>/dev/null || printf 'unavailable\n'
+printf 'oom_kill='; awk '$1 == "oom_kill" { print $2 }' /sys/fs/cgroup/memory.events 2>/dev/null || printf 'unavailable\n'
+printf 'pids_current='; cat /sys/fs/cgroup/pids.current 2>/dev/null || printf 'unavailable\n'
+printf 'pids_max='; cat /sys/fs/cgroup/pids.max 2>/dev/null || printf 'unavailable\n'
+printf 'tmp_available_kb='; df -Pk /tmp 2>/dev/null | awk 'NR == 2 { print $4 }'
+""".strip()
+
+
+def _probe_value_as_int(probe: dict[str, str], key: str) -> int | None:
+ try:
+ return int(probe[key])
+ except (KeyError, ValueError):
+ return None
+
+
+def _sandbox_wedge_verdict(probe: dict[str, str]) -> str:
+ pids_current = _probe_value_as_int(probe, "pids_current")
+ pids_max = _probe_value_as_int(probe, "pids_max")
+ if pids_current is not None and pids_max is not None and pids_current >= pids_max:
+ return "pids_exhausted"
+ tmp_available_kb = _probe_value_as_int(probe, "tmp_available_kb")
+ if tmp_available_kb is not None and tmp_available_kb <= 0:
+ return "disk_full"
+ if (_probe_value_as_int(probe, "oom_kill") or 0) > 0:
+ return "oom_seen"
+ return "unknown"
+
+
+def _probe_sandbox_wedge(sandbox: SandboxBase) -> tuple[str, dict[str, str]]:
+ try:
+ result = sandbox.execute(_SANDBOX_WEDGE_PROBE_COMMAND, timeout_seconds=10)
+ except Exception as error:
+ return "unknown", {"probe_error": str(error)}
+ probe = dict(line.split("=", 1) for line in result.stdout.splitlines() if "=" in line)
+ probe["exit_code"] = str(result.exit_code)
+ if result.stderr:
+ probe["stderr"] = result.stderr
+ return _sandbox_wedge_verdict(probe), probe
+
def _with_current_authorship(ctx: TaskProcessingContext) -> TaskProcessingContext:
"""Re-read the run's PR authorship, which `ctx.state` can no longer be trusted for.
@@ -183,6 +229,29 @@ def refresh_sandbox_credentials(input: RefreshSandboxCredentialsInput) -> Refres
increment_credential_refresh(credential.kind, "orphaned")
orphaned_kinds.append(credential.kind)
continue
+ except SandboxExecutionError as error:
+ if "path" in error.context and ctx.sandbox_backend == "modal":
+ verdict, probe = _probe_sandbox_wedge(sandbox)
+ write_stage = str(error.context.get("write_stage", "unknown"))
+ logger.warning(
+ "sandbox_wedge_probe",
+ kind=credential.kind,
+ sandbox_id=input.sandbox_id,
+ run_id=ctx.run_id,
+ verdict=verdict,
+ write_stage=write_stage,
+ probe=probe,
+ )
+ increment_sandbox_wedge_probe(verdict, write_stage)
+ logger.warning(
+ "sandbox_credential_refresh_failed",
+ kind=credential.kind,
+ sandbox_id=input.sandbox_id,
+ run_id=ctx.run_id,
+ exc_info=True,
+ )
+ increment_credential_refresh(credential.kind, "failed")
+ continue
except Exception:
logger.warning(
"sandbox_credential_refresh_failed",
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 ac5152511646..1522000f84bd 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
@@ -15,6 +15,7 @@ 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 (
RefreshSandboxCredentialsInput,
+ _sandbox_wedge_verdict,
refresh_sandbox_credentials,
)
from products.tasks.backend.temporal.process_task.sandbox_credentials import DEFAULT_REFRESH_INTERVAL_SECONDS
@@ -164,6 +165,40 @@ class TestRefreshSandboxCredentialsActivity:
assert output.next_refresh_seconds == DEFAULT_REFRESH_INTERVAL_SECONDS
assert output.sandbox_gone is False
+ def test_file_write_failure_records_wedge_probe(self, activity_environment, task_context, test_task, sandbox):
+ sandbox.write_file.return_value = ExecutionResult(
+ stdout="", stderr="write failed", exit_code=1, error="exec_write"
+ )
+ sandbox.execute.side_effect = [
+ ExecutionResult(stdout="", stderr="", exit_code=0),
+ ExecutionResult(
+ stdout="oom_kill=0\npids_current=100\npids_max=100\ntmp_available_kb=42\nfs_tool_present=1\n",
+ stderr="",
+ exit_code=0,
+ ),
+ ]
+ 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"),
+ patch(
+ "products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.increment_sandbox_wedge_probe"
+ ) as increment_probe,
+ ):
+ output = async_to_sync(activity_environment.run)(
+ refresh_sandbox_credentials,
+ RefreshSandboxCredentialsInput(context=task_context, sandbox_id="sandbox-abc"),
+ )
+
+ assert output.refreshed_kinds == []
+ increment_probe.assert_called_once_with("pids_exhausted", "exec_write")
+
def test_skips_refresh_when_sandbox_not_running(self, activity_environment, task_context, test_task, sandbox):
sandbox.is_running.return_value = False
with (
@@ -379,3 +414,50 @@ class TestRefreshSandboxCredentialsActivity:
assert output.refreshed_kinds == []
increment.assert_called_once_with("github", "failed")
+
+ def test_hogland_file_write_failure_does_not_run_modal_probe(
+ self, activity_environment, task_context, test_task, sandbox
+ ):
+ context = dataclasses.replace(task_context, sandbox_backend="hogland")
+ sandbox.write_file.side_effect = SandboxExecutionError(
+ "Failed to write file",
+ {"sandbox_id": "sandbox-abc", "path": "/tmp/credentials"},
+ cause=RuntimeError("write failed"),
+ )
+ 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"),
+ patch(
+ "products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.increment_sandbox_wedge_probe"
+ ) as increment_probe,
+ ):
+ output = async_to_sync(activity_environment.run)(
+ refresh_sandbox_credentials,
+ RefreshSandboxCredentialsInput(context=context, sandbox_id="sandbox-abc"),
+ )
+
+ assert output.refreshed_kinds == []
+ increment_probe.assert_not_called()
+
+
+ "probe,expected",
+ [
+ ({"oom_kill": "2"}, "oom_seen"),
+ (
+ {"oom_kill": "2", "pids_current": "50", "pids_max": "50"},
+ "pids_exhausted",
+ ),
+ ({"oom_kill": "0", "tmp_available_kb": "0"}, "disk_full"),
+ ({"oom_kill": "0", "tmp_available_kb": "10"}, "unknown"),
+ ],
+)
+def test_sandbox_wedge_verdict(probe, expected):
+ assert _sandbox_wedge_verdict(probe) == expected
diff --git a/products/tasks/backend/temporal/process_task/sandbox_credentials.py b/products/tasks/backend/temporal/process_task/sandbox_credentials.py
index c90acdc19083..b73b61b9c257 100644
--- a/products/tasks/backend/temporal/process_task/sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/sandbox_credentials.py
@@ -15,7 +15,7 @@ from posthog.models.integration import Integration
from posthog.models.user_integration import ReauthorizationRequired, UserGitHubIntegration, UserIntegration
from posthog.redis import get_client
-from products.tasks.backend.exceptions import CredentialUnavailableError
+from products.tasks.backend.exceptions import CredentialUnavailableError, SandboxExecutionError
from products.tasks.backend.logic.services.agentsh import GITHUB_ENV_FILE, OAUTH_ENV_FILE
from products.tasks.backend.logic.services.run_actor import loop_owner_eligible_for_credentials
from products.tasks.backend.models import Task, TaskRun
@@ -50,6 +50,7 @@ _GITHUB_REFRESH_INTERVAL_BY_PREFIX: dict[str, float] = {
"ghu_": 2 * 60 * 60,
}
DEFAULT_REFRESH_INTERVAL_SECONDS: float = 20 * 60
+CREDENTIAL_SANDBOX_EXEC_TIMEOUT_SECONDS = 15
def github_refresh_interval_seconds(token: str) -> float:
@@ -73,7 +74,7 @@ def set_git_remote_token(sandbox: "SandboxBase", repository: str, github_token:
f"git remote set-url origin {shlex.quote(remote_url)}; "
f"fi"
)
- result = sandbox.execute(update_remote, timeout_seconds=30)
+ result = sandbox.execute(update_remote, timeout_seconds=CREDENTIAL_SANDBOX_EXEC_TIMEOUT_SECONDS)
if result.exit_code != 0:
logger.warning(
"Failed to refresh git remote URL",
@@ -85,15 +86,26 @@ def set_git_remote_token(sandbox: "SandboxBase", repository: str, github_token:
def _write_sandbox_credential_file(sandbox: "SandboxBase", path: str, payload: bytes) -> bool:
"""Atomically replace one credential domain without a cross-key read-modify-write."""
- write = sandbox.write_file(path, payload)
+ write = sandbox.write_file(path, payload, timeout_seconds=CREDENTIAL_SANDBOX_EXEC_TIMEOUT_SECONDS)
if write.exit_code != 0:
+ if write.error in {"exec_write", "atomic_move"}:
+ raise SandboxExecutionError(
+ "Failed to write sandbox credential file",
+ {
+ "sandbox_id": sandbox.id,
+ "path": path,
+ "write_stage": write.error,
+ "exit_code": write.exit_code,
+ },
+ cause=RuntimeError(f"Sandbox credential write exited with code {write.exit_code}"),
+ )
logger.warning(
"Failed to refresh sandbox credential file",
extra={"sandbox_id": sandbox.id, "credential_file": path, "stderr": write.stderr},
)
return False
- chmod = sandbox.execute(f"chmod 600 {shlex.quote(path)}", timeout_seconds=30)
+ chmod = sandbox.execute(f"chmod 600 {shlex.quote(path)}", timeout_seconds=CREDENTIAL_SANDBOX_EXEC_TIMEOUT_SECONDS)
if chmod.exit_code != 0:
logger.warning(
"Failed to restrict sandbox credential file permissions",
@@ -168,10 +180,10 @@ def _actor_rebound_away_from_owner(run_id: str, state: dict | None, owner_id: in
# TTL derivation: the lock must outlive the whole critical section, or the lease can expire mid-write
# and let a concurrent refresh acquire and interleave (a regression we hit before). Each managed
-# write is a chain of in-sandbox execs, each bounded by a 30s timeout — set_git_remote_token (1 exec)
-# and _write_sandbox_credential_file (a file write + a chmod exec). The per-message gate can run two
+# write is a chain of in-sandbox execs, each bounded by a 15s timeout — set_git_remote_token (1 exec)
+# and _write_sandbox_credential_file (a write, move, and chmod). The per-message gate can run two
# such chains back-to-back in one lock hold (apply the new token, then, if that fails, log out), so
-# the worst case is ~4 × 30s ≈ 2 min. A 5 min TTL clears that with margin; recompute if those exec
+# the worst case is ~8 × 15s ≈ 2 min. A 5 min TTL clears that with margin; recompute if those exec
# timeouts change. The wait stays under the refresh activity's 2 min timeout, so a contender that
# can't acquire skips (fail-safe) rather than blocking the activity.
_CREDENTIAL_LOCK_TTL_SECONDS = 5 * 60
diff --git a/products/tasks/backend/tests/test_agentsh.py b/products/tasks/backend/tests/test_agentsh.py
index 2a8ce28534d7..79e9dcf3cdbe 100644
--- a/products/tasks/backend/tests/test_agentsh.py
+++ b/products/tasks/backend/tests/test_agentsh.py
@@ -600,7 +600,9 @@ class TestModalSandboxAgentShWrapping(TestCase):
cast_sandbox.is_running = Mock(return_value=True)
cast_sandbox._agent_server_is_healthy = Mock(return_value=False)
cast_sandbox._free_agent_server_port = Mock()
- cast_sandbox.write_file = Mock()
+ cast_sandbox.write_file = Mock(
+ return_value=ExecutionResult(stdout="", stderr="", exit_code=0, error=None),
+ )
cast_sandbox.execute = execute
sandbox.start_agent_server(