| 1 |
"""Tests for `EnvironmentWorker`. |
| 2 |
|
| 3 |
The worker composes the control-plane poller, the per-session |
| 4 |
`AgentToolContext` / skill download, the lease heartbeat, and the session tool |
| 5 |
runner. We stub `aiter_work`, the session tool runner, and the worker's |
| 6 |
`_copy_client_with_bearer_auth` helper so each test can drive a single |
| 7 |
claimed work item and assert the surrounding plumbing (skip non-session work, |
| 8 |
heartbeat the lease, force-stop on exit) — via both the `run()` poll loop |
| 9 |
and the single-item `handle_item()` entry point. |
| 10 |
|
| 11 |
After the auth refactor, heartbeat / force-stop traffic flows through a |
| 12 |
Bearer-only sub-client the worker constructs via the shared |
| 13 |
`_copy_client_with_bearer_auth` util. The tests intercept that helper so they |
| 14 |
can route those calls to a recording fake without spinning up a real |
| 15 |
`AsyncAnthropic` (and the httpx pool that comes with it). |
| 16 |
""" |
| 17 |
|
| 18 |
from __future__ import annotations |
| 19 |
|
| 20 |
import os |
| 21 |
import json |
| 22 |
import base64 |
| 23 |
import asyncio |
| 24 |
import logging |
| 25 |
import threading |
| 26 |
import contextlib |
| 27 |
from types import SimpleNamespace |
| 28 |
from typing import Any, Callable, cast |
| 29 |
from functools import partial |
| 30 |
from collections.abc import Awaitable, AsyncIterator |
| 31 |
from typing_extensions import override |
| 32 |
|
| 33 |
import anyio |
| 34 |
import httpx2 |
| 35 |
import pytest |
| 36 |
|
| 37 |
from anthropic import Anthropic, APIStatusError, AsyncAnthropic |
| 38 |
from anthropic._compat import PYDANTIC_V1 |
| 39 |
from anthropic.lib.environments import _worker as worker_mod |
| 40 |
from anthropic.lib.environments._worker import ( |
| 41 |
EnvironmentWorker, |
| 42 |
_Lease, |
| 43 |
_heartbeat_loop, |
| 44 |
_LeaseEndReason, |
| 45 |
_sessions_token_from_secret, |
| 46 |
) |
| 47 |
from anthropic.lib.tools._tool_dispatch import run_runnable_tool |
| 48 |
|
| 49 |
from ..tools.test_session_runner import _SyncTool |
| 50 |
|
| 51 |
|
| 52 |
def _encode_secret(payload: dict[str, Any]) -> str: |
| 53 |
"""Build a work-item `secret` the way the control plane does: URL-safe |
| 54 |
base64 of a JSON payload, without padding.""" |
| 55 |
return base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=") |
| 56 |
|
| 57 |
|
| 58 |
def _api_status_error(code: int, body: object = None) -> APIStatusError: |
| 59 |
request = httpx2.Request("POST", "https://api.example/heartbeat") |
| 60 |
response = httpx2.Response(status_code=code, request=request, content=json.dumps(body).encode()) |
| 61 |
return APIStatusError("boom", response=response, body=body) |
| 62 |
|
| 63 |
|
| 64 |
def _lease_lost_error() -> APIStatusError: |
| 65 |
"""The 412 the control plane answers a heartbeat with once the item's lease |
| 66 |
was cleared (re-queued) or is held by another worker.""" |
| 67 |
return _api_status_error( |
| 68 |
412, |
| 69 |
{ |
| 70 |
"type": "error", |
| 71 |
"error": { |
| 72 |
"type": "invalid_request_error", |
| 73 |
"message": "Heartbeat precondition failed: expected hb-1, actual was NULL", |
| 74 |
"details": { |
| 75 |
"error_code": "heartbeat_precondition_failed", |
| 76 |
"error_visibility": "user_facing", |
| 77 |
"current_state": { |
| 78 |
"state": "queued", |
| 79 |
"last_heartbeat": None, |
| 80 |
"lease_updated_at": None, |
| 81 |
"lease_extended": False, |
| 82 |
"ttl_seconds": 120, |
| 83 |
}, |
| 84 |
}, |
| 85 |
}, |
| 86 |
}, |
| 87 |
) |
| 88 |
|
| 89 |
|
| 90 |
class _FakeWorkResource: |
| 91 |
def __init__(self, *, heartbeat_state: str = "stopping", heartbeat_error: Exception | None = None) -> None: |
| 92 |
self._heartbeat_state = heartbeat_state |
| 93 |
self._heartbeat_error = heartbeat_error |
| 94 |
# When set, every heartbeat waits for this event before answering, so a |
| 95 |
# test decides *when* in the run the heartbeat's outcome lands. |
| 96 |
self.heartbeat_gate: asyncio.Event | None = None |
| 97 |
self.heartbeat_calls: list[dict[str, Any]] = [] |
| 98 |
self.stop_calls: list[dict[str, Any]] = [] |
| 99 |
|
| 100 |
async def heartbeat( |
| 101 |
self, |
| 102 |
work_id: str, |
| 103 |
*, |
| 104 |
environment_id: str, |
| 105 |
expected_last_heartbeat: str, # noqa: ARG002 |
| 106 |
extra_headers: Any = None, |
| 107 |
) -> Any: |
| 108 |
self.heartbeat_calls.append( |
| 109 |
{"work_id": work_id, "environment_id": environment_id, "extra_headers": extra_headers} |
| 110 |
) |
| 111 |
if self.heartbeat_gate is not None: |
| 112 |
await self.heartbeat_gate.wait() |
| 113 |
if self._heartbeat_error is not None: |
| 114 |
raise self._heartbeat_error |
| 115 |
return SimpleNamespace(last_heartbeat="hb-1", ttl_seconds=60, state=self._heartbeat_state, lease_extended=True) |
| 116 |
|
| 117 |
async def stop( |
| 118 |
self, |
| 119 |
work_id: str, |
| 120 |
*, |
| 121 |
environment_id: str, |
| 122 |
force: bool = False, |
| 123 |
extra_headers: Any = None, |
| 124 |
betas: Any = None, |
| 125 |
) -> None: |
| 126 |
self.stop_calls.append( |
| 127 |
{ |
| 128 |
"work_id": work_id, |
| 129 |
"environment_id": environment_id, |
| 130 |
"force": force, |
| 131 |
"extra_headers": extra_headers, |
| 132 |
"betas": betas, |
| 133 |
} |
| 134 |
) |
| 135 |
|
| 136 |
|
| 137 |
class _FakeSessions: |
| 138 |
def __init__(self) -> None: |
| 139 |
self.retrieve_calls: list[str] = [] |
| 140 |
|
| 141 |
async def retrieve(self, session_id: str, *, betas: Any = None) -> Any: # noqa: ARG002 |
| 142 |
self.retrieve_calls.append(session_id) |
| 143 |
return SimpleNamespace(agent=SimpleNamespace(skills=[]), resources=[]) |
| 144 |
|
| 145 |
|
| 146 |
def _fake_client(work: _FakeWorkResource, sessions: _FakeSessions) -> Any: |
| 147 |
return SimpleNamespace( |
| 148 |
beta=SimpleNamespace(sessions=sessions, environments=SimpleNamespace(work=work)), |
| 149 |
) |
| 150 |
|
| 151 |
|
| 152 |
def _install_scoped_client( |
| 153 |
monkeypatch: pytest.MonkeyPatch, work: _FakeWorkResource, sessions: _FakeSessions | None = None |
| 154 |
) -> list[dict[str, Any]]: |
| 155 |
"""Intercept the shared bearer-auth client factory. |
| 156 |
|
| 157 |
Returns the list of args the factory was called with so a test can assert |
| 158 |
on the helper-telemetry tag (one entry per call: poll, worker, …). |
| 159 |
""" |
| 160 |
calls: list[dict[str, Any]] = [] |
| 161 |
if sessions is None: |
| 162 |
sessions = _FakeSessions() |
| 163 |
fake_scoped = SimpleNamespace(beta=SimpleNamespace(sessions=sessions, environments=SimpleNamespace(work=work))) |
| 164 |
|
| 165 |
def fake_factory(client: Any, *, auth_token: str, helper: str) -> Any: # noqa: ARG001 |
| 166 |
calls.append({"auth_token": auth_token, "helper": helper}) |
| 167 |
return fake_scoped |
| 168 |
|
| 169 |
monkeypatch.setattr(worker_mod, "_copy_client_with_bearer_auth", fake_factory) |
| 170 |
return calls |
| 171 |
|
| 172 |
|
| 173 |
def _work_item( |
| 174 |
*, work_type: str = "session", work_id: str = "w_1", session_id: str = "s_1", secret: str | None = None |
| 175 |
) -> Any: |
| 176 |
return SimpleNamespace( |
| 177 |
id=work_id, environment_id="e_1", secret=secret, data=SimpleNamespace(type=work_type, id=session_id) |
| 178 |
) |
| 179 |
|
| 180 |
|
| 181 |
def _install_aiter_work(monkeypatch: pytest.MonkeyPatch, items: list[Any]) -> None: |
| 182 |
async def fake_aiter_work(_work: Any, **_kw: Any) -> AsyncIterator[Any]: |
| 183 |
for it in items: |
| 184 |
yield it |
| 185 |
|
| 186 |
monkeypatch.setattr(worker_mod, "aiter_work", fake_aiter_work) |
| 187 |
|
| 188 |
|
| 189 |
def _install_run_session_tools( |
| 190 |
monkeypatch: pytest.MonkeyPatch, |
| 191 |
record: dict[str, Any], |
| 192 |
*, |
| 193 |
serve: Callable[[], Awaitable[None]] | None = None, |
| 194 |
) -> None: |
| 195 |
@contextlib.asynccontextmanager |
| 196 |
async def fake_run_session_tools( |
| 197 |
_client: Any, |
| 198 |
session_id: str, |
| 199 |
*, |
| 200 |
tools: Any, |
| 201 |
max_idle: Any = None, |
| 202 |
environment_key: Any = None, |
| 203 |
extra_headers: Any = None, |
| 204 |
send_retry_window: Any = None, |
| 205 |
): |
| 206 |
record["run"] = { |
| 207 |
"session_id": session_id, |
| 208 |
"tools": tools, |
| 209 |
"max_idle": max_idle, |
| 210 |
"environment_key": environment_key, |
| 211 |
"extra_headers": extra_headers, |
| 212 |
} |
| 213 |
|
| 214 |
async def _iter() -> AsyncIterator[Any]: |
| 215 |
# With no `serve` the session completes on its own (no tool |
| 216 |
# calls) once the lease heartbeat has had a chance to land, and |
| 217 |
# the run ends via the normal session-completion path; the |
| 218 |
# heartbeat keeps the lease alive throughout and is stopped on the |
| 219 |
# way out. |
| 220 |
if serve is not None: |
| 221 |
await serve() |
| 222 |
else: |
| 223 |
await asyncio.sleep(0.05) |
| 224 |
record["send_retry_window"] = send_retry_window() if send_retry_window else None |
| 225 |
return |
| 226 |
yield # pragma: no cover (makes this an async generator function) |
| 227 |
|
| 228 |
yield _iter() |
| 229 |
|
| 230 |
monkeypatch.setattr(worker_mod, "_run_session_tools", fake_run_session_tools) |
| 231 |
|
| 232 |
|
| 233 |
@pytest.mark.skipif(PYDANTIC_V1, reason="tool functions are only supported with pydantic v2") |
| 234 |
@pytest.mark.asyncio() |
| 235 |
async def test_environment_worker_serves_session(monkeypatch: pytest.MonkeyPatch) -> None: |
| 236 |
work = _FakeWorkResource(heartbeat_state="running") |
| 237 |
sessions = _FakeSessions() |
| 238 |
client = _fake_client(work, sessions) |
| 239 |
_install_aiter_work(monkeypatch, [_work_item()]) |
| 240 |
scoped_calls = _install_scoped_client(monkeypatch, work, sessions) |
| 241 |
record: dict[str, Any] = {} |
| 242 |
_install_run_session_tools(monkeypatch, record) |
| 243 |
|
| 244 |
worker = EnvironmentWorker( |
| 245 |
client=client, |
| 246 |
environment_id="e_1", |
| 247 |
environment_key="env_key", |
| 248 |
workdir=".", |
| 249 |
max_idle=12.0, |
| 250 |
) |
| 251 |
await asyncio.wait_for(worker.run(), timeout=5) |
| 252 |
|
| 253 |
# AgentToolContext set up skills for the claimed session. |
| 254 |
assert sessions.retrieve_calls == ["s_1"] |
| 255 |
# The session tool runner ran with the right session + max_idle, the |
| 256 |
# environment key was threaded through, and the default toolset (a list of 6 |
| 257 |
# tools) was bound. |
| 258 |
assert record["run"]["session_id"] == "s_1" |
| 259 |
assert record["run"]["max_idle"] == 12.0 |
| 260 |
assert record["run"]["environment_key"] == "env_key" |
| 261 |
assert [t.name for t in record["run"]["tools"]] == ["bash", "read", "write", "edit", "glob", "grep"] |
| 262 |
# The lease was heartbeated, and the lease TTL it reported (60s) became the |
| 263 |
# runner's tool-result send retry window. |
| 264 |
assert len(work.heartbeat_calls) >= 1 |
| 265 |
assert record["send_retry_window"] == 60 |
| 266 |
# The work item was force-stopped on exit. |
| 267 |
assert len(work.stop_calls) == 1 |
| 268 |
assert work.stop_calls[0]["work_id"] == "w_1" |
| 269 |
assert work.stop_calls[0]["force"] is True |
| 270 |
# Auth flows through scoped sub-clients tagged with the right helper. |
| 271 |
# `run()` builds an `environments-work-poller`-tagged client for `aiter_work`; |
| 272 |
# each handled item builds an `environments-worker`-tagged client for the |
| 273 |
# heartbeat and force-stop. The environment key flows into both. |
| 274 |
assert scoped_calls == [ |
| 275 |
{"auth_token": "env_key", "helper": "environments-work-poller"}, |
| 276 |
{"auth_token": "env_key", "helper": "environments-worker"}, |
| 277 |
] |
| 278 |
|
| 279 |
|
| 280 |
@pytest.mark.asyncio() |
| 281 |
async def test_environment_worker_skips_non_session_item(monkeypatch: pytest.MonkeyPatch) -> None: |
| 282 |
"""The queue hands the worker a health check instead of a session. |
| 283 |
|
| 284 |
There is no session to look up or serve, but the item must still be |
| 285 |
stopped so the queue gets it back. |
| 286 |
""" |
| 287 |
# A worker whose queue holds a single health-check item. |
| 288 |
work = _FakeWorkResource(heartbeat_state="running") |
| 289 |
sessions = _FakeSessions() |
| 290 |
_install_aiter_work(monkeypatch, [_work_item(work_type="healthcheck")]) |
| 291 |
_install_scoped_client(monkeypatch, work, sessions) |
| 292 |
served: dict[str, Any] = {} |
| 293 |
_install_run_session_tools(monkeypatch, served) |
| 294 |
worker = EnvironmentWorker(_fake_client(work, sessions), environment_id="e_1", environment_key="k") |
| 295 |
|
| 296 |
await asyncio.wait_for(worker.run(), timeout=5) |
| 297 |
|
| 298 |
# No session was fetched or served... |
| 299 |
assert sessions.retrieve_calls == [] |
| 300 |
assert served == {} |
| 301 |
# ...but the item was still stopped. |
| 302 |
assert len(work.stop_calls) == 1 |
| 303 |
|
| 304 |
|
| 305 |
@pytest.mark.asyncio() |
| 306 |
async def test_environment_worker_accepts_tools_factory(monkeypatch: pytest.MonkeyPatch) -> None: |
| 307 |
work = _FakeWorkResource(heartbeat_state="running") |
| 308 |
sessions = _FakeSessions() |
| 309 |
client = _fake_client(work, sessions) |
| 310 |
_install_aiter_work(monkeypatch, [_work_item()]) |
| 311 |
_install_scoped_client(monkeypatch, work, sessions) |
| 312 |
record: dict[str, Any] = {} |
| 313 |
_install_run_session_tools(monkeypatch, record) |
| 314 |
|
| 315 |
sentinel = SimpleNamespace(name="custom") |
| 316 |
|
| 317 |
def factory(_env: Any) -> list[Any]: |
| 318 |
return [sentinel] |
| 319 |
|
| 320 |
worker = EnvironmentWorker( |
| 321 |
client=client, |
| 322 |
environment_id="e_1", |
| 323 |
environment_key="env_key", |
| 324 |
tools=factory, |
| 325 |
) |
| 326 |
await asyncio.wait_for(worker.run(), timeout=5) |
| 327 |
|
| 328 |
assert record["run"]["tools"] == [sentinel] |
| 329 |
|
| 330 |
|
| 331 |
@pytest.mark.skipif(PYDANTIC_V1, reason="tool functions are only supported with pydantic v2") |
| 332 |
@pytest.mark.asyncio() |
| 333 |
async def test_environment_worker_prefers_work_item_secret( |
| 334 |
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture |
| 335 |
) -> None: |
| 336 |
"""A claimed item carrying a per-item `secret` payload authenticates that |
| 337 |
item's heartbeat / force-stop / session-runner calls with the sessions |
| 338 |
token extracted from it; polling stays on the environment key. Neither the |
| 339 |
payload nor the token ever reaches the logs.""" |
| 340 |
secret = _encode_secret({"sessions_token": "sessions-token-item-1", "session_ingress_token": "ingress-token-1"}) |
| 341 |
work = _FakeWorkResource(heartbeat_state="running") |
| 342 |
sessions = _FakeSessions() |
| 343 |
client = _fake_client(work, sessions) |
| 344 |
_install_aiter_work(monkeypatch, [_work_item(secret=secret)]) |
| 345 |
scoped_calls = _install_scoped_client(monkeypatch, work, sessions) |
| 346 |
record: dict[str, Any] = {} |
| 347 |
_install_run_session_tools(monkeypatch, record) |
| 348 |
|
| 349 |
worker = EnvironmentWorker( |
| 350 |
client=client, |
| 351 |
environment_id="e_1", |
| 352 |
environment_key="env_key", |
| 353 |
workdir=".", |
| 354 |
) |
| 355 |
with caplog.at_level(logging.DEBUG, logger="anthropic.lib.environments"): |
| 356 |
await asyncio.wait_for(worker.run(), timeout=5) |
| 357 |
|
| 358 |
# Polling keeps the environment key; the per-item client switches to the |
| 359 |
# sessions token carried inside the work item's secret payload. |
| 360 |
assert scoped_calls == [ |
| 361 |
{"auth_token": "env_key", "helper": "environments-work-poller"}, |
| 362 |
{"auth_token": "sessions-token-item-1", "helper": "environments-worker"}, |
| 363 |
] |
| 364 |
# The session tool runner's bearer credential is the sessions token too. |
| 365 |
assert record["run"]["environment_key"] == "sessions-token-item-1" |
| 366 |
# The work item was still heartbeated and force-stopped as usual. |
| 367 |
assert len(work.heartbeat_calls) >= 1 |
| 368 |
assert work.stop_calls[0]["force"] is True |
| 369 |
# The credentials are opaque — neither the payload nor the extracted token |
| 370 |
# may appear in log output. |
| 371 |
assert secret not in caplog.text |
| 372 |
assert "sessions-token-item-1" not in caplog.text |
| 373 |
|
| 374 |
|
| 375 |
@pytest.mark.skipif(PYDANTIC_V1, reason="tool functions are only supported with pydantic v2") |
| 376 |
@pytest.mark.asyncio() |
| 377 |
async def test_environment_worker_falls_back_when_secret_undecodable( |
| 378 |
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture |
| 379 |
) -> None: |
| 380 |
"""A secret payload that doesn't decode (or carries no sessions token) |
| 381 |
falls back to the environment key, with a warning that doesn't include the |
| 382 |
payload itself.""" |
| 383 |
work = _FakeWorkResource(heartbeat_state="running") |
| 384 |
sessions = _FakeSessions() |
| 385 |
client = _fake_client(work, sessions) |
| 386 |
_install_aiter_work(monkeypatch, [_work_item(secret="not-a-valid-payload")]) |
| 387 |
scoped_calls = _install_scoped_client(monkeypatch, work, sessions) |
| 388 |
record: dict[str, Any] = {} |
| 389 |
_install_run_session_tools(monkeypatch, record) |
| 390 |
|
| 391 |
worker = EnvironmentWorker(client=client, environment_id="e_1", environment_key="env_key", workdir=".") |
| 392 |
with caplog.at_level(logging.DEBUG, logger="anthropic.lib.environments"): |
| 393 |
await asyncio.wait_for(worker.run(), timeout=5) |
| 394 |
|
| 395 |
assert scoped_calls == [ |
| 396 |
{"auth_token": "env_key", "helper": "environments-work-poller"}, |
| 397 |
{"auth_token": "env_key", "helper": "environments-worker"}, |
| 398 |
] |
| 399 |
assert record["run"]["environment_key"] == "env_key" |
| 400 |
assert "no sessions token could be extracted" in caplog.text |
| 401 |
assert "not-a-valid-payload" not in caplog.text |
| 402 |
|
| 403 |
|
| 404 |
def test_sessions_token_from_secret() -> None: |
| 405 |
"""The secret payload decodes from URL-safe base64 JSON (with or without |
| 406 |
padding); anything malformed or token-less resolves to None.""" |
| 407 |
payload = {"sessions_token": "sessions-token-abc", "auth": [{"type": "anthropic_oauth", "token": "oauth"}]} |
| 408 |
unpadded = _encode_secret(payload) |
| 409 |
padded = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode() |
| 410 |
|
| 411 |
assert _sessions_token_from_secret(unpadded) == "sessions-token-abc" |
| 412 |
assert _sessions_token_from_secret(padded) == "sessions-token-abc" |
| 413 |
assert _sessions_token_from_secret(None) is None |
| 414 |
assert _sessions_token_from_secret("") is None |
| 415 |
assert _sessions_token_from_secret("!!! not base64 !!!") is None |
| 416 |
# Valid base64 but not JSON / not an object / missing or empty token. |
| 417 |
assert _sessions_token_from_secret(base64.urlsafe_b64encode(b"plain text").decode()) is None |
| 418 |
assert _sessions_token_from_secret(_encode_secret({"session_ingress_token": "ingress-token-1"})) is None |
| 419 |
assert _sessions_token_from_secret(_encode_secret({"sessions_token": ""})) is None |
| 420 |
|
| 421 |
|
| 422 |
@pytest.mark.skipif(PYDANTIC_V1, reason="tool functions are only supported with pydantic v2") |
| 423 |
@pytest.mark.asyncio() |
| 424 |
async def test_secret_not_logged_on_error_paths( |
| 425 |
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture |
| 426 |
) -> None: |
| 427 |
"""Error-path logging (heartbeat shutdown, force-stop failure) must not leak |
| 428 |
the per-item secret payload or its sessions token.""" |
| 429 |
secret = _encode_secret({"sessions_token": "sessions-token-err"}) |
| 430 |
work = _FakeWorkResource(heartbeat_state="stopping") |
| 431 |
|
| 432 |
failing_stop_calls: list[str] = [] |
| 433 |
|
| 434 |
async def failing_stop(work_id: str, **_kw: Any) -> None: |
| 435 |
failing_stop_calls.append(work_id) |
| 436 |
raise RuntimeError("force-stop exploded") |
| 437 |
|
| 438 |
work.stop = failing_stop # type: ignore[method-assign] |
| 439 |
sessions = _FakeSessions() |
| 440 |
client = _fake_client(work, sessions) |
| 441 |
_install_aiter_work(monkeypatch, [_work_item(secret=secret)]) |
| 442 |
_install_scoped_client(monkeypatch, work, sessions) |
| 443 |
record: dict[str, Any] = {} |
| 444 |
_install_run_session_tools(monkeypatch, record) |
| 445 |
|
| 446 |
worker = EnvironmentWorker(client=client, environment_id="e_1", environment_key="env_key", workdir=".") |
| 447 |
with caplog.at_level(logging.DEBUG, logger="anthropic.lib.environments"): |
| 448 |
await asyncio.wait_for(worker.run(), timeout=5) |
| 449 |
|
| 450 |
# The error branches actually ran (heartbeat signalled shutdown, the |
| 451 |
# force-stop failure was logged) ... |
| 452 |
assert failing_stop_calls == ["w_1"] |
| 453 |
assert "force-stop on exit failed" in caplog.text |
| 454 |
# ... and none of them leaked the payload or the token inside it. |
| 455 |
assert secret not in caplog.text |
| 456 |
assert "sessions-token-err" not in caplog.text |
| 457 |
|
| 458 |
|
| 459 |
def _no_tools(_env: Any) -> list[Any]: |
| 460 |
return [] |
| 461 |
|
| 462 |
|
| 463 |
def _install_session_ended_by_heartbeat( |
| 464 |
monkeypatch: pytest.MonkeyPatch, work: _FakeWorkResource, record: dict[str, Any] |
| 465 |
) -> None: |
| 466 |
"""A session that never completes on its own, with the fake heartbeat held |
| 467 |
back until the runner is serving it: the heartbeat's outcome — not skill |
| 468 |
setup or session completion — decides how the run ends.""" |
| 469 |
serving = asyncio.Event() |
| 470 |
work.heartbeat_gate = serving |
| 471 |
|
| 472 |
async def serve() -> None: |
| 473 |
serving.set() |
| 474 |
await asyncio.Event().wait() |
| 475 |
|
| 476 |
_install_run_session_tools(monkeypatch, record, serve=serve) |
| 477 |
|
| 478 |
|
| 479 |
@pytest.mark.asyncio() |
| 480 |
async def test_heartbeat_412_releases_item_without_stopping_it( |
| 481 |
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture |
| 482 |
) -> None: |
| 483 |
"""A 412 on the heartbeat means the server cleared this worker's lease |
| 484 |
(re-queued the item, or another worker holds it). The run ends, the item |
| 485 |
is NOT force-stopped — that would take it away from its new holder — and |
| 486 |
the worker goes back to polling.""" |
| 487 |
work = _FakeWorkResource(heartbeat_error=_lease_lost_error()) |
| 488 |
sessions = _FakeSessions() |
| 489 |
client = _fake_client(work, sessions) |
| 490 |
_install_scoped_client(monkeypatch, work, sessions) |
| 491 |
record: dict[str, Any] = {} |
| 492 |
_install_session_ended_by_heartbeat(monkeypatch, work, record) |
| 493 |
|
| 494 |
polls: list[str] = [] |
| 495 |
|
| 496 |
async def fake_aiter_work(_work: Any, **_kw: Any) -> AsyncIterator[Any]: |
| 497 |
polls.append("poll") |
| 498 |
yield _work_item() |
| 499 |
polls.append("poll") |
| 500 |
|
| 501 |
monkeypatch.setattr(worker_mod, "aiter_work", fake_aiter_work) |
| 502 |
|
| 503 |
worker = EnvironmentWorker( |
| 504 |
client=client, environment_id="e_1", environment_key="env_key", workdir=".", tools=_no_tools |
| 505 |
) |
| 506 |
with caplog.at_level(logging.INFO, logger="anthropic.lib.environments"): |
| 507 |
await asyncio.wait_for(worker.run(), timeout=5) |
| 508 |
|
| 509 |
assert record["run"]["session_id"] == "s_1" |
| 510 |
assert len(work.heartbeat_calls) == 1 |
| 511 |
assert work.stop_calls == [] |
| 512 |
assert polls == ["poll", "poll"], "run() must go back to the poller after releasing the item" |
| 513 |
assert ( |
| 514 |
"lease lost: heartbeat precondition failed work_id=w_1 " |
| 515 |
"server_state=queued server_ttl_seconds=120 server_last_heartbeat=None" |
| 516 |
) in caplog.text |
| 517 |
assert "lease lost; released work_id=w_1 session_id=s_1 without stopping it" in caplog.text |
| 518 |
assert "work item failed" not in caplog.text |
| 519 |
|
| 520 |
|
| 521 |
@pytest.mark.asyncio() |
| 522 |
async def test_control_plane_stop_still_force_stops( |
| 523 |
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture |
| 524 |
) -> None: |
| 525 |
"""A heartbeat reporting `state == "stopped"` ends the run and the item |
| 526 |
is still force-stopped on the way out — only a *lost* lease skips that.""" |
| 527 |
work = _FakeWorkResource(heartbeat_state="stopped") |
| 528 |
sessions = _FakeSessions() |
| 529 |
client = _fake_client(work, sessions) |
| 530 |
_install_scoped_client(monkeypatch, work, sessions) |
| 531 |
_install_aiter_work(monkeypatch, [_work_item()]) |
| 532 |
record: dict[str, Any] = {} |
| 533 |
_install_session_ended_by_heartbeat(monkeypatch, work, record) |
| 534 |
|
| 535 |
worker = EnvironmentWorker( |
| 536 |
client=client, environment_id="e_1", environment_key="env_key", workdir=".", tools=_no_tools |
| 537 |
) |
| 538 |
with caplog.at_level(logging.INFO, logger="anthropic.lib.environments"): |
| 539 |
await asyncio.wait_for(worker.run(), timeout=5) |
| 540 |
|
| 541 |
assert record["run"]["session_id"] == "s_1" |
| 542 |
assert "heartbeat signals shutdown state=stopped" in caplog.text |
| 543 |
assert len(work.stop_calls) == 1 |
| 544 |
assert work.stop_calls[0]["work_id"] == "w_1" |
| 545 |
assert work.stop_calls[0]["force"] is True |
| 546 |
assert "without stopping it" not in caplog.text |
| 547 |
|
| 548 |
|
| 549 |
@pytest.mark.asyncio() |
| 550 |
async def test_lease_assumed_lost_releases_item_without_stopping_it( |
| 551 |
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture |
| 552 |
) -> None: |
| 553 |
"""Transient heartbeat failures lasting past the lease TTL mean another |
| 554 |
worker may hold the item by now, so it is released without a force-stop.""" |
| 555 |
work = _FakeWorkResource(heartbeat_error=_api_status_error(503)) |
| 556 |
sessions = _FakeSessions() |
| 557 |
client = _fake_client(work, sessions) |
| 558 |
_install_scoped_client(monkeypatch, work, sessions) |
| 559 |
_install_aiter_work(monkeypatch, [_work_item()]) |
| 560 |
record: dict[str, Any] = {} |
| 561 |
_install_session_ended_by_heartbeat(monkeypatch, work, record) |
| 562 |
|
| 563 |
# Each clock read lands 100s after the previous one, so the very first |
| 564 |
# transient failure is already past the 90s default TTL. |
| 565 |
ticks = iter(range(0, 10_000, 100)) |
| 566 |
monkeypatch.setattr(worker_mod, "time", SimpleNamespace(monotonic=lambda: float(next(ticks)))) |
| 567 |
|
| 568 |
worker = EnvironmentWorker( |
| 569 |
client=client, environment_id="e_1", environment_key="env_key", workdir=".", tools=_no_tools |
| 570 |
) |
| 571 |
with caplog.at_level(logging.INFO, logger="anthropic.lib.environments"): |
| 572 |
await asyncio.wait_for(worker.run(), timeout=5) |
| 573 |
|
| 574 |
assert record["run"]["session_id"] == "s_1" |
| 575 |
assert "lease assumed lost: no successful heartbeat in 90s" in caplog.text |
| 576 |
assert work.stop_calls == [] |
| 577 |
assert "lease lost; released work_id=w_1 session_id=s_1 without stopping it" in caplog.text |
| 578 |
|
| 579 |
|
| 580 |
@pytest.mark.asyncio() |
| 581 |
async def test_lease_lost_classification() -> None: |
| 582 |
"""Only the two reasons where the item now belongs to someone else read as |
| 583 |
lost; every other reason, and no recorded reason at all, keeps the |
| 584 |
force-stop. The first recorded reason wins over the runner's own finish.""" |
| 585 |
for reason, lost in [ |
| 586 |
(_LeaseEndReason.LEASE_LOST, True), |
| 587 |
(_LeaseEndReason.ASSUMED_LOST, True), |
| 588 |
(_LeaseEndReason.CONTROL_PLANE_STOP, False), |
| 589 |
(_LeaseEndReason.HEARTBEAT_REJECTED, False), |
| 590 |
(_LeaseEndReason.RUNNER_DONE, False), |
| 591 |
]: |
| 592 |
lease = _Lease() |
| 593 |
assert not lease.ended |
| 594 |
assert not lease.lost |
| 595 |
lease.finish(reason) |
| 596 |
lease.finish(_LeaseEndReason.RUNNER_DONE) |
| 597 |
assert lease.ended |
| 598 |
assert lease._end_reason is reason |
| 599 |
assert lease.lost is lost, reason |
| 600 |
|
| 601 |
|
| 602 |
@pytest.mark.asyncio() |
| 603 |
async def test_run_requires_environment_id_and_environment_key() -> None: |
| 604 |
work = _FakeWorkResource() |
| 605 |
sessions = _FakeSessions() |
| 606 |
client = _fake_client(work, sessions) |
| 607 |
|
| 608 |
worker = EnvironmentWorker(client, workdir=".") |
| 609 |
with pytest.raises(ValueError, match="environment_id and environment_key are required"): |
| 610 |
await worker.run() |
| 611 |
|
| 612 |
|
| 613 |
@pytest.mark.skipif(PYDANTIC_V1, reason="tool functions are only supported with pydantic v2") |
| 614 |
@pytest.mark.asyncio() |
| 615 |
async def test_handle_item_services_a_single_claimed_item(monkeypatch: pytest.MonkeyPatch) -> None: |
| 616 |
work = _FakeWorkResource(heartbeat_state="running") |
| 617 |
sessions = _FakeSessions() |
| 618 |
client = _fake_client(work, sessions) |
| 619 |
scoped_calls = _install_scoped_client(monkeypatch, work, sessions) |
| 620 |
record: dict[str, Any] = {} |
| 621 |
_install_run_session_tools(monkeypatch, record) |
| 622 |
# handle_item should not poll for work at all. |
| 623 |
_install_aiter_work(monkeypatch, []) |
| 624 |
# A leftover per-item secret on the host must not override the explicit key. |
| 625 |
monkeypatch.delenv("ANTHROPIC_WORK_SECRET", raising=False) |
| 626 |
|
| 627 |
# No environment_id needed for the single-item flow. |
| 628 |
worker = EnvironmentWorker(client, workdir=".", max_idle=7.0) |
| 629 |
await asyncio.wait_for( |
| 630 |
worker.handle_item(work_id="w_1", environment_id="e_1", session_id="s_1", environment_key="env_key"), |
| 631 |
timeout=5, |
| 632 |
) |
| 633 |
|
| 634 |
assert sessions.retrieve_calls == ["s_1"] |
| 635 |
assert record["run"]["session_id"] == "s_1" |
| 636 |
assert record["run"]["max_idle"] == 7.0 |
| 637 |
assert record["run"]["environment_key"] == "env_key" |
| 638 |
assert len(work.heartbeat_calls) >= 1 |
| 639 |
# Auth lives on the scoped sub-client now, not in extra_headers — so the |
| 640 |
# heartbeat goes out with no per-call extras (None) unless the worker was |
| 641 |
# constructed with passthrough headers. |
| 642 |
assert work.heartbeat_calls[0] == { |
| 643 |
"work_id": "w_1", |
| 644 |
"environment_id": "e_1", |
| 645 |
"extra_headers": None, |
| 646 |
} |
| 647 |
assert len(work.stop_calls) == 1 |
| 648 |
assert work.stop_calls[0]["work_id"] == "w_1" |
| 649 |
assert work.stop_calls[0]["force"] is True |
| 650 |
# `handle_item` doesn't poll, so only the heartbeat/force-stop scoped |
| 651 |
# client is built — tagged `environments-worker`. |
| 652 |
assert scoped_calls == [{"auth_token": "env_key", "helper": "environments-worker"}] |
| 653 |
|
| 654 |
|
| 655 |
@pytest.mark.skipif(PYDANTIC_V1, reason="tool functions are only supported with pydantic v2") |
| 656 |
@pytest.mark.asyncio() |
| 657 |
async def test_handle_item_falls_back_to_env_vars(monkeypatch: pytest.MonkeyPatch) -> None: |
| 658 |
work = _FakeWorkResource(heartbeat_state="running") |
| 659 |
sessions = _FakeSessions() |
| 660 |
client = _fake_client(work, sessions) |
| 661 |
scoped_calls = _install_scoped_client(monkeypatch, work, sessions) |
| 662 |
record: dict[str, Any] = {} |
| 663 |
_install_run_session_tools(monkeypatch, record) |
| 664 |
|
| 665 |
monkeypatch.setenv("ANTHROPIC_WORK_ID", "w_env") |
| 666 |
monkeypatch.setenv("ANTHROPIC_ENVIRONMENT_ID", "e_env") |
| 667 |
monkeypatch.setenv("ANTHROPIC_SESSION_ID", "s_env") |
| 668 |
monkeypatch.setenv("ANTHROPIC_ENVIRONMENT_KEY", "key_env") |
| 669 |
monkeypatch.delenv("ANTHROPIC_WORK_SECRET", raising=False) |
| 670 |
|
| 671 |
worker = EnvironmentWorker(client, workdir=".") |
| 672 |
await asyncio.wait_for(worker.handle_item(), timeout=5) |
| 673 |
|
| 674 |
assert sessions.retrieve_calls == ["s_env"] |
| 675 |
assert record["run"]["session_id"] == "s_env" |
| 676 |
assert record["run"]["environment_key"] == "key_env" |
| 677 |
assert work.heartbeat_calls[0] == { |
| 678 |
"work_id": "w_env", |
| 679 |
"environment_id": "e_env", |
| 680 |
"extra_headers": None, |
| 681 |
} |
| 682 |
assert work.stop_calls[0]["work_id"] == "w_env" |
| 683 |
assert scoped_calls == [{"auth_token": "key_env", "helper": "environments-worker"}] |
| 684 |
|
| 685 |
|
| 686 |
@pytest.mark.skipif(PYDANTIC_V1, reason="tool functions are only supported with pydantic v2") |
| 687 |
@pytest.mark.asyncio() |
| 688 |
async def test_handle_item_uses_constructor_environment_key(monkeypatch: pytest.MonkeyPatch) -> None: |
| 689 |
"""`environment_key` resolves to the worker's own key when not passed and |
| 690 |
no env var is set.""" |
| 691 |
work = _FakeWorkResource(heartbeat_state="running") |
| 692 |
sessions = _FakeSessions() |
| 693 |
client = _fake_client(work, sessions) |
| 694 |
scoped_calls = _install_scoped_client(monkeypatch, work, sessions) |
| 695 |
record: dict[str, Any] = {} |
| 696 |
_install_run_session_tools(monkeypatch, record) |
| 697 |
|
| 698 |
monkeypatch.delenv("ANTHROPIC_ENVIRONMENT_KEY", raising=False) |
| 699 |
monkeypatch.delenv("ANTHROPIC_WORK_SECRET", raising=False) |
| 700 |
|
| 701 |
worker = EnvironmentWorker(client, environment_key="ctor_key", workdir=".") |
| 702 |
await asyncio.wait_for( |
| 703 |
worker.handle_item(work_id="w_1", environment_id="e_1", session_id="s_1"), |
| 704 |
timeout=5, |
| 705 |
) |
| 706 |
|
| 707 |
assert record["run"]["environment_key"] == "ctor_key" |
| 708 |
assert scoped_calls == [{"auth_token": "ctor_key", "helper": "environments-worker"}] |
| 709 |
|
| 710 |
|
| 711 |
@pytest.mark.skipif(PYDANTIC_V1, reason="tool functions are only supported with pydantic v2") |
| 712 |
@pytest.mark.asyncio() |
| 713 |
async def test_handle_item_uses_work_secret_argument(monkeypatch: pytest.MonkeyPatch) -> None: |
| 714 |
"""An explicit `work_secret` payload supplies the per-item Bearer |
| 715 |
credential (its sessions token); an `environment_key` passed alongside it |
| 716 |
is only the fallback.""" |
| 717 |
secret = _encode_secret({"sessions_token": "sessions-token-arg"}) |
| 718 |
work = _FakeWorkResource(heartbeat_state="running") |
| 719 |
sessions = _FakeSessions() |
| 720 |
client = _fake_client(work, sessions) |
| 721 |
scoped_calls = _install_scoped_client(monkeypatch, work, sessions) |
| 722 |
record: dict[str, Any] = {} |
| 723 |
_install_run_session_tools(monkeypatch, record) |
| 724 |
|
| 725 |
worker = EnvironmentWorker(client, workdir=".") |
| 726 |
await asyncio.wait_for( |
| 727 |
worker.handle_item( |
| 728 |
work_id="w_1", |
| 729 |
environment_id="e_1", |
| 730 |
session_id="s_1", |
| 731 |
environment_key="env_key", |
| 732 |
work_secret=secret, |
| 733 |
), |
| 734 |
timeout=5, |
| 735 |
) |
| 736 |
|
| 737 |
assert scoped_calls == [{"auth_token": "sessions-token-arg", "helper": "environments-worker"}] |
| 738 |
assert record["run"]["environment_key"] == "sessions-token-arg" |
| 739 |
|
| 740 |
|
| 741 |
@pytest.mark.skipif(PYDANTIC_V1, reason="tool functions are only supported with pydantic v2") |
| 742 |
@pytest.mark.asyncio() |
| 743 |
async def test_handle_item_falls_back_to_work_secret_env_var(monkeypatch: pytest.MonkeyPatch) -> None: |
| 744 |
"""`work_secret` falls back to `ANTHROPIC_WORK_SECRET` (the env var the |
| 745 |
`worker poll --on-work` command sets alongside the others); when neither |
| 746 |
is present the environment key is used — the existing |
| 747 |
`test_handle_item_*` cases cover that path.""" |
| 748 |
secret = _encode_secret({"sessions_token": "sessions-token-env"}) |
| 749 |
work = _FakeWorkResource(heartbeat_state="running") |
| 750 |
sessions = _FakeSessions() |
| 751 |
client = _fake_client(work, sessions) |
| 752 |
scoped_calls = _install_scoped_client(monkeypatch, work, sessions) |
| 753 |
record: dict[str, Any] = {} |
| 754 |
_install_run_session_tools(monkeypatch, record) |
| 755 |
|
| 756 |
monkeypatch.setenv("ANTHROPIC_WORK_ID", "w_env") |
| 757 |
monkeypatch.setenv("ANTHROPIC_ENVIRONMENT_ID", "e_env") |
| 758 |
monkeypatch.setenv("ANTHROPIC_SESSION_ID", "s_env") |
| 759 |
monkeypatch.setenv("ANTHROPIC_ENVIRONMENT_KEY", "key_env") |
| 760 |
monkeypatch.setenv("ANTHROPIC_WORK_SECRET", secret) |
| 761 |
|
| 762 |
worker = EnvironmentWorker(client, workdir=".") |
| 763 |
await asyncio.wait_for(worker.handle_item(), timeout=5) |
| 764 |
|
| 765 |
assert scoped_calls == [{"auth_token": "sessions-token-env", "helper": "environments-worker"}] |
| 766 |
assert record["run"]["environment_key"] == "sessions-token-env" |
| 767 |
assert work.stop_calls[0]["work_id"] == "w_env" |
| 768 |
|
| 769 |
|
| 770 |
@pytest.mark.asyncio() |
| 771 |
async def test_handle_item_missing_required_raises(monkeypatch: pytest.MonkeyPatch) -> None: |
| 772 |
work = _FakeWorkResource() |
| 773 |
sessions = _FakeSessions() |
| 774 |
client = _fake_client(work, sessions) |
| 775 |
|
| 776 |
for var in ( |
| 777 |
"ANTHROPIC_WORK_ID", |
| 778 |
"ANTHROPIC_ENVIRONMENT_ID", |
| 779 |
"ANTHROPIC_SESSION_ID", |
| 780 |
"ANTHROPIC_ENVIRONMENT_KEY", |
| 781 |
"ANTHROPIC_WORK_SECRET", |
| 782 |
): |
| 783 |
monkeypatch.delenv(var, raising=False) |
| 784 |
|
| 785 |
worker = EnvironmentWorker(client, workdir=".") |
| 786 |
|
| 787 |
# Nothing supplied at all -> the first missing one (work_id) is named. |
| 788 |
with pytest.raises(ValueError, match=r"handle_item: work_id is required — pass it or set ANTHROPIC_WORK_ID"): |
| 789 |
await worker.handle_item() |
| 790 |
|
| 791 |
# environment_key still missing, and no work secret to stand in for it. |
| 792 |
with pytest.raises( |
| 793 |
ValueError, match=r"handle_item: environment_key is required — pass it or set ANTHROPIC_ENVIRONMENT_KEY" |
| 794 |
): |
| 795 |
await worker.handle_item(work_id="w_1", environment_id="e_1", session_id="s_1") |
| 796 |
|
| 797 |
|
| 798 |
@pytest.mark.skipif(PYDANTIC_V1, reason="tool functions are only supported with pydantic v2") |
| 799 |
@pytest.mark.asyncio() |
| 800 |
async def test_handle_item_runs_keyless_on_a_token_bearing_secret(monkeypatch: pytest.MonkeyPatch) -> None: |
| 801 |
"""With no environment key anywhere — argument, constructor, or env var — |
| 802 |
a work secret whose payload carries a sessions token is credential enough: |
| 803 |
every per-item call rides that token. (The on-prem Kubernetes sandbox hands |
| 804 |
the pod only the short-lived secret; the pod never holds the key.)""" |
| 805 |
secret = _encode_secret({"sessions_token": "sessions-token-keyless"}) |
| 806 |
work = _FakeWorkResource(heartbeat_state="running") |
| 807 |
sessions = _FakeSessions() |
| 808 |
client = _fake_client(work, sessions) |
| 809 |
scoped_calls = _install_scoped_client(monkeypatch, work, sessions) |
| 810 |
record: dict[str, Any] = {} |
| 811 |
_install_run_session_tools(monkeypatch, record) |
| 812 |
monkeypatch.delenv("ANTHROPIC_ENVIRONMENT_KEY", raising=False) |
| 813 |
monkeypatch.delenv("ANTHROPIC_WORK_SECRET", raising=False) |
| 814 |
|
| 815 |
worker = EnvironmentWorker(client, workdir=".") |
| 816 |
await asyncio.wait_for( |
| 817 |
worker.handle_item(work_id="w_1", environment_id="e_1", session_id="s_1", work_secret=secret), |
| 818 |
timeout=5, |
| 819 |
) |
| 820 |
|
| 821 |
assert scoped_calls == [{"auth_token": "sessions-token-keyless", "helper": "environments-worker"}] |
| 822 |
assert record["run"]["environment_key"] == "sessions-token-keyless" |
| 823 |
assert sessions.retrieve_calls == ["s_1"] |
| 824 |
assert work.stop_calls[0]["work_id"] == "w_1" |
| 825 |
|
| 826 |
|
| 827 |
@pytest.mark.asyncio() |
| 828 |
async def test_handle_item_keyless_with_a_tokenless_secret_raises(monkeypatch: pytest.MonkeyPatch) -> None: |
| 829 |
"""A work secret that yields no sessions token, with no environment key to |
| 830 |
fall back to, must not run the item unauthenticated: the error names both |
| 831 |
ways out (a token-bearing secret, or the key), and no call is made.""" |
| 832 |
work = _FakeWorkResource() |
| 833 |
sessions = _FakeSessions() |
| 834 |
client = _fake_client(work, sessions) |
| 835 |
scoped_calls = _install_scoped_client(monkeypatch, work, sessions) |
| 836 |
monkeypatch.delenv("ANTHROPIC_ENVIRONMENT_KEY", raising=False) |
| 837 |
|
| 838 |
worker = EnvironmentWorker(client, workdir=".") |
| 839 |
with pytest.raises(ValueError, match=r"sessions_token, or an environment key"): |
| 840 |
await worker.handle_item( |
| 841 |
work_id="w_1", environment_id="e_1", session_id="s_1", work_secret="not-a-valid-payload" |
| 842 |
) |
| 843 |
|
| 844 |
assert scoped_calls == [] |
| 845 |
assert work.heartbeat_calls == [] |
| 846 |
assert work.stop_calls == [] |
| 847 |
|
| 848 |
|
| 849 |
@pytest.mark.skipif(PYDANTIC_V1, reason="tool functions are only supported with pydantic v2") |
| 850 |
@pytest.mark.asyncio() |
| 851 |
async def test_worker_threads_extra_headers_into_poll_heartbeat_stop_and_runner( |
| 852 |
monkeypatch: pytest.MonkeyPatch, |
| 853 |
) -> None: |
| 854 |
"""A worker-level `extra_headers` is threaded, unchanged, into every |
| 855 |
per-request call the worker drives: the poll loop (forwarded to |
| 856 |
`aiter_work`), the lease heartbeat, the force-stop, and the session |
| 857 |
tool runner. |
| 858 |
|
| 859 |
The worker does no header munging — it passes the caller's mapping |
| 860 |
through to each call's `extra_headers=`. Auth stays on the scoped |
| 861 |
sub-clients the worker builds (`env_key` Bearer), independent of this |
| 862 |
passthrough. |
| 863 |
""" |
| 864 |
work = _FakeWorkResource(heartbeat_state="running") |
| 865 |
sessions = _FakeSessions() |
| 866 |
client = _fake_client(work, sessions) |
| 867 |
scoped_calls = _install_scoped_client(monkeypatch, work, sessions) |
| 868 |
|
| 869 |
aiter_kwargs: dict[str, Any] = {} |
| 870 |
|
| 871 |
async def fake_aiter_work(_work: Any, **kw: Any) -> AsyncIterator[Any]: |
| 872 |
aiter_kwargs.update(kw) |
| 873 |
yield _work_item() |
| 874 |
|
| 875 |
monkeypatch.setattr(worker_mod, "aiter_work", fake_aiter_work) |
| 876 |
record: dict[str, Any] = {} |
| 877 |
_install_run_session_tools(monkeypatch, record) |
| 878 |
|
| 879 |
extras = {"x-trace-id": "abc123"} |
| 880 |
worker = EnvironmentWorker( |
| 881 |
client=client, |
| 882 |
environment_id="e_1", |
| 883 |
environment_key="env_key", |
| 884 |
workdir=".", |
| 885 |
extra_headers=extras, |
| 886 |
) |
| 887 |
await asyncio.wait_for(worker.run(), timeout=5) |
| 888 |
|
| 889 |
# The poll loop, heartbeat and force-stop each receive the caller's |
| 890 |
# passthrough mapping unchanged. |
| 891 |
assert aiter_kwargs["extra_headers"] == extras |
| 892 |
assert work.heartbeat_calls[0]["extra_headers"] == extras |
| 893 |
assert work.stop_calls[0]["extra_headers"] == extras |
| 894 |
# The session tool runner is handed the same passthrough mapping (and the |
| 895 |
# environment key, which it uses to build its own scoped sub-client). |
| 896 |
assert record["run"]["extra_headers"] == extras |
| 897 |
assert record["run"]["environment_key"] == "env_key" |
| 898 |
# Two scoped sub-clients are constructed per run() pass: one for the |
| 899 |
# poller, one for the worker (heartbeat / force-stop). Both use the same |
| 900 |
# environment key as their Bearer credential. |
| 901 |
assert scoped_calls == [ |
| 902 |
{"auth_token": "env_key", "helper": "environments-work-poller"}, |
| 903 |
{"auth_token": "env_key", "helper": "environments-worker"}, |
| 904 |
] |
| 905 |
|
| 906 |
|
| 907 |
def test_work_resource_worker_builds_environment_worker() -> None: |
| 908 |
"""`client.beta.environments.work.worker(...)` builds an `EnvironmentWorker` |
| 909 |
bound to the client, with the options threaded through (mirrors `poller`).""" |
| 910 |
client = AsyncAnthropic(api_key="x") |
| 911 |
worker = client.beta.environments.work.worker( |
| 912 |
environment_id="e_1", |
| 913 |
environment_key="env_key", |
| 914 |
workdir="/workspace", |
| 915 |
max_idle=12.0, |
| 916 |
memory_sync_interval=45.0, |
| 917 |
memory_sync_deletions="log_only", |
| 918 |
worker_id="w-test", |
| 919 |
extra_headers={"x-trace-id": "abc123"}, |
| 920 |
) |
| 921 |
assert isinstance(worker, EnvironmentWorker) |
| 922 |
assert worker._client is client |
| 923 |
assert worker._environment_id == "e_1" |
| 924 |
assert worker._environment_key == "env_key" |
| 925 |
assert worker._workdir == "/workspace" |
| 926 |
assert worker._max_idle == 12.0 |
| 927 |
assert worker._memory_sync_interval == 45.0 |
| 928 |
assert worker._memory_sync_deletions == "log_only" |
| 929 |
assert worker._worker_id == "w-test" |
| 930 |
assert worker._extra_headers == {"x-trace-id": "abc123"} |
| 931 |
|
| 932 |
|
| 933 |
@pytest.mark.parametrize("value", [True, False]) |
| 934 |
def test_unrestricted_paths_is_rejected_at_construction(value: bool) -> None: |
| 935 |
client = AsyncAnthropic(api_key="x") |
| 936 |
with pytest.raises(TypeError, match="unrestricted_paths is no longer supported"): |
| 937 |
EnvironmentWorker(client, unrestricted_paths=value) # pyright: ignore[reportDeprecated] |
| 938 |
with pytest.raises(TypeError, match="unrestricted_paths is no longer supported"): |
| 939 |
client.beta.environments.work.worker(unrestricted_paths=value) # pyright: ignore[reportDeprecated] |
| 940 |
|
| 941 |
|
| 942 |
def test_work_resource_worker_defaults() -> None: |
| 943 |
worker = AsyncAnthropic(api_key="x").beta.environments.work.worker() |
| 944 |
assert isinstance(worker, EnvironmentWorker) |
| 945 |
assert worker._environment_id is None |
| 946 |
assert worker._environment_key is None |
| 947 |
assert worker._tools is None |
| 948 |
# Default workdir is the cwd snapshotted at construction (not a lazily |
| 949 |
# resolved ".") — TS parity with process.cwd()-at-construction. |
| 950 |
assert worker._workdir == os.getcwd() |
| 951 |
assert worker._max_idle == 60.0 |
| 952 |
assert worker._memory_sync_interval == 15.0 |
| 953 |
assert worker._memory_sync_deletions == "enabled" |
| 954 |
|
| 955 |
|
| 956 |
def test_work_resource_worker_and_poller_async_only() -> None: |
| 957 |
"""`worker()` / `poller()` build an async-only `EnvironmentWorker` / |
| 958 |
`aiter_work` generator, so they live on `AsyncWork` and are NOT exposed |
| 959 |
on the sync `Work` resource (calling them from the sync client would hand |
| 960 |
back coroutines/async iterators that can't run without an event loop).""" |
| 961 |
async_work = AsyncAnthropic(api_key="x").beta.environments.work |
| 962 |
assert hasattr(async_work, "worker") |
| 963 |
assert hasattr(async_work, "poller") |
| 964 |
|
| 965 |
sync_work = Anthropic(api_key="x").beta.environments.work |
| 966 |
assert not hasattr(sync_work, "worker") |
| 967 |
assert not hasattr(sync_work, "poller") |
| 968 |
|
| 969 |
|
| 970 |
@pytest.mark.skipif(PYDANTIC_V1, reason="tool functions are only supported with pydantic v2") |
| 971 |
@pytest.mark.asyncio() |
| 972 |
async def test_heartbeat_starts_before_skill_download(monkeypatch: pytest.MonkeyPatch) -> None: |
| 973 |
"""Regression: the lease heartbeat must already be running while skills are |
| 974 |
downloaded. |
| 975 |
|
| 976 |
Skill setup (`AgentToolContext.__aenter__`) can take longer than the |
| 977 |
lease TTL. If the first heartbeat only fired *after* that download (the old |
| 978 |
ordering) the lease could lapse mid-download and another worker would |
| 979 |
reclaim the item — both then serve the same session (split-brain). We make |
| 980 |
skill setup block until a heartbeat has fired: with the correct ordering it |
| 981 |
proceeds; with the old ordering it would hang and time out. |
| 982 |
""" |
| 983 |
import anthropic.lib.tools.agent_toolset as ats |
| 984 |
|
| 985 |
heartbeat_fired = asyncio.Event() |
| 986 |
order: list[str] = [] |
| 987 |
|
| 988 |
class _HeartbeatFirstWork(_FakeWorkResource): |
| 989 |
@override |
| 990 |
async def heartbeat( |
| 991 |
self, |
| 992 |
work_id: str, # noqa: ARG002 |
| 993 |
*, |
| 994 |
environment_id: str, # noqa: ARG002 |
| 995 |
expected_last_heartbeat: str, # noqa: ARG002 |
| 996 |
extra_headers: Any = None, # noqa: ARG002 |
| 997 |
) -> Any: |
| 998 |
order.append("heartbeat") |
| 999 |
heartbeat_fired.set() |
| 1000 |
# state="running" so the heartbeat loop keeps going (does not stop |
| 1001 |
# the run before skill setup / the session runner get to execute). |
| 1002 |
return SimpleNamespace(last_heartbeat="hb-1", ttl_seconds=60, state="running", lease_extended=True) |
| 1003 |
|
| 1004 |
work = _HeartbeatFirstWork() |
| 1005 |
sessions = _FakeSessions() |
| 1006 |
client = _fake_client(work, sessions) |
| 1007 |
_install_aiter_work(monkeypatch, [_work_item()]) |
| 1008 |
_install_scoped_client(monkeypatch, work, sessions) |
| 1009 |
|
| 1010 |
async def slow_setup_skills(_self: Any) -> None: |
| 1011 |
order.append("setup_start") |
| 1012 |
# If the heartbeat hasn't started yet (old bug) this hangs → timeout. |
| 1013 |
await asyncio.wait_for(heartbeat_fired.wait(), timeout=5) |
| 1014 |
order.append("setup_end") |
| 1015 |
|
| 1016 |
monkeypatch.setattr(ats.AgentToolContext, "setup_skills", slow_setup_skills) |
| 1017 |
|
| 1018 |
@contextlib.asynccontextmanager |
| 1019 |
async def fake_run_session_tools( |
| 1020 |
_client: Any, |
| 1021 |
session_id: str, # noqa: ARG001 |
| 1022 |
*, |
| 1023 |
tools: Any, # noqa: ARG001 |
| 1024 |
max_idle: Any = None, # noqa: ARG001 |
| 1025 |
environment_key: Any = None, # noqa: ARG001 |
| 1026 |
extra_headers: Any = None, # noqa: ARG001 |
| 1027 |
send_retry_window: Any = None, # noqa: ARG001 |
| 1028 |
): |
| 1029 |
async def _iter() -> AsyncIterator[Any]: |
| 1030 |
return |
| 1031 |
yield # pragma: no cover (makes this an async generator function) |
| 1032 |
|
| 1033 |
yield _iter() |
| 1034 |
|
| 1035 |
monkeypatch.setattr(worker_mod, "_run_session_tools", fake_run_session_tools) |
| 1036 |
|
| 1037 |
worker = EnvironmentWorker(client=client, environment_id="e_1", environment_key="env_key", workdir=".") |
| 1038 |
await asyncio.wait_for(worker.run(), timeout=5) |
| 1039 |
|
| 1040 |
assert "heartbeat" in order |
| 1041 |
assert "setup_end" in order |
| 1042 |
# The heartbeat fired before skill setup was allowed to finish. |
| 1043 |
assert order.index("heartbeat") < order.index("setup_end") |
| 1044 |
# The work item was still force-stopped on exit. |
| 1045 |
assert len(work.stop_calls) == 1 |
| 1046 |
|
| 1047 |
|
| 1048 |
# ---------- heartbeat loop --------------------------------------------------- |
| 1049 |
# |
| 1050 |
# `_heartbeat_loop` is driven directly with a scripted `work` fake and a |
| 1051 |
# fake clock, so the lease-staleness ceiling can be crossed without real |
| 1052 |
# waiting. The first scripted beat reports `ttl_seconds=0` so the loop keeps |
| 1053 |
# the (patched, tiny) default interval instead of the 1 s floor it applies to |
| 1054 |
# a server-provided ttl. |
| 1055 |
|
| 1056 |
_HANG = object() |
| 1057 |
_FAST_INTERVAL = 0.01 |
| 1058 |
_FAKE_TTL = 5.0 |
| 1059 |
|
| 1060 |
|
| 1061 |
class _FakeClock: |
| 1062 |
def __init__(self) -> None: |
| 1063 |
self.now = 0.0 |
| 1064 |
|
| 1065 |
def monotonic(self) -> float: |
| 1066 |
return self.now |
| 1067 |
|
| 1068 |
|
| 1069 |
class _ScriptedHeartbeatWork: |
| 1070 |
"""`heartbeat` pops `(clock_advance, outcome)` per call: an exception is |
| 1071 |
raised, `_HANG` never returns, anything else is the response.""" |
| 1072 |
|
| 1073 |
def __init__(self, clock: _FakeClock, script: list[tuple[float, Any]]) -> None: |
| 1074 |
self._clock = clock |
| 1075 |
self._script = list(script) |
| 1076 |
self.calls = 0 |
| 1077 |
|
| 1078 |
async def heartbeat(self, work_id: str, **_kwargs: Any) -> Any: # noqa: ARG002 |
| 1079 |
self.calls += 1 |
| 1080 |
advance, outcome = self._script.pop(0) |
| 1081 |
self._clock.now += advance |
| 1082 |
if isinstance(outcome, BaseException): |
| 1083 |
raise outcome |
| 1084 |
if outcome is _HANG: |
| 1085 |
await anyio.sleep_forever() |
| 1086 |
return outcome |
| 1087 |
|
| 1088 |
|
| 1089 |
def _beat_ok(ttl_seconds: int = 0) -> Any: |
| 1090 |
return SimpleNamespace(last_heartbeat="hb", ttl_seconds=ttl_seconds, state="running", lease_extended=True) |
| 1091 |
|
| 1092 |
|
| 1093 |
async def _run_heartbeat_loop( |
| 1094 |
monkeypatch: pytest.MonkeyPatch, script: list[tuple[float, Any]] |
| 1095 |
) -> tuple[_ScriptedHeartbeatWork, _Lease]: |
| 1096 |
clock = _FakeClock() |
| 1097 |
monkeypatch.setattr(worker_mod, "time", SimpleNamespace(monotonic=clock.monotonic)) |
| 1098 |
monkeypatch.setattr(worker_mod, "_HEARTBEAT_DEFAULT", _FAST_INTERVAL) |
| 1099 |
monkeypatch.setattr(worker_mod, "_HEARTBEAT_TTL_DEFAULT", _FAKE_TTL) |
| 1100 |
work = _ScriptedHeartbeatWork(clock, script) |
| 1101 |
lease = _Lease() |
| 1102 |
with anyio.fail_after(5): |
| 1103 |
await _heartbeat_loop(cast(Any, work), work_id="w_1", environment_id="e_1", lease=lease) |
| 1104 |
return work, lease |
| 1105 |
|
| 1106 |
|
| 1107 |
def _messages(caplog: pytest.LogCaptureFixture) -> list[str]: |
| 1108 |
return [r.getMessage() for r in caplog.records if r.name == worker_mod.__name__] |
| 1109 |
|
| 1110 |
|
| 1111 |
@pytest.mark.asyncio() |
| 1112 |
async def test_heartbeat_conflict_is_retried_until_the_lease_is_stale( |
| 1113 |
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture |
| 1114 |
) -> None: |
| 1115 |
caplog.set_level(logging.WARNING, logger=worker_mod.__name__) |
| 1116 |
work, lease = await _run_heartbeat_loop( |
| 1117 |
monkeypatch, |
| 1118 |
[(0, _beat_ok()), (_FAKE_TTL - 2, _api_status_error(409)), (_FAKE_TTL, _api_status_error(409))], |
| 1119 |
) |
| 1120 |
assert work.calls == 3 |
| 1121 |
assert lease.ended |
| 1122 |
assert lease.lost |
| 1123 |
messages = _messages(caplog) |
| 1124 |
assert any(m.startswith("transient heartbeat failure") for m in messages) |
| 1125 |
assert any(m.startswith("lease assumed lost") for m in messages) |
| 1126 |
assert not any(m.startswith("permanent heartbeat failure") for m in messages) |
| 1127 |
|
| 1128 |
|
| 1129 |
@pytest.mark.asyncio() |
| 1130 |
async def test_heartbeat_that_never_returns_is_cut_off_each_interval( |
| 1131 |
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture |
| 1132 |
) -> None: |
| 1133 |
caplog.set_level(logging.WARNING, logger=worker_mod.__name__) |
| 1134 |
work, lease = await _run_heartbeat_loop(monkeypatch, [(0, _beat_ok()), (_FAKE_TTL - 2, _HANG), (_FAKE_TTL, _HANG)]) |
| 1135 |
assert work.calls == 3 |
| 1136 |
assert lease.ended |
| 1137 |
assert lease.lost |
| 1138 |
assert any(m.startswith("lease assumed lost") for m in _messages(caplog)) |
| 1139 |
|
| 1140 |
|
| 1141 |
@pytest.mark.asyncio() |
| 1142 |
async def test_heartbeat_permanent_4xx_stops_immediately( |
| 1143 |
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture |
| 1144 |
) -> None: |
| 1145 |
caplog.set_level(logging.WARNING, logger=worker_mod.__name__) |
| 1146 |
work, lease = await _run_heartbeat_loop(monkeypatch, [(0, _api_status_error(401))]) |
| 1147 |
assert work.calls == 1 |
| 1148 |
assert lease.ended |
| 1149 |
assert not lease.lost |
| 1150 |
assert any(m.startswith("permanent heartbeat failure") for m in _messages(caplog)) |
| 1151 |
|
| 1152 |
|
| 1153 |
@pytest.mark.asyncio() |
| 1154 |
async def test_heartbeat_keeps_beating_while_a_sync_tool_blocks(monkeypatch: pytest.MonkeyPatch) -> None: |
| 1155 |
"""Heartbeat loop and tool call share one task group, as they do in `_handle_item`.""" |
| 1156 |
monkeypatch.setattr(worker_mod, "_HEARTBEAT_DEFAULT", _FAST_INTERVAL) |
| 1157 |
in_tool, release = threading.Event(), threading.Event() |
| 1158 |
|
| 1159 |
class _Work: |
| 1160 |
def __init__(self) -> None: |
| 1161 |
self.beats_during_tool = 0 |
| 1162 |
|
| 1163 |
async def heartbeat(self, work_id: str, **_kwargs: Any) -> Any: # noqa: ARG002 |
| 1164 |
if in_tool.is_set() and not release.is_set(): |
| 1165 |
self.beats_during_tool += 1 |
| 1166 |
if self.beats_during_tool >= 3: |
| 1167 |
release.set() |
| 1168 |
return _beat_ok() |
| 1169 |
|
| 1170 |
def blocking(_input: object) -> str: |
| 1171 |
in_tool.set() |
| 1172 |
if not release.wait(timeout=2): |
| 1173 |
raise RuntimeError("no heartbeat fired while the tool ran") |
| 1174 |
return "ok" |
| 1175 |
|
| 1176 |
work, lease = _Work(), _Lease() |
| 1177 |
result: object = None |
| 1178 |
try: |
| 1179 |
with anyio.fail_after(5): |
| 1180 |
async with anyio.create_task_group() as tg: |
| 1181 |
tg.start_soon( |
| 1182 |
partial(_heartbeat_loop, cast(Any, work), work_id="w_1", environment_id="e_1", lease=lease) |
| 1183 |
) |
| 1184 |
result = await run_runnable_tool(_SyncTool("blocking", blocking), {}) |
| 1185 |
lease.finish(_LeaseEndReason.RUNNER_DONE) |
| 1186 |
finally: |
| 1187 |
release.set() |
| 1188 |
|
| 1189 |
assert result == "ok" |
| 1190 |
assert work.beats_during_tool >= 3 |