agent-loop-breaker 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,368 @@
1
+ Metadata-Version: 2.5
2
+ Name: agent-loop-breaker
3
+ Version: 0.1.0
4
+ Summary: A circuit breaker for AI agents: stop runaway runs by step count, wall time, token or cost budget, and repeated tool calls, with a readable report.
5
+ Project-URL: Homepage, https://github.com/boscofoulsham/loop-breaker
6
+ Project-URL: Repository, https://github.com/boscofoulsham/loop-breaker
7
+ Project-URL: Issues, https://github.com/boscofoulsham/loop-breaker/issues
8
+ Author: Bosco Foulsham
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: agents,ai-agents,budget,circuit-breaker,crewai,langgraph,llm,loop-detection,openai-agents,pydantic-ai
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Software Development :: Libraries
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.10
25
+ Provides-Extra: crewai
26
+ Requires-Dist: crewai<2,>=1.15; extra == 'crewai'
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest-timeout>=2.3; extra == 'dev'
29
+ Requires-Dist: pytest>=8; extra == 'dev'
30
+ Provides-Extra: langgraph
31
+ Requires-Dist: langchain-core<2,>=1.8; extra == 'langgraph'
32
+ Requires-Dist: langgraph<2,>=1.2; extra == 'langgraph'
33
+ Provides-Extra: openai-agents
34
+ Requires-Dist: openai-agents<1,>=0.26; extra == 'openai-agents'
35
+ Provides-Extra: pydantic-ai
36
+ Requires-Dist: pydantic-ai-slim<3,>=2.77; extra == 'pydantic-ai'
37
+ Description-Content-Type: text/markdown
38
+
39
+ # loop-breaker
40
+
41
+ A circuit breaker for AI agents: hard limits on steps, wall time, tokens and cost that stop a run, plus loop detection (repeats, short cycles) that warns you by default, and a readable report of what happened.
42
+
43
+ Loop detection is a heuristic. It can't know what your agent is trying to do, so by default it only warns (a log line, a callback, a section in the report). The hard limits are exact and always stop the run. Turn on `on_loop="stop"` once you trust the warnings on your own runs.
44
+
45
+ ## The problem
46
+
47
+ Agents get stuck. They call the same tool with the same arguments again and again, or keep rephrasing a search that returns nothing, and every turn costs tokens. The built-in limits don't always hold: in Agno, `tool_call_limit` blocks the tools but the model keeps getting called ([agno#8304](https://github.com/agno-agi/agno/issues/8304)); in n8n, retry-on-fail after "max iterations" can restart the agent indefinitely ([n8n#37779](https://github.com/n8n-io/n8n/issues/37779)); Gemini CLI had to add loop detection for models that repeat themselves ([gemini-cli#3934](https://github.com/google-gemini/gemini-cli/issues/3934)). And a [Show HN on agent guardrails](https://news.ycombinator.com/item?id=48192383) (retry nudges, step enforcement, max-iteration errors) is a good read on why limits with context matter.
48
+
49
+ loop-breaker is one small library you can put under any agent loop, with thin adapters for LangGraph, the OpenAI Agents SDK, Pydantic AI and CrewAI.
50
+
51
+ ## Demo
52
+
53
+ ```text
54
+ $ loop-breaker demo
55
+ turn 1: model asks for search('weather in Paris')
56
+ turn 2: model asks for search('Paris weather forecast')
57
+ turn 3: model asks for search('Weather in Paris')
58
+ turn 4: model asks for search('weather in Paris?')
59
+ turn 5: model asks for search('weather in paris')
60
+ turn 6: model asks for search('WEATHER IN PARIS')
61
+ turn 7: model asks for search('weather in Paris')
62
+ turn 8: model asks for search('Weather in Paris')
63
+ ! search was called 6 times with near-identical arguments in the last 6 steps, with nothing new in between
64
+ turn 9: model asks for search('weather in Paris?')
65
+ turn 10: model asks for search('weather in paris')
66
+ turn 11: model asks for search('WEATHER IN PARIS')
67
+ turn 12: model asks for search('weather in Paris')
68
+ turn 13: model asks for search('Weather in Paris')
69
+
70
+ loop-breaker stopped [toy-agent]: hit max_steps=12; step 13 (search {"query": "Weather in Paris"}) was not run
71
+ usage 12 steps run | 0.0s | 23,075 tokens | $0.0747
72
+ limits max_steps=12, max_tokens=60000, on_loop=warn, loop_threshold=6, similarity=0.85, max_exact_repeats=10, cycle_repeats=3
73
+ blocked search {"query": "Weather in Paris"}
74
+ last steps
75
+ #3 search {"query": "Weather in Paris"} -> no results
76
+ #4 search {"query": "weather in Paris?"} -> no results
77
+ #5 search {"query": "weather in paris"} -> no results
78
+ #6 search {"query": "WEATHER IN PARIS"} -> no results
79
+ #7 search {"query": "weather in Paris"} -> no results
80
+ #8 search {"query": "Weather in Paris"} -> no results
81
+ #9 search {"query": "weather in Paris?"} -> no results
82
+ #10 search {"query": "weather in paris"} -> no results
83
+ #11 search {"query": "WEATHER IN PARIS"} -> no results
84
+ #12 search {"query": "weather in Paris"} -> no results
85
+ loop warnings (1)
86
+ loop-breaker warning [toy-agent] at step 8: search was called 6 times with near-identical arguments in the last 6 steps, with nothing new in between
87
+ most repeated calls
88
+ 12x search {"query": "weather in Paris"}
89
+ ```
90
+
91
+ <!-- demo.gif: record with vhs demo.tape -->
92
+
93
+ The toy agent in `loop-breaker demo` is scripted (no API key, no network). At turn 8 it has made the 6th near-identical search in a row with nothing new coming back, so it gets a warning. It keeps going, as a real agent would, until `max_steps=12` stops it.
94
+
95
+ ## Quickstart
96
+
97
+ ```bash
98
+ pip install agent-loop-breaker # Python 3.10+, no dependencies
99
+ loop-breaker demo
100
+ ```
101
+
102
+ The package on PyPI is `agent-loop-breaker` (the name `loop-breaker` was too close to an existing project); you import it as `loop_breaker`. From a clone: `pip install -e .` instead of the first line.
103
+
104
+ In your own agent loop, call `breaker.step()` before each tool call, `breaker.record_result()` after it, and `breaker.record_usage()` after each model call. Or wrap your tools with `@breaker.guard`, which does the first two for you:
105
+
106
+ ```python
107
+ from loop_breaker import Breaker, BreakerTripped
108
+
109
+ breaker = Breaker(max_steps=20, max_seconds=300, max_tokens=200_000)
110
+
111
+ @breaker.guard # every call goes through breaker.step()
112
+ def search(query: str) -> str:
113
+ return "no results"
114
+
115
+ try:
116
+ while True: # an agent that never gives up
117
+ breaker.record_usage(input_tokens=1200, output_tokens=40)
118
+ search("latest Python release")
119
+ except BreakerTripped as stop:
120
+ print(stop) # what happened, in plain text
121
+ log = stop.report.to_dict() # or as a dict for your logs
122
+ ```
123
+
124
+ ```text
125
+ loop-breaker warning [agent] at step 6: search was called 6 times with the same arguments in the last 6 steps, with nothing new in between
126
+ loop-breaker stopped [agent]: hit max_steps=20; step 21 (search {"query": "latest Python release"}) was not run
127
+ usage 20 steps run | 0.0s | 26,040 tokens | cost unknown
128
+ limits max_steps=20, max_seconds=300, max_tokens=200000, on_loop=warn, loop_threshold=6, similarity=0.85, max_exact_repeats=10, cycle_repeats=3
129
+ blocked search {"query": "latest Python release"}
130
+ last steps
131
+ #11 search {"query": "latest Python release"} -> no results
132
+ #12 search {"query": "latest Python release"} -> no results
133
+ #13 search {"query": "latest Python release"} -> no results
134
+ #14 search {"query": "latest Python release"} -> no results
135
+ #15 search {"query": "latest Python release"} -> no results
136
+ #16 search {"query": "latest Python release"} -> no results
137
+ #17 search {"query": "latest Python release"} -> no results
138
+ #18 search {"query": "latest Python release"} -> no results
139
+ #19 search {"query": "latest Python release"} -> no results
140
+ #20 search {"query": "latest Python release"} -> no results
141
+ loop warnings (1)
142
+ loop-breaker warning [agent] at step 6: search was called 6 times with the same arguments in the last 6 steps, with nothing new in between
143
+ most repeated calls
144
+ 21x search {"query": "latest Python release"}
145
+ ```
146
+
147
+ The first line is the warning, logged on the `loop_breaker` logger (Python prints it to stderr when you haven't set up logging). The rest is the report when `max_steps` stopped the run. "21x" counts the blocked call too.
148
+
149
+ **Always set a hard limit.** In warn mode nothing else ends a stuck run, and some frameworks' own limits are high: LangGraph's default `recursion_limit` is now 10,007.
150
+
151
+ To act on warnings, pass `on_warning=` (called once per stall with a `LoopWarning` that has `kind`, `message` and `step`; raise from it to stop the run with your own exception), or read `breaker.warnings`. To stop instead of warn, use `Breaker(..., on_loop="stop")`; the same script then ends at the 6th call:
152
+
153
+ ```text
154
+ loop-breaker stopped [agent]: search was called 6 times with the same arguments in the last 6 steps, with nothing new in between
155
+ usage 5 steps run | 0.0s | 7,440 tokens | cost unknown
156
+ ```
157
+
158
+ `BreakerTripped` has two subclasses: `BudgetExceeded` (`reason` is `"steps"`, `"time"`, `"tokens"` or `"cost"`) and `LoopDetected`, raised only with `on_loop="stop"` (`"repeat"`, `"cycle"` or `"no_progress"`).
159
+
160
+ A Breaker tracks one run. `with breaker:` starts a new run (it resets a breaker that has been used), and so does `breaker.new_run()`. When you call the Breaker yourself, use one per run (`breaker.fresh()` gives you an untouched copy with the same settings). The framework adapters do this for you: the breaker you give them is a template, and every run gets its own copy, so runs one after another or at the same time never share counts, a clock, warnings or a trip. `adapter.last_breaker` is the copy the latest run used (its `.warnings` are that run's warnings; `on_warning` is copied too); `per_run=False` shares one breaker (one budget) across runs instead.
161
+
162
+ ## Framework adapters
163
+
164
+ Each adapter is a small file on top of the framework's own public hook API, and is tested in CI against the real package with a stub model (no API calls), in both warn and stop mode. Install the extra you need.
165
+
166
+ **LangGraph** (`pip install "agent-loop-breaker[langgraph]"`): a LangChain callback handler, so it works for any graph or runnable, sync or async, including `stream` and `batch`. Each top-level run (every input of a `batch`) gets its own copy of the breaker. LangChain logs an exception raised in a callback ("Error in LoopBreakerCallback.on_tool_start callback: ...") before it re-raises it; the adapter adds a logging filter that drops that line for its own `BudgetExceeded` and `LoopDetected`, so you only see the exception. Anything else raised in the callback, such as your own exception from `on_warning`, is still logged.
167
+
168
+ ```python
169
+ from loop_breaker import Breaker
170
+ from loop_breaker.langgraph import LoopBreakerCallback
171
+
172
+ breaker = Breaker(max_steps=40, max_tokens=200_000)
173
+ graph.invoke(inputs, config={"callbacks": [LoopBreakerCallback(breaker)]}) # raises BudgetExceeded (or LoopDetected in stop mode)
174
+ ```
175
+
176
+ **OpenAI Agents SDK** (`pip install "agent-loop-breaker[openai-agents]"`): run hooks. The SDK wraps errors raised in hooks in its own `UserError`, so use `find_trip` to get ours back. Each run gets its own copy of the breaker, recognised by the run's usage object, so one hooks object can be shared by concurrent runs.
177
+
178
+ ```python
179
+ from agents import Runner
180
+ from loop_breaker import Breaker, find_trip
181
+ from loop_breaker.openai_agents import LoopBreakerHooks
182
+
183
+ breaker = Breaker(max_steps=40, max_cost_usd=2.0, price_per_mtok=(1.25, 10.0))
184
+ try:
185
+ result = await Runner.run(agent, "...", hooks=LoopBreakerHooks(breaker))
186
+ except Exception as exc:
187
+ trip = find_trip(exc)
188
+ if trip is None:
189
+ raise
190
+ print(trip.report)
191
+ ```
192
+
193
+ **Pydantic AI** (`pip install "agent-loop-breaker[pydantic-ai]"`): a capability. Our exceptions come out of `agent.run()` unchanged. The breaker you pass is a template: each run of the agent, including runs at the same time, gets its own copy, so an agent defined once at module level is fine. `cap.last_breaker` is the copy the latest run used.
194
+
195
+ ```python
196
+ from pydantic_ai import Agent
197
+ from loop_breaker import Breaker
198
+ from loop_breaker.pydantic_ai import LoopBreakerCapability
199
+
200
+ cap = LoopBreakerCapability(Breaker(max_steps=40, max_seconds=120))
201
+ agent = Agent(model, capabilities=[cap])
202
+ ```
203
+
204
+ **CrewAI** (`pip install "agent-loop-breaker[crewai]"`): execution hooks, registered while the `with` block is open. CrewAI swallows hook errors other than its own `HookAborted`, so the adapter blocks the tool call and then aborts the run at the next model call. The same goes for an exception you raise from `on_warning`: inside the `with` block it arrives as a `HookAborted` whose `__cause__` is your exception, and the `with` block re-raises your own exception. Each crew run gets its own copy of the breaker, keyed by the Crew object the hooks see; `kickoff_for_each` copies the crew per input, so each input is its own run. Kicking off the same Crew object twice inside one `with` block shares a breaker.
205
+
206
+ ```python
207
+ from loop_breaker import Breaker, find_trip
208
+ from loop_breaker.crewai import guard
209
+
210
+ breaker = Breaker(max_steps=30, max_seconds=600)
211
+ with guard(breaker):
212
+ try:
213
+ crew.kickoff()
214
+ except Exception as exc:
215
+ print(find_trip(exc) or exc)
216
+ ```
217
+
218
+ Every adapter takes `per_run=False` (CrewAI: `guard(breaker, per_run=False)`) if you want one budget across several runs.
219
+
220
+ Tested versions (exact pins in [`ci/tested-versions.txt`](ci/tested-versions.txt); CI also runs the newest allowed versions): langgraph 1.2.24 with langchain-core 1.8.5 (and LangChain 1.5.2's `create_agent`), openai-agents 0.26.1, pydantic-ai-slim 2.77.0, crewai 1.15.47.
221
+
222
+ Planned, not shipped: Agno, smolagents, AutoGen, Google ADK. Until then, `@breaker.guard` on your tool functions plus `record_usage()` after model calls works with anything.
223
+
224
+ ## What the frameworks already have, and what this adds
225
+
226
+ Use the built-in limits; they're good. loop-breaker is for what they don't cover, and for getting the same limits and the same report everywhere.
227
+
228
+ | Framework | Built in (checked in the installed source) | loop-breaker adds |
229
+ |---|---|---|
230
+ | LangGraph 1.2 | `recursion_limit` (default is now 10,007 supersteps); LangChain's `create_agent` has model- and tool-call-limit middleware | repeat and cycle detection (warn or stop), token/cost/time budgets, the report |
231
+ | OpenAI Agents SDK 0.26 | `max_turns` (default 10) | repeat and cycle detection (warn or stop), token/cost/time budgets, the report |
232
+ | Pydantic AI 2.77 | `UsageLimits`: requests (default 50), tool calls, tokens, cost | repeat and cycle detection (warn or stop), wall-clock limit, the report |
233
+ | CrewAI 1.15 | `max_iter` (default 25), `max_execution_time`, `max_rpm`; after 5 identical calls in a row with the same result it stops the agent's tool calls and lets it answer with what it has | repeats that aren't back to back or whose args are only near-identical, cycles, token and cost budgets, stopping the whole run, the report |
234
+
235
+ The other differences: one exception type and one report across frameworks, near-identical matching (case, spacing, key order, punctuation), and a breaker that stays tripped, so a framework that catches the first exception is stopped at its next model or tool call.
236
+
237
+ [loopbuster](https://github.com/liuchunwei732-cmyk/loopbuster) is a similar project with more detection strategies (output stagnation, adaptive thresholds), a Redis backend and a dashboard. loop-breaker is smaller: it raises through each framework's own hook API instead of returning a decision you check, and its adapters are tested against the current releases.
238
+
239
+ ## Replay a recorded run
240
+
241
+ Want to know where loop-breaker would have warned or stopped in a past run? Replay it. Exit codes: 0 nothing found, 2 it would have stopped (a hard limit, or a loop with `--on-loop stop`), 3 loop warnings only, 1 the file couldn't be read (not JSONL, bad numbers, nothing to replay). `--example` replays a bundled Claude Code run stuck between an edit that no longer applies and a test that keeps failing the same way.
242
+
243
+ ```text
244
+ $ loop-breaker replay --example
245
+ replayed claude trace: 18 tool calls in file
246
+ would have warned 1 time; with --on-loop stop it would have stopped before tool call 9 of 18
247
+ loop-breaker [example]: no limit hit
248
+ usage 18 steps run | 252.0s | 64,260 tokens | $0.6187
249
+ limits on_loop=warn, loop_threshold=6, similarity=0.85, max_exact_repeats=10, cycle_repeats=3
250
+ last steps
251
+ #9 Edit {"file_path": "/work/shop-api/src/cart.js", "new_string": "return a... -> <tool_use_error>String to replace not...
252
+ #10 Bash {"command": "npm test -- cart", "description": "Run cart tests"} -> FAIL tests/cart.test.js ● cart total ...
253
+ #11 Edit {"file_path": "/work/shop-api/src/cart.js", "new_string": "return a... -> <tool_use_error>String to replace not...
254
+ #12 Bash {"command": "npm test -- cart", "description": "Run cart tests"} -> FAIL tests/cart.test.js ● cart total ...
255
+ #13 Edit {"file_path": "/work/shop-api/src/cart.js", "new_string": "return a... -> <tool_use_error>String to replace not...
256
+ #14 Bash {"command": "npm test -- cart", "description": "Run cart tests"} -> FAIL tests/cart.test.js ● cart total ...
257
+ #15 Edit {"file_path": "/work/shop-api/src/cart.js", "new_string": "return a... -> <tool_use_error>String to replace not...
258
+ #16 Bash {"command": "npm test -- cart", "description": "Run cart tests"} -> FAIL tests/cart.test.js ● cart total ...
259
+ #17 Edit {"file_path": "/work/shop-api/src/cart.js", "new_string": "return a... -> <tool_use_error>String to replace not...
260
+ #18 Bash {"command": "npm test -- cart", "description": "Run cart tests"} -> FAIL tests/cart.test.js ● cart total ...
261
+ loop warnings (1)
262
+ loop-breaker warning [example] at step 9: the same 2 calls (Bash -> Edit) went round 3 times with the same results
263
+ most repeated calls
264
+ 8x Edit {"file_path": "/work/shop-api/src/cart.js", "new_string": "return a...
265
+ 8x Bash {"command": "npm test -- cart", "description": "Run cart tests"}
266
+ ```
267
+
268
+ Formats (auto-detected, or `--format`):
269
+
270
+ - Claude Code / Claude Agent SDK `stream-json` output: `claude -p "..." --output-format stream-json --verbose > run.jsonl`. Message shapes are from the [Agent SDK reference](https://code.claude.com/docs/en/agent-sdk/typescript); usage is counted once per message id, as the [cost-tracking guide](https://code.claude.com/docs/en/agent-sdk/cost-tracking) says.
271
+ - A generic JSONL trace you can write from anything: `{"tool": "search", "args": {...}, "result": "...", "input_tokens": 120, "output_tokens": 30, "cost": 0.001, "t": 12.5}`. Only `tool` is required; a line with no `tool` but with tokens or cost is a model call.
272
+
273
+ Every setting below is a flag (`loop-breaker replay --help`), plus `--json`.
274
+
275
+ ## How it works
276
+
277
+ `step(tool, args)` normalises the arguments (sorted keys, JSON strings parsed, floats rounded, `ignore_arg_keys` dropped) and hashes them. `record_result()` remembers the answer with timestamps, dates, durations (`0.43s`, `12 ms`), ids (UUIDs, `req_...`, `<...@mail>`, long hex), memory addresses (`<Cart object at 0x7f3a2b1c4d50>`) and printed random seeds (`--randomly-seed=1234`) masked, so `1 failed in 0.43s` and `1 failed in 0.47s` are the same answer. In answers, any 10- or 13-digit number starting with 1 counts as a unix time. Plain numbers are kept: a progress count going 5, 18, 33 is news. An answer longer than 8 KB is compared by a hash of its whole masked text, so a change anywhere in it counts.
278
+
279
+ "Something new" means a call not seen before in this run, or an answer not seen before. Each rule counts from the last time something new happened, over the whole run (the last 2,000 calls), not a short window:
280
+
281
+ - **Repeat** (`loop_threshold`, 6): the 6th call to one tool with near-identical arguments and nothing new in between. Two calls match if their hashes are equal, or if all of these hold:
282
+ - every number is the same, including digit runs inside strings, so `?page=2` and `?page=3`, `"page": "2"` and `"page": "3"`, or `id-123` and `id-124` never match;
283
+ - the character-trigram similarity of the arguments is at least `similarity` (0.85), with prose compared case- and punctuation-blind (single tokens such as paths keep their case, so `src/Config.py` and `src/config.py` differ);
284
+ - no word was swapped for a different one: `figures`/`figure` or `corporation`/`corp` match, `country = 'FR'`/`'DE'` don't.
285
+
286
+ A wait in between makes it a poll, not a repeat: a call to a wait tool (`sleep`, `wait`, `delay`, `pause`... see `wait_tools`), or a call that sleeps itself (`sleep 30 && gh run view` in a `command` argument). A poll whose answer changes (`queued`, `running`, `done`) is not a loop either.
287
+ - **Exact repeat** (`max_exact_repeats`, 10): the 10th call with exactly the same tool and arguments since anything new, even with waits in between. A new answer from that call resets the count, with one exception: if the call came straight back to itself and only numbers or ids changed (`issue #812`, then `issue #813`), that's how a duplicate side effect looks, so it still counts.
288
+ - **Cycle** (`cycle_repeats`, 3): the same 2, 3 or 4 calls going round 3 times with the same (masked) answers, such as Read, Edit that fails, a test that fails the same way. The calls are compared with times, dates and ids in their arguments masked, so a timestamped note in the cycle, or a new draft, sandbox or idempotency key made on each try, doesn't hide it. Ids here are UUIDs, runs of 12 or more lowercase hex digits or digits, ids with a listed prefix (`req_`, `request_`, `msg_`, `message_`, `evt_`, `event_`, `run_`, `job_`, `txn_`, `ch_`, `pi_`, `in_`, `trace_`, `span_`, also with `-`), message ids, dates and unix times (any 10- or 13-digit number starting with 1); and, when a tool's answer made the id, also a short prefix with a digit in the rest (`sbx_4kQ93nTz`, `sess-8Hn2kd91`) or a token of 16-64 letters and digits with both in it (`r1800042377190366891`, compact sandbox ids). For this rule, an id of those wider shapes in the create call's answer doesn't make the answer new, as long as the loop uses it in its arguments. But at least one call must be the same every round (times masked): the create or re-read next to the fresh id. In a batch every call names its own item (label then archive each email, run then check each day's backfill), so a batch is not a cycle. And an id that an answer showed before the same call's previous round (the search or list that started a batch, or the same list re-read before each item) is a batch item, not a fresh id: re-reading the workflow states before moving each issue from a search is not flagged. A fresh id is first shown inside the loop, or never (an idempotency key). When deciding whether one call is the same every round, a 10- or 13-digit number in the arguments counts as a unix time only under a time-like key or after a time word (`"at": 1764755000`, `"createdAt"`, `since=`), so ISBN-10s, book ASINs and `Date.now()`-style ids stay ids.
289
+ - **No progress** (`no_progress_steps`, off): N calls in a row with nothing new. Off by default because a batch of different writes that each answer "ok" has nothing new either.
290
+
291
+ With `on_loop="warn"` (the default), the first rule to fire gives one warning; nothing more is reported until something new happens, and the same loop is reported again only once it has been broken: the repeated call got a different answer (not just a new number straight after itself), or the cycle stopped going round. So an agent that re-runs a failing test, fixes it, and then gets stuck on the next failure of the same command gets a second warning. One loop gets at most 3 warnings in a run; the 3rd says so. The first warning is exactly where `on_loop="stop"` would have stopped. The hard limits stop the run in both modes. `record_usage()` adds tokens and cost (yours, or from `price_per_mtok`) and checks those budgets; wall time is checked on every event. Once tripped, every later `step`, `check` and `record_usage` raises the same exception until a new run starts. The work per call stays flat however long a stuck run goes on. No dependencies, no network calls, no telemetry. Thread-safe.
292
+
293
+ ### How well it does, and why the default is 6
294
+
295
+ `tests/realistic_traces.py` has seven sets of hand-written traces. The builder wrote 14 normal traces (polling, paging by URL, string page numbers and cursors, SQL per country, sibling and case-different files, refining a search, a flaky request, edit-and-test cycles) and 6 loops. Two independent reviewers, who were checking the detection rules, wrote 20 more normal traces (backoff retries, polls with and without a wait tool, test-fix-test runs, clicking "Next" through pages, an SWE-agent reproduce loop, computer-use screenshots, a shell poll with `sleep 30 &&`, a queue reader, a research run) and 10 more loops (a declined charge with a fresh request id each time, the same email sent again and again, edit flip-flops, Read/Edit/pytest cycles whose test output carries a new duration, searches rephrased with a request id in each answer). After the redesign the builder added 4 normal traces (15 file writes that each answer "ok", 15 welcome emails, 15 issue labels with no answer recorded, a job polled 30 times with a wait tool) and 2 duplicate side effects whose answer carries a number that goes up. A third reviewer added 10 more normal traces (label and archive each of 12 emails, assign and tag 10 tickets, a backfill per date, a coding agent fixing one test per round, a browser agent scrolling a feed, a game agent walking, order lookups and refunds, scrolling a file, a shell poll of a rising counter, a retried SQL timeout) and 6 more loops (Read/Edit/pytest cycles whose output shows an object address or a new random seed, a test that gets stuck again after a real fix, a form that keeps showing the same error, a 5-call round, the same Slack post again and again). A fourth reviewer added 5 more normal traces (booking interview slots, a Slack triage bot keyed by message time, adding and tagging books by ISBN-10, an SQS worker long-polling 120 times, a daily Airflow backfill) and 6 more loops (a new Gmail draft, a new code sandbox or a fresh payment idempotency key on each try, a Read/Edit/`pytest -v` cycle with 14 KB of output, the same cycle again after a real change, re-triggering a failing Airflow DAG). A fifth reviewer added 5 more normal traces (re-reading Linear's workflow states before moving each of 8 issues, re-reading a Notion schema before each meeting page, fixing lint one file per round, labelling PRs by number, sending receipts) and 5 more loops (a new browser session each try, a declined charge retried with only a fresh idempotency key, new draft/attach/send each try, an archived issue moved again and again, re-dispatching a failing deploy workflow). The traces of reviews 4 to 6 were written after the defaults were set. The cycle rule was changed because of some of them: review 4's email, ticket and backfill batches (a batch is not a cycle), review 5's fresh-id loops (a new id each round is still a cycle) and its book batch (10-digit ids are not times), and review 6's Linear batch (ids an earlier answer listed are batch items) and its sandbox ids (wider id shapes). With every setting at its default (`python tests/realistic_traces.py` prints this table and the next one):
296
+
297
+ | trace set | normal traces | flagged (false positives) | loops | caught | calls before a loop is flagged (avg) |
298
+ |---|---|---|---|---|---|
299
+ | builder | 14 | 0 | 6 | 6 | 5.0 |
300
+ | review 2 | 10 | 0 | 5 | 4 | 6.5 |
301
+ | review 3 | 10 | 1 | 5 | 5 | 6.2 |
302
+ | builder, round 3 | 4 | 0 | 2 | 2 | 9.0 |
303
+ | review 4 | 10 | 2 | 6 | 6 | 10.7 |
304
+ | review 5 | 5 | 2 | 6 | 6 | 6.0 |
305
+ | review 6 | 5 | 0 | 5 | 3 | 6.0 |
306
+ | **all** | 58 | 5 | 35 | 32 | 7.0 |
307
+
308
+ "Flagged" means a warning at the defaults, which is the same as a stop with `on_loop="stop"`. The false positives: N17 is 14 polls of a job straight after each other, with no wait, where only the elapsed seconds change. That is exactly what a duplicate side effect with a new id looks like, so the exact-repeat cap flags the 10th poll; a wait between polls clears it. N25 (a `scroll_down` that always answers the same text, flagged at the 6th call) and N26 (a `move` whose answer changes only in the position, flagged at the 10th) are the same thing for tools that change state without saying so; `exclude_tools` clears them (see Limits). N34 is an SQS worker that long-polls: the wait happens on the server, so loop-breaker sees polls with no wait and the same empty answer, and flags the 6th empty poll in a row (call 14). It warns again after two later idle gaps, then stops (3 warnings for one loop). N35, a daily Airflow backfill, is a batch keyed only by a time (each logical date is a midnight datetime), flagged at the 6th call. Both are in Limits. The 5-call round in review 4 is beyond the cycle rule (2-4 calls), so only the exact-repeat cap catches it, at call 30; that is most of why review 4's average is high. Three loops are missed, all in Limits. A search padded with filler words ("setup guide", "how to setup", "setup tutorial"...): string matching can't see that those mean the same thing, and only `no_progress_steps=10` (off by default) catches it, at the 12th call. Review 6's L42, a declined charge retried on its own 30 times with only a new idempotency key: every call is new, so nothing fires; `ignore_arg_keys=["idempotency_key"]` catches it at the 6th call. Review 6's L45, re-dispatching a failing GitHub workflow: each run id is a plain 11-digit number, which isn't masked, so every round is new and only the hard limits stop it.
309
+
310
+ Other values of `loop_threshold`, everything else at its default:
311
+
312
+ | loop_threshold | false positives (of 58 normal) | loops caught (of 35) | calls before a loop is flagged (avg) |
313
+ |---|---|---|---|
314
+ | 4 | 7 | 32 | 6.0 |
315
+ | 5 | 6 | 32 | 6.5 |
316
+ | 6 (default) | 5 | 32 | 7.0 |
317
+ | 7 | 5 | 31 | 7.5 |
318
+ | 8 | 5 | 31 | 7.9 |
319
+
320
+ 6 is the lowest value with no more false positives than 7 or 8: 5 also flags a poll that answers "processing" four times and then "ready". 7 misses six identical calls fired in one model message (no answers yet, so only the repeat rule can see them). These are hand-written traces, not a benchmark of real agents.
321
+
322
+ ## Settings
323
+
324
+ | Argument | Default | Meaning |
325
+ |---|---|---|
326
+ | `max_steps` | off | tool calls allowed; the next one is blocked |
327
+ | `max_seconds` | off | wall time from the first event (or `with breaker:`) |
328
+ | `max_tokens` | off | input + output tokens |
329
+ | `max_cost_usd` | off | spend; needs costs from `record_usage(cost=)`, the adapter, or `price_per_mtok` |
330
+ | `on_loop` | `"warn"` | `"warn"`: log, call `on_warning`, keep going. `"stop"`: raise `LoopDetected` |
331
+ | `on_warning` | none | called with a `LoopWarning` once per stall; the same loop again only after it was broken, at most 3 times per run |
332
+ | `loop_threshold` | 6 | near-identical calls with nothing new in between (`None` = off) |
333
+ | `similarity` | 0.85 | 0-1; `1.0` = exact matches only |
334
+ | `max_exact_repeats` | 10 | identical calls since anything new, waits or not (`None` = off) |
335
+ | `cycle_repeats` | 3 | rounds of a 2-4 call cycle with the same answers (`None` = off) |
336
+ | `no_progress_steps` | off | N calls in a row with nothing new |
337
+ | `loop_window` | whole run | the repeat rules only look back this many calls (the whole run is capped at the last 2,000); must be at least `loop_threshold`, `max_exact_repeats` and `cycle_repeats`. The cycle rule always looks at the last 2-4 × `cycle_repeats` calls, whatever the window |
338
+ | `exclude_tools` | none | tools never treated as loops; they still count towards `max_steps` |
339
+ | `wait_tools` | `sleep`, `wait`, `wait_for`, `wait_seconds`, `delay`, `pause`, `time_sleep`, `asyncio_sleep` | tools that only pass time, matched in any case. Passing a list replaces the default one |
340
+ | `ignore_arg_keys` | none | argument keys to ignore when comparing, at any depth (request ids, timestamps) |
341
+ | `price_per_mtok` | none | `(input_usd, output_usd)` per million tokens |
342
+
343
+ ## Limits
344
+
345
+ - Loop detection is a heuristic, which is why it warns by default. The numbers above come from hand-written traces; check the warnings on your own runs (replay helps) before you switch to `on_loop="stop"`.
346
+ - In warn mode only the hard limits end a run. Without `max_steps`, `max_seconds` or a budget, a stuck agent runs until the framework's own limit, which can be very high (LangGraph: 10,007 supersteps).
347
+ - It checks at events: before a tool call, before and after a model call. It can't interrupt a single call that hangs. A stalled stream like the ones in [claude-code#26224](https://github.com/anthropics/claude-code/issues/26224) and [claude-code#46987](https://github.com/anthropics/claude-code/issues/46987) needs a client-side timeout, not this.
348
+ - Token and cost budgets are checked after the model call that crossed them, so a run can go over by one call's worth.
349
+ - Polls. A poll whose answer doesn't change at all is flagged at the 10th poll even with a wait between polls (with `on_loop="stop"`, 9 go through), so a long job polled every 30 seconds gets a warning after about 5 minutes. A poll straight after itself, with no wait, whose answer changes only in a number (a progress count, elapsed time) is also flagged at the 10th call, because that's how a duplicate side effect with a new id looks. Without any wait and with the same answer, the 6th poll is flagged. Fixes: wait between polls (a wait tool, or a sleep in the command), raise `max_exact_repeats`, or put the status tool in `exclude_tools` (then only the hard limits apply to it). A poller that waits on the server (SQS long polling with `WaitTimeSeconds`, a `receive` with a timeout) looks like polls with no wait, and a long-running one is flagged again after each idle stretch that follows new messages, up to 3 warnings for that loop in a run; put its receive tool in `exclude_tools`.
350
+ - Tools whose answer doesn't show that anything changed are flagged when called back to back, like a poll: a `scroll_down` that always answers "Scrolled down the page" is flagged at the 6th call, and a `move` or `next` whose answer changes only in a number (a position) at the 10th. Key presses and other stateful steps behave the same. Put such tools in `exclude_tools` (then only the hard limits apply to them).
351
+ - What counts as "something new" is generous: any call or answer not seen before in the run, after masking timestamps, dates, durations, ids, memory addresses and printed seeds. An answer that carries some other changing value (a counter, a port, a temp-dir name, a random token, a run id that is a plain number like GitHub's) is new every time. If the same call comes straight back and only numbers in its answer changed, it still counts towards the exact-repeat cap; otherwise such a value hides the loop: a near-identical repeat, or a cycle (Read, Edit, a test whose output shows a new port each run), and only the hard limits catch it. A duplicate side effect that alternates with another call, each answering with a new number, is not caught by loop detection at all.
352
+ - The cycle rule masks times in arguments, so a batch keyed only by a time (backfill each hour of `2026-11-01T03:00:00Z`, or daily runs whose dates are datetimes, like Airflow's `logical_date`), with the same answers, looks like a cycle and is flagged at the 6th call. It also masks ids and dates when one call is the same every round. A batch that makes the same call before each item and gets the same answers (reads the same label, then adds it to each email by its id) is not flagged when an earlier answer listed its ids (the search that found the emails), but it is when nothing did, for example ids typed into the prompt, or when each item's id first shows up inside the batch (creating several identical sandboxes one by one and running the same install in each, or a next-item tool that answers only a name like `IMG_20261201`): it then looks like a loop that makes a fresh id on each try, and is flagged at the 6th call (the 9th or 12th with 3 or 4 calls per item). Turn the cycle rule off for such a run (`cycle_repeats=None`) or put the batch's tools in `exclude_tools`.
353
+ - The other side of that rule: an agent that goes round a list it was shown (each saved card, region or volume in turn, all failing, then the list again) is not a cycle, because every id was listed. Only the repeat rules catch it, once every item has been tried and nothing new comes back (a 4-volume version in the tests, re-reading the server before each try, is flagged at call 20), and if each try also carries a fresh key (an idempotency key) it may not be caught at all (3 saved cards charged in turn, 30 declined tries: no warning). Put the key in `ignore_arg_keys` (the same 3-card run is then flagged at call 18), and set `max_steps`.
354
+ - Fresh ids are only recognised in the shapes listed under How it works. A new sandbox, session or draft each try whose id has another shape (a plain number of up to 11 digits, like GitHub's run ids, other than a 10-digit one starting with 1; a word without digits; a token longer than 64 characters, an unlisted prefix that no answer showed) makes every round new, and only the hard limits stop the loop. A call retried on its own, with nothing in between and only a fresh idempotency key in its arguments, is new every time too, so a declined payment retried like that isn't caught: put the key in `ignore_arg_keys` (`Breaker(..., ignore_arg_keys=["idempotency_key"])`, or `--ignore-arg-key idempotency_key` in replay) and it is flagged at the 6th call.
355
+ - Answers longer than 8 KB are masked and hashed in full, which takes time: on our test machine about 10 ms for a 14 KB pytest log, 24 ms for 50 KB, and at most about 0.1 s (0.3 s for text that is mostly digits) per answer. Past 256 KB only the first and last 128 KB are compared, so a change in the middle of a bigger answer isn't seen.
356
+ - The similarity measure is cheap string matching, not semantics. "weather in Paris" and "what's the forecast for Paris" don't match, and a search padded with filler words is only caught with `no_progress_steps`. Code edits that differ only in whitespace or case inside a sentence do match.
357
+ - Shell sleeps are recognised in arguments named `command`, `cmd`, `commands`, `script`, `code` or `argv` (or when the arguments are a plain string): `sleep N`, `Start-Sleep`, `timeout /t N`, `time.sleep(`, `asyncio.sleep(`, `setTimeout(`.
358
+ - Cost is only known if something reports it. Pydantic AI reports a best-effort cost per response; for the other adapters set `price_per_mtok` or the report says "cost unknown" and `max_cost_usd` never fires.
359
+ - If a framework catches our exception, the breaker stays tripped and the run stops at the next model or tool call instead (LangGraph `ToolNode(handle_tool_errors=True)`, CrewAI's blocked tool call). LangGraph and Pydantic AI hand you our exception as is; the OpenAI Agents SDK and CrewAI wrap it in their own, so use `find_trip(exc)`, or `adapter.last_breaker.tripped` afterwards. `find_trip` also follows `__context__`, so an error raised while handling a trip is traced back to it.
360
+ - Each adapter keys runs on something the framework hands it: the root run id (LangGraph), the run's usage object (OpenAI Agents SDK), the Crew object (CrewAI), `for_run` (Pydantic AI). A LangChain tool or model invoked on its own, outside any chain, is a run of one call. CrewAI hooks are global to the process while `guard()` is open, and kicking off the same Crew object twice inside one block shares a breaker.
361
+ - OpenAI Agents SDK: hosted tools (web search, file search, code interpreter) don't fire `on_tool_start`, and `Agent.as_tool` sub-runs don't get the parent's hooks, so the breaker doesn't see those calls (their model calls in the main run still count). When a stop hits one of several parallel calls in one response, the SDK cancels the rest of that batch.
362
+ - The adapters are tested with stub models, not live APIs. Framework APIs change; the CI job against the newest allowed versions is there to catch that.
363
+ - `crewai` and `openai-agents` currently need different major versions of `openai`, so their extras can't be installed together.
364
+ - Replay: Claude Code's per-message `output_tokens` is a placeholder per the cost-tracking guide, so replayed token totals undercount output; `total_cost_usd` only arrives at the end of the run. Claude Code's on-disk session transcripts (`~/.claude/projects/...`) look similar but their format isn't documented; they may or may not replay correctly.
365
+
366
+ ## Licence
367
+
368
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,20 @@
1
+ loop_breaker/__init__.py,sha256=4VMGHf77aaDMT1nPfgUrxelawvj_lvq0wHpDZQ4OnYQ,854
2
+ loop_breaker/__main__.py,sha256=ev6t1FIlUhYLSYDceY1ixjUeIwJgI8TcP0DvCihqjz0,51
3
+ loop_breaker/_runs.py,sha256=Livv_NuQ2thacbF9xCnP398cs80_2sU3vrEmZmXmQyg,2672
4
+ loop_breaker/cli.py,sha256=bS-llcZXbFs2D0ITxCPVX7amOaNrTM0cRzEqEiwr2x0,8505
5
+ loop_breaker/core.py,sha256=y7uUHWUgttJdWxNIFvsAUDmMGiXU6sg0Snn6Ta6OqGM,50089
6
+ loop_breaker/crewai.py,sha256=lqPw5pJlBSqBsDzr6atBHliuaBOM9Uo8Kpz3kGabWnE,11145
7
+ loop_breaker/demo.py,sha256=p-B9ZJMxwqt12QcSD7eW3LkpIRtodiUyfM3ds5lDyIM,2792
8
+ loop_breaker/langgraph.py,sha256=UA3_VhVB93LC9gPzo2khS1N8fJ7FZ0zoTio2hktr6qU,10135
9
+ loop_breaker/openai_agents.py,sha256=qh8BJrsX-HPDrAEGMk_OLhl_cRBN8IWuIJ3rhTnJG6U,4335
10
+ loop_breaker/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ loop_breaker/pydantic_ai.py,sha256=uDjIExP9LYovfZbPMdpOu8CgJEM_PKNJk2fk_fnm5fE,4418
12
+ loop_breaker/replay.py,sha256=POEuSc0tac79r1oO_lzSuzujXl45uRthdC5ET-Nuvy8,9888
13
+ loop_breaker/report.py,sha256=4MDp-x6KiAQfFBOk6sTxN5PgucNrDuFwQLbofS1Exbk,3303
14
+ loop_breaker/similarity.py,sha256=bHiEf88aRWQXyS3p1ULd6jEYRKFgz5qHFB9PJGFJcG8,19769
15
+ loop_breaker/examples/claude_stream.jsonl,sha256=RqmfUOpblg-Z32RZfBz_Ozy55p6u67FOIbnZERGhKwU,20596
16
+ agent_loop_breaker-0.1.0.dist-info/METADATA,sha256=sFEjDSy4e9HjMbUJ094VunCh5L6zIbSWJA0k_03m1Ro,40863
17
+ agent_loop_breaker-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
18
+ agent_loop_breaker-0.1.0.dist-info/entry_points.txt,sha256=5BDesd3vozynLgix779IY39z-hslg0rLChLKVeGLW3I,55
19
+ agent_loop_breaker-0.1.0.dist-info/licenses/LICENSE,sha256=0FiuxoOkCwUcrCwkRrO1jsXE0m9I-o0Kl0mdAef1hCY,1071
20
+ agent_loop_breaker-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ loop-breaker = loop_breaker.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bosco Foulsham
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,30 @@
1
+ """loop-breaker: a circuit breaker for AI agents.
2
+
3
+ from loop_breaker import Breaker, LoopDetected, BudgetExceeded
4
+
5
+ breaker = Breaker(max_steps=50, max_seconds=300, max_tokens=200_000)
6
+ breaker.step("search", {"query": "..."}) # before each tool call
7
+ breaker.record_usage(input_tokens=..., output_tokens=...) # after each model call
8
+
9
+ Framework adapters live in ``loop_breaker.langgraph``,
10
+ ``loop_breaker.openai_agents``, ``loop_breaker.pydantic_ai`` and
11
+ ``loop_breaker.crewai``.
12
+ """
13
+
14
+ from .core import Breaker, BreakerTripped, BudgetExceeded, LoopDetected, LoopWarning, Step, find_trip
15
+ from .report import Report, StepView
16
+
17
+ __version__ = "0.1.0"
18
+
19
+ __all__ = [
20
+ "Breaker",
21
+ "BreakerTripped",
22
+ "BudgetExceeded",
23
+ "LoopDetected",
24
+ "LoopWarning",
25
+ "Report",
26
+ "Step",
27
+ "StepView",
28
+ "find_trip",
29
+ "__version__",
30
+ ]
@@ -0,0 +1,4 @@
1
+ import sys
2
+ from .cli import main
3
+
4
+ sys.exit(main())
loop_breaker/_runs.py ADDED
@@ -0,0 +1,81 @@
1
+ """One Breaker per run, made from a template. Used by the framework adapters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ import weakref
7
+ from typing import Any, Callable, Hashable
8
+
9
+ from .core import Breaker
10
+
11
+
12
+ class PerRun:
13
+ """Hands out ``template.fresh()`` once per run key.
14
+
15
+ Keys are either hashable ids (LangGraph root run ids) or live objects
16
+ that identify a run (the OpenAI Agents SDK's per-run usage object, a
17
+ CrewAI crew copy). Live objects are held weakly: when one is garbage
18
+ collected its breaker is dropped, and a new object that happens to get
19
+ the same ``id()`` doesn't inherit it.
20
+
21
+ With ``per_run=False`` every run shares the template itself.
22
+ """
23
+
24
+ def __init__(self, template: Breaker, per_run: bool = True) -> None:
25
+ self.template = template
26
+ self.per_run = per_run
27
+ self.last: Breaker | None = None
28
+ self._by_key: dict[Hashable, Breaker] = {}
29
+ self._by_obj: dict[int, tuple[Callable[[], Any], Breaker]] = {}
30
+ self._lock = threading.RLock() # weakref callbacks may fire while held
31
+
32
+ def _new(self) -> Breaker:
33
+ b = self.template.fresh()
34
+ self.last = b
35
+ return b
36
+
37
+ def for_key(self, key: Hashable) -> Breaker:
38
+ if not self.per_run:
39
+ self.last = self.template
40
+ return self.template
41
+ with self._lock:
42
+ b = self._by_key.get(key)
43
+ if b is None:
44
+ b = self._by_key[key] = self._new()
45
+ return b
46
+
47
+ def drop_key(self, key: Hashable) -> None:
48
+ with self._lock:
49
+ self._by_key.pop(key, None)
50
+
51
+ def for_object(self, obj: Any) -> Breaker:
52
+ if not self.per_run:
53
+ self.last = self.template
54
+ return self.template
55
+ k = id(obj)
56
+ with self._lock:
57
+ entry = self._by_obj.get(k)
58
+ if entry is not None and entry[0]() is obj:
59
+ return entry[1]
60
+ b = self._new()
61
+ try:
62
+ ref: Callable[[], Any] = weakref.ref(obj, lambda r, k=k: self._forget(k, r))
63
+ except TypeError:
64
+ ref = lambda: obj # noqa: E731 - kept until clear()
65
+ self._by_obj[k] = (ref, b)
66
+ return b
67
+
68
+ def _forget(self, k: int, ref: Any) -> None:
69
+ with self._lock:
70
+ entry = self._by_obj.get(k)
71
+ if entry is not None and entry[0] is ref:
72
+ del self._by_obj[k]
73
+
74
+ def clear(self) -> None:
75
+ with self._lock:
76
+ self._by_key.clear()
77
+ self._by_obj.clear()
78
+
79
+ def active(self) -> int:
80
+ with self._lock:
81
+ return len(self._by_key) + len(self._by_obj)