Skip to content

refactor(agent): move Bob's usage reading into agent/bob - #1052

Merged
amiddavid merged 2 commits into
feat/agent-bob-sessionfrom
feat/agent-bob-usage
Nov 11, 2026
Merged

amiddavid merged 2 commits into
feat/agent-bob-sessionfrom
feat/agent-bob-usage

Conversation

@vz-ibm

@vz-ibm vz-ibm commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #1045 (which is stacked on #1029). Merge those first. This PR's own changes are the last 2 commits, from refactor(agent): move Bob's usage reading into agent/bob.

No behavior change. proxy/bobusage_test.go, Bob's usage tests, is byte-identical and green.

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 a bob flag in its usage code.

What changed

agent/bob/usage.go (was proxy/bobusage.go):

  • Bob.ReadUsage reads Bob's cache-write fields from a buffered or streamed reply.
  • It imports only agent and gjson. It never imports a host.

proxy/agentusage.go, new helper readAgentUsage:

  • It gives the agent the 5 token counts of the shared reading, and copies back only those 5 counts. Every other field (searches, stop reason, tool names) stays as the shared parser read it.
  • Fail open: a panic in the agent gives the shared reading. The log names the types only, never the panic message, because that message could hold reply text.

proxy/proxy.go:

  • serve gets the route's agent once (h.agentFor(up.path)).
  • streamRecOn takes an agent.Agent in place of bob bool. streamRec passes agent.Base{}.
  • The gates are the same: the buffered path asks the agent only inside its existing ok block, and the streamed path only when ok.

Data dependence

None changed. Usage is token counts only (metadata).

How it was tested

  • proxy/bobusage_test.go is byte-identical and green. Its 5 direct-parser tests compile through a test-only shim, proxy/bobusage_shim_test.go, that calls readAgentUsage with bob.Bob{}. Its end-to-end tests are the real proof.
  • go test -race ./proxy/: OK (524 s). ./agent/..., go vet, gofmt: OK.
  • New tests:
    • Identity: readAgentUsage with agent.Base returns every field of the input unchanged (checked by reflection over all fields).
    • Token counts only: an agent that changes the counts cannot change any other field.
    • Fail open, streamed and buffered: a panicking agent gives the shared reading. The buffered case fails when its readAgentUsage call is removed.
    • Empty usage chunk: an empty {} or null usage chunk after the real one does not reset the counts. It fails when the present check is broken; the old stream test did not.
  • The grep for bob :=, bobUsage, bobCount and if bob in proxy production files is empty.

Technical notes

  • The rule that says a usage block is there (an object with at least one field) is now internal/providerusage.Present. The proxy and agent/bob both use it, so they always pick the same stream chunk.
  • Bob code still in the proxy, for the next A2 moves: the backend label (feat(proxy): label each Bob reply with the IBM backend that served it #975), the summary-call route, the route setup, and BobUpstream.

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 vz-ibm 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 (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 of usagePresent is guarded in one direction only. The new test fails if present accepts {} or null. It does not fail if someone changes proxy/usage.go:164 and leaves the copy as it is. A shared copy in a library package removes the drift risk. internal/providerusage is a library package, the proxy already imports it, and agent/bob may 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:24 is out of date. The agent/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 or CacheWrite1h > CacheWrite, and the row records them. The agent.Agent.ReadUsage doc puts this check on the agent, and Bob does it (count, write1h > write, CacheRead+write > prompt). This is acceptable with one agent. A host-side sanity check (fall back to base on 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, then bobResponseUsage only when bob (buffered, inside the ok block) and only when bob && ok (stream).
    • New: ag := h.agentFor(up.path), then readAgentUsage in the same ok gates. bobModelPath is bob.ModelPath, and proxy.go imports agent/bob, so init() registers Bob in the default registry. New sets agentFor: agent.ForPath. Bob's route therefore gets Bob.ReadUsage, and every other route gets Base.
    • Base.ReadUsage returns base. readAgentUsage copies the 5 counts out and back, so it is the identity. TestReadAgentUsageWithTheNeutralAgentIsTheIdentity proves it over all 12 Usage fields. I counted the 12 fields in proxy/usage.go:18, and everyFieldSet sets all of them. Its reflection check catches a new field that is left zero.
    • streamRec (non-chat callers, rectee tests) now passes agent.Base{} where it passed false. The result is the same.
  • The moved parser is byte-for-byte the old logic. readUsage/count are the renamed bobUsage/bobCount. Bob.ReadUsage is bobResponseUsage. present is the same as usagePresent (proxy/usage.go:164).
  • Fail open. readAgentUsage recovers a panic and returns base. It logs only %T of the agent and of the panic value, not the message. TestPanickingAgentReadUsageFailsOpenToTheSharedReading covers both host paths: the no-tools body goes to the !advertised → streamRecOn path, and the tools body goes to the default buffered 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 from doUpstream → silenceAttempt, which derives from r.Context() (context.WithCancelCause(parent)). So the hosted per-tenant logger (proxy.go:1311) carries through. The context.Background() fallback is only for hand-built responses in tests.
  • The shim (proxy/bobusage_shim_test.go) wraps u.Raw as {"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 no prompt_tokens, so the result is base. readAgentUsage keeps StopReason, which sameUsage compares.
  • End-to-end proof uses the real default registry. bobUsageHandler builds through New, so TestBobRouteRowReadsCacheWrites (JSON and SSE), ...OnTheBufferedPath and TestNonBobRoutesIgnoreBobCacheWrites exercise agent.ForPath → Bob.
  • Library boundary. agent/bob/usage.go imports only strings, agent and gjson. agent/imports_test.go (from #1045) already lists agent/bob and refuses host imports.
  • Data dependence. No change. Bob reads only the counts in the usage block, as before. The docs/data-dependence.md row ("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 vz-ibm 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 (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:24 is now incomplete. The agent/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 present copy can drift in one direction only. proxy/usage.go:162 says agent/bob/usage_test.go fails if the copy accepts an empty block. That is true for {} and null. But if someone makes usagePresent stricter 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.go wraps u.Raw as {"usage":<raw>} and calls through readAgentUsage. For the not json case the wrapped body is {"usage":not json}. gjson reads that usage as a literal (not an object), so the result is still base, and the test is still correct. The test now proves less about the raw parser than its name says, but agent/bob/usage_test.go covers the parser directly. No change needed.
  • The fail-open test's "streamed" case uses a JSON upstream reply. It exercises the streamRecOn call site, but not the event-stream branch of Bob.ReadUsage under a panic. That is fine because the recover sits in readAgentUsage, 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 registers bob.ModelPath from init(), and proxy.go:736 imports agent/bob, so production resolves the same route to Bob. Every other route gets agent.Base, whose ReadUsage returns base.
    • Streamed path (proxy.go:2788): old bob && ok, new ok plus the neutral agent. Same result.
    • Buffered path (proxy.go:2393): the call stays inside the existing ok block.
    • streamRec (proxy.go:2750) passes agent.Base{}, as it passed false before.
    • Bob.ReadUsage and readUsage are the old bobResponseUsage and bobUsage with renames only. I compared them line by line. present is a byte copy of usagePresent.
  • Mapping in readAgentUsage: it copies exactly the 5 token fields in and out (FreshInput, CacheRead, CacheWrite, CacheWrite1h, Output). It keeps Searches, SearchLoaded, SearchDropped, Live, StopReason, ToolUseNames, ToolUseIncomplete from base. I checked the Usage struct in proxy/usage.go:18. The reflection test fails if a new field is left zero.
  • Fail open: recover sets out = 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 from doUpstream → doWithSilenceGuard(r.Context(), …). That is the context that proxy.go:1311 gives the tenant logger, so the recovery line carries tenant and route. The nil check covers hand-built responses in tests.
  • Import rule: agent/bob/usage.go imports only strings, agent and gjson. agent/imports_test.go already guards agent/bob against host imports.
  • Tests: agent/bob/usage_test.go (cold, warm, stream last chunk, empty and null tail chunk, fallback fields, unreadable replies) and proxy/agentusage_test.go (identity, token counts only, panic on both call sites, with a call counter). proxy/bobusage_test.go is 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:221 still 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]>
@vz-ibm

vz-ibm commented Nov 10, 2026

Copy link
Copy Markdown
Collaborator Author

Round 1 replies. Both reviewers approve. Fixed in 562bb9f:

  1. The present copy (both reviewers): fixed. The rule is now internal/providerusage.Present, one copy. proxy/usage.go (usagePresent) and agent/bob/usage.go both call it. A new test, TestPresentIsTrueOnlyForAnObjectWithAField, failed first (no Present) and then passed.
  2. docs/design.md (both reviewers): fixed. The agent/bob/ row now names the usage reading.
  3. No host check of the agent's counts (reviewer 1): not changed. The agent.Agent.ReadUsage doc puts this check on the agent, and Bob does it. I will add a host check when a second agent arrives.
  4. The shim, and the streamed fail-open case (reviewer 2): no change needed, as the review says.

Checks: go test -race ./proxy/ ./agent/... ./internal/providerusage/ OK (proxy 523 s). go vet and gofmt OK.

@vz-ibm vz-ibm 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 (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, present copy drifts in one direction: fixed. One copy now: internal/providerusage.Present. proxy/usage.go:163 (usagePresent) and agent/bob/usage.go:23 both call it.
  • Reviewer 2, docs/design.md:24 incomplete: 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.ReadUsage doc puts the check on the agent, Bob does the check, and the author adds a host check when a second agent arrives. I accept this. Today only Bob and Base exist. Bob's readUsage rejects negative counts, write1h > write, and CacheRead + write > prompt (agent/bob/usage.go:44-70). Base returns base.

Non-blocking

  • usagePresent is now a one-line wrapper with 5 callers in proxy/. The callers could call providerusage.Present directly. 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 — 562bb9fc refactor(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.
  • Present is the same rule as before. Its body is a byte copy of the old usagePresent and the old present: an object with at least one field. So the proxy and agent/bob pick the same stream chunk as in round 1.
  • The library rule holds. internal/providerusage imports only gjson (providerusage.go:11). It is not a host, so agent/imports_test.go still passes in principle. agent/bob is in the same module, so it may import an internal/ package.
  • Tests. TestPresentIsTrueOnlyForAnObjectWithAField covers an object with a field, {"x":null}, {}, null, an array, a number, a string, and a missing path. TestReadUsageIgnoresAnEmptyUsageChunkAfterTheRealOne in agent/bob still guards Bob's use of the rule. Its comment now names providerusage.Present.
  • Docs. docs/design.md:24 now says the package holds the model route, the session id and the usage reading. proxy/usage.go:162 points 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 -race on ./proxy/, ./agent/... and ./internal/providerusage/ as OK.

@vz-ibm vz-ibm 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 (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:

  1. The present copy (reviewer 1 and reviewer 2): fixed. internal/providerusage.Present is now the one copy. proxy/usage.go:163 (usagePresent) and agent/bob/usage.go:23 both call it. agent/bob has no present function now. The drift risk is gone in both directions.
  2. docs/design.md row (reviewer 1 and reviewer 2): fixed. The agent/bob/ row now names the usage reading (the cache writes and their 1-hour part).
  3. No host check of the agent's counts (reviewer 1): rejected by the author. The reason: the ReadUsage contract puts the check on the agent, Bob does 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.
  4. 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.
  • Present is the same rule as before. I compared internal/providerusage/providerusage.go:76 with the removed usagePresent and present bodies line by line: not an object → false, else true when ForEach yields one field. So the proxy and Bob pick the same chunks as before.
  • usagePresent stays as a one-line wrapper. Its 4 callers in proxy/usage.go (lines 187, 201, the stream loop and the nested-path loop) do not change. Its long doc comment above still explains why {} and null are absent.
  • Import rules. providerusage imports only gjson. agent/bob may import internal/providerusage, because the Go internal/ rule allows any package under the module root. providerusage is not a host package, so agent/imports_test.go still passes by reading.
  • New test. TestPresentIsTrueOnlyForAnObjectWithAField checks an object with a field, an object whose only field is null (true, as before), {}, null, an array, a number, a string, and a missing path. Each case asserts the exact bool. The agent/bob empty-chunk test still covers the stream use.
  • Docs. docs/design.md:24 now names the usage reading. docs/data-dependence.md needs 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 -race on ./proxy/, ./agent/... and ./internal/providerusage/ as OK.

@amiddavid
amiddavid merged commit 562bb9f into feat/agent-bob-session Nov 11, 2026
7 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 11, 2026
amiddavid pushed a commit that referenced this pull request Nov 11, 2026
…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]>
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.

2 participants