Repository navigation
Feat: Break one agent's last hour down by model - #1222
Conversation
Under an agent scope the spend drawer read BY NONE for LAST 1H while every ledger-backed span read BY MODEL. The ring tallies each axis separately, so narrowing it to one agent through the agent axis left nothing to break that agent's traffic down by, and /v1/usage served agent= on a ring window as group none. The aggregator now keeps a whole ring per recognised coding agent (pipeline.IsKnownAgent), and AgentSnapshot answers a recognised agent with no session from it, honouring the requested group. Only known names get a ring, so the count is fixed in code and nothing is capped or evicted; a raw User-Agent and session+agent are served as none, as before. The drawer already asked for group=model with agent=, so it needs no change. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (9)
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review. 📝 WalkthroughWalkthroughRecognized agents now have separate usage rings. Ring-backed requests can retain the requested grouping for a recognized agent when no session is specified. The spend drawer test verifies that a scoped agent can display a model breakdown. ChangesAgent usage breakdowns
Priority: ⬇️ Low Estimated code review effort: 3 (Moderate) | ~25 minutes Change: Feature Sequence Diagram(s)sequenceDiagram
participant SessionAPI
participant AgentSnapshot
participant Snapshot
participant AgentRing
SessionAPI->>AgentSnapshot: request agent and group
AgentSnapshot->>Snapshot: snapshot recognized agent with requested group
Snapshot->>AgentRing: select agent ring when no session is specified
AgentRing-->>SessionAPI: grouped usage buckets
Suggested reviewers: Merge Risk: ⚪ Minimal · up to No concrete merge-blocking issue is identified. Recognized agents gain scoped breakdowns while session-scoped and unrecognized-agent requests retain their fallback behavior. Merge after normal checks. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to The change bounds resource growth and preserves session filtering. No new security weakness was established, but actual network confinement of the unauthenticated endpoint was not verified. Retained concerns Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Fixes review: Rekeyed did not relabel the per-agent rings, so agent=<known>&group=session named the pending id after adoption Files: - core/cost/usage/rekey.go - core/cost/usage/rekey_test.go Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
mrsabath
left a comment
There was a problem hiding this comment.
Well-constructed change to a tricky area: the ring tallies axes separately, so adding a per-agent ring is the right fix rather than trying to make the agent axis carry a second dimension.
What I verified independently:
- The memory bound holds.
AgentLabelfolds throughpipeline.AgentNameand is versionless, soIsKnownAgent(AgentLabel(...))does match. Worth stating becauseIsKnownAgent's own doc warns it is "false for any label carrying a version" — hadAgentLabelreturned a versioned label, the gate would have been dead code and no ring would ever have been created. Key space is bounded at 3. - The
Recordplacement is load-bearing and correct. The session branch below has three return paths, not one (existing ring,maxSess == 0, and the new-ring fall-through). Folding after it would have skipped the agent ring for every already-tracked session — silent under-counting. The comment documents this accurately. - The second commit fixes a real bug. Adding per-agent rings without teaching
Rekeyedabout them would leave stalepending:ids visible underagent=<known>&group=session, and the test asserts both directions. MaxSeriesInResponsevsmath.MaxIntis not a regression. The new path's cap of 16 applies to series within one agent's ring, same as any normalSnapshot; themath.MaxIntin the fallback does a different job (finding the agent on the agent axis), andTestAgentSnapshot_FindsAnAgentPastTheSeriesCapstill guards that path.
Test coverage is genuinely discriminating rather than decorative: TheAgentRingAgreesWithTheAgentAxis is the correct guard against the two folds drifting apart, and AnUnrecognisedAgentIsServedAsNone asserts the memory bound directly via len(a.agents).
Finding not in any diff hunk
core/cost/usage/usage.go:1058 and :1074 — two comments state that foldInto runs "up to twice" / "twice" per event. With this change a recognised agent's event folds three times. The nearest hunk starts at 1130, so this cannot be anchored inline. Noting it because these comments are stale precisely because this PR changed the behaviour they describe without touching the lines that describe it. (Already on your deferred list.)
Two notes beyond the nits, neither blocking
- The PR is candid that
Record's extra fold is unbenchmarked (~+0.9µs, +10 allocs per event) and runs undera.mu. On a hot path under a write lock that is worth a follow-up measurement, though a ceiling of 3 known agents bounds the blast radius. - The "side effect" paragraph is right that a scoped ring answer now carries per-agent latency,
PricedBy/UnpricedBy/IncompleteByand per-series currencies that nothing renders. Dead payload rather than wrong payload — but it does mean theagent=response shape now differs between ring and ledger windows in fields beyondgroup.
Areas reviewed: Go (core/cost/usage aggregator, core/sessionapi handler, agentop TUI), tests, docs, commit conventions
Commits: 2, both signed off ✅
CI status: all passing (25 pass, 1 skipped)
| // code, so nothing here is capped or evicted — and because nothing is evicted, a ring holds | ||
| // its agent's whole history and a narrowed total can never come up short. | ||
| // | ||
| // It can come up LONGER than the agent axis's row for the same agent, in one case: a minute |
There was a problem hiding this comment.
nit: "a ring holds its agent's whole history" overstates it — the ring is NumBuckets (360) minute buckets and laps, so it holds the agent's last six hours, not its whole history.
The conclusion the sentence is drawing still stands, though, and it's worth keeping: what matters for "a narrowed total can never come up short" is that nothing is evicted the way a session ring is, so the agent's share of any window the ring still covers is complete. Maybe "a ring is never evicted, so a narrowed total can never come up short for a window the ring still covers".
| does. The drawer drops its agent axis and breaks the agent's spend down by model or | ||
| endpoint in every window. It reads `BY NONE` under `Other`, and against an older proxy | ||
| that cannot break the last hour down for one agent. Unscoped, the sessions pane gains an `AGENT` column when | ||
| two agents are listed, and the agents pane a `SESSIONS` count once sessions name |
There was a problem hiding this comment.
nit: this reflowed line runs to about 110 columns against the paragraph's ~88. (Already on your deferred list — flagging it here just so the fix lands where the line is.)
esnible
left a comment
There was a problem hiding this comment.
Focused change, and the core reasoning is right: a bucket tallies each axis independently, so reading byAgent to narrow to one agent consumes the only axis left to break that agent's traffic down by. A dedicated per-agent ring is the correct fix rather than a workaround on the axis.
Things I verified rather than took on faith:
- The memory bound holds.
pipeline.IsKnownAgentmatches againstknownClients, a fixed map with three canonical values, soa.agentsis bounded at 3 rings (~330KB). Gating on the known set is the right call for the stated reason — an unrecognised label is a client-set header. - Nil-safety is fine.
AgentLabel->Label()returnsUnknownClientLabelfor a nil client, whichIsKnownAgentrejects, so header-less traffic gets no ring and there's no nil deref on the new path. Rekeyedlocking is correct. The new loop overa.agentsruns under the existinga.mu.Lock().- The
math.MaxInt->MaxSeriesInResponseswitch is not a regression.MaxIntexists on the legacy path only so the agent-axis lookup finds an agent past the cap before narrowing. The new path is a real serving surface grouped by model, so the 16-series response bound is the correct one there — that's the bound whose absence previously produced a 4.7MB response. - Tests pin the invariants that matter.
TestAgentSnapshot_TheAgentRingAgreesWithTheAgentAxispins the two-folds-of-one-stream property, and the idle-agent test correctly pins that the label — not whether a ring exists yet — decides the response shape, so an agent's first request doesn't flip it.
The (other)-vs-ring divergence called out in the agents field comment is real, and resolving it in the ring's favour is right.
No blocking issues. Three non-blocking notes inline; two of them you already listed under "Deferred from review", so they're just recorded here rather than new asks.
Author: huang195 (MEMBER — maintainer)
Areas reviewed: Go (core/cost/usage, core/sessionapi, cmd/agentop/tui), Docs
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes
CI status: passing (26 checks; Spellcheck skipped)
|
|
||
| // BEFORE the session ring, whose branch below returns early on both of its paths. See the | ||
| // agents field for why only a recognised agent gets a ring. | ||
| if agent := AgentLabel(e.Client); pipeline.IsKnownAgent(agent) { |
There was a problem hiding this comment.
suggestion — This fold is correctly placed above the session branch (both of its paths return early), but it also sits above the a.maxSess == 0 early return at line 1151. WithMaxSessions(0) is documented as "no per-session rings at all", and after this change that configuration still allocates up to 3 x ~110KB of agent rings.
That's intent/documentation drift rather than a bug — the bound is still fixed and small, and arguably agent rings should be independent of the session-ring budget. Worth either a line in WithMaxSessions saying agent rings are unaffected, or gating the fold on maxSess != 0 if the option is meant to mean "no extra rings".
|
|
||
| // BEFORE the session ring, whose branch below returns early on both of its paths. See the | ||
| // agents field for why only a recognised agent gets a ring. | ||
| if agent := AgentLabel(e.Client); pipeline.IsKnownAgent(agent) { |
There was a problem hiding this comment.
nit (already in your deferred list, recording for the follow-up) — AgentLabel(e.Client) is computed here and again in the byAgent fold at line 1407, so it runs twice per event under a.mu. Hoisting it once and passing it down would also give foldInto a single source for the label.
| // unrecognised agent's label is its raw User-Agent, set off-host, so a ring per label would | ||
| // let a caller grow this process by varying a header. The known names are a closed set in | ||
| // code, so nothing here is capped or evicted — and because nothing is evicted, a ring holds | ||
| // its agent's whole history and a narrowed total can never come up short. |
There was a problem hiding this comment.
nit (also in your deferred list) — "a ring holds its agent's whole history" overstates it: the ring is NumBuckets = 360 minutes and laps, so it holds the last 6 hours. The claim that matters — nothing is capped or evicted, so a narrowed total can't come up short — is true and worth keeping; it's just "whole history" that needs softening to something like "its agent's whole window".
Problem
With agentop scoped to one agent (
agent=claude-code), the spend drawer's LAST 1H span readBY NONEand showed "no model breakdown for one agent in LAST 1H", while TODAY / 7 DAYS / THIS MONTH readBY MODEL.The three named spans come from the cost ledger, whose rows carry (endpoint, model, agent), so filtering to an agent and then grouping by model works. LAST 1H comes from the in-memory ring, which tallies each axis separately (
byMethod,byEndpoint,byAgent, …). To narrow to one agent,AgentSnapshothad to readbyAgent, which leaves nothing to break that agent's traffic down by. So/v1/usage?agent=on a ring window was served withgroup: none.Change
core/cost/usage: the aggregator keeps a whole ring per recognised coding agent (pipeline.IsKnownAgent: claude-code, bob-shell, ibm-bob), next to the existing per-session rings.Recordfolds each such event into it.AgentSnapshottakes the requestedgroup, and for a recognised agent with nosession=it answers from that agent's ring, keeping the group.unknown, and session + agent are still narrowed from the agent axis and served asgroup: none.core/sessionapi:/v1/usagepassesgroupthrough; its doc comment says when it is kept.group=modelwithagent=and only shows its note when the server answersnone. README updated:BY NONEnow appears only underOtheror against an older proxy.Side effect: a scoped ring answer now also carries per-agent latency,
PricedBy/UnpricedBy/IncompleteByand per-series currencies, since it reads a full ring. Nothing renders these yet. The usage pane still narrows on its own side (group=agent) and is left for a follow-up.Tests
core/cost/usage/agent_snapshot_test.go:core/sessionapi/usage_agent_test.go:TestHandleUsage_AgentAndGroupCurrencyused to assert the ring servesgroup=currencyas none for one agent. It now asserts the ring splits Bob's spend by unit, matching the ledger.cmd/agentop/tui/agent_scope_test.go: a scoped drawer that the server breaks down showsBY MODELand the model row, with no note. This passes without a client change; I confirmed it fails withBY NONEwhen the server answers ungrouped.go vetandgofmtare clean;coreandcmd/agentoptests pass. One local exception:cmd/agentopcmd_exec_test.go:1128fails when the shell exportsSSL_CERT_FILE. It's a pre-existing isolation issue in that test and passes with the variable unset.Not yet verified against a live proxy, and the extra
foldIntoper recognised-agent event inRecordis not benchmarked.Deferred from review
Record: the extra fold for a recognised agent's event runs undera.muand is unbenchmarked (a reviewer measured about +0.9µs and +10 allocs per event);AgentLabelruns twice per event.Record: two comments still sayfoldIntoruns "up to twice" / "twice" per event; a recognised agent's event folds three times.Aggregator.agentsdoc: "a ring holds its agent's whole history" overstates it, since the ring covers 360 minutes and laps.Rekeyeddoc comment does not name the agent rings it now relabels.cmd/agentop/README.md:1236: one reflowed line is about 110 columns against the paragraph's ~88.Assisted-By: Claude (Anthropic AI) [email protected]
Summary by CodeRabbit