Debian Codegraph @

tests/lib/environments/test_poller_method.py

raw
1 """Tests for `iter_work` / `aiter_work` (the implementations behind
2 `client.beta.environments.work.poller()`).
3
4 We don't need a real HTTP mock here because the generators only ever talk to
5 a `Work`/`AsyncWork` resource through three methods (`poll`, `ack`,
6 `stop`). The fakes below stand in for that resource and let each test feed
7 a script of poll responses while recording ack/stop call sites.
8 """
9
10 from __future__ import annotations
11
12 import time
13 import asyncio
14 import logging
15 from typing import Any, cast
16 from collections.abc import AsyncIterator
17
18 import httpx2
19 import pytest
20
21 from anthropic import APIStatusError
22 from anthropic.lib.environments import _poller as poller_mod
23 from anthropic.lib.environments._poller import iter_work, aiter_work
24
25
26 class _StubWorkData:
27 type = "session"
28
29
30 class _StubWork:
31 """Minimal stand-in for `BetaSelfHostedWork` — only fields the poller reads."""
32
33 def __init__(self, *, id: str = "work_1") -> None:
34 self.id = id
35 self.data = _StubWorkData()
36
37
38 def _api_status_error(code: int) -> APIStatusError:
39 request = httpx2.Request("POST", "https://api.example/poll")
40 response = httpx2.Response(status_code=code, request=request, content=b"{}")
41 return APIStatusError("boom", response=response, body=None)
42
43
44 class FakeWork:
45 """Sync resource fake. `poll_script` is consumed in order; values are
46 either `BetaSelfHostedWork`-shaped stubs, `None` (no work available),
47 `Exception` instances (raised from poll), or callables producing one of
48 those (so a script step can also move a fake clock).
49 """
50
51 def __init__(self, poll_script: list[Any]) -> None:
52 self._poll_script = list(poll_script)
53 self.poll_calls: list[dict[str, Any]] = []
54 self.ack_calls: list[tuple[str, dict[str, Any]]] = []
55 self.stop_calls: list[tuple[str, dict[str, Any]]] = []
56
57 def poll(self, environment_id: str, **kwargs: Any) -> Any:
58 self.poll_calls.append({"environment_id": environment_id, **kwargs})
59 return _next_poll_result(self._poll_script)
60
61 def ack(self, work_id: str, **kwargs: Any) -> None:
62 self.ack_calls.append((work_id, kwargs))
63
64 def stop(self, work_id: str, **kwargs: Any) -> None:
65 self.stop_calls.append((work_id, kwargs))
66
67
68 class FakeAsyncWork:
69 def __init__(self, poll_script: list[Any]) -> None:
70 self._poll_script = list(poll_script)
71 self.poll_calls: list[dict[str, Any]] = []
72 self.ack_calls: list[tuple[str, dict[str, Any]]] = []
73 self.stop_calls: list[tuple[str, dict[str, Any]]] = []
74
75 async def poll(self, environment_id: str, **kwargs: Any) -> Any:
76 self.poll_calls.append({"environment_id": environment_id, **kwargs})
77 return _next_poll_result(self._poll_script)
78
79 async def ack(self, work_id: str, **kwargs: Any) -> None:
80 self.ack_calls.append((work_id, kwargs))
81
82 async def stop(self, work_id: str, **kwargs: Any) -> None:
83 self.stop_calls.append((work_id, kwargs))
84
85
86 class _StopTest(BaseException):
87 """Sentinel used to break a poller out of its infinite loop in tests.
88
89 Inherits from BaseException so it bypasses the generator's
90 `except Exception` arms (which would otherwise treat the empty-script
91 error as a transient poll failure and retry forever).
92 """
93
94
95 def _next_poll_result(script: list[Any]) -> Any:
96 if not script:
97 raise _StopTest("poll script exhausted")
98 nxt = script.pop(0)
99 if callable(nxt):
100 nxt = nxt()
101 if isinstance(nxt, BaseException):
102 raise nxt
103 return nxt
104
105
106 def _sync_noop(_seconds: float) -> None:
107 return None
108
109
110 async def _async_noop(_seconds: float) -> None:
111 return None
112
113
114 @pytest.fixture(autouse=True)
115 def _no_sleep(monkeypatch: pytest.MonkeyPatch) -> None: # pyright: ignore[reportUnusedFunction]
116 monkeypatch.setattr(time, "sleep", _sync_noop)
117 monkeypatch.setattr(asyncio, "sleep", _async_noop)
118
119
120 def _drain_one(it: Any) -> Any:
121 """Pull a single item from a sync iterator; assert there was one."""
122 try:
123 return next(it)
124 except _StopTest:
125 pytest.fail("poller exhausted script before yielding any work")
126
127
128 async def _adrain_one(ait: AsyncIterator[Any]) -> Any:
129 try:
130 return await ait.__anext__()
131 except _StopTest:
132 pytest.fail("poller exhausted script before yielding any work")
133
134
135 def test_iter_work_yields_acks_and_stops_one_item() -> None:
136 work = _StubWork()
137 fake = FakeWork(poll_script=[work])
138 it = iter_work(cast(Any, fake), environment_id="env_1")
139
140 item = _drain_one(it)
141 assert item is work
142 assert fake.ack_calls == [("work_1", fake.ack_calls[0][1])]
143 assert fake.stop_calls == [], "stop should not be called until body returns"
144
145 with pytest.raises(_StopTest):
146 next(it)
147 assert len(fake.stop_calls) == 1
148 assert fake.stop_calls[0][0] == "work_1"
149
150
151 def test_iter_work_calls_stop_when_body_raises() -> None:
152 work = _StubWork(id="work_boom")
153 fake = FakeWork(poll_script=[work])
154 it = iter_work(cast(Any, fake), environment_id="env_1")
155
156 next(it)
157 # Throwing into the generator simulates the consumer's body raising.
158 # iter_work returns Iterator publicly but is a Generator internally.
159 with pytest.raises(RuntimeError):
160 cast(Any, it).throw(RuntimeError("body failed"))
161 assert fake.stop_calls == [("work_boom", fake.stop_calls[0][1])]
162
163
164 @pytest.mark.parametrize("status", [500, 409])
165 def test_iter_work_backs_off_on_transient_error(status: int) -> None:
166 fake = FakeWork(poll_script=[_api_status_error(status), _StubWork(id="work_2")])
167 it = iter_work(cast(Any, fake), environment_id="env_1")
168
169 item = _drain_one(it)
170 assert item.id == "work_2"
171 assert len(fake.poll_calls) == 2
172
173
174 def test_iter_work_raises_on_permanent_4xx() -> None:
175 fake = FakeWork(poll_script=[_api_status_error(401)])
176 it = iter_work(cast(Any, fake), environment_id="env_1")
177
178 with pytest.raises(APIStatusError):
179 next(it)
180
181
182 def test_iter_work_stop_conflict_is_silent(caplog: pytest.LogCaptureFixture) -> None:
183 """A 409 from `stop` means the work already ended; it is neither logged
184 nor allowed to break the loop."""
185 fake = FakeWork(poll_script=[_StubWork(id="work_done")])
186
187 def _stop(_work_id: str, **_kwargs: Any) -> None:
188 raise _api_status_error(409)
189
190 fake.stop = _stop # type: ignore[method-assign]
191 it = iter_work(cast(Any, fake), environment_id="env_1")
192
193 _drain_one(it)
194 with pytest.raises(_StopTest):
195 next(it)
196 assert len(fake.poll_calls) == 2
197 assert not [r for r in caplog.records if "stop failed" in r.getMessage()]
198
199
200 def test_iter_work_backs_off_on_httpx_transport_error() -> None:
201 """A raw `httpx` transport error (not wrapped in an SDK `APIError`) is
202 still transient and must be retried, not propagated."""
203 fake = FakeWork(poll_script=[httpx2.ConnectError("connection refused"), _StubWork(id="work_2")])
204 it = iter_work(cast(Any, fake), environment_id="env_1")
205
206 item = _drain_one(it)
207 assert item.id == "work_2"
208 assert len(fake.poll_calls) == 2
209
210
211 def test_iter_work_propagates_non_api_error_instead_of_retrying() -> None:
212 """A programming error (here `KeyError`) is not a transient API/transport
213 failure, so it must propagate immediately rather than be swallowed and
214 retried forever. `poll` is only called once — no backoff/retry."""
215 fake = FakeWork(poll_script=[KeyError("bug"), _StubWork(id="work_2")])
216 it = iter_work(cast(Any, fake), environment_id="env_1")
217
218 with pytest.raises(KeyError):
219 next(it)
220 assert len(fake.poll_calls) == 1
221
222
223 def test_iter_work_propagates_non_api_error_from_ack() -> None:
224 """Same for a non-API error raised by `ack` — it propagates rather than
225 backing off and retrying."""
226 fake = FakeWork(poll_script=[_StubWork(id="work_bad")])
227
228 def _ack(_work_id: str, **_kwargs: Any) -> None:
229 raise RuntimeError("ack bug")
230
231 fake.ack = _ack # type: ignore[method-assign]
232 it = iter_work(cast(Any, fake), environment_id="env_1")
233
234 with pytest.raises(RuntimeError, match="ack bug"):
235 next(it)
236 assert fake.stop_calls == []
237
238
239 def test_iter_work_force_stops_on_permanent_ack_failure() -> None:
240 """A permanent 4xx on ack force-stops the item rather than re-delivering it."""
241 fake = FakeWork(poll_script=[_StubWork(id="work_bad")])
242
243 def _ack(_work_id: str, **_kwargs: Any) -> None:
244 raise _api_status_error(403)
245
246 fake.ack = _ack # type: ignore[method-assign]
247 it = iter_work(cast(Any, fake), environment_id="env_1")
248
249 with pytest.raises(_StopTest):
250 next(it)
251 assert [c[0] for c in fake.stop_calls] == ["work_bad"]
252 assert fake.stop_calls[0][1]["force"] is True
253
254
255 def test_iter_work_drain_returns_on_empty_queue() -> None:
256 a, b = _StubWork(id="work_a"), _StubWork(id="work_b")
257 fake = FakeWork(poll_script=[a, b, None])
258 it = iter_work(cast(Any, fake), environment_id="env_1", drain=True)
259
260 items = list(it)
261 assert [i.id for i in items] == ["work_a", "work_b"]
262 # Generator returned cleanly — no _StopTest raised, script not exhausted.
263 assert len(fake.poll_calls) == 3
264
265
266 def test_iter_work_drain_returns_immediately_when_queue_empty() -> None:
267 fake = FakeWork(poll_script=[None])
268 it = iter_work(cast(Any, fake), environment_id="env_1", drain=True)
269
270 assert list(it) == []
271 assert len(fake.poll_calls) == 1
272
273
274 def test_iter_work_auto_stop_false_never_stops() -> None:
275 """A dispatcher hands work off to another process that owns the stop call.
276
277 The poller must not stop the lease out from under that process.
278 """
279 a, b = _StubWork(id="work_a"), _StubWork(id="work_b")
280 fake = FakeWork(poll_script=[a, b, None])
281 it = iter_work(cast(Any, fake), environment_id="env_1", drain=True, auto_stop=False)
282
283 assert [item.id for item in it] == ["work_a", "work_b"]
284 assert [c[0] for c in fake.ack_calls] == ["work_a", "work_b"], "every item should still be ack'd"
285 assert fake.stop_calls == []
286
287
288 def test_iter_work_auto_stop_false_does_not_stop_on_body_raise() -> None:
289 work = _StubWork(id="work_boom")
290 fake = FakeWork(poll_script=[work])
291 it = iter_work(cast(Any, fake), environment_id="env_1", auto_stop=False)
292
293 next(it)
294 with pytest.raises(RuntimeError):
295 cast(Any, it).throw(RuntimeError("body failed"))
296 assert fake.stop_calls == []
297
298
299 def test_iter_work_forwards_reclaim_older_than_ms() -> None:
300 fake = FakeWork(poll_script=[None])
301 it = iter_work(cast(Any, fake), environment_id="env_1", drain=True, reclaim_older_than_ms=2000)
302
303 list(it)
304 assert fake.poll_calls[0]["reclaim_older_than_ms"] == 2000
305
306
307 def test_iter_work_block_ms_none_omits_param() -> None:
308 """The server rejects block_ms=0; None must translate to the omit sentinel
309 so the poll is non-blocking instead of 400ing."""
310 from anthropic._types import omit
311
312 fake = FakeWork(poll_script=[None])
313 it = iter_work(cast(Any, fake), environment_id="env_1", drain=True, block_ms=None)
314
315 list(it)
316 assert fake.poll_calls[0]["block_ms"] is omit
317
318
319 # ---------- idle-loop visibility ------------------------------------------
320 #
321 # An idle poller must show up in the logs without an INFO line per poll: one
322 # INFO line when it goes idle (after start-up or after releasing an item),
323 # DEBUG per empty poll after that, and an INFO reminder every 5 minutes.
324
325
326 class _FakeClock:
327 """Stands in for the `time` module inside the poller: a settable
328 monotonic clock plus a no-op `sleep`."""
329
330 def __init__(self) -> None:
331 self.now = 0.0
332
333 def monotonic(self) -> float:
334 return self.now
335
336 def sleep(self, _seconds: float) -> None:
337 return None
338
339 def advance(self, seconds: float) -> None:
340 self.now += seconds
341
342
343 def _idle_script(clock: _FakeClock) -> list[Any]:
344 """Three empty polls, a fourth 301s later, a fifth, one claim, then one
345 more empty poll before the script runs out."""
346
347 def empty_poll_301s_later() -> None:
348 clock.advance(301)
349
350 return [None, None, None, empty_poll_301s_later, None, _StubWork(id="work_a"), None]
351
352
353 _EXPECTED_IDLE_INFO_LINES = [
354 "idle; polling environment_id=env_1 for work",
355 "still polling environment_id=env_1; idle for 301s",
356 "claimed work work_id=work_a work_type=session",
357 "idle; polling environment_id=env_1 for work",
358 ]
359
360
361 def _poller_records(caplog: pytest.LogCaptureFixture, level: int) -> list[str]:
362 return [
363 r.getMessage()
364 for r in caplog.records
365 if r.name == poller_mod.__name__ and r.levelno == level and not r.getMessage().startswith("poller starting")
366 ]
367
368
369 def test_iter_work_logs_idle_polling(monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture) -> None:
370 clock = _FakeClock()
371 monkeypatch.setattr(poller_mod, "time", clock)
372 fake = FakeWork(poll_script=_idle_script(clock))
373 caplog.set_level(logging.DEBUG, logger=poller_mod.__name__)
374
375 with pytest.raises(_StopTest):
376 for _ in iter_work(cast(Any, fake), environment_id="env_1", auto_stop=False):
377 pass
378
379 assert _poller_records(caplog, logging.INFO) == _EXPECTED_IDLE_INFO_LINES
380 assert len(_poller_records(caplog, logging.DEBUG)) == 3
381
382
383 @pytest.mark.asyncio()
384 async def test_aiter_work_logs_idle_polling(monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture) -> None:
385 clock = _FakeClock()
386 monkeypatch.setattr(poller_mod, "time", clock)
387 monkeypatch.setattr(poller_mod.anyio, "sleep", _async_noop)
388 fake = FakeAsyncWork(poll_script=_idle_script(clock))
389 caplog.set_level(logging.DEBUG, logger=poller_mod.__name__)
390
391 with pytest.raises(_StopTest):
392 async for _ in aiter_work(cast(Any, fake), environment_id="env_1", auto_stop=False):
393 pass
394
395 assert _poller_records(caplog, logging.INFO) == _EXPECTED_IDLE_INFO_LINES
396 assert len(_poller_records(caplog, logging.DEBUG)) == 3
397
398
399 @pytest.mark.asyncio()
400 async def test_aiter_work_yields_acks_and_stops_one_item() -> None:
401 work = _StubWork()
402 fake = FakeAsyncWork(poll_script=[work])
403 ait = aiter_work(cast(Any, fake), environment_id="env_1")
404
405 item = await _adrain_one(ait)
406 assert item is work
407 assert fake.ack_calls == [("work_1", fake.ack_calls[0][1])]
408 assert fake.stop_calls == []
409
410 with pytest.raises(_StopTest):
411 await ait.__anext__()
412 assert len(fake.stop_calls) == 1
413
414
415 @pytest.mark.asyncio()
416 async def test_aiter_work_calls_stop_when_body_raises() -> None:
417 work = _StubWork(id="work_boom")
418 fake = FakeAsyncWork(poll_script=[work])
419 ait = aiter_work(cast(Any, fake), environment_id="env_1")
420
421 await ait.__anext__()
422 with pytest.raises(RuntimeError):
423 await cast(Any, ait).athrow(RuntimeError("body failed"))
424 assert fake.stop_calls == [("work_boom", fake.stop_calls[0][1])]
425
426
427 @pytest.mark.asyncio()
428 @pytest.mark.parametrize("status", [500, 409])
429 async def test_aiter_work_backs_off_on_transient_error(status: int) -> None:
430 fake = FakeAsyncWork(poll_script=[_api_status_error(status), _StubWork(id="work_2")])
431 ait = aiter_work(cast(Any, fake), environment_id="env_1")
432
433 item = await _adrain_one(ait)
434 assert item.id == "work_2"
435 assert len(fake.poll_calls) == 2
436
437
438 @pytest.mark.asyncio()
439 async def test_aiter_work_stop_conflict_is_silent(caplog: pytest.LogCaptureFixture) -> None:
440 fake = FakeAsyncWork(poll_script=[_StubWork(id="work_done")])
441
442 async def _stop(_work_id: str, **_kwargs: Any) -> None:
443 raise _api_status_error(409)
444
445 fake.stop = _stop # type: ignore[method-assign]
446 ait = aiter_work(cast(Any, fake), environment_id="env_1")
447
448 await _adrain_one(ait)
449 with pytest.raises(_StopTest):
450 await ait.__anext__()
451 assert len(fake.poll_calls) == 2
452 assert not [r for r in caplog.records if "stop failed" in r.getMessage()]
453
454
455 async def test_aiter_work_propagates_non_api_error_instead_of_retrying() -> None:
456 """Async counterpart: a non-API/non-transport error propagates instead of
457 being retried forever."""
458 fake = FakeAsyncWork(poll_script=[AttributeError("bug"), _StubWork(id="work_2")])
459 ait = aiter_work(cast(Any, fake), environment_id="env_1")
460
461 with pytest.raises(AttributeError):
462 await ait.__anext__()
463 assert len(fake.poll_calls) == 1
464
465
466 @pytest.mark.asyncio()
467 async def test_aiter_work_drain_auto_stop_false_dispatch_shape() -> None:
468 a, b = _StubWork(id="work_a"), _StubWork(id="work_b")
469 fake = FakeAsyncWork(poll_script=[a, b, None])
470 ait = aiter_work(cast(Any, fake), environment_id="env_1", drain=True, auto_stop=False)
471
472 items = [item async for item in ait]
473 assert [i.id for i in items] == ["work_a", "work_b"]
474 assert [c[0] for c in fake.ack_calls] == ["work_a", "work_b"]
475 assert fake.stop_calls == []
476 assert len(fake.poll_calls) == 3
477
478
479 # ---------- extra_headers per-request passthrough ---------------------------
480 #
481 # These assert the caller-supplied `extra_headers` actually reaches every
482 # underlying `poll` / `ack` / `stop` call (the resource methods route it
483 # through `make_request_options`). The fakes record the kwargs each method
484 # was called with, so a missing thread-through shows up as `None`.
485
486 _EXTRA = {"x-trace-id": "trace-123"}
487
488
489 def test_iter_work_threads_extra_headers_into_poll_ack_stop() -> None:
490 fake = FakeWork(poll_script=[_StubWork(id="work_h")])
491 it = iter_work(cast(Any, fake), environment_id="env_1", extra_headers=_EXTRA)
492
493 item = _drain_one(it)
494 assert item.id == "work_h"
495 assert fake.poll_calls[0]["extra_headers"] == _EXTRA
496 assert fake.ack_calls[0][1]["extra_headers"] == _EXTRA
497
498 with pytest.raises(_StopTest):
499 next(it)
500 assert fake.stop_calls[0][1]["extra_headers"] == _EXTRA
501
502
503 def test_iter_work_threads_extra_headers_into_force_stop() -> None:
504 """A permanent ack failure force-stops the item; the passthrough header
505 must ride along on that force-stop call too."""
506 fake = FakeWork(poll_script=[_StubWork(id="work_bad")])
507
508 def _ack(_work_id: str, **_kwargs: Any) -> None:
509 raise _api_status_error(403)
510
511 fake.ack = _ack # type: ignore[method-assign]
512 it = iter_work(cast(Any, fake), environment_id="env_1", extra_headers=_EXTRA)
513
514 with pytest.raises(_StopTest):
515 next(it)
516 assert fake.stop_calls[0][0] == "work_bad"
517 assert fake.stop_calls[0][1]["force"] is True
518 assert fake.stop_calls[0][1]["extra_headers"] == _EXTRA
519
520
521 @pytest.mark.asyncio()
522 async def test_aiter_work_threads_extra_headers_into_poll_ack_stop() -> None:
523 fake = FakeAsyncWork(poll_script=[_StubWork(id="work_h")])
524 ait = aiter_work(cast(Any, fake), environment_id="env_1", extra_headers=_EXTRA)
525
526 item = await _adrain_one(ait)
527 assert item.id == "work_h"
528 assert fake.poll_calls[0]["extra_headers"] == _EXTRA
529 assert fake.ack_calls[0][1]["extra_headers"] == _EXTRA
530
531 with pytest.raises(_StopTest):
532 await ait.__anext__()
533 assert fake.stop_calls[0][1]["extra_headers"] == _EXTRA
534
535
536 @pytest.mark.asyncio()
537 async def test_aiter_work_threads_extra_headers_into_force_stop() -> None:
538 fake = FakeAsyncWork(poll_script=[_StubWork(id="work_bad")])
539
540 async def _ack(_work_id: str, **_kwargs: Any) -> None:
541 raise _api_status_error(403)
542
543 fake.ack = _ack # type: ignore[method-assign]
544 ait = aiter_work(cast(Any, fake), environment_id="env_1", extra_headers=_EXTRA)
545
546 with pytest.raises(_StopTest):
547 await ait.__anext__()
548 assert fake.stop_calls[0][0] == "work_bad"
549 assert fake.stop_calls[0][1]["force"] is True
550 assert fake.stop_calls[0][1]["extra_headers"] == _EXTRA