Skip to content

fix(accounting): book the cost of model calls that finish after the request - #2144

Merged
boazdavid merged 2 commits into
rossoctl:mainfrom
boazdavid:fix/2140-late-spend
Nov 26, 2026
Merged

boazdavid merged 2 commits into
rossoctl:mainfrom
boazdavid:fix/2140-late-spend

Conversation

@boazdavid

Copy link
Copy Markdown
Contributor

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

  1. Run seals the op list right before RequestEnd.
  2. appendOps dropped every op reported after the seal, and counted it in LateOpsDropped.
  3. A reproduction test, a plugin that reports a spend from a goroutine after Run returns, gave: spend ops at RequestEnd = 0, Report accepted = false, LateOpsDropped delta = 1.

What changed

  1. Pipeline: a new optional capability, pipeline.LateOpsAccountant. Before the seal, Run asks the accountant for a late handler. An op reported after the seal goes to that handler, with Call.Detached = true. With no handler, the op is dropped and counted, as before.
  2. accounting.Host: implements it. LateOps(pctx) keeps the session, thread, billing, upstream and client of the request. The handler books each late spend:
    • It runs accountant.ComputeStandalone, which reads and writes no ThreadState.
    • It prices the call at its own model, host and prompt size (CallUSDCurrency), as an in-request spend is priced.
    • It writes one cost event with Purpose: "detached-spend" and one SpendRecord, which keeps the ChangeID.
  3. Ledger and /v1/usage: a detached-spend record adds to pluginSpend* only. It adds nothing to requests, tokens, coverage, errors or latency. A refused or dry-run detached spend writes no row.
  4. Session store: AddDetachedSpend adds the cost to the session's plugin spend. It does not make the session active. cmd/cortex registers it through AddDetachedSpendListener.
  5. Metrics: Sink.ObserveDetached pushes the spend to llm.savings.*. It moves no llm.inference.* or llm.keepalive.* counter.
  6. Docs: docs/pricing.md and docs/context-guru-plugin.md.

The plugin's late_model_calls_dropped metric now counts only the calls that are really lost: no accountant, no session, or the host is closed.

How it was tested

  • 13 new tests:
    • pipeline: a late op goes to the handler with Detached set, and the caller's ModelCall is not changed. With no handler, the op is dropped and counted. TestRun_SealSplitsOpsExactlyOnce checks with -race that each op goes to RequestEnd or to the handler, never to both.
    • accounting: the record's spend equals CallUSD (19,500 micros). A call with zero usage is marked Refused and counts in no total. A rewrite op or a request with no session is not kept. After Close, nothing is kept. The pushed llm.savings.added.usd{kind="spend"} equals CallUSD.
    • cost/ledger, cost/usage, session: plugin spend only, no request, no session ring, no activity.
  • gofmt -l prints nothing. go vet ./... is clean in core and cmd/cortex.
  • go test -race passes in accounting, pipeline, session, plugins/contextguru, plugins/inferenceparser, plugins/sessionbudget. go test ./... passes in cmd/cortex.
  • Failures that this PR did not cause:
    • TestMidnightTransitions_* (cost/ledger), TestStartOfLocalDay_* and TestParseWindowSpec_* (cost/usage) also fail on a clean origin/main (311f7419). They depend on the time-zone data on the machine.
    • The DebugOff allocation tests in parse/* fail only under -race. They pass without it. This PR does not touch parse.

Open questions

  1. Billing. A detached call takes the billing of its request. This is the known limitation in accountant spec §9 ("the payer of a call is the payer of its request"). It is the same as for the call when it finishes inside the request. docs(wiring): describe how Cortex books a detached model call (W4.8 B) accountant#119 documents it.
  2. Dry-run spend. A late dry-run spend is recorded as Projected and adds to no total, the same rule as an in-request spend.

Technical notes

  • The seal and the handler are both set under opsMu. appendOps reads 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.
  • goObserve now returns false after Close. So the handler reports 0 kept, and the pipeline counts the op as dropped.
  • Detached is 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: ComputeStandalone prices a call by its own usage.
  • Not in this PR: pipeline.LateOpsDropped() is still not published as its own metric. The context-guru proxy still has no path for a late call (OpsEmitter is not built).

Assisted-By: Claude (Anthropic AI) noreply@anthropic.com

@boazdavid
boazdavid requested a review from a team as a code owner November 26, 2026 09:23
@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You'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.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 80ecbd1a-5b40-4834-b69d-7236e940209d
Commits

Reviewing files that changed from the base of the PR and between 333f52b and 36eaeae.

Files selected for processing: 23

  • cmd/cortex/main.go
  • core/accounting/detached.go
  • core/accounting/detached_test.go
  • core/accounting/host.go
  • core/accounting/metrics.go
  • core/accounting/ping.go
  • core/cost/event/event.go
  • core/cost/ledger/detached_test.go
  • core/cost/ledger/writer.go
  • core/cost/usage/detached_test.go
  • core/cost/usage/usage.go
  • core/pipeline/accounting.go
  • core/pipeline/context.go
  • core/pipeline/late_ops_test.go
  • core/pipeline/pipeline.go
  • core/plugins/contextguru/incoming_anthropic.go
  • core/plugins/contextguru/plugin.go
  • core/session/detached_test.go
  • core/session/history.go
  • core/session/store.go
  • core/session/summary.go
  • docs/context-guru-plugin.md
  • docs/pricing.md
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@github-actions github-actions Bot added the ready-for-ai-review Request automated AI code review from clawgenti label Nov 26, 2026

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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})

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Partly fixed in 36eaeae, with the reason below.

  • The library acmetrics.Sink has one method, Observe. It always adds 1 to llm.savings.requests, and to llm.savings.estimated when 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, in bookDetached, and in docs/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 clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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/contextguru and cmd/cortex build and tests — github.com/rossoctl/context-guru v0.7.9 is 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; the core packages 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{}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 36eaeae. Thank you, this was a real bug.

  • LateOps now gives each late spend with no ID an ID of its own (late-<n>) before ComputeStandalone. So the refusal finds the op, and a call of unknown usage is Refused and counts in no total.
  • TestLateOps_UnknownUsageIsRefused now sends an op with no ID, as cgModel and meteredDispatcher do. It checks that the spend is Refused and that the figures are zero.

Comment thread core/accounting/detached.go Outdated
if h.detachedListeners == nil {
h.detachedListeners = map[uint64]DetachedSpendListener{}
}
h.pingListenerSeq++

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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>

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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: lateOps now gives each no-ID spend an ID of its own (late-<n>, from a per-request counter) before ComputeStandalone, so a call of unknown usage is recorded as Refused and counts in no total. I checked this three ways. (1) TestLateOps_UnknownUsageIsRefused now sends a no-ID op, as cgModel/meteredDispatcher do. (2) Positive control: when I removed the ID assignment, that test failed with Refused: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's Operation values were not changed, because op is a loop copy. I deleted the probe afterwards.
  • llm.savings.requests/estimated: the counting is now documented in ObserveDetached, bookDetached and docs/pricing.md. The docs are accurate: a priced ping also reaches the library Observe through Host.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 ./... and go vet in core, and gofmt -l on the touched packages: all clean.
  • go test -race for accounting/..., pipeline, session, plugins/{contextguru,inferenceparser,sessionbudget} and cost/event: all pass.
  • go vet + go test for cmd/cortex: pass.

Failures that this PR did not cause, because they reproduce on base 333f52b1:

  • TestMidnightTransitions_* (cost/ledger), and TestStartOfLocalDay_* and TestParseWindowSpec_* (cost/usage): they depend on the machine's time-zone data.
  • TestWriteSession_FailedEraseKeepsNumbering (session/archive): it fails in this sandbox, which runs as root.

@boazdavid
boazdavid merged commit d1fb95a into rossoctl:main Nov 26, 2026
60 of 62 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 26, 2026
@boazdavid
boazdavid deleted the fix/2140-late-spend branch November 26, 2026 11:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

fix(accounting): book the cost of operator model calls that finish after the request

2 participants