Repository navigation
fix(accounting): book the cost of model calls that finish after the request - #2144
Conversation
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 56 minutes. View limit details
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. |
clawgenti
left a comment
There was a problem hiding this comment.
Summary
The fix does what it says. A spend reported after the seal now goes to Host.LateOps, is priced with ComputeStandalone and spendRecord exactly like an in-request spend (same host fallback, same Refused/Projected rules), and lands as plugin spend only in the ledger, /v1/usage and the session store. It moves no request, token, coverage or latency figure, creates no session ring and does not change the active session. I checked the seal/handler hand-off under opsMu and the goObserve-after-Close path. Both are correct, and TestRun_SealSplitsOpsExactlyOnce passes under -race. The session-store merge in ListSessions and withPriorLocked matches the keep-alive pattern and does not double count.
One non-blocking metrics point is inline: each detached call is counted as a request in llm.savings.requests and llm.savings.estimated, and those two counters are the denominators of the unpriced and estimated ratio recording rules.
Author: boazdavid (CONTRIBUTOR association, admin repo permission, so a maintainer)
Areas reviewed: Go (pipeline, accounting, cost/ledger, cost/usage, session, contextguru), Docs
Agent/IDE config (.claude/.vscode): none
Commits: 1 commit, signed off: yes
CI status: all checks pass except Go CI (core peerproc, macOS), which is still pending. The core Go CI jobs have no failure annotations and no continue-on-error steps.
What I ran locally on the head commit: go build ./..., go vet on the touched packages, and go test -race for accounting, pipeline, session and plugins/contextguru. All pass. The TestMidnightTransitions_*, TestStartOfLocalDay_* and TestParseWindowSpec_* failures in cost/ledger and cost/usage also fail on the base commit 311f7419 on my machine, so this PR did not cause them. That matches what the PR description says.
| }() | ||
| s.pricer.request = binding{endpoint: endpoint} | ||
| s.pricer.byModel = bindingsFor(meta.Model, s.pricer.request, res) | ||
| s.sink.Observe(acmetrics.Observation{Meta: meta, Result: res}) |
There was a problem hiding this comment.
suggestion: acmetrics.Sink.Observe ends with s.requests.Add(ctx, 1, result=...), and it also adds to llm.savings.estimated when the billing is not API or the rate is a fallback. So each detached call counts as one more llm.savings.requests. I confirmed this with a probe: after one ObserveDetached on API billing, llm.savings.requests = 1 and llm.savings.estimated = 1, and both go up again on a subscription call. A refused detached call (zero usage) also counts as result="unpriced" plus one llm.savings.unpriced.
Those counters are the denominators of proxy:llm_savings_unpriced_ratio:rate5m and proxy:llm_savings_estimated_ratio:rate5m (deploy/central/base/prometheus/rules/recording.yml) and of the estimated-share panels on the savings and machines dashboards. A summarizer that often finishes late therefore moves those ratios, while the ledger and /v1/usage count no request for the same call. Keep-alive pings avoid this because they go through CountPing rather than Observe.
If the upstream sink can't skip the request count, you could document that llm.savings.requests includes detached calls. Otherwise, you could book the spend tiers directly, as CountPing does. It would also help to assert the chosen behaviour in TestSink_ObserveDetachedBooksOnlyTheSpend, which currently checks only the llm.inference.* and llm.keepalive.* counters. Not blocking.
There was a problem hiding this comment.
Partly fixed in 36eaeae, with the reason below.
- The library
acmetrics.Sinkhas one method,Observe. It always adds 1 tollm.savings.requests, and tollm.savings.estimatedwhen the figure is estimated. Cortex cannot skip that for one call without a change to the accountant library and a new release. - A priced keep-alive ping already counts there the same way. So this PR follows the rule that exists.
- 36eaeae documents it in
Sink.ObserveDetached, inbookDetached, and indocs/pricing.md: the two counters count each result the sink sees, so they can be a little higher than the number of agent requests. - To skip it, the library needs a standalone flag on
Observation. That is a separate accountant change.
clawgenti
left a comment
There was a problem hiding this comment.
Summary
Follow-up to review 6071677978 at this same head (93df6203), which a concurrent run of this program posted a couple of minutes into mine: I re-reviewed independently and have not repeated its point about llm.savings.requests/estimated. I found two things of my own, both below the must-fix line: one suggestion, where the Refused flag never fires for the op shape the producers actually emit (probe inline), and one nit on the listener id counter.
What I verified on head: go test on core/accounting, core/pipeline, core/session, core/cost/event and the Detached tests in core/cost/{ledger,usage}; go test -race on pipeline, accounting and session; and a positive control — sealing with a nil handler (pctx.sealOps(nil)) fails TestRun_LateSpendGoesToTheLateHandler with late handler got 0 ops, want 1, so the new test does catch the behaviour it claims. The line was restored afterwards, and the probe I cite below was deleted. The PR's central claim holds in every surface I could run: a late call lands as plugin spend in the ledger, /v1/usage and the session store, and moves no request, token, coverage or latency figure.
Author: boazdavid (CONTRIBUTOR — returning external)
Areas reviewed: Go (pipeline, accounting, cost/ledger, cost/usage, cost/event, session, session store, contextguru wiring, cmd/cortex), Docs
Agent/IDE config (.claude/.vscode): none
Commits: 1 commit, all signed-off: yes
CI status: passing at this head (Go CI, CodeQL, Bandit, Dependency Review, Hadolint, DCO; CodeRabbit skipped)
Not checked:
core/plugins/contextguruandcmd/cortexbuild and tests —github.com/rossoctl/context-guru v0.7.9is not in this sandbox's module cache and the module proxy is unreachable from here, so the end-to-end detached-call path could not be run; thecorepackages this PR changes were built and tested.- head-vs-base differential probe — not run; the mutation above is the positive control instead.
Generated by repoman github-pr-review@af425c8.
| Version: 1, RequestID: d.requestID, Session: d.session, Thread: accountant.Thread{ID: d.thread}, | ||
| At: at, Billing: d.billing, Ops: ops, | ||
| }) | ||
| refused := map[string]bool{} |
There was a problem hiding this comment.
suggestion: Refused never fires for the spend-op shape the producers actually emit.
refused is keyed by Unpriced.OpID, which the library copies from Operation.ID, and both producers of a spend op leave ID empty: cgModel.spend (core/plugins/contextguru/plugin.go:210) and meteredDispatcher.Do (core/plugins/contextguru/incoming_anthropic.go:215). The new test passes only because it sets ID: "op1".
Probe (a throwaway test in core/accounting, deleted afterwards): h.LateOps(detachedPctx()) with accountant.Operation{Kind: accountant.KindSpend, Operator: "context-guru", Call: &accountant.ModelCall{Model: "claude-haiku-4-5", Detached: true}} — zero usage, no ID — records Refused:false USD:0; the identical op with ID:"op1" records Refused:true. So a call whose cost is unknown is published as a known $0.00 spend, which is the case the PR body says is covered ("A call with zero usage is marked Refused and counts in no total").
No total moves either way — Figures() stays zero, so the ledger's !avoidedCost guard and /v1/usage's avoided.IsZero() guard both drop the record — so this is a wrong flag on the record, not a wrong figure.
Suggested fix: match by position rather than by id (ComputeStandalone appends one res.Ops entry per input op, in order), or have stampOps assign op.ID when it is empty. The same helper would fix the identical id-keyed map on the in-request path at core/accounting/savings.go:159.
There was a problem hiding this comment.
Fixed in 36eaeae. Thank you, this was a real bug.
LateOpsnow gives each late spend with no ID an ID of its own (late-<n>) beforeComputeStandalone. So the refusal finds the op, and a call of unknown usage isRefusedand counts in no total.TestLateOps_UnknownUsageIsRefusednow sends an op with no ID, ascgModelandmeteredDispatcherdo. It checks that the spend isRefusedand that the figures are zero.
| if h.detachedListeners == nil { | ||
| h.detachedListeners = map[uint64]DetachedSpendListener{} | ||
| } | ||
| h.pingListenerSeq++ |
There was a problem hiding this comment.
nit: AddDetachedSpendListener takes its id from h.pingListenerSeq, so one counter now numbers two maps and ping-listener ids skip whenever a detached listener registers. Harmless, since the maps are separate and the field comment says as much, but a listenerSeq name (or a counter per map) would save the next reader the double-take.
There was a problem hiding this comment.
Fixed in 36eaeae. The counter is now listenerSeq, with a comment: it gives the ids of both listener maps, and an id is only compared inside its own map.
…equest A model call that an engine detaches from its request (a background summarizer) used to report its spend after the op list was sealed. The pipeline dropped it, so the net saving left out its cost. - pipeline: a new optional LateOpsAccountant capability. Run asks it for a handler before the seal. An op reported after the seal goes to the handler with Call.Detached set, or is dropped and counted as before. - accounting.Host implements it. It books each late spend with ComputeStandalone as one cost event with Purpose detached-spend, priced at the call's own model and prompt size (CallUSDCurrency). - ledger and /v1/usage book that event as plugin spend only: no request, token, coverage or latency figure. - session.Store adds it to the session's plugin spend (a listener, as for keep-alive pings). Sink.ObserveDetached pushes it to llm.savings.* and to no llm.inference.* or llm.keepalive.* counter. Fixes rossoctl#2140 Assisted-By: Claude (Anthropic AI) <noreply@anthropic.com> Signed-off-by: DAVID BOAZ <DAVIDBO@il.ibm.com>
Review on rossoctl#2144. - cgModel and meteredDispatcher send a spend op with no ID, and ComputeStandalone names a refused op by its ID. So a late call of unknown usage was booked as a known $0. LateOps now gives each late spend with no ID an ID of its own. The test uses an op with no ID. - Say that a detached call adds 1 to llm.savings.requests, as a priced keep-alive ping does. The library sink has no way to skip it. - One listener id counter, named listenerSeq, for both listener maps. Assisted-By: Claude (Anthropic AI) <noreply@anthropic.com> Signed-off-by: DAVID BOAZ <DAVIDBO@il.ibm.com>
93df620 to
36eaeae
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
Re-review at 36eaeaef (rebased onto 333f52b1, plus the fix-up commit). The three points from the earlier reviews are resolved:
- Refused late spends:
lateOpsnow gives each no-ID spend an ID of its own (late-<n>, from a per-request counter) beforeComputeStandalone, so a call of unknown usage is recorded asRefusedand counts in no total. I checked this three ways. (1)TestLateOps_UnknownUsageIsRefusednow sends a no-ID op, ascgModel/meteredDispatcherdo. (2) Positive control: when I removed the ID assignment, that test failed withRefused:false. (3) A throwaway probe sent a no-ID batch with one priced call and one zero-usage call, then a second no-ID batch from the same request. The results were 19,500 micros counted; refused/uncounted; refused/uncounted. The three event IDs were distinct, and the caller'sOperationvalues were not changed, becauseopis a loop copy. I deleted the probe afterwards. llm.savings.requests/estimated: the counting is now documented inObserveDetached,bookDetachedanddocs/pricing.md. The docs are accurate: a priced ping also reaches the libraryObservethroughHost.observe(ping.go:148), so the library sink cannot skip this without a library change.listenerSeq: renamed, with a comment.
The rebase onto #2147 does not touch the detached path. Figure/savingsBilled change only the in-request saving dollars, and detached spends are still priced by spendRecord + CallUSDCurrency.
A follow-up worth filing (not this PR): the in-request path still matches Unpriced.OpID against op IDs that the same producers leave empty, in savings.go:208 and bindingsFor in metrics.go:456. So an in-request zero-usage spend is likely still marked as a known $0 instead of Refused. That code is unchanged on main, and I did not probe it.
Author: boazdavid (CONTRIBUTOR association, admin repo permission, so a maintainer)
Areas reviewed: Go (accounting, pipeline, session, cost/event, cost/ledger, cost/usage, contextguru wiring, cmd/cortex), Docs
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes
CI status: passing, except two jobs. Go CI (core peerproc, macOS) was cancelled when it hit the job's 10-minute limit in step 8 (Build and test cmd/cortex (local profile)). Steps 1-7 passed. The same job was also cancelled on the previous head 93df6203 and on base 333f52b1, so this PR did not cause it. Go CI (authbridge agentop) was still pending. Go CI (core) has no annotations.
What I ran locally at this head:
go build ./...andgo vetincore, andgofmt -lon the touched packages: all clean.go test -raceforaccounting/...,pipeline,session,plugins/{contextguru,inferenceparser,sessionbudget}andcost/event: all pass.go vet+go testforcmd/cortex: pass.
Failures that this PR did not cause, because they reproduce on base 333f52b1:
TestMidnightTransitions_*(cost/ledger), andTestStartOfLocalDay_*andTestParseWindowSpec_*(cost/usage): they depend on the machine's time-zone data.TestWriteSession_FailedEraseKeepsNumbering(session/archive): it fails in this sandbox, which runs as root.
Summary
Cortex dropped the cost of a model call that finishes after its request is accounted, such as a background summarizer. Effect: the net saving was too high by that cost. Now Cortex books each such call as plugin spend.
Fixes #2140.
What we found
Runseals the op list right beforeRequestEnd.appendOpsdropped every op reported after the seal, and counted it inLateOpsDropped.Runreturns, gave:spend ops at RequestEnd = 0, Report accepted = false, LateOpsDropped delta = 1.What changed
pipeline.LateOpsAccountant. Before the seal,Runasks the accountant for a late handler. An op reported after the seal goes to that handler, withCall.Detached = true. With no handler, the op is dropped and counted, as before.accounting.Host: implements it.LateOps(pctx)keeps the session, thread, billing, upstream and client of the request. The handler books each late spend:accountant.ComputeStandalone, which reads and writes noThreadState.CallUSDCurrency), as an in-request spend is priced.Purpose: "detached-spend"and oneSpendRecord, which keeps theChangeID./v1/usage: adetached-spendrecord adds topluginSpend*only. It adds nothing torequests, tokens, coverage, errors or latency. A refused or dry-run detached spend writes no row.AddDetachedSpendadds the cost to the session's plugin spend. It does not make the session active.cmd/cortexregisters it throughAddDetachedSpendListener.Sink.ObserveDetachedpushes the spend tollm.savings.*. It moves nollm.inference.*orllm.keepalive.*counter.docs/pricing.mdanddocs/context-guru-plugin.md.The plugin's
late_model_calls_droppedmetric now counts only the calls that are really lost: no accountant, no session, or the host is closed.How it was tested
pipeline: a late op goes to the handler withDetachedset, and the caller'sModelCallis not changed. With no handler, the op is dropped and counted.TestRun_SealSplitsOpsExactlyOncechecks with-racethat each op goes toRequestEndor to the handler, never to both.accounting: the record's spend equalsCallUSD(19,500 micros). A call with zero usage is markedRefusedand counts in no total. A rewrite op or a request with no session is not kept. AfterClose, nothing is kept. The pushedllm.savings.added.usd{kind="spend"}equalsCallUSD.cost/ledger,cost/usage,session: plugin spend only, no request, no session ring, no activity.gofmt -lprints nothing.go vet ./...is clean incoreandcmd/cortex.go test -racepasses inaccounting,pipeline,session,plugins/contextguru,plugins/inferenceparser,plugins/sessionbudget.go test ./...passes incmd/cortex.TestMidnightTransitions_*(cost/ledger),TestStartOfLocalDay_*andTestParseWindowSpec_*(cost/usage) also fail on a cleanorigin/main(311f7419). They depend on the time-zone data on the machine.DebugOffallocation tests inparse/*fail only under-race. They pass without it. This PR does not touchparse.Open questions
Projectedand adds to no total, the same rule as an in-request spend.Technical notes
opsMu.appendOpsreads them under the same lock, then calls the handler with no lock held. The handler only starts a goroutine (goObserve), so it does not block the plugin.goObservenow returnsfalseafterClose. So the handler reports 0 kept, and the pipeline counts the op as dropped.Detachedis set for every op after the seal. The seal is before the request goes upstream, so this includes a call that finishes before the response. The price is the same:ComputeStandaloneprices a call by its own usage.pipeline.LateOpsDropped()is still not published as its own metric. The context-guru proxy still has no path for a late call (OpsEmitteris not built).Assisted-By: Claude (Anthropic AI) noreply@anthropic.com