Skip to content

Feat: Break one agent's last hour down by model - #1222

Merged
huang195 merged 2 commits into
rossoctl:mainfrom
huang195:feat/ring-agent-breakdown
Oct 1, 2026
Merged

huang195 merged 2 commits into
rossoctl:mainfrom
huang195:feat/ring-agent-breakdown

Conversation

@huang195

@huang195 huang195 commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

Problem

With agentop scoped to one agent (agent=claude-code), the spend drawer's LAST 1H span read BY NONE and showed "no model breakdown for one agent in LAST 1H", while TODAY / 7 DAYS / THIS MONTH read BY 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, AgentSnapshot had to read byAgent, which leaves nothing to break that agent's traffic down by. So /v1/usage?agent= on a ring window was served with group: 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. Record folds each such event into it. AgentSnapshot takes the requested group, and for a recognised agent with no session= it answers from that agent's ring, keeping the group.
  • Only known names get a ring. That's the memory bound: an unrecognised agent's label is its raw User-Agent, set by the client, so a ring per label would let a caller grow the process. The known set is fixed in code, so nothing is capped or evicted, and a narrowed total can never come up short because of an eviction. About 110KB preallocated per agent ring.
  • Unchanged: a raw User-Agent, unknown, and session + agent are still narrowed from the agent axis and served as group: none.
  • core/sessionapi: /v1/usage passes group through; its doc comment says when it is kept.
  • agentop: no code change. The drawer already sent group=model with agent= and only shows its note when the server answers none. README updated: BY NONE now appears only under Other or against an older proxy.

Side effect: a scoped ring answer now also carries per-agent latency, PricedBy / UnpricedBy / IncompleteBy and 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:
    • a recognised agent keeps its grouping, with only its own models;
    • an idle recognised agent keeps its grouping;
    • a raw User-Agent gets no ring and is served as none;
    • session + agent is served as none;
    • the agent ring's totals equal the agent axis's narrowing of the same traffic.
  • core/sessionapi/usage_agent_test.go: TestHandleUsage_AgentAndGroupCurrency used to assert the ring serves group=currency as 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 shows BY MODEL and the model row, with no note. This passes without a client change; I confirmed it fails with BY NONE when the server answers ungrouped.
  • go vet and gofmt are clean; core and cmd/agentop tests pass. One local exception: cmd/agentop cmd_exec_test.go:1128 fails when the shell exports SSL_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 foldInto per recognised-agent event in Record is not benchmarked.

Deferred from review

  • Record: the extra fold for a recognised agent's event runs under a.mu and is unbenchmarked (a reviewer measured about +0.9µs and +10 allocs per event); AgentLabel runs twice per event.
  • Record: two comments still say foldInto runs "up to twice" / "twice" per event; a recognised agent's event folds three times.
  • Aggregator.agents doc: "a ring holds its agent's whole history" overstates it, since the ring covers 360 minutes and laps.
  • Rekeyed doc 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

  • New Features
    • The spend drawer now breaks down an individual agent’s usage by model or endpoint across supported time windows.
    • Recognized agents can retain the selected grouping, such as currency, when viewing usage without a session filter.
  • Bug Fixes
    • The drawer now shows a “no breakdown” notice only for time windows the server cannot break down for that agent.

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]>
@coderabbitai

coderabbitai Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

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 configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 543dbbaf-71c3-4851-91c1-87b26949667e

📥 Commits

Reviewing files that changed from the base of the PR and between e703289 and a704825.

📒 Files selected for processing (9)
  • cmd/agentop/README.md
  • cmd/agentop/tui/agent_scope.go
  • cmd/agentop/tui/agent_scope_test.go
  • core/cost/usage/agent_snapshot_test.go
  • core/cost/usage/scope.go
  • core/cost/usage/snapshot.go
  • core/cost/usage/usage.go
  • core/sessionapi/usage.go
  • core/sessionapi/usage_agent_test.go

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

Recognized 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.

Changes

Agent usage breakdowns

Layer / File(s) Summary
Record recognized-agent usage
core/cost/usage/usage.go
The aggregator initializes separate bucket rings for recognized agents and records matching events in those rings.
Select and serve agent snapshots
core/cost/usage/scope.go, core/cost/usage/snapshot.go, core/sessionapi/usage.go, core/cost/usage/agent_snapshot_test.go, core/sessionapi/usage_agent_test.go
Recognized agents without a session retain the requested group in ring-backed snapshots. Session-scoped and unrecognized-agent requests use the narrowed GroupAgent snapshot path. Tests cover grouping, totals, idle agents, unrecognized agents, and session-scoped requests.
Display agent breakdowns
cmd/agentop/tui/agent_scope.go, cmd/agentop/tui/agent_scope_test.go, cmd/agentop/README.md
The drawer test checks that a model breakdown appears for a scoped agent. The comment and documentation describe breakdown availability across windows.

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
Loading

Suggested reviewers: esnible

Merge Risk: ⚪ Minimal · up to a7048

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 Review

Security architecture risk: 🔵 Low · up to a7048

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
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • observed — A reachable HTTP caller can request recognized-agent breakdowns across sessions when no session filter is supplied. Cross-session agent totals were already available before this PR; the changed exposure is finer breakdowns within that existing telemetry scope, not a new authenticated identity scope.

Trust Boundaries and Controls

  • observed — Varying an unrecognized header cannot create arbitrary agent-ring keys: allocation requires exact membership in the code-defined recognized set. Each ring has 360 slots and reuses capped label maps. A supplied session prevents selection of the cross-session agent ring; this is filtering, not authorization.

Resilience and Maintainability Implications

  • inferred — The locked update sequence prevents concurrent readers from observing a partially updated agent ring. Repeated response events would still be counted repeatedly, as in the prior global and session paths; the inspected change does not add deduplication or establish an upstream at-most-once delivery contract.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 8 files. (1 skipped: 1…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: enabling model breakdown for a single agent during the last-hour usage window.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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. AgentLabel folds through pipeline.AgentName and is versionless, so IsKnownAgent(AgentLabel(...)) does match. Worth stating because IsKnownAgent's own doc warns it is "false for any label carrying a version" — had AgentLabel returned 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 Record placement 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 Rekeyed about them would leave stale pending: ids visible under agent=<known>&group=session, and the test asserts both directions.
  • MaxSeriesInResponse vs math.MaxInt is not a regression. The new path's cap of 16 applies to series within one agent's ring, same as any normal Snapshot; the math.MaxInt in the fallback does a different job (finding the agent on the agent axis), and TestAgentSnapshot_FindsAnAgentPastTheSeriesCap still 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

  1. The PR is candid that Record's extra fold is unbenchmarked (~+0.9µs, +10 allocs per event) and runs under a.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.
  2. The "side effect" paragraph is right that a scoped ring answer now carries per-agent latency, PricedBy/UnpricedBy/IncompleteBy and per-series currencies that nothing renders. Dead payload rather than wrong payload — but it does mean the agent= response shape now differs between ring and ledger windows in fields beyond group.

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)

Comment thread core/cost/usage/usage.go
// 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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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".

Comment thread cmd/agentop/README.md
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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.IsKnownAgent matches against knownClients, a fixed map with three canonical values, so a.agents is 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() returns UnknownClientLabel for a nil client, which IsKnownAgent rejects, so header-less traffic gets no ring and there's no nil deref on the new path.
  • Rekeyed locking is correct. The new loop over a.agents runs under the existing a.mu.Lock().
  • The math.MaxInt -> MaxSeriesInResponse switch is not a regression. MaxInt exists 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_TheAgentRingAgreesWithTheAgentAxis pins 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)

Comment thread core/cost/usage/usage.go

// 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) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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".

Comment thread core/cost/usage/usage.go

// 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) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Comment thread core/cost/usage/usage.go
// 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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".

@huang195
huang195 merged commit 4ede0cc into rossoctl:main Oct 1, 2026
27 checks passed
@huang195
huang195 deleted the feat/ring-agent-breakdown branch October 1, 2026 18:14
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants