"""A transient Bedrock 503 must not end a seven-hour trial. Only the mixin is under test, so Harbor's provider classes are stubbed when Harbor is not importable from this interpreter. Sleeping is stubbed too: what matters is that the waits grow, stay inside the budget, and are jittered. """ import asyncio import logging import sys import types import unittest from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1]/"scripts")) try: import harbor.agents.computer_1.providers.anthropic # noqa: F401 except ImportError: module = types.ModuleType("harbor.agents.computer_1.providers.anthropic") module.AnthropicProvider = type("AnthropicProvider", (), {}) module.BedrockProvider = type("BedrockProvider", (), {}) for name in ("harbor", "harbor.agents", "harbor.agents.computer_1", "harbor.agents.computer_1.providers"): sys.modules.setdefault(name, types.ModuleType(name)) sys.modules[module.__name__] = module import resilient_providers # noqa: E402 from pruned_providers import PrunedAnthropicMessages # noqa: E402 from test_pruning import conversation # noqa: E402 from resilient_providers import ( # noqa: E402 MAX_BACKOFF_SECONDS, RetryingAnthropicCalls, retryable, status_of, ) UNAVAILABLE = "Error code: 503 - {'message': 'Bedrock is unable to process your request.'}" TOO_LONG = "Error code: 400 - {'message': 'Input is too long.'}" class Status(Exception): """An anthropic SDK error, which carries its HTTP status.""" def __init__(self, code, message): super().__init__(message) self.status_code = code class Refusing: """Stands in for the real request; refuses the first *failures* calls.""" async def _call_api(self): self.calls += 1 if self.calls <= self.failures: raise self.error return "response" class Provider(RetryingAnthropicCalls, Refusing): def __init__(self, failures=0, error=None): self.failures = failures self.error = error or Status(503, UNAVAILABLE) self.calls = 0 class Sleepless(unittest.TestCase): """Record what would have been waited instead of waiting it.""" def setUp(self): # The retries are meant to be noisy in a run, not in the test output. resilient_providers.LOG.setLevel(logging.CRITICAL) self.addCleanup(resilient_providers.LOG.setLevel, logging.NOTSET) self.waits = [] self.real_sleep = resilient_providers.asyncio.sleep self.clock = [0.] async def sleep(seconds): self.waits.append(seconds) self.clock[0] += seconds resilient_providers.asyncio.sleep = sleep self.real_monotonic = resilient_providers.time.monotonic resilient_providers.time.monotonic = lambda: self.clock[0] def tearDown(self): resilient_providers.asyncio.sleep = self.real_sleep resilient_providers.time.monotonic = self.real_monotonic class Retrying(Sleepless): def test_a_transient_refusal_is_retried(self): provider = Provider(failures=3) self.assertEqual(asyncio.run(provider._call_api()), "response") self.assertEqual(provider.calls, 4) self.assertEqual(provider.api_retries, 3) def test_the_first_call_does_not_wait(self): provider = Provider() asyncio.run(provider._call_api()) self.assertEqual(self.waits, []) self.assertEqual(provider.api_retries, 0) def test_the_waits_grow_and_are_capped(self): provider = Provider(failures=12) provider.retry_budget_seconds = 10_000 asyncio.run(provider._call_api()) self.assertLessEqual(max(self.waits), MAX_BACKOFF_SECONDS) self.assertGreater(self.waits[-1], self.waits[0]) def test_the_waits_are_jittered(self): provider = Provider(failures=8) provider.retry_budget_seconds = 10_000 asyncio.run(provider._call_api()) tail = self.waits[-4:] # all four are at the ceiling before jitter self.assertEqual(len(set(tail)), len(tail)) def test_a_long_outage_gives_up_inside_its_budget(self): provider = Provider(failures=10_000) provider.retry_budget_seconds = 120 with self.assertRaises(Status): asyncio.run(provider._call_api()) self.assertLessEqual(sum(self.waits), 120.001) self.assertGreater(provider.api_retries, 1) def test_an_over_long_prompt_is_not_a_wait(self): # Pruning fixes that one, by sending a different request. provider = Provider(failures=1, error=Status(400, TOO_LONG)) with self.assertRaises(Status): asyncio.run(provider._call_api()) self.assertEqual(provider.calls, 1) self.assertEqual(self.waits, []) def test_a_refusal_without_a_status_is_read_from_its_text(self): provider = Provider(failures=1, error=RuntimeError(UNAVAILABLE)) self.assertEqual(asyncio.run(provider._call_api()), "response") self.assertEqual(provider.calls, 2) def test_pruning_still_sees_the_errors_it_recovers_from(self): class Both(PrunedAnthropicMessages, Provider): pass provider = Both(failures=2, error=Status(400, TOO_LONG)) provider._messages = conversation(40) # enough for pruning to have work self.assertEqual(asyncio.run(provider._call_api()), "response") self.assertEqual(provider.calls, 3) # pruned and resent, not waited out self.assertEqual(self.waits, []) def test_pruning_does_not_swallow_a_capacity_refusal(self): class Both(PrunedAnthropicMessages, Provider): pass provider = Both(failures=2) provider._messages = conversation(40) # enough for pruning to have work self.assertEqual(asyncio.run(provider._call_api()), "response") self.assertEqual(provider.api_retries, 2) class Classification(unittest.TestCase): def test_statuses(self): self.assertTrue(retryable(Status(503, UNAVAILABLE))) self.assertTrue(retryable(Status(429, "Too many requests"))) self.assertTrue(retryable(Status(529, "Overloaded"))) self.assertFalse(retryable(Status(400, TOO_LONG))) self.assertFalse(retryable(Status(403, "Access denied"))) self.assertFalse(retryable(Status(404, "Not found"))) def test_text_when_there_is_no_status(self): self.assertTrue(retryable(RuntimeError("Model overloaded"))) self.assertTrue(retryable(RuntimeError("Connection error."))) self.assertFalse(retryable(RuntimeError("Input is too long"))) def test_a_status_on_the_response_is_found(self): error = RuntimeError("no") error.response = types.SimpleNamespace(status_code=503) self.assertEqual(status_of(error), 503) self.assertTrue(retryable(error)) self.assertIsNone(status_of(RuntimeError("no"))) if __name__ == "__main__": unittest.main()