Skip to content

fix(tooldefer): the follow-ups to tool deferral from #866 - #874

Merged
amiddavid merged 3 commits into
mainfrom
feat/tooldefer-866
Nov 3, 2026
Merged

amiddavid merged 3 commits into
mainfrom
feat/tooldefer-866

Conversation

@amiddavid

@amiddavid amiddavid commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Behavior change (needs a human developer's yes)

Who it affects: only accounts on the ultrahigh preset (tool deferral). No other preset changes.

Item Old behavior New behavior Changes what is deferred?
N3 The history keeps the newest 64 sessions per account. It also keeps the newest 10 sessions of each project. The project veto sees them, so a tool this project used stays loaded. Yes: fewer tools deferred for users in many projects.
N4 After a lost record, Rebuild saves the set the rule gives now, even if the history drifted. When that set leaves out a tool our search loaded, the proxy sends the original request and saves nothing. Yes: that request is not deferred.
N12a The probe sends no anthropic-beta header. A subscription token on direct Anthropic can get a 401, so deferral stays off. The probe sends the client's own oauth-* beta. Yes: deferral can turn on for those users.
Late tenant A tenant that picks ultrahigh after the start builds its state at its first request, so that request reads "probe unknown". An account change builds the state and seeds the tenant in the background. Yes: the first session can defer.
N7 The net saving leaves out the cache write of a loaded definition. It adds that write once per load. No. The reported net saving is lower.

How to turn it off: pick another preset, or set toolfilter: {defer: off}, or set ENABLE_TOOL_SEARCH=false in the client.

N6 changes nothing: I documented the 200-token rule as "200 o200k tokens" and did not scale it. Scaling it would change which tools get deferred.

Summary

This PR fixes the follow-ups to tool deferral from #866, and the notes from the GLM review of #872. N9 is not here: #869 does it. Refs #861, #872.

Data dependence: the kind of data does not change. The history holds tool names, session ids, project paths and times, as before. N3 changes how much it keeps: the newest 64 sessions per user, plus the newest 10 of each project, up to 256 per user (was 64). docs/data-dependence.md is updated, and David Amid (the row's "Decided by") must confirm it before merge.

What changed

# Item Status What changed
N1 A failed history flush loses its sessions Done A failed write marks the sessions dirty again. The next flush retries them.
N2 Every request rewrites every tool row Done A session is dirty only when its tool sets or project change. last_ts is written with a set change, at close, or when it is 1 hour behind (half the retention if that is shorter).
N3 The project veto loses older project sessions Done Keep the newest 64 per account, plus the newest 10 per project. Total cap: 256 per account.
N4 Rebuild can drift Done Rebuild runs the rule as at the first request. If that set leaves out a tool our search loaded, the proxy sends the original and does not save. New counter: rebuilds_unproven.
N5 A search counted twice in a 64–128 KiB stream Done The stream-through path reads the sniffer window with the overlap removed (sniffer.disjoint). Tested at 100 KiB.
N6 The 200-token rule uses o200k tokens Done (docs only) The code comment and docs/reference/presets.md say "200 o200k tokens, about 340 Claude tokens".
N7 The net saving leaves out a cache write Done Cost adds LoadedTokens × write price once per load. The price is the 1-hour write price when the request was billed at the 1-hour tier.
N8 Missing metrics Done The /stats tool_defer block has accounts (per-account ledger), wrong_guesses and dropped_searches. The ledger has both fields too. tooldefer.WrongGuesses is the one rule, and the dashboard (#869) calls it too.
N9 Seeded history misses built-ins Not here #869 does it.
N10 Running sessions count as history Done A comment on UserSessions gives the replay numbers and says not to "fix" it.
N12a The probe sends no OAuth beta Done RunProbeBeta sends the client's oauth-* betas only. Other betas change behavior, so the probe leaves them out.
N12b false/0/no/off No change The owner decided on 2026-11-02 to keep all four.
#872 Stray truncated comment Done Removed from proxy/tooldefer_repair_test.go.
#872 The start can wait 20 s Done One 10 s bound for the load and the seeds together. It is a context, not a timer channel. A timer channel fires once, so a second wait on it would block forever.
#872 A tenant registered after the start Done An account change builds the state and seeds the tenant in the background.
#872 setLoaded without sync.Once Done sync.Once closes the ready channel.
#872 repairOnMissingRef closes the body before the stub can fail Done The stub runs first. On failure, the body is put back, readable.
#874 r1 The late build seeds before the history load Done seedAfterLoad waits for the load, then seeds, as the start does. A seed that landed first hid the table's used flags for that session.

Still open in #866: the turn-off map after a 400 (Gate.broken) is one global map capped at 20,000. One tenant's 400s can push out another tenant's turn-offs. That note was added to #866 after the item table, and it is not in this PR.

How it was tested

All runs were on the eval box with CGO_ENABLED=1 go test -race -count=1. The library set and ./dash/... ran at 98fff339. ./tooldefer/... and ./proxy/... ran again at the head, 66c08dc6: both ok (proxy 483 s).

  • ./tooldefer/... ./apply/... ./config/... ./components/... ./store/... ./metrics/... ./internal/modelinfo/...: all ok.
  • ./proxy/...: ok (477 s).
  • ./dash/...: ok (570 s).

New tests, one or more per item:

Item Test
N1 TestHistoryFailedFlushRetries
N2 TestHistoryTimeAloneIsNotDirty
N3 TestHistoryKeepsTenPerProject
N4 TestApplyRebuildThatDriftedSendsTheOriginal
N5 TestSnifferDisjointCountsOnce, TestToolDeferLedgerCountsA100KiBStreamOnce
N7 TestLedgerNetSaving (extended)
N8 TestReadSearchesCountsDropped, TestToolDeferStatsCountWrongGuessesPerAccount, TestLedgerNetSaving, TestWrongGuesses
N12a TestProbeSendsAuthBetas, TestToolDeferProbeSendsTheClientsOAuthBeta
#872 TestRepairOnMissingRefKeepsTheBodyWhenTheStubFails, TestToolDeferTenantAfterStartBuildsTheState, TestWaitAllIsOneBound, TestHistorySetLoadedTwice
#874 r1 TestSeedAfterLoadKeepsTheLoadedUses

Mutations: there were 18, one or more per item with code. Each one broke the new code, and a test assertion failed (not a compile error):

Mutation Failing test
N1: do not set dirty back TestHistoryFailedFlushRetries
N2: a new time marks dirty TestHistoryTimeAloneIsNotDirty
N2: no final flush at close TestHistoryTimeAloneIsNotDirty
N3: drop the per-project bound TestHistoryKeepsTenPerProject
N4: skip the drift check TestApplyRebuildThatDriftedSendsTheOriginal
N5: read the spliced window TestToolDeferLedgerCountsA100KiBStreamOnce
N5: keep the whole tail TestSnifferDisjointCountsOnce
N7: no write cost TestLedgerNetSaving
N8: no wrong-guess count TestToolDeferStatsCountWrongGuessesPerAccount
N8: miscount results TestReadSearchesCountsDropped
N8: count a tool loaded earlier TestWrongGuesses
N8: count a tool we did not defer TestWrongGuesses
N8: no per-account add TestLedgerNetSaving
N12a: no client betas TestToolDeferProbeSendsTheClientsOAuthBeta
Repair: close before the stub TestRepairOnMissingRefKeepsTheBodyWhenTheStubFails
Late tenant: wrong change kind TestToolDeferTenantAfterStartBuildsTheState
Start bound: ignore the context TestWaitAllIsOneBound
Late seed: drop the wait for the load TestSeedAfterLoadKeepsTheLoadedUses

There were no live paid runs.

Technical notes

  • N4, what "proven" means: a tool that a tool_search_tool_result of our search loaded, that the request still declares as loaded, and that is not on the never-defer list. Loads by Claude Code's own ToolSearch are left out: Claude Code deferred those, not us. The rule then runs with the history that leaves out this session. The proven loads, and the calls after them, do not count as uses. A drift on a tool no search loaded leaves no trace, so this check cannot see it. The code comment says so.
  • N5: sniffer.disjoint() returns the exact body when the head and the tail overlap, and bytes() when there is a gap. Only the search count reads it. The usage parser still reads bytes(), as before.
  • N8: a wrong guess is a tool that meets all three conditions: it is in this request's deferred set (ours, not Claude Code's), a search in its response loaded it, and no earlier message of the transcript had loaded it. Each tool counts once per request. A re-search of a tool loaded earlier does not count again. tooldefer.WrongGuesses holds the rule (commit 50f6694). dropped_searches is the server-side search calls minus the tool_search_tool_result blocks in the same response. The per-account map is capped at 10,000 accounts. Past the cap, a new account counts in the total only.
  • Late tenant: Handler.onRegistryChange replaces the dashboard's direct listener. It still drops the dashboard caches, and it calls deferTenantsChanged on an account change. That function re-reads the tenant list in a goroutine and never waits. After Close it does nothing.
  • API: tooldefer.Rebuild now returns (set, ok). SearchesIn and SearchesInSSE keep their signatures. ReadSearches and ReadSearchesSSE add the result count. RunProbe is kept, and RunProbeBeta adds the header.

Part of #866.

🤖 Generated with Claude Code

- N1: a failed history flush marks its sessions dirty again.
- N2: a session is dirty only when its tool sets change; last_ts is
  written with a set change, at close, or once it is an hour behind.
- N3: the history also keeps the newest 10 sessions of each project.
- N4: a Rebuild whose set leaves out a tool our search loaded sends the
  original and saves nothing.
- N5: the stream-through search count reads the sniffer window with no
  byte twice.
- N6: the 200-token minimum is documented as o200k tokens.
- N7: the net saving adds the cache write of a loaded definition.
- N8: per-account ledger totals, wrong_guesses and dropped_searches in
  the /stats tool_defer block.
- N10: a comment says why running sessions count as history.
- N12a: the probe sends the client's OAuth beta.
- #872 review: the stray comment, one 10 s start bound, an eager build
  for a tenant that turns deferral on after the start, sync.Once for the
  ready channel, and a readable body when the stub fails.

Part of #866.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
A wrong guess is now a tool that is in this request's deferred set,
that a search in its response loaded, and that no earlier message of
the transcript had loaded. The second condition is new: a re-search of
a tool loaded earlier in the thread no longer counts again.

/stats counts with tooldefer.WrongGuesses, and the dashboard (#869)
calls the same function, so the two numbers agree.

Part of #866.

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 98fff339c64e blocking

Verdict: blocking

Findings

  1. docs/data-dependence.md:218 — the history row still states the old 64-session bound; this PR keeps up to 256 sessions per user
    • What fails: An operator reads the row and believes the history keeps the newest 64 sessions per user. After this PR, sortLocked also keeps the newest 10 sessions of every project, up to maxKeptSessions = 256 per user. A user in many projects now stores up to 4x the rows.
    • Proof: tooldefer/history.go:25-35 and tooldefer/history.go:406-425 change the bound. docs/data-dependence.md:218 still says "It keeps the newest 64 sessions per user". The diff touches only docs/reference/presets.md.
    • Fix: Update the row's reason in plain words: the newest 64 sessions per user, plus the newest 10 of each project (the project veto reads those), capped at 256 in all. CLAUDE.md requires this update when a feature's data dependence changes. The row's "Decided by" (David Amid) should confirm the change.

Non-blocking

  • proxy/tooldefer.go:179-188 — waitAll: when the context is done and a channel is also closed, select picks at random. In startToolDefer, a load that used the full 10 s can make the final ready log field read false even when every seed channel was already closed. Log field only.
  • proxy/proxy.go:2539-2545 — the non-SSE branch still reads sn.bytes(), which holds the overlap twice for a 64-128 KiB response. Only the SSE branch reads disjoint(). A spliced non-stream window is not valid JSON, so ReadSearches on it was already unreliable; the N5 fix covers the branch that counts events. Pre-existing shape, not a regression.
  • proxy/tooldefer.go:194-212 — deferTenantsChanged lists every tenant and parses every configuration (docDefers) on each account write, in a new goroutine per write. Off the request path and bounded, but repeated work on a registry with many accounts and frequent writes.
  • tooldefer/tooldefer.go:383-400 — Rebuild can still defer a tool that Claude Code's own search loaded in the transcript: such a load is in neither calledIn nor proven, so decide may defer it and the proven-subset check cannot see it. The old code forced the same outcome (it unioned every loaded tool into the set unconditionally), so this is no regression; the new code is rule-gated instead. Worth a line in Rebuild's known limits.

What I checked

  • The full diff 75c52f2c..98fff339, every file, and the code around each change: proxy/proxy.go, proxy/tooldefer.go, proxy/usage.go, tooldefer/apply.go, tooldefer/history.go, tooldefer/ledger.go, tooldefer/probe.go, tooldefer/tooldefer.go, tooldefer/repair.go, plus every new test.
  • sniffer.disjoint arithmetic: the tail is cut at len(head) - (total - len(tail)). I verified the overlap case (no byte twice, length equals the body), the gap case (falls back to bytes() with the newline), and the short-body case.
  • sortLocked per-project keeping against the test's numbers: 64 newest plus 10 of project /b gives 74; the total cap gives 256; the memory array is reused safely and the dropped sessions are nil-ed.
  • The history flush rewrite: written starts at the disk value on load; a failed write restores dirty and leaves written alone, so both the row writes and the time-only writes retry; the disk last_ts never falls more than min(1 h, retention/2) behind memory, so the retention DELETE cannot remove a running session's rows; the keep delete now carries up to 256 parameters, inside SQLite's limit.
  • repairOnMissingRef: the stub is tried before the response body is closed; on failure the read bytes go back in front of the unread rest, in order. The old code closed the body first and lost it when the stub failed.
  • Rebuild and the rebuild_unproven path: the original is sent, nothing is saved, the counter is bumped, and the bytes stay stable on later requests. I checked that a Claude Code load is handled no worse than before (see non-blocking).
  • The ledger: the per-account map is bounded at 10,000 accounts; the N7 cache-write cost matches its tests, including the 1-hour tier; WrongGuesses counts one per tool however many results load it.
  • The probe: AuthBetas keeps oauth-* values only, in the client's order; RunProbeBeta with no beta sends no Anthropic-Beta header, same as before; a 401 stays an error, not a verdict.
  • startToolDefer/deferTenantsChanged: one context bounds the load and the seeds together; the closed-flag check and the build share one mutex, so Close cannot leak a state; the registry change hook keeps the old cache invalidation.
  • Fail open: every new failure path (rebuild_unproven, a failed history write, a stub that cannot extend tools) sends or keeps the original bytes.
  • I did not run builds or tests (not approved). Per the round-1 rule I did not read the PR description or conversation, so I could not check that the PR names its behavior changes at the top; the process should confirm that separately.

@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 98fff339c64e blocking

Verdict: blocking

Note on the head: the PR gained a second commit (50f6694c, the wrong-guess rule) while this
review ran. My worktree holds 98fff339, the head I was given. I read 50f6694c in full too,
and the findings below hold at both heads.

Findings

  1. docs/data-dependence.md:218 — the history row states a bound this PR changes, and the PR says the doc needs no change

    • What fails: N3 changes what the history keeps: the newest 64 sessions per user, plus the
      newest 10 of each project, up to 256 in all (tooldefer/history.go:25-35, sortLocked at
      history.go:406-425). The doc row still says "It keeps the newest 64 sessions per user".
      The PR text says "docs/data-dependence.md needs no change". After the merge, the row is false.
    • Proof: docs/data-dependence.md:218 vs tooldefer/history.go:31-35
      (MaxSessions = 64, maxKeptSessions = 4 * MaxSessions) and the per-project keep in
      sortLocked (history.go:417).
    • Fix: update that one sentence in the row. Say the newest 64 per user plus the newest 10 per
      project, 256 in all, and why: the project veto must still see a project's older sessions.
  2. proxy/tooldefer.go:208-210 — the background build seeds a tenant before the history load ends, so a seeded session can hide the table's row for the same id

    • What fails: a tenant picks ultrahigh after the start. deferTenantsChanged builds the state
      (the table load starts) and calls SeedTenant at once. The seed reads the dashboard's
      inventory; the load reads the history table. Both merge only session ids memory does not
      hold (history.go:268 and history.go:313). When the seed lands first, memory keeps the
      seed's copy, and the table's used flags for that session never load. The rule can then
      defer a tool that session used: one wrong guess, one search turn. The disk keeps the flags
      (MAX upsert), so a restart heals it.
    • Proof: startToolDefer waits for the load before it seeds, with the comment "the seeds
      start after the load: a loaded session wins" (proxy/tooldefer.go:169).
      deferTenantsChanged has no wait (proxy/tooldefer.go:194-212). The seed goroutine is the
      likely winner: it runs one query, the load runs two plus the verdict table.
    • Fix: in the goroutine, wait on ds.hist.ReadyC() before the SeedTenant loop. The goroutine
      is background, so the wait blocks no request.

Non-blocking

  • The PR text, at head 98fff339, cited TestWrongGuesses twice in the mutation table and
    tooldefer.WrongGuesses in the item table. Neither existed at that head, and the wrong-guess
    count there had no "loaded earlier" check, so a re-search counted again. Commit 50f6694c
    adds both and fixes the count. The text and the code now agree.
  • Rebuild drops more than the proven loads from used: a tool Claude Code's own search loaded,
    with no call after it, is not in used either (tooldefer.go:383-399). The rebuilt set can
    defer such a tool where the thread's first decision kept it loaded: one prefix rewrite. The
    old code had the same gap, worse. The known-limits comment covers history drift, not this.
  • waitAll (proxy/tooldefer.go:179-188): when the context is done and every channel is also
    closed, select may pick ctx.Done() and report failure. Only the ready flag in the start
    log line is affected.
  • deferTenantsChanged re-reads the tenant list and parses every tenant's YAML on each account
    write. Admin-rate writes only, so this is fine as is.

What I checked

  • The full diff 75c52f2c..98fff339, and commit 50f6694c in full. docs/design.md for the
    package rules.
  • sniffer.disjoint() (proxy/usage.go:744-761): I checked the index math. The overlap case
    returns the exact body; the gap case returns bytes(); the short case returns the head. The
    SSE search count at proxy/proxy.go:2539-2547 now reads each byte once.
  • sortLocked (tooldefer/history.go:406-425): I checked the in-place ss[:0] rewrite (safe,
    writes at index ≤ i), the per-project bound, and that the newest 64 always survive, so the
    disk's NOT-IN delete always runs when memory trimmed.
  • flush/write (tooldefer/history.go:525-658): the dirty re-mark on a failed write, the
    written bookkeeping, the retention ordering inside the one transaction, and the
    lastTSEvery ≤ retention/2 claim. A running session's disk last_ts lags at most
    every + flush interval, which stays inside the retention.
  • Rebuild/provenDeferred (tooldefer/tooldefer.go:383-431): the tool-shape checks match
    decide's candidate filter, and the CC-load exclusion works by block type
    (tool_search_tool_result only).
  • repairOnMissingRef (proxy/tooldefer.go:481-502): the read body is restored on every path
    where the stub does not run or fails. The old code closed the body first; the new one cannot
    lose it.
  • AuthBetas/RunProbeBeta (tooldefer/probe.go): only oauth-* values pass; an empty result
    sends no header.
  • The ledger (tooldefer/ledger.go): per-account map, the 10,000 cap, the N7 write cost, and
    WrongGuesses from 50f6694c (the "loaded earlier" exclusion and the once-per-tool delete).
  • The new tests: I read each one and matched it to the item it claims to cover. The fixtures
    (streamThrough, sse100k, hdrD) exist and compile against the current helpers.
  • Live tests were not run. Go is not on this machine, and the brief did not approve them.

Round 1 of the #874 review:
- deferTenantsChanged now waits for the history load before it seeds
  (seedAfterLoad), as startToolDefer does. A seed that landed first hid
  the table's row for the same session, with its used flags.
- docs/data-dependence.md: the history keeps the newest 64 sessions per
  user plus the newest 10 of each project, 256 in all.
- waitAll reports a closed channel as done even when the bound has passed.
- Rebuild's known limits name a tool Claude Code's own search loaded.

Part of #866.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 1 replies. Both blocking findings are fixed in 66c08dc6, a new commit on top of 50f6694c. There was no force-push.

Finding 1 (both reviewers): docs/data-dependence.md, the history bound. Fixed. The row now says: the newest 64 sessions per user, plus the newest 10 sessions of each project, up to 256 per user in all. It also gives the reason: the rule checks whether this project used a tool in its last 10 sessions, so a project's older sessions must stay. I removed "needs no change" from the PR body. The bound changes the stored amount of metadata, not its kind. The row's "Decided by" (David Amid) must confirm it before merge.

Finding 2 (reviewer 2): the late build seeds before the history load. Fixed. deferTenantsChanged now calls seedAfterLoad. It waits on ReadyC(), then seeds, as startToolDefer does. The goroutine is in the background, so no request waits.

  • Test: TestSeedAfterLoadKeepsTheLoadedUses. The history table holds a session that used Workflow, and the dashboard inventory has the same session with no use. The seed starts before the load. The loaded used flag must win.
  • Mutation: I dropped the wait. The test then fails with the seeded copy hid the loaded uses: [{Declared:map[Workflow:true] Used:map[]}].

Non-blocking notes I took:

  • waitAll (both reviewers): a closed channel is now done even when the bound has passed too. TestWaitAllIsOneBound checks this.
  • Rebuild and Claude Code's own search loads (both reviewers): the known-limits comment now names this case.
  • Reviewer 2, the PR text at 98fff339 naming WrongGuesses before it existed: 50f6694c added it, and the text and the code agree now.

Not changed:

  • The non-SSE bytes() branch: a spliced JSON window was never parseable, so there is nothing to count twice. This shape is older than this PR.
  • deferTenantsChanged re-reads every tenant's configuration on each account write: this is admin-rate, and both reviewers called it fine.

Tests at 66c08dc6, on the eval box with CGO_ENABLED=1 go test -race -count=1:

  • ./tooldefer/...: ok.
  • ./proxy/...: ok (483 s).

🤖 Generated with Claude Code

@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 66c08dc61e51 approve

Verdict: approve

Findings

None. Both round-1 findings are fixed, and the two new commits introduce no defect I can show.

Earlier findings

  1. docs/data-dependence.md:218, the history bound (mine, and reviewer 1's finding 1).
    Fixed in 66c08dc6. The row now says: the newest 64 sessions per user, plus the newest 10 of
    each project, up to 256 in all. It gives the reason in plain words: the project veto reads a
    project's last 10 sessions. I checked the text against tooldefer/history.go:31-35 and
    sortLocked (history.go:406-425). The PR body now states the change too, and names the
    confirmation the row needs. Open item, not a code defect: the row's "Decided by" (David Amid)
    confirms before merge, per the repo's rule.
  2. The late build seeded before the history load (my finding 2).
    Fixed in 66c08dc6. deferTenantsChanged now calls seedAfterLoad (proxy/tooldefer.go:222-230),
    which waits on ReadyC() before it seeds, so the table's row for a session wins over the seed's
    copy. I checked the wait holds no lock, and that ReadyC always closes: the load's queries run
    under a 30 s context, and Open closes it at once when there is no database. A Close during
    the wait is safe: the goroutine then seeds a stopped memory, which writes nothing.
    TestSeedAfterLoadKeepsTheLoadedUses covers it: the seed is made to want to run before the
    load, and the loaded used flags must still win. I read the test; its assertion fails on the
    old code by construction (the load skips a session the seed already added, history.go:268).

New commits

  • 50f6694c — one wrong-guess rule, tooldefer.WrongGuesses. Read in full during round 1 and
    again now. The rule adds the "no earlier message had loaded it" check (Loaded(original)) and
    counts each tool once. deferLedger now calls it (proxy/tooldefer.go:544).
    TestWrongGuesses covers six cases, including a re-search and a Claude Code load. Sound.
  • 66c08dc6 — the round-1 fixes: seedAfterLoad, the waitAll closed-channel pre-check, the
    doc row, and the Rebuild known-limits line. All checked below.

Non-blocking

  • deferTenantsChanged's comment still opens with "It never waits." The goroutine now waits on
    the load before it seeds. The caller still never waits, and seedAfterLoad's own comment says
    it plainly. Wording only.
  • The author's test claims (the eval-box runs and the mutation results) are the author's. I could
    not run them: live tests were not approved. I verified each claim by reading the code.

What I checked

  • Last review: round 1, 98fff339c64e1709fecdf89e917aef0b41779621, 2026-11-03T20:57:43Z.
  • New commits read: 2 — 50f6694c (one wrong-guess rule, tooldefer.WrongGuesses),
    66c08dc6 (seed a late tenant after the history load; doc row).
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files; the inline file is
    empty).
  • New items since my last review, and what I did about each:
    • Commit 50f6694c: read the full diff; checked the rule and its test (see New commits).
    • Commit 66c08dc6: read the full diff and the code around each change (below).
    • The author's comment at 21:11:25Z: checked every claim against the code. All hold.
    • The PR body edit: re-read it. "Needs no change" is gone; the N3 bound change is stated.
  • seedAfterLoad (proxy/tooldefer.go:222-230): the wait, the lock discipline, the unbounded
    wait's end (the load's 30 s context), the Close race, and concurrent goroutines after one
    account change each (the seeded map makes repeats no-ops).
  • waitAll (proxy/tooldefer.go:179-193): the non-blocking pre-check makes a closed channel
    always read as done, even with the bound passed. An open channel with the bound passed still
    returns false. The 100-iteration loop in TestWaitAllIsOneBound covers the random pick.
  • TestSeedAfterLoadKeepsTheLoadedUses: the fixture (a history table with a use, a dashboard
    inventory without it), the driver registration (dash imports modernc.org/sqlite, which the
    proxy test binary links), and the assertion's failure mode on the old code.
  • The doc row (docs/data-dependence.md:218) against the code's bounds.
  • The Rebuild known-limits comment (tooldefer/tooldefer.go:379-384): it now names the Claude
    Code load case, as both reviewers asked.
  • The two "not changed" items in the author's comment: I agree with both reasons. The non-SSE
    bytes() branch cannot double-count (gjson reads the first content match, which sits in the
    head), and a spliced JSON window was never parseable — a shape older than this PR. The
    per-account YAML re-read is admin-rate.
  • Live tests were not run. Go is not on this machine, and the brief did not approve them.

@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 66c08dc61e51 approve

Verdict: approve

Findings

None. Both round-1 blocking findings are fixed, and the two new commits introduce no defect I can show.

Earlier findings

  • Mine, finding 1 (docs/data-dependence.md:218, the history bound): fixed. The row now says: the newest 64 sessions per user, plus the newest 10 of each project, up to 256 in all, and gives the reason (the project veto reads a project's last 10 sessions). Plain words, as the rule requires. The row's "Decided by" (David Amid) still must confirm before merge — the reply says so too.
  • Reviewer 2, finding 1 (same doc row): fixed, same change. Agree with reviewer 2, finding 1; no new proof to add.
  • Reviewer 2, finding 2 (the late build seeds before the history load): fixed. seedAfterLoad waits on ReadyC() before it seeds, so the table's rows land first and the seed's copy cannot hide their used flags. I checked the wait cannot hang: Open's goroutine always reaches setLoaded, on error too, and its queries carry 5 s and 30 s bounds. The test TestSeedAfterLoadKeepsTheLoadedUses proves the order: with the wait removed, the seeded copy (no uses) wins and the test fails; with the wait, the loaded Used["Workflow"] survives. I traced both branches.
  • Mine, non-blocking waitAll (random pick on a closed channel plus a done context): fixed. The fast-path select with default reads a closed channel as done before the bounded wait. TestWaitAllIsOneBound loops it 100 times.
  • Mine, non-blocking Rebuild and Claude Code's own search loads: addressed. The known-limits comment now names the case and its cost (one prefix rewrite).
  • Mine, non-blocking non-SSE bytes() branch: declined, and I accept the reason. A spliced JSON window is not parseable, so nothing is counted twice; the shape is older than this PR. This matches what I wrote in round 1.
  • Mine, non-blocking deferTenantsChanged re-parsing every tenant config: declined, and I accept the reason. Admin-rate writes only, off the request path.
  • Reviewer 2, non-blocking (the PR text naming WrongGuesses before it existed): resolved by commit 50f6694c.

Non-blocking

  • proxy/tooldefer.go:203 — deferTenantsChanged's comment still ends "It never waits." The goroutine now waits on the history load before it seeds (bounded in practice at about 35 s). seedAfterLoad's own comment says so; only this one sentence is stale.
  • tooldefer/ledger.go:100-104 — the WrongGuesses comment says the dashboard (#869) calls the same function. No dashboard caller exists in this repo at this head; #869 is a separate PR. The statement is forward-looking, not false.

What I checked

  • Last review: round 1, 98fff33, 2026-11-03T20:54:31Z.
  • New commits read: 2 — 50f6694c "one wrong-guess rule, tooldefer.WrongGuesses" (new to me: it landed after my round-1 worktree was cut), 66c08dc6 "seed a late tenant after the history load; doc row".
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt).
  • New items since my last review, and what I did about each:
    • Commit 50f6694c — read the full diff. WrongGuesses moves the count into tooldefer, adds the "no earlier message had loaded it" rule, and counts once per tool. I checked the rule against deferLedger's inputs (di.outcome.Deferred, di.original, the response's loaded) and against every row of TestWrongGuesses, including the re-search and the two-tools cases. No defect.
    • Commit 66c08dc6 — read the full diff. Verified seedAfterLoad, the waitAll fast path, the doc row, and the known-limits wording, as described above.
    • The author's reply comment (2026-11-03T21:11:25Z) — checked each claim against the code. The claimed test results on the eval box (./tooldefer/... and ./proxy/... with -race) are the author's; I did not run them.
  • No inline comments exist on the PR (the file is empty), so there was nothing to miss there.
  • I did not run builds or tests (not approved).

@amiddavid
amiddavid merged commit 0022f45 into main Nov 3, 2026
7 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 3, 2026
amiddavid added a commit that referenced this pull request Nov 3, 2026
After the rebase on #874, the ledger counts our search's add-backs
through tooldefer.WrongGuesses: the loaded names reach the ledger and
are in the request's deferred set. The end-to-end tests now check
wrong_guesses, once per tool, also for a mixed call that the next request
repairs. add_backs and mixed_searches stay as counters of our search.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Nov 3, 2026
…e ledger

The lead decided one wrong-guess rule, in tooldefer.WrongGuesses (#874):
a tool this request deferred, that a search in its response loaded, and
that no earlier message had loaded. deferLedger already computes it on
the tooldefer.Request it books, so the dashboard row now takes
r.WrongGuesses from there. The second copy (proxy's wrongGuesses) is
gone, so /stats and the panel cannot disagree.

The row and the panel also carry r.DroppedSearches (#866 N8): searches
with no result, because the client drops a search sent beside another
tool call. One more additive column, defer_dropped_searches.

Rebased on #874 (feat/tooldefer-866), which merges first.

Refs #869, #866.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Nov 3, 2026
…e ledger

The lead decided one wrong-guess rule, in tooldefer.WrongGuesses (#874):
a tool this request deferred, that a search in its response loaded, and
that no earlier message had loaded. deferLedger already computes it on
the tooldefer.Request it books, so the dashboard row now takes
r.WrongGuesses from there. The second copy (proxy's wrongGuesses) is
gone, so /stats and the panel cannot disagree.

The row and the panel also carry r.DroppedSearches (#866 N8): searches
with no result, because the client drops a search sent beside another
tool call. One more additive column, defer_dropped_searches.

Rebased on #874 (feat/tooldefer-866), which merges first.

Refs #869, #866.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
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.

1 participant