Skip to content

fix(tooldefer): cap the 400 turn-off map per tenant - #896

Merged
amiddavid merged 3 commits into
mainfrom
feat/tenant-400-881
Nov 4, 2026
Merged

amiddavid merged 3 commits into
mainfrom
feat/tenant-400-881

Conversation

@amiddavid

@amiddavid amiddavid commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Behavior change

  • Who: a proxy that serves many tenants. A single-tenant proxy changes only when it has more than 64 broken models: it drops the oldest turn-off, pays one extra 400 and retry, and turns it off again.
  • Old: one global map held 20,000 turn-offs. One tenant's 400s could push out another tenant's turn-offs. That tenant then paid one extra 400 and retry.
  • New: each tenant keeps its own turn-offs: 64 per tenant, 10,000 tenants (the same caps as the opt-out map). The oldest entry of the same tenant goes first.
  • Turn off: no switch. The effect is an eviction order only. An entry lost to the cap costs one extra 400 and retry, as before.

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.broken is now map[tenant]map[model]time.
  • New shared constants maxPerTenant (64) and maxTenants (10,000) serve both maps.
  • New helper putCapped holds the per-tenant cap logic. NoteToolSearch and Break both use it. There is one copy.
  • DropTenant deletes the tenant's turn-offs in one step. The purge in proxy/tooldefer.go already calls it, so no change in dash.
  • Data dependence: none new. Nothing new is stored.

How it was tested

On box 2, fresh tar sync:

  • go test -race ./tooldefer/...: ok
  • go test -race ./proxy/...: ok (511 s)
  • go vet ./tooldefer/ ./proxy/, gofmt -l: clean
  • New test TestGateBreakEvictsOldestPerTenant: a tenant at its cap evicts only its own oldest entry. Another tenant's entry stays. DropTenant drops exactly one tenant.
  • Mutations, each restored: one bucket for all tenants (eviction test fails); drop the !ok guard (refresh test fails); drop the expired-tenant sweep (slot test fails).
  • dash is untouched, so its tests did not run.

Technical notes

  • The old total cap was 20,000. The new cap is 64 per tenant. A tenant with more than 64 broken models loses its oldest. A lost entry costs one extra 400 and retry.
  • When the tenant map is full (10,000), putCapped first frees the slot of one tenant whose entries all passed the 24 h TTL. Without it, expired tenants would block new ones for ever.
  • TurnedOff counts only a turn-off that was stored.
  • 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.

🤖 Generated with Claude Code

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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. 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 in TestGateBreakEvictsOldestPerTenant and TestGatePendingOptOutIsPerTenant is new, so the !ok branch at line 92 is never exercised at the cap. A regression that reinstates the unconditional prune would pass all tests.
    • Proof: putCapped line 92 guards the prune with _, ok := t[key]; !ok &&. Both tests insert distinct keys only (m0..m63, new, s0..s73, x0..x73), so ok is 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.
  2. 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) == maxTenants and never shrinks. Broken expires an entry after 24 h but nothing deletes it. Only DropTenant removes a tenant. From then on, putCapped returns 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: putCapped refuses a new tenant when len(m) >= maxTenants and nothing else deletes from g.broken (grep for delete(g.broken shows only DropTenant, line 128). Broken (line 149) hides expired entries but leaves them in the map. The pending map drains itself: TakePending deletes 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 gateTTL before refusing. This scan runs only at the cap, so it costs nothing in the normal case.

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.md requires. That yes must be on record before merge.
  • pruneOldest picks a random entry among equal timestamps. Pre-existing, not introduced here.

What I checked

  • Full diff 4090759b..HEAD (2 commits, tooldefer/gate.go and tooldefer/tooldefer_test.go), and gate.go in full.
  • All callers: proxy/tooldefer.go (Break, DropTenant), tooldefer/clientsearch.go and tooldefer/apply.go (Broken, TakePending). No caller depends on the old [2]string shape.
  • Locking: putCapped runs only under g.mu (NoteToolSearch line 75, Break line 159).
  • TakePending and NoteToolSearch keep their old semantics; the only change is the shared putCapped and the !ok guard.
  • 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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. tooldefer/gate.go:92 — the new "refresh does not evict" path has no test
    • What fails: putCapped skips pruneOldest when 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 !ok check and no test fails.
    • Proof: I checked every caller of putCapped in tooldefer/tooldefer_test.go. TestGateBreakEvictsOldestPerTenant (line 411) and TestGatePendingOptOutIsPerTenant (line 639) only insert distinct keys. No test sends the same tenant+key twice while the tenant is at its cap. For pending, NoteToolSearch deletes the session before putCapped, so only Break can reach this path.
    • Fix: add one case to TestGateBreakEvictsOldestPerTenant. Fill a tenant to maxPerTenant, then Break the same model again. Assert the map still holds maxPerTenant entries and no other entry was evicted.

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 — Break counts TurnedOff before the store attempt. When putCapped refuses a new tenant at maxTenants (10,000), the counter says a turn-off happened but none was stored. Metric drift only, and only at that edge. Retries stays 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 base 4090759b.
  • putCapped logic by hand: new tenant at maxTenants, existing key at perTenant, new key at perTenant. All three paths behave as documented. Nil-map reads in Broken and TakePending are safe.
  • pruneOldest interaction: 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 the broken map's shape. dash is untouched.
  • The test TestGateBreakEvictsOldestPerTenant line 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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 1 fixed in 68b9e7a.

  • Refresh path: new test TestGateBreakRefreshKeepsTheOthers. Dropping the !ok guard makes it fail.
  • Full tenant map: putCapped now frees one tenant whose entries all passed the TTL before it refuses. New test TestGateExpiredTenantsFreeTheirSlots. Dropping the sweep makes it fail.
  • TurnedOff counts only a stored turn-off.
  • PR body: the Behavior change section now says a single-tenant proxy with more than 64 broken models drops its oldest turn-off.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. Mine, round 1, gate.go:92 — no test for the no-evict-on-refresh fix. Fixed.
    • TestGateBreakRefreshKeepsTheOthers fills a tenant to maxPerTenant, then Breaks m5 again.
    • I traced it: with the !ok guard dropped, pruneOldest evicts m0, and !g.Broken("t", "m0") fails the test. The guard is now pinned. The TurnedOff == 65 assertion also pins the new counting.
  2. Mine, round 1, gate.go:86 — a full turn-off map refuses new tenants forever. Fixed.
    • dropExpiredTenant frees one tenant whose entries all passed gateTTL before putCapped refuses. This is the fix I proposed.
    • TestGateExpiredTenantsFreeTheirSlots covers both sides: a full map of live entries refuses (line 470), and after gateTTL + 1s a new tenant takes a freed slot while the tenant count stays at maxTenants.
    • The sweep also serves the pending map. That is consistent: TakePending expires a flag by the same TTL, so dropping an all-expired pending tenant loses nothing.
  3. Reviewer 2, round 1 — same missing refresh test. Fixed, same test as my finding 1. I checked it myself; no new proof to add.
  4. Reviewer 2, round 1, non-blocking — TurnedOff counted before the store attempt. Fixed. Break now counts only a stored turn-off (gate.go:181-183).
  5. 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

  • dropExpiredTenant scans up to 10,000 tenants x 64 entries under g.mu when 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. Broken and TakePending share 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. The Break doc comment says it right; only the field comment lags.
  • TakePending treats an entry exactly at gateTTL as still valid (> gateTTL), while dropExpiredTenant treats it as expired (< gateTTL is 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.go and proxy/tooldefer.go:569-588 around the changes.
  • Both new tests traced by hand: timestamps, eviction order, tenant count, and the TurnedOff counts (65 after the refresh; maxTenants after the refusal) all match the code.
  • The PR body's three mutation claims: dropping the !ok guard fails the refresh test via the m0 check (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).
  • TurnedOff consumers: proxy/tooldefer.go:724 stats only. Undercounting at the refusal edge is the intended change and affects /stats only.
  • Locking: putCapped and the sweep run only under g.mu. Delete during range is safe in Go.
  • Fail-open: an expired slot or a refused turn-off still fails open. The client never sees the 400; deferRetry answers with the original.
  • The behavior change still needs a human developer's yes before merge, as the PR body itself states.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. Mine, round 1 — no test for the refresh-does-not-evict path. Fixed. TestGateBreakRefreshKeepsTheOthers (tooldefer/tooldefer_test.go:441) fills a tenant to maxPerTenant, breaks m5 again, and asserts the count stays at the cap with m0 and m5 present. I traced the mutation: without the !ok guard, pruneOldest evicts m0 and the test fails. It also asserts TurnedOff = 65, which pins the counting change.
  2. Reviewer 1, round 1, finding 1 — same as mine. Fixed by the same test. Agree with reviewer 1; I verified it myself above.
  3. Reviewer 1, round 1, finding 2 — a full tenant map refused new tenants for ever. Fixed. putCapped (tooldefer/gate.go:89) now calls dropExpiredTenant before it refuses. That helper deletes one tenant whose entries all passed gateTTL. I checked the logic and both tests by hand:
    • TestGateExpiredTenantsFreeTheirSlots fills all 10,000 slots at a fixed now, asserts a new tenant is refused and TurnedOff stays at 10,000, then advances now past the TTL and asserts the new tenant is stored with the map still at 10,000.
    • Mutation trace: removing the sweep makes putCapped refuse "late", and the test fails at g.Broken("late", "m").
    • The sweep also serves the pending map, and it deletes lingering empty inner maps. Both are improvements.
  4. My round-1 non-blocking notes — all addressed. TurnedOff now 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 — dropExpiredTenant scans under g.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. Break sits on the rare retry path, so I do not count the cost.
  • Expiry boundary differs by one edge. dropExpiredTenant treats an entry exactly gateTTL old as dead; TakePending treats 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, plus gate.go lines 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; deferRetry answers with the original.
  • Data dependence: unchanged, metadata only.

@amiddavid
amiddavid merged commit 47de51a into main Nov 4, 2026
5 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

fix(tooldefer): cap the 400 turn-off map per tenant

1 participant