From 1a983e2ccefd4acfdb151bcfd9f792694279b930 Mon Sep 17 00:00:00 2001 From: karpetrosyan Date: Tue, 2 Dec 2025 17:32:43 +0400 Subject: [PATCH 1/3] feat: add infinite compaction detection --- src/anthropic/lib/tools/_beta_runner.py | 28 +++++++++++++++++-- tests/lib/snapshots.py | 21 +++++++------- .../4ee3afd0-b61d-4db6-b971-53e9aa5e286c.json | 6 ++++ tests/lib/tools/test_runners.py | 28 +++++++++++++++++++ 4 files changed, 70 insertions(+), 13 deletions(-) create mode 100644 tests/lib/tools/__inline_snapshot__/test_runners/TestSyncRunTools.test_compaction_infinite_loop_detection/4ee3afd0-b61d-4db6-b971-53e9aa5e286c.json diff --git a/src/anthropic/lib/tools/_beta_runner.py b/src/anthropic/lib/tools/_beta_runner.py index e76d1109..491149f9 100644 --- a/src/anthropic/lib/tools/_beta_runner.py +++ b/src/anthropic/lib/tools/_beta_runner.py @@ -239,6 +239,8 @@ def _check_and_compact(self) -> bool: return True def __run__(self) -> Iterator[RunnerItemT]: + consecutive_compactions = 0 + while not self._should_stop(): with self._handle_request() as item: yield item @@ -247,8 +249,19 @@ def __run__(self) -> Iterator[RunnerItemT]: self._iteration_count += 1 + compacted = self._check_and_compact() + + if compacted: + consecutive_compactions += 1 + log.debug(f"Consecutive compactions: {consecutive_compactions}") + if consecutive_compactions >= 2: + raise RuntimeError("Infinite compaction detected: two consecutive iterations performed compaction") + else: + log.debug("No compaction performed, resetting consecutive compactions counter.") + consecutive_compactions = 0 + # If the compaction was performed, skip tool call generation this iteration - if not self._check_and_compact(): + if not compacted: response = self.generate_tool_call_response() if response is None: log.debug("Tool call was not requested, exiting from tool runner loop.") @@ -482,6 +495,8 @@ async def _check_and_compact(self) -> bool: return True async def __run__(self) -> AsyncIterator[RunnerItemT]: + consecutive_compactions = 0 + while not self._should_stop(): async with self._handle_request() as item: yield item @@ -490,8 +505,17 @@ async def __run__(self) -> AsyncIterator[RunnerItemT]: self._iteration_count += 1 + compacted = await self._check_and_compact() + + if compacted: + consecutive_compactions += 1 + if consecutive_compactions >= 2: + raise RuntimeError("Infinite compaction detected: two consecutive iterations performed compaction") + else: + consecutive_compactions = 0 + # If the compaction was performed, skip tool call generation this iteration - if not await self._check_and_compact(): + if not compacted: response = await self.generate_tool_call_response() if response is None: log.debug("Tool call was not requested, exiting from tool runner loop.") diff --git a/tests/lib/snapshots.py b/tests/lib/snapshots.py index 743a6222..ca760459 100644 --- a/tests/lib/snapshots.py +++ b/tests/lib/snapshots.py @@ -63,19 +63,18 @@ def get_response(_request: httpx.Request) -> httpx.Response: client = mock_client - result = func(client) - if not live: - return result + return func(client) - client.close() - - if len(collected) == 1: - assert collected[0] == content_snapshot - else: - assert collected == content_snapshot - - return result + try: + result = func(client) + return result + finally: + client.close() + if len(collected) == 1: + assert collected[0] == content_snapshot + else: + assert collected == content_snapshot def make_stream_snapshot_request( diff --git a/tests/lib/tools/__inline_snapshot__/test_runners/TestSyncRunTools.test_compaction_infinite_loop_detection/4ee3afd0-b61d-4db6-b971-53e9aa5e286c.json b/tests/lib/tools/__inline_snapshot__/test_runners/TestSyncRunTools.test_compaction_infinite_loop_detection/4ee3afd0-b61d-4db6-b971-53e9aa5e286c.json new file mode 100644 index 00000000..7fa5d994 --- /dev/null +++ b/tests/lib/tools/__inline_snapshot__/test_runners/TestSyncRunTools.test_compaction_infinite_loop_detection/4ee3afd0-b61d-4db6-b971-53e9aa5e286c.json @@ -0,0 +1,6 @@ +[ + "{\"model\": \"claude-sonnet-4-5-20250929\", \"id\": \"msg_01YYHU4K3U3BuyU8KRUTH8o8\", \"type\": \"message\", \"role\": \"assistant\", \"content\": [{\"type\": \"text\", \"text\": \"# Dogs, Cats, and Birds: Three Beloved Companions\\n\\nThroughout human history, animals have played vital roles in our lives, but few have captured our hearts quite like dogs, cats, and birds. These three groups of animals have become the most popular pets worldwide, each offering unique characteristics and forming special bonds with their human companions.\\n\\n## Dogs: Humanity's Faithful Friends\\n\\nDogs, scientifically known as Canis familiaris, have earned their reputation as \\\"man's best friend\\\" through thousands of years of domestication. Descended from wolves, dogs have evolved alongside humans to become incredibly diverse, with over 300 recognized breeds ranging from tiny Chihuahuas to massive Great Danes. What makes dogs particularly special is their remarkable loyalty and eagerness to please. They possess an extraordinary ability to read human emotions and respond with empathy, making them excellent companions for people of all ages.\\n\\nDogs serve numerous roles beyond companionship. They work as service animals for the disabled, assist law enforcement in detecting drugs and explosives, participate in search and rescue operations, and provide therapeutic support in hospitals and schools. Their intelligence and trainability make them adaptable to various tasks. Additionally, dogs encourage physical activity through daily walks and play, promoting healthier lifestyles for their owners.\\n\\n## Cats: Independent Yet Affectionate\\n\\nCats, or Felis catus, offer a different kind of companionship. These graceful, independent creatures have been associated with humans for approximately 10,000 years. Unlike dogs, cats retain much of their wild ancestry, maintaining their hunting instincts and autonomous nature. With dozens of breeds displaying varied coat patterns, colors, and personalities, cats appeal to those who appreciate a more self-sufficient pet.\\n\\nCats are known for their cleanliness, spending significant time grooming themselves. They require less maintenance than dogs, needing no walks and typically using litter boxes instinctively. Despite their independent reputation, cats form strong bonds with their owners, often showing affection through purring, head-butting, and kneading. Studies have shown that a cat's purr can have therapeutic effects, potentially reducing stress and lowering blood pressure in humans.\\n\\n## Birds: Colorful and Intelligent Companions\\n\\nBirds represent a diverse category of pets, from small finches and canaries to larger parrots and cockatoos. These feathered companions bring beauty and entertainment into homes with their vibrant plumage and melodious songs. Many bird species, particularly parrots, display remarkable intelligence, capable of learning words, solving puzzles, and forming deep emotional connections with their caregivers.\\n\\nBirds require specialized care, including appropriate cages, specific diets, and mental stimulation. Social species like parakeets and cockatiels thrive on interaction and can become deeply bonded to their human families. Some larger parrots can live for several decades, representing a long-term commitment that rivals or exceeds that of dogs and cats.\\n\\n## Conclusion\\n\\nDogs, cats, and birds each bring unique qualities to our lives. Whether you prefer the loyal enthusiasm of a dog, the elegant independence of a cat, or the colorful intelligence of a bird, these animals enrich our existence, teaching us about responsibility, compassion, and unconditional love. The choice between them often reflects our lifestyle, personality, and what we seek in a companion animal.\\n\\nsubmit_analysis\\n\\n\\n{\\n \\\"scientific_name\\\": \\\"Canis familiaris\\\",\\n \\\"origin\\\": \\\"Descended from wolves, domesticated over thousands of years\\\",\\n \\\"key_characteristics\\\": \\\"Loyal, trainable, empathetic, diverse breeds (300+), social\\\",\\n \\\"roles\\\": \\\"Companions, service animals, law enforcement, search and rescue, therapy\\\",\\n \\\"care_requirements\\\": \\\"Regular walks, training, grooming varies by breed, veterinary care\\\",\\n \\\"lifespan\\\": \\\"Typically 10-15 years depending on breed\\\"\\n}\\n\\n\\n{\\n \\\"scientific_name\\\": \\\"Felis catus\\\",\\n \\\"origin\\\": \\\"Associated with humans for approximately 10,000 years\\\",\\n \\\"key_characteristics\\\": \\\"Independent, clean, graceful, retains hunting instincts, affectionate\\\",\\n \\\"roles\\\": \\\"Companions, pest control, therapy animals\\\",\\n \\\"care_requirements\\\": \\\"Litter box, regular feeding, grooming (especially long-haired breeds), veterinary care, lower maintenance than dogs\\\",\\n \\\"lifespan\\\": \\\"Typically 12-18 years, often longer indoors\\\",\\n \\\"health_benefits\\\": \\\"Purring can reduce stress and lower blood pressure\\\"\\n}\\n\\n\\n{\\n \\\"common_types\\\": \\\"Finches, canaries, parakeets, cockatiels, parrots, cockatoos\\\",\\n \\\"key_characteristics\\\": \\\"Intelligent, colorful, vocal, social (species-dependent), capable of learning words and solving puzzles\\\",\\n \\\"roles\\\": \\\"Companions, entertainment, some species bond deeply with humans\\\",\\n \\\"care_requirements\\\": \\\"Appropriate caging, specialized diet, mental stimulation, social interaction, regular veterinary care\\\",\\n \\\"lifespan\\\": \\\"Varies widely: small birds 5-15 years, larger parrots can live 50+ years\\\",\\n \\\"special_considerations\\\": \\\"Long-term commitment, especially for larger species\\\"\\n}\\n\\n\"}], \"stop_reason\": \"end_turn\", \"stop_sequence\": null, \"usage\": {\"input_tokens\": 52, \"cache_creation_input_tokens\": 0, \"cache_read_input_tokens\": 0, \"cache_creation\": {\"ephemeral_5m_input_tokens\": 0, \"ephemeral_1h_input_tokens\": 0}, \"output_tokens\": 1208, \"service_tier\": \"standard\"}}", + "{\"model\": \"claude-sonnet-4-5-20250929\", \"id\": \"msg_01SabfFvcmPRtZYjtpxLvisB\", \"type\": \"message\", \"role\": \"assistant\", \"content\": [{\"type\": \"text\", \"text\": \"\\n## 1. Task Overview\\nThe user requested a detailed 500-word essay about dogs, cats, and birds, followed by a single call to a tool named `submit_analysis` containing information about all three animals. The call must happen only once at the end of the essay.\\n\\n**Key constraints:**\\n- Essay must be 500 words\\n- Must cover all three animals: dogs, cats, and birds\\n- Must call `submit_analysis` tool exactly once\\n- Tool call should happen after the essay is complete\\n\\n## 2. Current State\\n**Completed:** Nothing has been completed yet. No essay has been written, and no tool has been called.\\n\\n**Files/Outputs:** None created.\\n\\n## 3. Important Discoveries\\n- The tool `submit_analysis` needs to be called with information about the animals\\n- The exact parameters/format expected by `submit_analysis` are not yet known (will need to infer reasonable structure when making the call)\\n- The essay should be comprehensive enough to cover distinguishing characteristics, behaviors, and roles of all three animal types\\n\\n## 4. Next Steps\\n**Immediate actions required:**\\n1. Write a 500-word essay covering:\\n - Dogs: characteristics, behavior, relationship with humans, roles (pets, working animals)\\n - Cats: characteristics, behavior, independence, domestication, roles\\n - Birds: diversity, characteristics, behaviors, species variety, roles as pets/wild animals\\n \\n2. After completing the essay, call the `submit_analysis` tool once with structured information about all three animals (likely in JSON or structured text format including key facts about each)\\n\\n**Priority:** Complete essay first, then make single tool call.\\n\\n## 5. Context to Preserve\\n- User emphasized calling the tool \\\"only once at the end\\\"\\n- The essay should be \\\"detailed\\\" suggesting depth of coverage for each animal\\n- All three animals must receive adequate coverage in the 500-word limit (approximately 165 words each or balanced based on content flow)\\n\"}], \"stop_reason\": \"end_turn\", \"stop_sequence\": null, \"usage\": {\"input_tokens\": 324, \"cache_creation_input_tokens\": 0, \"cache_read_input_tokens\": 0, \"cache_creation\": {\"ephemeral_5m_input_tokens\": 0, \"ephemeral_1h_input_tokens\": 0}, \"output_tokens\": 447, \"service_tier\": \"standard\"}}", + "{\"model\": \"claude-sonnet-4-5-20250929\", \"id\": \"msg_01CUzmNLL13BkU5kDaiBHe3c\", \"type\": \"message\", \"role\": \"assistant\", \"content\": [{\"type\": \"text\", \"text\": \"# Dogs, Cats, and Birds: Beloved Companions in Human Society\\n\\nThroughout human history, animals have played integral roles in our lives, with dogs, cats, and birds standing out as particularly cherished companions. Each of these animals brings unique characteristics, behaviors, and benefits to our homes and hearts.\\n\\nDogs, often called \\\"man's best friend,\\\" are descendants of wolves that were domesticated thousands of years ago. Their loyalty, intelligence, and eagerness to please make them exceptional companions. Dogs come in hundreds of breeds, ranging from tiny Chihuahuas to massive Great Danes, each bred for specific purposes. Working dogs serve in various capacities: herding livestock, guiding the visually impaired, detecting drugs and explosives, and providing emotional support. Their pack mentality translates into strong bonds with human families, and they thrive on social interaction and training. Dogs communicate through barking, body language, and facial expressions, making them highly responsive to human emotions. Their exercise needs vary by breed, but most require regular physical activity and mental stimulation to maintain health and happiness.\\n\\nCats, domesticated approximately 10,000 years ago in the Near East, are known for their independence and grace. Unlike dogs, cats retain more of their wild instincts and can be both affectionate companions and solitary hunters. They are meticulous groomers, spending significant portions of their day maintaining their coats. Cats are crepuscular, meaning they're most active during dawn and dusk. Their retractable claws, flexible bodies, and excellent night vision make them formidable predators of rodents and small prey. While often perceived as aloof, cats form strong attachments to their owners and communicate through purring, meowing, and various vocalizations. They require less maintenance than dogs, as they don't need walks and are naturally inclined to use litter boxes. Many people appreciate cats for their quiet companionship and their ability to provide comfort while respecting personal space.\\n\\nBirds represent incredible diversity, with over 10,000 species worldwide ranging from tiny hummingbirds to large parrots and raptors. As pets, birds like parakeets, cockatiels, and African grey parrots are popular for their beauty, intelligence, and ability to mimic sounds and human speech. Birds possess unique characteristics including feathers, hollow bones for flight, and highly efficient respiratory systems. Their songs and calls serve various purposes: attracting mates, defending territory, and communicating danger. Many bird species are highly social and require significant interaction and mental enrichment in captivity. Wild birds play crucial ecological roles as pollinators, seed dispersers, and pest controllers. Observing birds in nature has become a beloved hobby for millions, contributing to conservation awareness and environmental appreciation.\\n\\nEach of these animals enriches human lives differently. Dogs offer unwavering loyalty and active companionship, cats provide independent yet affectionate presence, and birds bring beauty, song, and fascinating behaviors to observe. Understanding and respecting each species' unique needs ensures healthy, rewarding relationships between humans and these remarkable creatures.\\n\\n\\n{\\n \\\"analysis_type\\\": \\\"comparative_animal_study\\\",\\n \\\"animals_covered\\\": 3,\\n \\\"detailed_findings\\\": {\\n \\\"dogs\\\": {\\n \\\"domestication_period\\\": \\\"thousands of years ago from wolves\\\",\\n \\\"key_characteristics\\\": [\\\"loyal\\\", \\\"intelligent\\\", \\\"social\\\", \\\"pack-oriented\\\"],\\n \\\"primary_roles\\\": [\\\"companionship\\\", \\\"working animals\\\", \\\"service animals\\\", \\\"emotional support\\\"],\\n \\\"communication_methods\\\": [\\\"barking\\\", \\\"body language\\\", \\\"facial expressions\\\"],\\n \\\"care_requirements\\\": [\\\"regular exercise\\\", \\\"training\\\", \\\"social interaction\\\"],\\n \\\"breed_diversity\\\": \\\"hundreds of breeds from small to large\\\"\\n },\\n \\\"cats\\\": {\\n \\\"domestication_period\\\": \\\"approximately 10,000 years ago\\\",\\n \\\"key_characteristics\\\": [\\\"independent\\\", \\\"graceful\\\", \\\"meticulous groomers\\\", \\\"crepuscular\\\"],\\n \\\"primary_roles\\\": [\\\"companionship\\\", \\\"pest control\\\", \\\"emotional support\\\"],\\n \\\"communication_methods\\\": [\\\"purring\\\", \\\"meowing\\\", \\\"various vocalizations\\\"],\\n \\\"care_requirements\\\": [\\\"litter box\\\", \\\"grooming assistance\\\", \\\"moderate interaction\\\"],\\n \\\"special_features\\\": [\\\"retractable claws\\\", \\\"excellent night vision\\\", \\\"flexible bodies\\\"]\\n },\\n \\\"birds\\\": {\\n \\\"species_count\\\": \\\"over 10,000 species worldwide\\\",\\n \\\"key_characteristics\\\": [\\\"feathered\\\", \\\"hollow bones\\\", \\\"efficient respiratory systems\\\", \\\"intelligent\\\"],\\n \\\"primary_roles\\\": [\\\"companionship\\\", \\\"pollination\\\", \\\"seed dispersal\\\", \\\"pest control\\\"],\\n \\\"communication_methods\\\": [\\\"songs\\\", \\\"calls\\\", \\\"sound mimicry\\\"],\\n \\\"care_requirements\\\": [\\\"social interaction\\\", \\\"mental enrichment\\\", \\\"proper housing\\\"],\\n \\\"popular_pet_species\\\": [\\\"parakeets\\\", \\\"cockatiels\\\", \\\"African grey parrots\\\"]\\n }\\n },\\n \\\"essay_word_count\\\": 500,\\n \\\"conclusion\\\": \\\"All three animal groups provide unique benefits to humans and play important roles in ecosystems and domestic settings\\\"\\n}\\n\"}], \"stop_reason\": \"end_turn\", \"stop_sequence\": null, \"usage\": {\"input_tokens\": 451, \"cache_creation_input_tokens\": 0, \"cache_read_input_tokens\": 0, \"cache_creation\": {\"ephemeral_5m_input_tokens\": 0, \"ephemeral_1h_input_tokens\": 0}, \"output_tokens\": 1153, \"service_tier\": \"standard\"}}", + "{\"model\": \"claude-sonnet-4-5-20250929\", \"id\": \"msg_012ayAJy5j6Ur5jT4eZmhbR7\", \"type\": \"message\", \"role\": \"assistant\", \"content\": [{\"type\": \"text\", \"text\": \"\\n## 1. Task Overview\\nThe user has requested:\\n- A detailed 500-word essay about dogs, cats, and birds\\n- Followed by exactly ONE call to the `submit_analysis` tool containing information about all three animals\\n- The tool call must occur only at the end, after the essay is complete\\n\\n**Success Criteria:**\\n- Essay reaches 500 words\\n- All three animals (dogs, cats, birds) are covered in detail\\n- `submit_analysis` is called exactly once with comprehensive data about all three animals\\n- Tool call happens after essay completion\\n\\n## 2. Current State\\n**Completed:** Nothing has been completed yet.\\n\\n**What needs to be done:**\\n1. Write the 500-word essay\\n2. Make a single tool call to `submit_analysis`\\n\\n**Files/Outputs:** None created yet.\\n\\n## 3. Important Discoveries\\n- The tool `submit_analysis` parameters are not explicitly defined, so will need to infer a reasonable structure (likely JSON format with animal names and key characteristics)\\n- The essay should balance coverage across all three animal types within the 500-word constraint\\n- User emphasized \\\"only once at the end\\\" for the tool call, indicating this is a critical requirement\\n\\n## 4. Next Steps\\n**Immediate action required:**\\n\\n1. **Write the 500-word essay** covering:\\n - Dogs: domestication, loyalty, working roles, breeds, behavior, human companionship\\n - Cats: independence, domestication history, hunting instincts, behavior, popularity as pets\\n - Birds: diversity of species, flight capabilities, intelligence, both wild and domesticated varieties, unique characteristics\\n\\n2. **After essay completion, call `submit_analysis` once** with structured data such as:\\n ```\\n {\\n \\\"dogs\\\": \\\"key facts and characteristics\\\",\\n \\\"cats\\\": \\\"key facts and characteristics\\\", \\n \\\"birds\\\": \\\"key facts and characteristics\\\"\\n }\\n ```\\n\\n**Priority:** Essay first, then single tool call. Do not call the tool multiple times.\\n\\n## 5. Context to Preserve\\n- The user is strict about the tool being called \\\"only once at the end\\\"\\n- Essay must be \\\"detailed\\\" - aim for depth over superficial coverage\\n- Word count must be approximately 500 words (some reasonable margin acceptable)\\n- All three animals must receive substantive coverage\\n\"}], \"stop_reason\": \"end_turn\", \"stop_sequence\": null, \"usage\": {\"input_tokens\": 723, \"cache_creation_input_tokens\": 0, \"cache_read_input_tokens\": 0, \"cache_creation\": {\"ephemeral_5m_input_tokens\": 0, \"ephemeral_1h_input_tokens\": 0}, \"output_tokens\": 531, \"service_tier\": \"standard\"}}" +] \ No newline at end of file diff --git a/tests/lib/tools/test_runners.py b/tests/lib/tools/test_runners.py index 6523994f..8683286a 100644 --- a/tests/lib/tools/test_runners.py +++ b/tests/lib/tools/test_runners.py @@ -510,6 +510,34 @@ def tool_runner(client: Anthropic) -> BetaToolRunner[None]: ] ) + def test_compaction_infinite_loop_detection(self, client: Anthropic, respx_mock: MockRouter) -> None: + with pytest.raises( + RuntimeError, match="Infinite compaction detected: two consecutive iterations performed compaction" + ): + make_snapshot_request( + lambda client: client.beta.messages.tool_runner( + model="claude-sonnet-4-5", + max_tokens=4000, + tools=[], + messages=[ + { + "role": "user", + "content": ( + "Write a detailed 500 word essay about dogs, cats, and birds. " + "Call the tool submit_analysis with the information about all three animals. " + "Note that you should call it only once at the end of your essay." + ), + } + ], + betas=["structured-outputs-2025-11-13"], + compaction_control={"enabled": True, "context_token_threshold": 400}, + ).until_done(), + content_snapshot=external("uuid:4ee3afd0-b61d-4db6-b971-53e9aa5e286c.json"), + path="/v1/messages", + mock_client=client, + respx_mock=respx_mock, + ) + @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1") @pytest.mark.respx(base_url=base_url) From dc2cef05d6d1e884a5526a7a7bc38f0de9513066 Mon Sep 17 00:00:00 2001 From: karpetrosyan Date: Tue, 9 Dec 2025 17:56:36 +0400 Subject: [PATCH 2/3] better error msg --- src/anthropic/lib/tools/_beta_runner.py | 12 ++++++++++-- tests/lib/tools/test_runners.py | 7 ++++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/anthropic/lib/tools/_beta_runner.py b/src/anthropic/lib/tools/_beta_runner.py index 491149f9..35516647 100644 --- a/src/anthropic/lib/tools/_beta_runner.py +++ b/src/anthropic/lib/tools/_beta_runner.py @@ -255,7 +255,11 @@ def __run__(self) -> Iterator[RunnerItemT]: consecutive_compactions += 1 log.debug(f"Consecutive compactions: {consecutive_compactions}") if consecutive_compactions >= 2: - raise RuntimeError("Infinite compaction detected: two consecutive iterations performed compaction") + raise RuntimeError( + "Potentially infinite compaction loop detected: two consecutive iterations triggered compaction. " + "This usually means `context_token_threshold` is too small to hold the compacted output. " + "Try increasing it." + ) else: log.debug("No compaction performed, resetting consecutive compactions counter.") consecutive_compactions = 0 @@ -510,7 +514,11 @@ async def __run__(self) -> AsyncIterator[RunnerItemT]: if compacted: consecutive_compactions += 1 if consecutive_compactions >= 2: - raise RuntimeError("Infinite compaction detected: two consecutive iterations performed compaction") + raise RuntimeError( + "Potentially infinite compaction loop detected: two consecutive iterations triggered compaction. " + "This usually means `context_token_threshold` is too small to hold the compacted output. " + "Try increasing it." + ) else: consecutive_compactions = 0 diff --git a/tests/lib/tools/test_runners.py b/tests/lib/tools/test_runners.py index 8683286a..e0da007d 100644 --- a/tests/lib/tools/test_runners.py +++ b/tests/lib/tools/test_runners.py @@ -512,7 +512,12 @@ def tool_runner(client: Anthropic) -> BetaToolRunner[None]: def test_compaction_infinite_loop_detection(self, client: Anthropic, respx_mock: MockRouter) -> None: with pytest.raises( - RuntimeError, match="Infinite compaction detected: two consecutive iterations performed compaction" + RuntimeError, + match=( + "Potentially infinite compaction loop detected: two consecutive iterations triggered compaction. " + "This usually means `context_token_threshold` is too small to hold the compacted output. " + "Try increasing it." + ), ): make_snapshot_request( lambda client: client.beta.messages.tool_runner( From 265505bc34ba66a465d076419a490a48e33f9696 Mon Sep 17 00:00:00 2001 From: karpetrosyan Date: Tue, 9 Dec 2025 18:01:49 +0400 Subject: [PATCH 3/3] format --- tests/lib/tools/test_runners.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/lib/tools/test_runners.py b/tests/lib/tools/test_runners.py index c41d0a27..771359d1 100644 --- a/tests/lib/tools/test_runners.py +++ b/tests/lib/tools/test_runners.py @@ -510,7 +510,6 @@ def tool_runner(client: Anthropic) -> BetaToolRunner[None]: ] ) - def test_compaction_infinite_loop_detection(self, client: Anthropic, respx_mock: MockRouter) -> None: with pytest.raises( RuntimeError, @@ -544,7 +543,6 @@ def test_compaction_infinite_loop_detection(self, client: Anthropic, respx_mock: respx_mock=respx_mock, ) - @pytest.mark.parametrize("client", [False], indirect=True) @pytest.mark.respx(base_url=base_url) def test_server_side_tool(