Repository navigation
fix(tooldefer): cap the 400 turn-off map per tenant - #896
Merged
Merged
Conversation
Key Gate.broken by tenant with a per-tenant cap (256) and a tenant cap (10000), the same shape as the pending opt-out map. One shared helper, putCapped, serves both. One tenant's 400s no longer push out another tenant's turn-offs. The purge already calls DropTenant. Closes #881 Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
Both per-tenant maps share maxPerTenant (64) and maxTenants (10000). Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
amiddavid
commented
Nov 4, 2026
amiddavid
left a comment
Collaborator
Author
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.317 | offload-review skill, @amiddavid's session | fresh | 1 of 2 | 1 of 2 | aacc94513bb7 |
blocking |
Verdict: blocking
Findings
-
tooldefer/gate.go:92 — the no-evict-on-refresh fix has no test
- What fails: the PR says
putCapped"does not evict when the key already exists. This also fixes a small flaw in the old pending code, where a refresh at the cap evicted an unrelated entry." No test covers that path. Every key inTestGateBreakEvictsOldestPerTenantandTestGatePendingOptOutIsPerTenantis new, so the!okbranch at line 92 is never exercised at the cap. A regression that reinstates the unconditional prune would pass all tests. - Proof:
putCappedline 92 guards the prune with_, ok := t[key]; !ok &&. Both tests insert distinct keys only (m0..m63,new,s0..s73,x0..x73), sookis always false there. - Fix: add a case that puts the same key twice while the tenant is at its cap, then asserts the map size did not drop and the other entries stayed.
- What fails: the PR says
-
tooldefer/gate.go:86 — a full turn-off map refuses new tenants forever, because expired entries never free their tenant slot
- What fails: a long-lived proxy that sees 400s from more than 10,000 distinct tenants, over its whole lifetime, ends with
len(g.broken) == maxTenantsand never shrinks.Brokenexpires an entry after 24 h but nothing deletes it. OnlyDropTenantremoves a tenant. From then on,putCappedreturns false for every new tenant (line 86), so those tenants never get a turn-off stored. Each of their requests on a broken model pays one 400 plus a retry, for the rest of the process lifetime. The old code did not have this failure mode: at its 20,000 cap it evicted the global oldest and always stored the newcomer. - Proof:
putCappedrefuses a new tenant whenlen(m) >= maxTenantsand nothing else deletes fromg.broken(grepfordelete(g.brokenshows onlyDropTenant, line 128).Broken(line 149) hides expired entries but leaves them in the map. The pending map drains itself:TakePendingdeletes a tenant when its last session is taken (lines 107-110). The broken map has no such drain. - Fix: when the outer map is full, drop one tenant whose entries are all past
gateTTLbefore refusing. This scan runs only at the cap, so it costs nothing in the normal case.
- What fails: a long-lived proxy that sees 400s from more than 10,000 distinct tenants, over its whole lifetime, ends with
Non-blocking
- Worst-case memory grows about 32x: 20,000 entries before, 10,000 tenants x 64 now. This matches the pending map's bound by design, so I do not count it as a defect.
- The PR names the behavior change at the top and asks for a human developer's yes, as
CLAUDE.mdrequires. That yes must be on record before merge. pruneOldestpicks a random entry among equal timestamps. Pre-existing, not introduced here.
What I checked
- Full diff
4090759b..HEAD(2 commits,tooldefer/gate.goandtooldefer/tooldefer_test.go), andgate.goin full. - All callers:
proxy/tooldefer.go(Break,DropTenant),tooldefer/clientsearch.goandtooldefer/apply.go(Broken,TakePending). No caller depends on the old[2]stringshape. - Locking:
putCappedruns only underg.mu(NoteToolSearchline 75,Breakline 159). TakePendingandNoteToolSearchkeep their old semantics; the only change is the sharedputCappedand the!okguard.- Both changed tests: traced the timestamps and eviction order by hand; they assert what they claim.
docs/data-dependence.md: no update needed. Nothing new is stored; the PR states this.- CLAUDE.md rules: fail-open (a lost turn-off costs a retry, not a dropped request), behavior-change naming, and library/proxy boundaries all hold.
amiddavid
commented
Nov 4, 2026
amiddavid
left a comment
Collaborator
Author
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.317 | offload-review skill, @amiddavid's session | fresh | 2 of 2 | 1 of 2 | aacc94513bb7 |
blocking |
Verdict: blocking
Findings
- tooldefer/gate.go:92 — the new "refresh does not evict" path has no test
- What fails:
putCappedskipspruneOldestwhen the key already exists. The PR body names this as a fix ("the old pending code, where a refresh at the cap evicted an unrelated entry"). No test covers it. A later refactor can drop the!okcheck and no test fails. - Proof: I checked every caller of
putCappedintooldefer/tooldefer_test.go.TestGateBreakEvictsOldestPerTenant(line 411) andTestGatePendingOptOutIsPerTenant(line 639) only insert distinct keys. No test sends the same tenant+key twice while the tenant is at its cap. Forpending,NoteToolSearchdeletes the session beforeputCapped, so onlyBreakcan reach this path. - Fix: add one case to
TestGateBreakEvictsOldestPerTenant. Fill a tenant tomaxPerTenant, thenBreakthe same model again. Assert the map still holdsmaxPerTenantentries and no other entry was evicted.
- What fails:
Non-blocking
- PR body, Behavior change section. It says "A single-tenant proxy sees no change". The Technical notes section contradicts it: a tenant with more than 64 broken models loses its oldest entry, where the old code kept up to 20,000. The cost is one extra 400 and retry, and it self-heals. Keep the headline accurate, because the human signs off on that line.
- gate.go:157-161 —
BreakcountsTurnedOffbefore the store attempt. WhenputCappedrefuses a new tenant atmaxTenants(10,000), the counter says a turn-off happened but none was stored. Metric drift only, and only at that edge.Retriesstays correct. - Worst-case memory grows from 20,000 to 640,000 entries (64 × 10,000). This matches the bound the pending map already had, so it is not a new class of risk. Entries that expire by TTL stay in the map until evicted or dropped; the cap bounds that, same as before.
- The 64-per-tenant cap serves two different key spaces. Pending keys are sessions; broken keys are models. A tenant rotating through many model names hits the model cap sooner than the old global 20,000. The PR discloses this cost, so it is the human's call.
What I checked
- Both commits (
c4b75d9a,aacc9451) and the full diff against base4090759b. putCappedlogic by hand: new tenant atmaxTenants, existing key atperTenant, new key atperTenant. All three paths behave as documented. Nil-map reads inBrokenandTakePendingare safe.pruneOldestinteraction: eviction keeps the map at the cap, never above it.- Fail-open: an evicted or refused turn-off only means deferral is retried, the provider 400s again, and
deferRetry(proxy/tooldefer.go:578) answers with the original. The client never sees the 400. - Callers outside
tooldefer:proxy/tooldefer.go(Break,DropTenant,NewGate) and the proxy tests. Nothing else reads thebrokenmap's shape.dashis untouched. - The test
TestGateBreakEvictsOldestPerTenantline by line: the arithmetic (64 breaks, then the 65th key) matches the cap, and each assertion matches the code. - Issue #881 and the PR body, for the behavior-change disclosure.
- Data dependence: unchanged, metadata only (tenant, model, timestamp).
…t real turn-offs putCapped drops one tenant whose entries all passed the TTL when the outer map is full, so a full map does not refuse new tenants for ever. TurnedOff counts only a stored entry. Tests cover both and the refresh. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
Collaborator
Author
|
Round 1 fixed in 68b9e7a.
|
amiddavid
commented
Nov 4, 2026
amiddavid
left a comment
Collaborator
Author
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.317 | offload-review skill, @amiddavid's session | resumed | 1 of 2 | 2 of 2 | 68b9e7a6cf6d |
approve |
Verdict: approve
Earlier findings
- Mine, round 1, gate.go:92 — no test for the no-evict-on-refresh fix. Fixed.
TestGateBreakRefreshKeepsTheOthersfills a tenant tomaxPerTenant, then Breaksm5again.- I traced it: with the
!okguard dropped,pruneOldestevictsm0, and!g.Broken("t", "m0")fails the test. The guard is now pinned. TheTurnedOff == 65assertion also pins the new counting.
- Mine, round 1, gate.go:86 — a full turn-off map refuses new tenants forever. Fixed.
dropExpiredTenantfrees one tenant whose entries all passedgateTTLbeforeputCappedrefuses. This is the fix I proposed.TestGateExpiredTenantsFreeTheirSlotscovers both sides: a full map of live entries refuses (line 470), and aftergateTTL + 1sa new tenant takes a freed slot while the tenant count stays atmaxTenants.- The sweep also serves the pending map. That is consistent:
TakePendingexpires a flag by the same TTL, so dropping an all-expired pending tenant loses nothing.
- Reviewer 2, round 1 — same missing refresh test. Fixed, same test as my finding 1. I checked it myself; no new proof to add.
- Reviewer 2, round 1, non-blocking —
TurnedOffcounted before the store attempt. Fixed.Breaknow counts only a stored turn-off (gate.go:181-183). - Reviewer 2, round 1, non-blocking — PR body headline. Fixed. The Behavior change section now says a single-tenant proxy changes above 64 broken models.
Findings
None.
Non-blocking
dropExpiredTenantscans up to 10,000 tenants x 64 entries underg.muwhen the map is full and all entries are live. That is a few milliseconds of lock hold, on the 400-retry path only, and only in that state.BrokenandTakePendingshare the lock, so a request could wait. Acceptable for the edge; worth a look if that state ever shows in stats.- The struct comment on
TurnedOff(gate.go:30) still says "the Retries whose original succeeded". It now also requires a stored entry. TheBreakdoc comment says it right; only the field comment lags. TakePendingtreats an entry exactly atgateTTLas still valid (> gateTTL), whiledropExpiredTenanttreats it as expired (< gateTTLis live). Only exact equality differs, and only for a pending tenant dropped by the sweep. No visible effect.
What I checked
- Last review: round 1, aacc945, 2026-11-04T14:37:07Z.
- New commits read: 1 (
68b9e7a6"fix(tooldefer): free slots of expired tenants, test the refresh, count real turn-offs"). - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files in my folder).
- New items since my last review: reviewer 2's round-1 review (read in full; its finding matches my finding 1, its non-blocking items are fixed or the human's call), the author's comment at 14:48:57Z (each claim checked below), and commit
68b9e7a6. - The new commit's full diff, plus
gate.goandproxy/tooldefer.go:569-588around the changes. - Both new tests traced by hand: timestamps, eviction order, tenant count, and the
TurnedOffcounts (65 after the refresh;maxTenantsafter the refusal) all match the code. - The PR body's three mutation claims: dropping the
!okguard fails the refresh test via them0check (traced); dropping the sweep fails the slot test (traced,Broken("late")would be false); one-bucket keys fail the eviction test (traced in round 1). TurnedOffconsumers:proxy/tooldefer.go:724stats only. Undercounting at the refusal edge is the intended change and affects/statsonly.- Locking:
putCappedand the sweep run only underg.mu. Delete duringrangeis safe in Go. - Fail-open: an expired slot or a refused turn-off still fails open. The client never sees the 400;
deferRetryanswers with the original. - The behavior change still needs a human developer's yes before merge, as the PR body itself states.
amiddavid
commented
Nov 4, 2026
amiddavid
left a comment
Collaborator
Author
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.317 | offload-review skill, @amiddavid's session | resumed | 2 of 2 | 2 of 2 | 68b9e7a6cf6d |
approve |
Verdict: approve
Findings
None.
Earlier findings
- Mine, round 1 — no test for the refresh-does-not-evict path. Fixed.
TestGateBreakRefreshKeepsTheOthers(tooldefer/tooldefer_test.go:441) fills a tenant tomaxPerTenant, breaksm5again, and asserts the count stays at the cap withm0andm5present. I traced the mutation: without the!okguard,pruneOldestevictsm0and the test fails. It also assertsTurnedOff = 65, which pins the counting change. - Reviewer 1, round 1, finding 1 — same as mine. Fixed by the same test. Agree with reviewer 1; I verified it myself above.
- Reviewer 1, round 1, finding 2 — a full tenant map refused new tenants for ever. Fixed.
putCapped(tooldefer/gate.go:89) now callsdropExpiredTenantbefore it refuses. That helper deletes one tenant whose entries all passedgateTTL. I checked the logic and both tests by hand:TestGateExpiredTenantsFreeTheirSlotsfills all 10,000 slots at a fixednow, asserts a new tenant is refused andTurnedOffstays at 10,000, then advancesnowpast the TTL and asserts the new tenant is stored with the map still at 10,000.- Mutation trace: removing the sweep makes
putCappedrefuse "late", and the test fails atg.Broken("late", "m"). - The sweep also serves the pending map, and it deletes lingering empty inner maps. Both are improvements.
- My round-1 non-blocking notes — all addressed.
TurnedOffnow counts only a stored turn-off (gate.go:184). The PR body's Behavior change section now states the single-tenant >64-models case. The memory and two-key-space notes stand as accepted design, disclosed in the PR.
Non-blocking
- gate.go:104 —
dropExpiredTenantscans underg.mu. It runs only when the outer map is full and the tenant is new. Worst case is about 10,000 tenants with some live entry each, so the scan is short and bounded.Breaksits on the rare retry path, so I do not count the cost. - Expiry boundary differs by one edge.
dropExpiredTenanttreats an entry exactlygateTTLold as dead;TakePendingtreats it as live (> gateTTL). The window is one clock tick and the loss is fail-open. No action needed. - The human developer's yes is still not on record. The PR body asks for it and no comment grants it. It must be there before merge, as CLAUDE.md requires.
What I checked
- Last review: round 1, aacc945, 2026-11-04T14:37:50Z.
- New commits read: 1 (
68b9e7a6"fix(tooldefer): free slots of expired tenants, test the refresh, count real turn-offs"). Full diff read, plusgate.golines 78-127 in the final file. - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three saved files).
- New items since my last review: the commit above (reviewed as a first review), the author's comment at 14:48:57Z (each claim checked against the code and tests), and the updated PR body (Behavior change, How it was tested, Technical notes sections re-read).
- Both new tests traced by hand, including the two mutation claims.
- Fail-open re-check on the new code: a refused or swept turn-off still only costs one 400 and retry;
deferRetryanswers with the original. - Data dependence: unchanged, metadata only.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Behavior change
Needs a human developer's yes before merge.
Summary
Closes #881. The 400 turn-off map (
Gate.broken) follows the same per-tenant pattern as the pending opt-out map (#861).What changed
Gate.brokenis nowmap[tenant]map[model]time.maxPerTenant(64) andmaxTenants(10,000) serve both maps.putCappedholds the per-tenant cap logic.NoteToolSearchandBreakboth use it. There is one copy.DropTenantdeletes the tenant's turn-offs in one step. The purge inproxy/tooldefer.goalready calls it, so no change indash.How it was tested
On box 2, fresh tar sync:
go test -race ./tooldefer/...: okgo test -race ./proxy/...: ok (511 s)go vet ./tooldefer/ ./proxy/,gofmt -l: cleanTestGateBreakEvictsOldestPerTenant: a tenant at its cap evicts only its own oldest entry. Another tenant's entry stays.DropTenantdrops exactly one tenant.!okguard (refresh test fails); drop the expired-tenant sweep (slot test fails).dashis untouched, so its tests did not run.Technical notes
putCappedfirst frees the slot of one tenant whose entries all passed the 24 h TTL. Without it, expired tenants would block new ones for ever.TurnedOffcounts only a turn-off that was stored.putCappeddoes not evict when the key already exists. This also fixes a small flaw in the old pending code, where a refresh at the cap evicted an unrelated entry.🤖 Generated with Claude Code