Repository navigation
refactor(agent): move Bob's usage reading into agent/bob - #1052
Conversation
The shared proxy decided with a bob flag, in 4 places, whether to read Bob's cache-write fields, and held the parser in proxy/bobusage.go. The parser is now Bob.ReadUsage in agent/bob, and the proxy asks the route's agent through one helper, readAgentUsage. The flag and bobusage.go are gone. No behavior change. proxy/bobusage_test.go is byte-identical; its 5 direct-parser tests compile through a test-only shim, and its end-to-end tests are the proof. - readAgentUsage starts from the shared reading and copies back only the 5 token counts, so every other field stays as it was. - A panic in the agent gives the shared reading (fail open); the log names the types only. - The same gates: the buffered path calls the agent only inside its ok block, the streamed path only when ok. agent/bob copies usagePresent (a library cannot import the proxy). A test fails if the copy accepts an empty block after the real one. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Vitaly Zabershinsky <[email protected]>
vz-ibm
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (claude, user of @vz-ibm) | Claude Code 2.1.316 | offload-review skill, @vz-ibm's session | fresh | 1 of 2 | 1 of 2 | 98d50cd89a68 |
approve |
Verdict: approve
Findings
None. I found no wrong behavior, no broken fail-open path and no missing test for the moved logic.
Non-blocking
agent/bob/usage.go:87— the copy ofusagePresentis guarded in one direction only. The new test fails ifpresentaccepts{}ornull. It does not fail if someone changesproxy/usage.go:164and leaves the copy as it is. A shared copy in a library package removes the drift risk.internal/providerusageis a library package, the proxy already imports it, andagent/bobmay import it. CLAUDE.md says to move shared logic into a library package. Moving the rule is an option for a later A2 step.docs/design.md:24is out of date. Theagent/bob/row says "its model route and its session id (X-Task-Id)". After this PR the package also holds Bob's usage reading (cache writes and the 1h part). Add that to the row.proxy/agentusage.go:24— the host does not check the agent's counts. A buggy agent can return negative counts orCacheWrite1h > CacheWrite, and the row records them. Theagent.Agent.ReadUsagedoc puts this check on the agent, andBobdoes it (count,write1h > write,CacheRead+write > prompt). This is acceptable with one agent. A host-side sanity check (fall back tobaseon negative counts) would make the fail-open path cover a buggy agent too, not only a panicking one.
What I checked
- I read the full diff (7 files, +335/−39) and the one commit
98d50cd8. I also read the code around each change. - No behavior change. I compared the old and new code:
- Old:
bob := up.path == bobModelPath, thenbobResponseUsageonly whenbob(buffered, inside theokblock) and only whenbob && ok(stream). - New:
ag := h.agentFor(up.path), thenreadAgentUsagein the sameokgates.bobModelPathisbob.ModelPath, andproxy.goimportsagent/bob, soinit()registersBobin the default registry.NewsetsagentFor: agent.ForPath. Bob's route therefore getsBob.ReadUsage, and every other route getsBase. Base.ReadUsagereturnsbase.readAgentUsagecopies the 5 counts out and back, so it is the identity.TestReadAgentUsageWithTheNeutralAgentIsTheIdentityproves it over all 12Usagefields. I counted the 12 fields inproxy/usage.go:18, andeveryFieldSetsets all of them. Its reflection check catches a new field that is left zero.streamRec(non-chat callers,recteetests) now passesagent.Base{}where it passedfalse. The result is the same.
- Old:
- The moved parser is byte-for-byte the old logic.
readUsage/countare the renamedbobUsage/bobCount.Bob.ReadUsageisbobResponseUsage.presentis the same asusagePresent(proxy/usage.go:164). - Fail open.
readAgentUsagerecovers a panic and returnsbase. It logs only%Tof the agent and of the panic value, not the message.TestPanickingAgentReadUsageFailsOpenToTheSharedReadingcovers both host paths: the no-tools body goes to the!advertised→streamRecOnpath, and the tools body goes to thedefaultbuffered path. The test checks that the agent was called, that the row equals the no-agent row (fresh 12), that the recovery was logged, and that the canary is not in the log. - Logger context on the stream path.
resp.Request.Context()comes fromdoUpstream→silenceAttempt, which derives fromr.Context()(context.WithCancelCause(parent)). So the hosted per-tenant logger (proxy.go:1311) carries through. Thecontext.Background()fallback is only for hand-built responses in tests. - The shim (
proxy/bobusage_shim_test.go) wrapsu.Rawas{"usage":…}. I traced the 5 old direct tests through it, including the garbage cases (not json,array,{}). Each one gives a non-object or a block with noprompt_tokens, so the result isbase.readAgentUsagekeepsStopReason, whichsameUsagecompares. - End-to-end proof uses the real default registry.
bobUsageHandlerbuilds throughNew, soTestBobRouteRowReadsCacheWrites(JSON and SSE),...OnTheBufferedPathandTestNonBobRoutesIgnoreBobCacheWritesexerciseagent.ForPath→Bob. - Library boundary.
agent/bob/usage.goimports onlystrings,agentand gjson.agent/imports_test.go(from #1045) already listsagent/boband refuses host imports. - Data dependence. No change. Bob reads only the counts in the usage block, as before. The
docs/data-dependence.mdrow ("Only that route reads these counts") is still true. - I read the PR description. I did not run Go builds or tests, as this review was not approved for live tests.
vz-ibm
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (claude, user of @vz-ibm) | Claude Code 2.1.316 | offload-review skill, @vz-ibm's session | fresh | 2 of 2 | 1 of 2 | 98d50cd89a68 |
approve |
Verdict: approve
Findings
None. I found no wrong behavior, no broken fail-open path, and no missing test for the moved code.
Non-blocking
docs/design.md:24is now incomplete. Theagent/bob/row says "its model route and its session id (X-Task-Id)". After this PR the package also owns Bob's usage reading (the cache writes and the 1-hour part). Add "and its usage reading (ReadUsage)", so a reader finds the code from the layout table.- The
presentcopy can drift in one direction only.proxy/usage.go:162saysagent/bob/usage_test.gofails if the copy accepts an empty block. That is true for{}andnull. But if someone makesusagePresentstricter later (for example, it requires a token field), no test fails, and Bob's stream reader can pick a different chunk than the shared parser. Both the comment and the test exist, so this is a known risk. A move of the rule into a small library package that both import would remove it. That can wait for a later A2 step. - The shim changes what the 5 old direct tests exercise.
proxy/bobusage_shim_test.gowrapsu.Rawas{"usage":<raw>}and calls throughreadAgentUsage. For thenot jsoncase the wrapped body is{"usage":not json}. gjson reads thatusageas a literal (not an object), so the result is stillbase, and the test is still correct. The test now proves less about the raw parser than its name says, butagent/bob/usage_test.gocovers the parser directly. No change needed. - The fail-open test's "streamed" case uses a JSON upstream reply. It exercises the
streamRecOncall site, but not the event-stream branch ofBob.ReadUsageunder a panic. That is fine because the recover sits inreadAgentUsage, not in the branch.
What I checked
- The full diff
4519eeea..98d50cd8(1 commit, 7 files), every line. - Behavior is the same as before:
- Old gate:
up.path == bobModelPath. New:h.agentFor(up.path). Bob registersbob.ModelPathfrominit(), andproxy.go:736importsagent/bob, so production resolves the same route to Bob. Every other route getsagent.Base, whoseReadUsagereturnsbase. - Streamed path (
proxy.go:2788): oldbob && ok, newokplus the neutral agent. Same result. - Buffered path (
proxy.go:2393): the call stays inside the existingokblock. streamRec(proxy.go:2750) passesagent.Base{}, as it passedfalsebefore.Bob.ReadUsageandreadUsageare the oldbobResponseUsageandbobUsagewith renames only. I compared them line by line.presentis a byte copy ofusagePresent.
- Old gate:
- Mapping in
readAgentUsage: it copies exactly the 5 token fields in and out (FreshInput,CacheRead,CacheWrite,CacheWrite1h,Output). It keepsSearches,SearchLoaded,SearchDropped,Live,StopReason,ToolUseNames,ToolUseIncompletefrombase. I checked theUsagestruct inproxy/usage.go:18. The reflection test fails if a new field is left zero. - Fail open:
recoversetsout = base. The log line has the agent type and the panic type only, not the message. The test checks the canary is absent. On the streamed path the bytes already went to the client before the agent runs, so a panic cannot cut the response. - Logger context: on the streamed path,
resp.Request.Context()comes fromdoUpstream→doWithSilenceGuard(r.Context(), …). That is the context thatproxy.go:1311gives the tenant logger, so the recovery line carries tenant and route. Thenilcheck covers hand-built responses in tests. - Import rule:
agent/bob/usage.goimports onlystrings,agentand gjson.agent/imports_test.goalready guardsagent/bobagainst host imports. - Tests:
agent/bob/usage_test.go(cold, warm, stream last chunk, empty and null tail chunk, fallback fields, unreadable replies) andproxy/agentusage_test.go(identity, token counts only, panic on both call sites, with a call counter).proxy/bobusage_test.gois unchanged; its end-to-end tests cover the Bob route on JSON, SSE and the buffered path, and the non-Bob routes. - Data dependence: unchanged. Token counts only.
docs/data-dependence.md:221still holds ("Only that route reads these counts"). - I did not run Go builds or tests. Live tests are not approved, and Go is not installed here.
The proxy and agent/bob each kept a copy of the rule that says a usage block is there (an object with at least one field). A test guarded the copy in one direction only. The rule is now providerusage.Present, and both use it. docs/design.md names the usage reading in the agent/bob row. Both round-1 reviewers of #1052 raised these 2 points. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Vitaly Zabershinsky <[email protected]>
|
Round 1 replies. Both reviewers approve. Fixed in 562bb9f:
Checks: |
vz-ibm
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (claude, user of @vz-ibm) | Claude Code 2.1.316 | offload-review skill, @vz-ibm's session | resumed | 2 of 2 | 2 of 2 | 562bb9fcef16 |
approve |
Verdict: approve
Findings
None. The new commit moves one rule into a shared library function. It does not change behavior.
Status of earlier points
All round-1 points were non-blocking. Neither reviewer raised a finding.
- Reviewer 2,
presentcopy drifts in one direction: fixed. One copy now:internal/providerusage.Present.proxy/usage.go:163(usagePresent) andagent/bob/usage.go:23both call it. - Reviewer 2,
docs/design.md:24incomplete: fixed. The row now names the usage reading. - Reviewer 2, shim and streamed fail-open case: no change. The author agrees with my note. Nothing to do.
- Reviewer 1, no host check of the agent's counts: not changed by the author. Reason: the
agent.Agent.ReadUsagedoc puts the check on the agent,Bobdoes the check, and the author adds a host check when a second agent arrives. I accept this. Today onlyBobandBaseexist.Bob'sreadUsagerejects negative counts,write1h > write, andCacheRead + write > prompt(agent/bob/usage.go:44-70).Basereturnsbase.
Non-blocking
usagePresentis now a one-line wrapper with 5 callers inproxy/. The callers could callproviderusage.Presentdirectly. This is style only, and a wrapper keeps this diff small.
What I checked
- Last review: round 1,
98d50cd89a68ce3318921847d0ab637f6e652d31, 2026-11-10T13:45:41Z - New commits read: 1 —
562bb9fcrefactor(usage): share the usage-present rule in providerusage - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files)
- New items since my last review:
- Comment by @vz-ibm at 2026-11-10T13:57:08Z (the round-1 replies). I checked each of its 4 points against the code. See "Status of earlier points".
- Commit
562bb9fc. I read the whole diff (6 files, +40/−30) and the code around it.
Presentis the same rule as before. Its body is a byte copy of the oldusagePresentand the oldpresent: an object with at least one field. So the proxy andagent/bobpick the same stream chunk as in round 1.- The library rule holds.
internal/providerusageimports only gjson (providerusage.go:11). It is not a host, soagent/imports_test.gostill passes in principle.agent/bobis in the same module, so it may import aninternal/package. - Tests.
TestPresentIsTrueOnlyForAnObjectWithAFieldcovers an object with a field,{"x":null},{},null, an array, a number, a string, and a missing path.TestReadUsageIgnoresAnEmptyUsageChunkAfterTheRealOneinagent/bobstill guards Bob's use of the rule. Its comment now namesproviderusage.Present. - Docs.
docs/design.md:24now says the package holds the model route, the session id and the usage reading.proxy/usage.go:162points to the shared rule. - Data dependence: unchanged. Token counts only.
- I did not run Go builds or tests. Live tests are not approved, and Go is not installed here. The author reports
go test -raceon./proxy/,./agent/...and./internal/providerusage/as OK.
vz-ibm
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (claude, user of @vz-ibm) | Claude Code 2.1.316 | offload-review skill, @vz-ibm's session | resumed | 1 of 2 | 2 of 2 | 562bb9fcef16 |
approve |
Verdict: approve
Findings
None. The new commit moves one rule into a library package and changes no behavior.
Status of round-1 points
Neither reviewer had a blocking finding in round 1. These are the status of the non-blocking points:
- The
presentcopy (reviewer 1 and reviewer 2): fixed.internal/providerusage.Presentis now the one copy.proxy/usage.go:163(usagePresent) andagent/bob/usage.go:23both call it.agent/bobhas nopresentfunction now. The drift risk is gone in both directions. docs/design.mdrow (reviewer 1 and reviewer 2): fixed. Theagent/bob/row now names the usage reading (the cache writes and their 1-hour part).- No host check of the agent's counts (reviewer 1): rejected by the author. The reason: the
ReadUsagecontract puts the check on the agent,Bobdoes it, and the author adds a host check when a second agent arrives. I accept this. It was non-blocking, and the one agent today checks its counts. - The shim, and the streamed fail-open case (reviewer 2): no change. Reviewer 2 said no change was needed. I agree.
Non-blocking
- None.
What I checked
- Last review: round 1,
98d50cd89a68ce3318921847d0ab637f6e652d31, 2026-11-10T13:45:35Z - New commits read: 1 —
562bb9fc refactor(usage): share the usage-present rule in providerusage(6 files, +40/−30) - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files)
- New items since my last review:
- Review by reviewer 2, round 1 (13:45:41Z): read in full. Its 2 doc and copy points are the same as mine, and both are fixed. Its shim and streamed-case points need no change.
- Comment by @vz-ibm (13:57:08Z), round-1 replies: I checked each of its 4 points against the code (see "Status of round-1 points").
- Commit
562bb9fc: reviewed below.
Presentis the same rule as before. I comparedinternal/providerusage/providerusage.go:76with the removedusagePresentandpresentbodies line by line: not an object → false, else true whenForEachyields one field. So the proxy and Bob pick the same chunks as before.usagePresentstays as a one-line wrapper. Its 4 callers inproxy/usage.go(lines 187, 201, the stream loop and the nested-path loop) do not change. Its long doc comment above still explains why{}andnullare absent.- Import rules.
providerusageimports only gjson.agent/bobmay importinternal/providerusage, because the Gointernal/rule allows any package under the module root.providerusageis not a host package, soagent/imports_test.gostill passes by reading. - New test.
TestPresentIsTrueOnlyForAnObjectWithAFieldchecks an object with a field, an object whose only field isnull(true, as before),{},null, an array, a number, a string, and a missing path. Each case asserts the exact bool. Theagent/bobempty-chunk test still covers the stream use. - Docs.
docs/design.md:24now names the usage reading.docs/data-dependence.mdneeds no change: the data dependence is the same. - I did not run Go builds or tests, as this review was not approved for live tests. The author reports
go test -raceon./proxy/,./agent/...and./internal/providerusage/as OK.
…nd usage (#1029) A new package, agent/, gives client agents such as IBM Bob one extension point. Bob's session id and usage reading move out of proxy/proxy.go into agent/bob. This folds in #1045 and #1052. - agent/: the Agent interface (Name, Paths, SessionID, ReadUsage), Base (the neutral agent), and a Registry found by route path. The Registry refuses a nil agent, an empty path and a path another agent already claims. - #1045: Bob's session id (X-Task-Id) comes from agent/bob. - #1052: Bob's usage reading comes from agent/bob, through internal/providerusage, which proxy and agent/bob share. Behavior change: none. Each Bob request and reply keeps the same session id, usage numbers, cost and routes; proxy tests pass unchanged. Data dependence: metadata only, the same as before (header values and token counts). Reviews: #1029 2 offload reviews (GLM), round 3 on the folded head, both approve at 3ee169e, which is the PR head. #1045 and #1052 each had 2 approvals (round 2) before the fold. The merge of main had no hand resolution. Signed-off-by: Vitaly Zabershinsky <[email protected]> Signed-off-by: DAVID AMID <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
Summary
This is the second move of step A2. It moves Bob's usage reading (the cache-write fields) out of the shared proxy and into
agent/bob. The shared proxy no longer has abobflag in its usage code.What changed
agent/bob/usage.go(wasproxy/bobusage.go):Bob.ReadUsagereads Bob's cache-write fields from a buffered or streamed reply.agentand gjson. It never imports a host.proxy/agentusage.go, new helperreadAgentUsage:proxy/proxy.go:servegets the route's agent once (h.agentFor(up.path)).streamRecOntakes anagent.Agentin place ofbob bool.streamRecpassesagent.Base{}.okblock, and the streamed path only whenok.Data dependence
None changed. Usage is token counts only (metadata).
How it was tested
proxy/bobusage_test.gois byte-identical and green. Its 5 direct-parser tests compile through a test-only shim,proxy/bobusage_shim_test.go, that callsreadAgentUsagewithbob.Bob{}. Its end-to-end tests are the real proof.go test -race ./proxy/: OK (524 s)../agent/...,go vet,gofmt: OK.readAgentUsagewithagent.Basereturns every field of the input unchanged (checked by reflection over all fields).readAgentUsagecall is removed.{}ornullusage chunk after the real one does not reset the counts. It fails when thepresentcheck is broken; the old stream test did not.bob :=,bobUsage,bobCountandif bobin proxy production files is empty.Technical notes
internal/providerusage.Present. The proxy andagent/bobboth use it, so they always pick the same stream chunk.BobUpstream.