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): fail fast when the claude token never reaches the sandbox (#107712)

Alessandro Pogliaghia83789701080
diff --git a/products/tasks/backend/logic/services/agent_server_launcher.py b/products/tasks/backend/logic/services/agent_server_launcher.py
index d0b99cd87234..0fdbb869d5a6 100644
--- a/products/tasks/backend/logic/services/agent_server_launcher.py
+++ b/products/tasks/backend/logic/services/agent_server_launcher.py
@@ -238,6 +238,17 @@ def build_agent_server_preflight_script(*, probe_health: bool, executable_paths:
return "\n".join(lines)
+CLAUDE_CREDENTIAL_UNAVAILABLE_MARKER = "claude_credential_unavailable"
+CODEX_CREDENTIAL_UNAVAILABLE_MARKER = "codex_credential_unavailable"
+
+
+def _credential_marker(*sources: str) -> str | None:
+ for marker in (CLAUDE_CREDENTIAL_UNAVAILABLE_MARKER, CODEX_CREDENTIAL_UNAVAILABLE_MARKER):
+ if any(marker in source for source in sources):
+ return marker
+ return None
+
+
def _health_duration_ms(stdout: str) -> int | None:
for line in stdout.splitlines():
if line.startswith(AGENT_SERVER_HEALTH_DURATION_PREFIX):
@@ -422,6 +433,9 @@ class AgentServerLaunchMixin(SandboxBase):
diagnostics["log"] = log_result.stdout
if len(log_result.stdout.encode()) >= STARTUP_LOG_MAX_BYTES:
diagnostics["log_truncated"] = "true"
+ if _credential_marker(log_result.stdout) is not None:
+ diagnostics["failure_reason"] = "agent-server reported a missing subscription token"
+ return diagnostics
health_result = self.execute(
f"curl -s --max-time 3 http://localhost:{AGENT_SERVER_PORT}/health || echo 'no-health-response'",
timeout_seconds=5,
@@ -567,26 +581,11 @@ class AgentServerLaunchMixin(SandboxBase):
health_duration_ms = _health_duration_ms(launch_result.stdout)
if wait_for_health and health_duration_ms is not None:
diagnostics = self._diagnose_startup_failure(allowed_domains)
- if (
- "claude_credential_unavailable" in launch_result.stdout
- or "claude_credential_unavailable" in diagnostics.get("log", "")
- ):
- raise ProcessTaskFatalError(
- "The Claude token did not arrive. Open Desktop and check your token in Settings > Harness. Then start the task again.",
- {"task_id": task_id, "run_id": run_id},
- RuntimeError("Claude token unavailable"),
- capture=False,
- )
- if (
- "codex_credential_unavailable" in launch_result.stdout
- or "codex_credential_unavailable" in diagnostics.get("log", "")
- ):
- raise ProcessTaskFatalError(
- CODEX_CREDENTIAL_UNAVAILABLE_MESSAGE,
- {"task_id": task_id, "run_id": run_id},
- RuntimeError("ChatGPT token unavailable"),
- capture=False,
- )
+ credential_error = self._credential_unavailable_error(
+ launch_result.stdout, diagnostics.get("log", ""), context={"task_id": task_id, "run_id": run_id}
+ )
+ if credential_error is not None:
+ raise credential_error
raise SandboxExecutionError(
"Agent-server failed to start",
{
@@ -767,16 +766,51 @@ class AgentServerLaunchMixin(SandboxBase):
logger.info(f"Agent-server ready in sandbox {self.id}")
return
diagnostics = self._diagnose_startup_failure(allowed_domains)
+ credential_error = self._credential_unavailable_error(
+ diagnostics.get("log", ""), context={"sandbox_id": self.id}
+ )
+ if credential_error is not None:
+ raise credential_error
raise SandboxExecutionError(
"Agent-server failed to start",
{"sandbox_id": self.id, **diagnostics},
cause=RuntimeError(diagnostics.get("failure_reason", "Health check failed after retries")),
)
+ def _credential_unavailable_error(self, *sources: str, context: dict[str, str]) -> ProcessTaskFatalError | None:
+ """Turn a missing subscription token into a non-retryable error.
+
+ The health poll sees the marker only while the agent-server still answers. After the
+ relay timeout ends the session, the marker survives only in the log. Checking the log
+ too means the run fails at once, instead of relaunching and waiting out the same
+ timeout again for a token the user has to supply.
+ """
+ marker = _credential_marker(*sources)
+ if marker == CLAUDE_CREDENTIAL_UNAVAILABLE_MARKER:
+ return ProcessTaskFatalError(
+ "The Claude token did not arrive. Open Desktop and check your token in Settings > Harness. Then start the task again.",
+ context,
+ RuntimeError("Claude token unavailable"),
+ capture=False,
+ )
+ if marker == CODEX_CREDENTIAL_UNAVAILABLE_MARKER:
+ return ProcessTaskFatalError(
+ CODEX_CREDENTIAL_UNAVAILABLE_MESSAGE,
+ context,
+ RuntimeError("ChatGPT token unavailable"),
+ capture=False,
+ )
+ return None
+
def _startup_timeout_with_diagnostics(
self, allowed_domains: list[str] | None, timeout_seconds: int
- ) -> SandboxTimeoutError:
+ ) -> SandboxTimeoutError | ProcessTaskFatalError:
diagnostics = self._diagnose_startup_failure(allowed_domains)
+ credential_error = self._credential_unavailable_error(
+ diagnostics.get("log", ""), context={"sandbox_id": self.id}
+ )
+ if credential_error is not None:
+ return credential_error
logger.warning(
"Agent-server health poll timed out in sandbox %s after %ss: %s",
self.id,
diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.py
index 80ce17a32ffe..83f4a6c011b6 100644
--- a/products/tasks/backend/logic/services/docker_sandbox.py
+++ b/products/tasks/backend/logic/services/docker_sandbox.py
@@ -1156,19 +1156,36 @@ class DockerSandbox(AgentServerLaunchMixin):
def wait_for_agent_server_ready(
self, allowed_domains: list[str] | None = None, *, claude_model_access: str | None = None
) -> None:
- if self._wait_for_health_check(max_attempts=300 if claude_model_access == "own-subscription" else 240):
+ try:
+ healthy = self._wait_for_health_check(
+ max_attempts=300 if claude_model_access == "own-subscription" else 240
+ )
+ except SandboxTimeoutError:
+ credential_error = self._credential_unavailable_error(
+ self._read_agent_server_log(), context={"sandbox_id": self.id}
+ )
+ if credential_error is not None:
+ raise credential_error from None
+ raise
+ if healthy:
logger.info(f"Agent-server ready on port {self._host_port}")
return
- log_result = self.execute("cat /tmp/agent-server.log 2>/dev/null || echo 'No log file'", timeout_seconds=5)
- logger.warning(f"Agent-server health check failed for sandbox {self.id}. Log output:\n{log_result.stdout}")
+ log_output = self._read_agent_server_log()
+ logger.warning(f"Agent-server health check failed for sandbox {self.id}. Log output:\n{log_output}")
+ credential_error = self._credential_unavailable_error(log_output, context={"sandbox_id": self.id})
+ if credential_error is not None:
+ raise credential_error
# Transient timeout Temporal retries — skip error-tracking capture to avoid noisy issues.
raise SandboxExecutionError(
"Agent-server failed to start",
- {"sandbox_id": self.id, "log": log_result.stdout},
+ {"sandbox_id": self.id, "log": log_output},
cause=RuntimeError("Health check failed after retries"),
capture=False,
)
+ def _read_agent_server_log(self) -> str:
+ return self.execute("cat /tmp/agent-server.log 2>/dev/null || echo 'No log file'", timeout_seconds=5).stdout
+
def mark_repo_ready(self, repo_ready_file: str) -> None:
self.execute(f"touch {shlex.quote(repo_ready_file)}", timeout_seconds=10)
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 64f77e4e4c6f..c6f3f5688c92 100644
--- a/products/tasks/backend/logic/services/tests/test_docker_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_docker_sandbox.py
@@ -8,7 +8,7 @@ from unittest.mock import patch
from parameterized import parameterized
from products.tasks.backend.constants import POSTHOG_EXEC_PERMISSION_REGEX
-from products.tasks.backend.exceptions import SandboxExecutionError
+from products.tasks.backend.exceptions import ProcessTaskFatalError, SandboxExecutionError, SandboxTimeoutError
from products.tasks.backend.logic.services.agent_server_launcher import (
AGENT_SERVER_LAUNCH_CAPABILITIES,
AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX,
@@ -76,6 +76,31 @@ def test_wait_for_agent_server_ready_timeout_is_retryable_and_not_captured(sandb
capture_exception.assert_not_called()
[email protected]("health_poll", ["unhealthy", "timed_out"])
+def test_wait_for_agent_server_ready_fails_fast_when_credential_never_arrived(
+ sandbox: DockerSandbox, health_poll: str
+) -> None:
+ log = ExecutionResult(stdout="[AgentServer] [warn] claude_credential_unavailable", stderr="", exit_code=0)
+ poll_timeout = SandboxTimeoutError(
+ "Execution timed out", {"sandbox_id": sandbox.id}, cause=TimeoutError(), capture=False
+ )
+ with (
+ patch.object(
+ sandbox,
+ "_wait_for_health_check",
+ return_value=False,
+ side_effect=poll_timeout if health_poll == "timed_out" else None,
+ ),
+ patch.object(sandbox, "execute", return_value=log),
+ patch("products.tasks.backend.exceptions.capture_exception") as capture_exception,
+ pytest.raises(ProcessTaskFatalError, match="The Claude token did not arrive") as exc,
+ ):
+ sandbox.wait_for_agent_server_ready(claude_model_access="own-subscription")
+
+ assert exc.value.non_retryable is True
+ capture_exception.assert_not_called()
+
+
def test_start_agent_server_health_check_timeout_is_retryable_and_not_captured(sandbox: DockerSandbox):
with (
patch.object(sandbox, "is_running", return_value=True),
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 bb933bc45c2a..5d0c495734a0 100644
--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
@@ -30,6 +30,7 @@ from requests.exceptions import (
from products.tasks.backend.constants import DEFAULT_SANDBOX_WORKING_DIR, SNAPSHOT_KIND_DIRECTORY
from products.tasks.backend.exceptions import (
+ ProcessTaskFatalError,
SandboxControlPlaneError,
SandboxControlPlaneUnavailableError,
SandboxExecutionError,
@@ -82,6 +83,7 @@ from products.tasks.backend.logic.services.modal_sandbox import (
_session_init_probe_hosts,
)
from products.tasks.backend.logic.services.sandbox import (
+ CODEX_CREDENTIAL_UNAVAILABLE_MESSAGE,
AgentServerResult,
ExecutionResult,
SandboxConfig,
@@ -953,8 +955,6 @@ class TestModalSandboxAgentServer:
],
)
def test_wait_for_health_check(self, mock_sandbox: Any, exit_code, stdout, expected):
- from products.tasks.backend.exceptions import ProcessTaskFatalError
-
mock_sandbox.execute = MagicMock(
return_value=ExecutionResult(stdout=stdout, stderr="", exit_code=exit_code, error=None),
)
@@ -1021,6 +1021,40 @@ class TestModalSandboxAgentServer:
wait_for_ready.assert_not_called()
assert "./node_modules/.bin/agent-server" in _agent_server_launch_command(mock_sandbox.execute)
+ @pytest.mark.parametrize(
+ "marker, message",
+ [
+ ("claude_credential_unavailable", "The Claude token did not arrive"),
+ ("codex_credential_unavailable", CODEX_CREDENTIAL_UNAVAILABLE_MESSAGE),
+ ],
+ )
+ @pytest.mark.parametrize("health_poll", ["unhealthy", "timed_out"])
+ def test_wait_for_agent_server_ready_fails_fast_when_credential_never_arrived(
+ self, mock_sandbox: Any, marker: str, message: str, health_poll: str
+ ) -> None:
+ diagnostics = {
+ "log": f"[AgentServer] [warn] {marker}\n[AgentServer] [error] Fatal agent-server error; marking run failed",
+ "failure_reason": "agent server alive but never reported hasSession=true",
+ }
+ poll_timeout = SandboxTimeoutError(
+ "Execution timed out", {"sandbox_id": mock_sandbox.id}, cause=TimeoutError(), capture=False
+ )
+ with (
+ patch.object(
+ mock_sandbox,
+ "_wait_for_health_check",
+ return_value=False,
+ side_effect=poll_timeout if health_poll == "timed_out" else None,
+ ),
+ patch.object(mock_sandbox, "_diagnose_startup_failure", return_value=diagnostics),
+ patch("products.tasks.backend.exceptions.capture_exception") as capture_exception,
+ pytest.raises(ProcessTaskFatalError, match=message) as error,
+ ):
+ mock_sandbox.wait_for_agent_server_ready(claude_model_access="own-subscription")
+
+ assert error.value.non_retryable
+ capture_exception.assert_not_called()
+
def test_wait_for_agent_server_ready_rejects_unhealthy_agentsh(self, mock_sandbox: Any):
with (
patch.object(mock_sandbox, "_wait_for_health_check", return_value=True),
@@ -1510,6 +1544,26 @@ class TestStartupFailureDiagnostics:
assert "never reported hasSession=true" in diagnostics["failure_reason"]
assert diagnostics["host_pressure"] == "ok"
+ def test_skips_probes_when_the_log_shows_a_missing_credential(self) -> None:
+ sandbox = self._sandbox()
+
+ def _exec(command: str, timeout_seconds: Any = None) -> ExecutionResult:
+ if "agent-server.log" in command:
+ return ExecutionResult(
+ stdout="[AgentServer] [warn] claude_credential_unavailable", stderr="", exit_code=0, error=None
+ )
+ return ExecutionResult(stdout="ok", stderr="", exit_code=0, error=None)
+
+ with (
+ patch.object(sandbox, "is_running", return_value=True),
+ patch.object(sandbox, "execute", side_effect=_exec) as execute,
+ ):
+ diagnostics = sandbox._diagnose_startup_failure(allowed_domains=["github.com"])
+
+ assert "missing subscription token" in diagnostics["failure_reason"]
+ assert "host_pressure" not in diagnostics
+ assert all("agent-server.log" in call.args[0] for call in execute.call_args_list)
+
def test_host_pressure_probe_failure_keeps_the_failure_reason(self):
sandbox = self._sandbox()