Repository navigation
Conversation
Cortex hosts the accountant library to compute context savings with the same rules as the context-guru proxy, records them in the ledger, and pushes the llm.savings counters to the central collector. Accounting works without context-guru. Keep-alive from PR rossoctl#1412 comes in the same PR. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
core/accounting/wire, facts, skip.go and thread.go are the W6/W5.2 host obligations from accountant/docs/cortex-wiring.md, ported from the context-guru proxy's accParse and entryFacts: wire.Parse splits an inference body into the sections and breakpoints accountant.NewBody wants; facts.Classify and facts.For give a provider's cache facts; SkipReason says when not to call Compute; ThreadOf gives the default accountant.Thread. No caller wires these in yet (task 2+). cases_test.go plays every github.com/rossoctl/accountant/test/cases case through the library and compares to Expected, the way the library's own case runner does; all 160 pass with no entries needed in the new docs/accounting-differences.json. boundary_test.go pins that core/accounting never depends on context-guru. core/go.mod now requires accountant v0.2.0 directly; cmd/cortex and cmd/cortex-envoy pick up the same version indirectly via go mod tidy. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…y test
Review round 1 on the accountant host code:
- facts.For now matches the context-guru proxy's entryFacts exactly
(G6): it sets only TTL and Lifetime, never MinCacheable or
Provider.{ReadGranularity,TTLs}, which the proxy's own entryFacts
never sets either. The Anthropic 1h rule is now "every raw
cache_control mark asks 1h" (apply.AllBreakpointsAskExtendedTTL),
not "any merged breakpoint does" — a position can merge a 5m and a
1h mark into one Breakpoint{TTL:"1h"}, which would read wrongly
under the old rule. This needed information the merged
[]accountant.Breakpoint slice cannot carry, so For's signature
changes to take an allMarksAsk1h bool (from the new
wire.AllMarksAsk1h) instead of the breakpoints slice. OpenAI now
gets the proxy's model-aware gate too: GPT-5.6+ is
LifetimeMinimum/30m (modelinfo.OpenAI30MinuteCache), everything else
stays LifetimeUnknown/5m.
- wire.Parse's section detection now matches the proxy's accScan and
responsesSections verbatim: it reads the body's own shape (does it
have a messages array, or an input array/string instead) rather
than branching on the Format argument, prefers an explicit system
field over instructions when a body has both, and reads a body
shaped like Responses the same way regardless of which Format the
caller passed.
- facts.Classify no longer falls back to a host-substring guess; an
unrecognized path is ProviderUnknown even on a host named
"anthropic" or "openai", matching the proxy's path-only rule.
- boundary_test.go is now an allowlist (stdlib, accountant, OTel,
core/..., tidwall) rather than a context-guru denylist, so an
unreviewed dependency of any kind fails loudly.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
… changes Add the pipeline surface for the accountant: pctx.ReportOps, the client body, a thread override, and a RequestStart/RequestEnd hook that Pipeline.Run calls when it is built WithAccountant. RequestEnd is not called on a Reject or a cancel. core/accounting gains Host, one per process and shared by every pipeline a reload builds. RequestEnd parses both bodies and opens and ends the library record on a goroutine of its own. Compute waits at most 2s, runs under recover, and is latched per request. The Tracker state is saved as a snapshot on a local install, and a snapshot older than 1h is refused. The top-level accounting.enabled (auto | true | false) decides whether the Host is built. auto turns it on when the outbound chain has context-guru or tool-prune. A reload that changes the resolved answer is refused, as for mtls.*. tool-prune reports one rewrite op per removed tool, with a ChangeID that is stable across turns. inference-parser asks the Host for the Result once and logs it at DEBUG. No figure is written yet. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…the accountant Switches the plugin from apply.BodyWithModel to apply.BodyOpts so Result.Trace reaches it, then: - reports the engine's own context operations (res.Trace.Ops) to the accountant via pctx.ReportOps, which stamps DryRun under on_error: observe; - names the request's accounting thread from res.Trace.Thread, falling back to core/accounting.ThreadOf's "main" default when the engine resolved none (no Opts.ThreadOf is wired yet, so this is currently always the fallback); - wraps cgModel so each in-request call through the plugin's static or reconstructed-incoming model reports a KindSpend op with the call's billed usage, via a pctx captured at call time (the static model is a template shared across requests; OnRequest copies it per request). Ports ChatUsage/PromptTokenDetails/CachedTokens (and their test) from PR rossoctl#1412 on feat/contextguru-keepalive into core/llmclient so cgModel can read a call's token usage off the response. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…y basis The user chose BillingFrom in the accountant library and the full recording of accountant design 7.1: a basis on each saving, usage-limit units for subscription savings, and money totals that count only usd. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
… spend test Review fix round 1 on the context-guru accounting commit: - Extract OnRequest's accounting side into reportResult(pctx, res) so it is testable against a hand-built apply.Result without re-running the engine (a second apply.BodyOpts call would observe already-mutated store state). Add TestReportResult_ForwardsOpsUnchanged, which deep-equals pctx.ReportedOps() against two hand-built ops with distinct Kind/ChangeID/At/Spans/SizeBefore/ SizeAfter, and checks SizeBefore.Bytes > SizeAfter.Bytes on the rewrite op. Tighten the existing end-to-end TestPlugin_ReportsEngineOps to an exact op count and the same size check, instead of only a non-empty check. - Assert op.Operator == "context-guru" in TestPlugin_ModelCallIsSpendOp. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…type RequestStart now reads the client's x-api-key / Authorization header, before any plugin (token-exchange) can rewrite it, and stores the accountant.Billing it implies via accountant.BillingFrom (design §5.7, accountant branch feat/billing-from). RequestEnd uses that mode for RequestMeta.Billing instead of the Task 2 BillingAPI placeholder, and Host now keeps the last mode seen per (session, thread) via the new ThreadBilling method, for a later task's keep-alive pings. Only the resulting mode is ever stored; the header value itself is never kept, copied into an event, or logged. Adds a dev-only replace of github.com/rossoctl/accountant at the local billing-from worktree in every go.mod that requires it (core, cmd/cortex, cmd/cortex-envoy, cmd/agentop), to be dropped once accountant v0.3.0 is tagged. Adds a contract test that feeds accountant's own TestBillingFrom table through Host.RequestStart. Documents in accounting-differences.json that the standalone context-guru proxy still hard-codes BillingAPI. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
Host.threadBilling grew by one entry per (session, thread) pair for the life of the process. Bound it the same way accountant.Trackers bounds its own thread map (library internal/engine/state.go:47-114, maxThreads = 10000, trimmed to 9000 oldest-first): add threadBillingCap/threadBillingTrimTo, stamp each entry with lastSeen, and trim once setThreadBilling pushes the map over the cap. Also note in docs/accounting-differences.json's proxy.billing-mode-hardcoded entry that it should be removed once the context-guru proxy adopts accountant.BillingFrom. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
… the accountant Bring PR rossoctl#1412's keeper into the context-guru plugin (keepalive.go, dispatcher.go, windows.go, mask.go and their tests, build_test.go, the verify script), merged by hand into the current plugin.go. Its spend path (core/cost/spend, Deps.Costs, spend.LogRecorder, saving/unique/ spend.go and the 82cd72b pricer) is not taken. Each ping now goes through core/accounting: the plugin's pingEmitter converts the KeepAliveReport to an accountant.Ping (wiring W4.6) and calls the new Host.Ping. The host refuses a ping with no window, a non-2xx status or no usage, prices it with PingOps and ComputeStandalone under the thread's last billing mode, writes its spend to the cost recorders as a Source "keep-alive" record priced by settle.SettleInput (never through the session store), and keeps its PingFacts for the thread's next priced request, which credits the rescue under the ping's ChangeID. A manual ping keeps no facts. context-guru moves to v0.7.4-beta.1. Its rossoctl#776 rule (a plain ping after an Anthropic text turn) is why the substitute test's fixture now ends at a tool_result turn. Pings now carry the plugin's per-process sentinel, and their transport raises MaxIdleConnsPerHost. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…t's session Review round 1 of the keep-alive task. - A ping's cost record keeps Source and Provenance as settle set them and carries a new additive event.Event field, Purpose (event.PurposeKeepAlive). Overwriting Source lost how the cost was arrived at. The plugin doc now says the ledger and /v1/usage do not read Purpose yet and fold ping spend into the agent's rows. - cgSessions is bounded (10,000, trimmed by age to 9,000), the same pattern as the accountant host's per-thread maps. - A ping is accounted only under pctx.SessionID, the key Host.RequestEnd uses. A ping tracked under the caller's identity is only logged, not accounted with BillingUnknown and facts no request reads. - A test pins that two concurrent requests reading the same ping facts credit one rescue: the library's thread-state replace (R53) prices the second against the first. - The structural "no session store" guarantee is a comment, not an assertion that could not fail. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
Adds the 1h cache-write tier the pricing package's own doc used to call deliberately absent. TierCacheWrite1h addresses it through Rates.For (falls back to the 5m write rate) and the new Rates.CacheWrite1hRate, which derives 2x input for an Anthropic-shaped table with no explicit rate and marks a non-Anthropic fallback estimated. settle.modelledCost adds the delta for the 1h subset on top of CostByTier's existing 5m pricing, since Usage.CacheWrite1h is a subset of Usage.CacheWrite and folding it into the generic per-tier loop would double-bill it. Parses usage.cache_creation.ephemeral_1h_input_tokens into InferenceExtension.CacheWrite1hTokens (a subset of CacheWriteTokens), threaded through parsercommon.TokenUsage so every provider path shares one Fill. core/accounting's Host.Compute and Ping.recordPing (task 6's keep-alive path) now fill accountant.Usage.CacheWrite1h the same way, so a 1h ping write prices at the 1h rate too. Task 7 of 10, accountant-integration (2026-11-17). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…ng test TestPing_ConcurrentRequestsCreditOneRescue did not always create the race it tests: the second record could peek the ping facts after the first request was priced and had dropped them (2 of 15 runs). Both records now wait at a two-party barrier in factsHook, after the peek and before the record is ended, so neither can be priced until both have read the same facts. With the race forced, the library still credits one rescue, so the Host's peek-then-drop stays as it is. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
Fix round 1 for the 1h cache-write tier (task 7): the output-only half of SettleInput zeroed Input/CacheWrite/CacheRead but left CacheWrite1h set, so modelledCost's 1h-vs-5m delta landed a second time on a figure that carries no cache-write tokens at all. outputOnly now zeroes CacheWrite1h too. CacheWrite1hDeltaMicros now returns Rates.CacheWrite1hRate's own estimated alongside the delta, threaded through modelledCost's new estimated1h return and published on Settled via the existing Incomplete/ModelledIncomplete fields under a new ReasonCacheWrite1hRateEstimated, rather than a parallel field — spec: "price at the 5m rate and mark the figure estimated." PlausibleUsage now also refuses a negative CacheWrite1h, one past maxPlausibleTokens, or one exceeding CacheWrite itself — Usage.tokens() excludes CacheWrite1h (it is a subset, not a sibling tier), so none of those were checked before. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
Task 7 added InferenceExtension.CacheWrite1hTokens without updating the three guards that pin the extension's fields, so core/pipeline and core/sessionapi failed at 80ada88: the parsed-request field list, the session event golden file, the session-api.md field docs, and summarizeEvent's field count. The count is a token figure a row's cost is priced from, so it is timeline data and summarizeEvent keeps it; the test now asserts that. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…current figure
core/accounting gains the one pricing function of the accountant's figures
(USD, TierUSD: the process rate table at the request's endpoint, model and
prompt total, with the 1h cache-write tier and its estimated fallback) and
the conversion from an accountant.Result to one event.Saving per operator
(Savings, SavingsBilled, Host.Savings), following wiring W7.1: Saved priced
plus positive effects in USD, Caused plus each attributed break's net cost
plus the operator's own model calls in PenaltyUSD, a rescue to the keeper,
InBaseline effects skipped, unowned breaks in UnattributedBreakUSD. The
basis follows the client's billing mode (usd, subscriptionEquivalent,
unknown); a subscription saving is also valued in usage-limit units with
accounting.subscription_weights (defaults 1, 1.25, 2, 0.1, 5, each >= 0; a
reload that changes them is refused).
event.Saving gains PenaltyUSD, Operator, OpsVersion, Basis, Units and
PenaltyUnits, and event.Event gains UnattributedBreakUSD and Thread, all
omitempty and read by nothing yet. TotalAvoidedUSD is unchanged.
inference-parser now computes the accountant's savings beside
settle.Avoided's, still publishes the old figure, and logs each component
whose net figure differs by more than $0.000001 at INFO ("accounting:
shadow"), counted in two plugin metrics. Host.Savings also writes one DEBUG
"accounting: tokens" line per operator for the cross-host harness.
tool-prune reports the cache mark it moves from a pruned tool to the last
survivor as a rewrite in place of the survivor, so the library's sum check
holds and the request is priced.
The Cortex / context-guru proxy / control harness and the LiteLLM
integration test come from feat/contextguru-keepalive; P1 now compares the
accountant's tokens per operator with the proxy dashboard's per component.
docs/accounting-differences.json lists the expected shadow and cross-host
differences.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
Review round 1 of the accountant pricing and shadow commit. - The context-guru plugin reports the tools and system changes apply makes without an op (cachesplit, toolfilter, toolschema, headttl) by diffing its own input and output, ported from the proxy's envelopeOps, so those requests pass the library's sum check and are priced. - A spend op (an operator's model call) is no longer inside a Saving: it is one event.SpendRecord in Extras.Spends and the new Event.Spends field, priced with its output and at its own prompt size. - An operator's dry-run ops make their own projected saving instead of adding to its applied figure. - The shadow logs operators only the accountant prices at DEBUG and counts them apart, so the INFO line and "differed" mean a real difference. - Every differences entry names its section; UnattributedBreakUSD's doc says it holds every unowned effect. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…and agentop The cost record's savings are now the accountant's figure, end to end. The shadow comparison and the old tool-prune pricing are gone. - inference-parser publishes Host.Savings as event.Event.Avoided, with the request's Thread, UnattributedBreakUSD and Spends. A spend alone publishes a record. The shadow log lines and their three plugin metrics are removed. Host.Savings sets each saving's Provenance from the rate table. - Money totals count only basis "usd": TotalAvoidedUSD (gross, not floored) and the new TotalPenaltyUSD/TotalPenaltyMicros. event.Event.Figures splits a record by basis for every aggregate. - usage.Counts, ledger rows, /v1/usage and the sessions list gain penaltyMicros, avoidedUnits, penaltyUnits (milli-units), avoidedApiEquivalentMicros, avoidedUnknownMicros, pluginSpendMicros, pluginSpendUnits, pluginSpendUnknownMicros, and (ledger, /v1/usage) keepAliveMicros and keepAlivePings. Plugin spend is kept out of costMicros. A keep-alive ping counts in no request, token, cost, coverage or latency figure. Old ledger rows read the new fields as 0. - agentop: the events table sums every operator's saving net of its penalty, not floored (rowSavingFor, from rossoctl#1412). The sessions SAVED column is the net and may be negative. `agentop cost` and the spend drawer show saved, penalty and net, usage-limit units with their API equivalent, unknown billing apart, plugin model calls and keep-alive. - Deleted: core/cost/settle/avoided.go, settle/decode.go, core/cost/pricing/estimate.go (EstimateTokensFromBytes, AvoidedUsage) and their tests. tool-prune's event keeps its fields; its pane counts dollars only for a usd saving. - docs/accounting-differences.json: the envelope-op tool indexes after tool-prune, multi-round requests, accounting off and legacy savings with no basis; the shadow entries now describe the switch. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…s, add UNITS Review round 1 of the switch to the accountant figure. - An empty Saving.Basis is usd (Saving.EffectiveBasis): settle.Avoided's savings were dollars and the ledger counts them, so the replayed ring, the archive re-fold and agentop now count them too. - The accountant is not asked when settle refused the token report, and Host.Compute refuses counts that fail pricing.PlausibleUsage, as the old saving did. - agentop's sessions table gains an optional UNITS column after SAVED for usage-limit savings; its full text carries the API equivalent. - A keep-alive ping creates and refreshes no per-session usage ring. - The context-guru plugin's model calls never use HTTPS_PROXY, so a call cannot loop back through Cortex and count as both agent and plugin spend. - The window's unit for every accountant line, CurrenciesIn counts the API equivalent, the dead SavedUSD fields are gone, and comments, the integration script and CLAUDE.md are brought up to date. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
The accountant host now hands each computed request's Result (once, as Compute is latched) and each keep-alive ping's standalone Result (empty RequestID) to accountant/metrics, off the request goroutine and under a recover. The pricer is bound to one request under Sink.mu and prices through accounting.USD, so the pushed llm.savings.saved.usd equals the ledger's saving to the micro. core/accounting/push builds the OTel MeterProvider: OTLP/HTTP to <url>/v1/metrics, cumulative, Authorization: Bearer <token>, resource service.instance.id (~/.cortex/machine-id on a local install, per process in a cluster), service.version and service.name=cortex. A failed export increments llm.proxy.export_failures and WARNs at most once a minute; it never reaches a request. Config: a top-level metrics_push block (enabled, url, token, interval; METRICS_PUSH* env overrides). No default URL, so nothing is sent until a user sets one. https only, except loopback. A reload that changes it is refused. Docs cover metrics_push and accounting, including subscription_weights. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…tials out of logs Review round 1 of the metrics push: - The sink binds each model the library prices to its own endpoint and prompt total: the request's model to the request's, each spend's call model to the call's host and own prompt size (CallUSD, now shared with Host.Savings). Pushed spend dollars equal the ledger's spends[] to the micro. A model collision falls back to the request's binding; documented and tested. - SafeURL strips user info, query and fragment from metrics_push.url wherever it reaches an error, a log or the exporter's endpoint. - The export-failure counter is an atomic pointer: the periodic reader can export before Start stores it (a race the new test found). - Tests that subscription and unknown billing move tokens, never USD. - Docs: the exact pricing binding and the four remaining differences (CostUSD, collisions, dry-run/refused spends, cache-effect attribution); where a bad block is caught (config.Load) and where the env is (a WARN, no push). cortex-envoy's version gap is documented in a comment. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
Review round 2: the ledger summed every operator model call into PluginSpendMicros/Units/UnknownMicros, including a dry run's (an operator under on_error: observe) and one the accountant refused to price. The metrics sink books neither (accountant R12; metrics.md rules 1 and 3), so the two outputs disagreed. SpendRecord gains Projected (op.DryRun) and Refused (op listed in Result.Unpriced), both omitempty. SavingsBilled sets them and keeps the records visible in Event.Spends; Event.Figures leaves them out of every spend total (SpendRecord.Counted). The wire pin test covers the two new keys. pricing.md drops this from the remaining-differences list and says why both outputs exclude them. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…oroutine context-guru calls Model.Complete concurrently (six goroutines in its extract stage) and after OnRequest returns (summarize_async, cache_aware_async), and cgModel reported through pctx.ReportOps, which appended to an unguarded slice and read the plugin being dispatched. - pipeline.Context guards its op list with a mutex. ReportOpsAs records ops with an operator and dry-run state the caller captured, and reads no dispatch state. Run seals the list right before RequestEnd; an op reported after that is dropped, logged at DEBUG and counted (LateOpsDropped). - cgModel captures the plugin's observe state when OnRequest builds it and reports as context-guru through ReportOpsAs. A late call is also counted in the plugin's late_model_calls_dropped metric. - Host.Compute releases the request's handle on a timeout, as on every other no-figure path. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…asis Every ping was priced into KeepAliveMicros whatever the credential, while the metrics sink moved no dollars for a subscription or unknown login, so the ledger and the push disagreed and API-equivalent dollars reached a money total. - A ping's cost record carries the basis of Host.ThreadBilling (usd, subscriptionEquivalent, unknown), Estimated on every non-usd basis, and on a subscription its usage-limit units from the configured weights, output included. - event.Figures splits a ping's spend like a plugin's: KeepAliveMicros (usd only), KeepAliveUnits (milli-units), KeepAliveAPIEquivalentMicros (not money) and KeepAliveUnknownMicros. KeepAlivePings counts every ping. The ledger, the usage ring and /v1/usage book them through it; agentop's keep-alive line shows each part. - The ledger's keep-alive branch adds the record's figures once, after the branch decision, instead of twice. - docs: the keep-alive spend paragraph and the plugin's schema text now say what the ledger does; pricing.md has the split and the spend formula, and says budgets see neither plugin nor keep-alive spend. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…nstall Two defaults were right for a laptop and wrong for a pod. - context_window.model_info defaulted to litellm everywhere, so every pod fetched the LiteLLM model map from the public internet on its first gated request and again per hot reload. It now defaults to litellm only on a local install and to off elsewhere; an explicit model_info always wins, and a model_info_url with model_info unset turns the map on. - The plugin's model calls and keep-alive pings pinned Proxy: nil. On a laptop HTTPS_PROXY points at Cortex itself, so the pin stops a double count; in a cluster it is the egress proxy, and ignoring it breaks calls where egress is mandatory. The pin now applies only on a local install; elsewhere the clients keep ProxyFromEnvironment. The ping client's pin came from PR rossoctl#1412 and gets the same rule. The plugin learns the install through plugins.LocalInstallConsumer. - docs: the model_info default, and a section on where the plugin's own calls go, with the caveat for a pod whose HTTPS_PROXY is its own sidecar. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…t an erase keeps - MetricsPushConfig.Validate refuses a URL with user info or a query string, which the exporter drops on the way out (the collector then answers 401). The error quotes only SafeURL and points to token. In the file it fails startup; in METRICS_PUSH_URL it WARNs and turns the push off, as any refused METRICS_PUSH_URL does. - docs/accounting-differences.json: threadBilling and pingFacts are not in the snapshot, so the first ping after a restart is BillingUnknown and a pending rescue is lost. - CLAUDE.md, docs/session-api.md and docs/laptop-service.md: neither DELETE route clears the accountant's per-session state, what that state holds, and how it ages out. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
boazdavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (claude, user of @boazdavid) | Claude Code 2.1.241 | offload-review skill, @boazdavid's session | fresh | 1 of 2 | 1 of 2 | 79024c3c1bbf |
blocking |
Verdict: blocking
Scope note: the base SHA in the review request (7821df67) is an old origin/main of the fork. Diffed against it, the PR shows 1,830 files, because most of that is main's own history. I reviewed the PR's own change: git diff 49aa57ac..79024c3c (the merge base with upstream/main). That is 203 files, +20,189 / −1,073, which matches the PR body.
Findings
-
core/cost/event/event.go:590-591 — a negative net "API equivalent" or "unknown" saving becomes 0, so these figures read too high
- What fails:
FigurescomputesequivSavedandunknownSavedas net figures (s.USD - s.PenaltyUSD, lines 564 and 568). The field docs say "May be negative" (event.goFigures; usage.goAvoidedUnknownMicros). But both go throughpricing.MicrosOrZero, andMicrosFromUSDreturns(0, false)for anyusd < 0(pricing/cost.go:166). Take a subscription request whose context-guru rewrite broke the cache:USD 0.10, PenaltyUSD 0.40. ItsAvoidedAPIEquivalentMicrosis 0, not −300,000. In a session with records +$0.50 and −$0.30 net, the session total is $0.50, not $0.20. The clamp is per record, before any sum, so every surface overstates the figure: the ledger,/v1/usage, the sessions list,agentop cost("API equivalent net"), and the sessions UNITS text. The units net on the same line (AvoidedUnits − PenaltyUnits) can go negative, so on one line the two figures disagree in sign. A subscription login is the normal laptop case (Claude Code OAuth), andxhighon by default makes penalties common. - Proof: event.go:564/568 subtract. Then cost.go:320
MicrosOrZero→ cost.go:166if usd < 0 { return 0, false }. No test covers a net below zero:TestFigures_SplitsByBasisuses only positive nets (2 − 1). - Fix: convert these two fields with a signed conversion (round
usd*1e6and keep the sign, with the same NaN/Inf/bound checks). Add aFigurestest with a negative net for both bases.figureSumandCounts.addIntoalready accept negatives (AddSat).
- What fails:
-
core/plugins/contextguru/incoming_anthropic.go:62-79 — a held caller credential is not released 2 h after its last use, and it can stay in memory with no time limit
- What fails:
credHolds.holdreleases expired holds only insidehold, so only when a later Anthropic request arrives. Nothing else (no timer, no sweep) callsReleaseexceptreleaseAllat Configure and Shutdown. So with the new default config, the last Claude Code credential stays held, masked, until the next gated Anthropic request or a restart or reload. On a laptop service that runs for days, that can be days.anthropicIncomingtakes the hold on every gated Anthropic request that carries a credential and a model, whether or not a component uses the incoming model (modelsFor, plugin.go:740). - Proof:
grep incomingHoldTTLfinds only the comparison at line 67. docs/context-guru-plugin.md:24 says the credential is "released 2 hours after its last use, on a config reload, or atShutdown". Also, docs/session-api.md:388 and docs/laptop-service.md:682 list the credential a DELETE leaves in memory as only the keeper's (about 13.5 minutes). They do not name this hold. With keep-alive off, which is the default, this hold is the only credential retention. - Fix: add a periodic sweep (for example from
Init, stopped inShutdown), or release on a timer for each hold. Then name this hold in the session-api.md and laptop-service.md lists of what an erase keeps.
- What fails:
-
core/plugins/contextguru/plugin.go:495 with incoming_anthropic.go:294 — the "received" body is keyed by session, so two concurrent main-role requests can stash one request's input beside another's output
- What fails:
p.pending.Store(sid, pctx.Body)keys by session id, andstashSenttakes it withLoadAndDelete(sid). Then it stores it aspreBodybeside this request'spctx.Bodyasforwarded. Claude Code sends one-shot completions (title, permission monitor) under the same session id, and these are not subagent-role (core/parse/inference/subagent.go:24-28). Interleaving: one-shot B starts (Store B). Main turn A starts (Store A, which overwrites B). B finishes first and gets A's body. The stash now holdspreBody = Aandforwarded = B. A finishes and finds nothing, so it does not stash.CoversSpannormalizespreBody(A), so the span check passes. ButAskappends the summarizer's question toforwarded(B, the one-shot). The summary can then describe the wrong body, andcache_aware_summarizersplices it into the main conversation. That is silent context loss, and it is now on by default. - Proof: plugin.go:492-496 (Store by
sid, gated only by!isSubagent); incoming_anthropic.go:293-304 (LoadAndDelete(sid),put(key, provider, pre, pctx.Body)); incoming_anthropic.go:275-286 (CoversSpan readspreBody); incoming_anthropic.go:312-318 (Ask readsforwarded). I traced this by reading the code. I did not run it, because live tests are not approved. - Fix: keep the received body on the request itself (
pipeline.SetState(pctx, …)), not in a map keyed by session, so OnFinish always pairs a request's own two bodies. Add a test that interleaves two requests on one session.
- What fails:
-
docs/pricing.md:718-719 and docs/context-guru-plugin.md:7-9 — two docs disagree with the code
- What fails: pricing.md says
avoidedApiEquivalentMicrosis "theusdof those same savings" andavoidedUnknownMicrosis "theusdof savings with basisunknown", which reads as gross. The code puts the net there (USD − PenaltyUSD, event.go:564/568), and the agentop line labels it "API equivalent net". context-guru-plugin.md still says the plugin is "Opt-in at build time (-tags include_plugin_contextguru)". This PR puts it in thelocal,fullandfullcpexprofiles and turns it on in the--localconfig, and that doc does not say so. - Proof: the lines cited. Compare scripts/profile-tags/profiles.go membership and cmd/cortex/local.go:349-358.
- Fix: say "net of their penalty" in both pricing.md rows (after finding 1, also say that it can be negative). In context-guru-plugin.md, say which profiles carry the plugin and that a local install runs it with
preset: xhighby default.
- What fails: pricing.md says
Non-blocking
- Observe mode still spends real money and reports none of it in any total. Under
on_error: observe,apply.BodyOptsstill gets the static and incoming models. Soxhigh's model-calling components make billed calls on the user's own credential. Those spends areProjectedand are left out of everypluginSpend*total (pricing.md documents this). The keep-alive code refuses to hold under observe for this exact reason ("a ping is real, billed spend — the opposite of a shadow run"). The engine's model calls do not follow the same rule. local.go:353 and plugin-catalog.md suggest observe "to measure without changing any bytes". Think about not passing models under observe, or say plainly in both places that observe still makes billed calls. - The inference-router interacts with the incoming model.
agentop server addputs the router after context-guru. So the incoming Anthropic hold is taken on the client's original host and credential (before the redirect andsetKey). But the stashedforwardedbody is the routed body that went to the other server. A prefix ask then sends the routed body (possibly with the routed model name) to the original host. Please check that this works, or turn off the prefix ask whenpctx.Redirected(). - Stale comments that say a reload which turns accounting off is refused: core/config/accounting.go:31-33 and cmd/cortex/main.go:544-547. The code accepts it (
validateAccounting). Also CLAUDE.md:299 says "Both blocks need a restart", but turningaccountingoff reloads (CLAUDE.md:314-316). - PR body, Dependencies: it says
modernc.org/sqliteis "ingo.sumonly" and is not linked. Since9d8ad9e0, core/plugins/contextguru/statedb.go imports_ "modernc.org/sqlite", and core/go.mod requires it directly. So thelocal,fullandfullcpexbinaries link it. The size figures in the body may also be out of date. - cmd/agentop/tui/sessions_pane.go:574: the comment says "API-equivalent dollars of the gross saving", but the field is net.
- scripts/dev/integration-contextguru-litellm.py:54: the default
LITELLM_BASEis an internal hostname (ete-litellm.ai-models.vpc.res.ibm.com) in a public repo. TheA1-ping-spendandA2INFO texts are out of date: pings now reach a cost recorder, and a PrefixAsker exists.--sharedrewrites the live~/.cortex/config.yaml. - scripts/dev/compare-contextguru-savings.py:40: the usage line shows
--keep, but argparse defines no--keep, so that command line fails. - Tests: three America/Havana DST tests fail in
core/cost/usage(and the PR sayscore/cost/ledgertoo). The PR says they fail onmaintoo. I did not check them onmain.
What I checked
- I read CLAUDE.md and core/plugins/CLAUDE.md. I read the design (§5.3, §5.3a, §5.4) and searched the plan for the reload and observe rules. I also read the accountant v0.4.0 docs I needed (spec R29, R25, R27; BillingFrom; the persist format for the snapshot trim).
- I read every production file in full: core/accounting/* (host, ping, savings, price, metrics, push, snapshot, snapshot_trim, skip, thread, options, wire, facts), core/pipeline/accounting.go, context.go, pipeline.go, core/plugins/deps.go, the whole contextguru plugin (plugin, incoming_anthropic, dispatcher, envelope, keepalive, ping, mask, modelclient, statedb, windows), toolprune, inferenceparser, config/accounting.go, validate.go, reloader.go, cost/event, pricing (rates, cost, inference, multiplier), settle, ledger writer and query, usage, session (figures, fold, history, store, summary), llmclient, parse/inference/anthropic.go, parsercommon, cmd/cortex (main, accounting, local), cmd/cortex-envoy/main.go, the Dockerfiles, build.yaml, profile-tags, and the agentop money, cost and tui changes.
- I read every changed doc: CLAUDE.md, architecture, configuration, context-guru-plugin, laptop-service, laptop-token-savings, plugin-catalog, pricing, proxy-contract, session-api, session-budget-plugin, tool-prune-plugin, accounting-differences.json. I read the shell harness in full and both Python harnesses.
- I read the test diffs that change existing tests (forwardproxy chainedwriters, settle bound_agreement, ledger admission, usage tests, litellm_budgettrack, session currencies) to check that no assertion was weakened without reason. I skimmed the new test files where they bear on a finding (event_test
TestFigures_SplitsByBasis). - Traces: the extproc response pctx is the request-body pctx, so the pending handle reaches Compute. The billing snapshot is taken before any plugin. Ops are sealed before RequestEnd. Resends do not re-run
Run.Redirectupdatespctx.Host, so keep-alive holds pair host and credential. Positions per operator are in the space of that operator's own input (R29). The 1h cache-write delta is added once, and it is zeroed on the output half. - I ran:
go veton core (with no tags and with thelocaltags), on cmd/cortex (local), on cmd/cortex-envoy (envoy) and on cmd/agentop. All are clean.go test: core accounting, pipeline, plugins, toolprune, inferenceparser, contextguru and all (withinclude_plugin_contextguru), cost (all but the Havana DST tests), session, sessionapi, reloader, config, parse and llmclient all pass. cmd/cortex (localtags) passes. cmd/agentop money and tui pass. I did not run the fullcmd/agentoproot package,go mod tidy -diff, or any live test.
Two independent reviewers (offload-review, round 1) found 3 blocking defects: - core/cost/event/event.go: AvoidedAPIEquivalentMicros and AvoidedUnknownMicros are net figures (saved minus penalty) but were converted with pricing.MicrosOrZero, which refuses any negative input. A request whose penalty exceeded its saving booked 0 instead of a negative net, overstating every total that includes it (the ledger, /v1/usage, the sessions list, agentop). Add pricing.SignedMicrosOrZero, which preserves the sign through the same NaN/Inf/bound guards, and use it for both fields. - core/plugins/contextguru/incoming_anthropic.go: an incoming-model credential hold past incomingHoldTTL was released only when a later matching request called hold() again. On an installation with no such later request, the masked credential stayed held for the life of the process. Add a holdSweepInterval (10m) ticker, started in Init and stopped (and waited on) in Shutdown, so a hold is released within one interval of its TTL regardless of traffic. - core/plugins/contextguru/plugin.go, incoming_anthropic.go: the body a request received was kept in a sync.Map keyed by session id, for OnFinish to stash beside the body that went upstream. Claude Code's one-shot calls (title, permission monitor) share the main turn's session id, so two requests in flight on one session could clobber each other's entry: OnFinish could then pair one request's received body with a DIFFERENT request's forwarded body, and the summarizer's prefix ask would splice the mismatched pair into the conversation. Keep the body on the request's own pctx (pipeline.SetState) instead, which is single-threaded per request, so the pairing is exact by construction. Also: docs/pricing.md and docs/context-guru-plugin.md described the two net figures as gross and the plugin as opt-in-at-build-time; both now match the code. cmd/agentop/tui/sessions_pane.go's stale "gross" comment is fixed too. The three DELETE /v1/sessions retention texts (CLAUDE.md, docs/laptop-service.md, docs/session-api.md) now name the incoming-model hold and the forwarded-body stash. Tests: TestFigures_NegativeNetIsNegative, TestSignedMicrosOrZero, TestStartSweepReleasesAlreadyExpiredHoldWithNoRequest, TestStopSweepWithoutStartIsANoop, TestInitStartsAndShutdownStopsTheHoldSweep, TestStashedBodyIsNotMixedUpBetweenOverlappingRequestsOnOneSession (the last confirmed to fail against the reverted old logic and pass with the fix). core/plugins/contextguru passes with -race. gofmt clean. Co-Authored-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
boazdavid
left a comment
There was a problem hiding this comment.
This replies to both reviewers' finding 1 (negative net savings floored to 0).
Fixed in c2c07ac.
AvoidedAPIEquivalentMicros and AvoidedUnknownMicros are net figures (saved
minus penalty). They went through pricing.MicrosOrZero, which refuses a
negative input by design (that helper is for a charge, which cannot be
negative). A penalty bigger than the saving floored to 0 instead of a
negative net.
Fix: a new pricing.SignedMicrosOrZero keeps the sign through the same
NaN/Inf/bound checks, and event.Figures now uses it for both fields.
Tests: TestFigures_NegativeNetIsNegative asserts -300000 for both fields on
reviewer 1's exact example (USD 0.10, PenaltyUSD 0.40). TestSignedMicrosOrZero
covers the boundary cases (negative zero, NaN, Inf, the MaxCostMicros bound).
Also fixed docs/pricing.md, which called these two columns gross.
boazdavid
left a comment
There was a problem hiding this comment.
This replies to both reviewers' finding 2 (held credential had no time-bound
release).
Fixed in c2c07ac.
An incoming-model credential hold past incomingHoldTTL (2h) was released
only when a later request on the same credential called hold() again. On a
quiet installation with no such request, the masked credential (and the
forwarded-body stash beside it) stayed held for the life of the process.
Fix: credHolds now runs a holdSweepInterval (10m) ticker, started in Init
and stopped (with a wait on its exit) in Shutdown. It releases every expired
hold on its own, whether or not a request arrives.
Tests: TestStartSweepReleasesAlreadyExpiredHoldWithNoRequest (an already-
expired hold is released within 2s of startSweep, with zero requests).
TestStopSweepWithoutStartIsANoop (a credHolds built without Init, as the
existing tests do via configured(), does not block on stopSweep).
TestInitStartsAndShutdownStopsTheHoldSweep (the plugin's own lifecycle
wiring). core/plugins/contextguru passes with -race.
Also named this hold, and the already size-bounded forwarded-body stash,
in the 3 DELETE /v1/sessions retention texts (CLAUDE.md,
docs/laptop-service.md, docs/session-api.md), and tightened the claim in
docs/context-guru-plugin.md to say the release is on a timer.
boazdavid
left a comment
There was a problem hiding this comment.
This replies to reviewer 1's finding 3 (received body paired across
requests, not per request).
Fixed in c2c07ac.
The body a request received was kept in a sync.Map keyed by session id,
for OnFinish to stash beside the body that went upstream. Claude Code's
one-shot calls (title, permission monitor) share the main turn's session
id, so two requests in flight on one session could overlap: a later
Store() on the same key overwrote an earlier one, so OnFinish could pair
one request's received body with a DIFFERENT request's forwarded body.
Fix: the body is now kept on the request's own pctx (pipeline.SetState),
which is single-threaded per request, so the pairing is exact by
construction regardless of what else is in flight on the same session.
Test: TestStashedBodyIsNotMixedUpBetweenOverlappingRequestsOnOneSession
reproduces the exact interleaving (one-shot B starts, main turn A starts
on the same session before B finishes, B finishes first). I confirmed it
fails against the reverted old session-keyed logic (got A's body where
B's was wanted) and passes with the fix.
boazdavid
left a comment
There was a problem hiding this comment.
This replies to both reviewers' finding 4 / non-blocking notes about stale
docs.
Fixed in c2c07ac:
- docs/pricing.md: avoidedApiEquivalentMicros and avoidedUnknownMicros now
say "net of its penalty... may be negative", not "the usd of" (gross). - docs/context-guru-plugin.md: no longer says "Opt-in at build time". Now
says it ships in local, full and fullcpex, and names lite/envoy/cpex as
the profiles that leave it out. - docs/context-guru-plugin.md: the credential-release sentence now says
"on a timer, not only on the next matching request", matching the
finding-2 fix. - cmd/agentop/tui/sessions_pane.go: the comment calling the API-equivalent
figure "of the gross saving" now says "of the NET saving (may be
negative)".
The PR body's Dependencies section also had a stale claim that
modernc.org/sqlite was in go.sum only. I confirmed it is linked (go
version -m on a local-tagged binary lists modernc.org/sqlite v1.56.0) and
corrected the body.
Not changed in this round: the open_error:observe billed-model-calls point,
the possible OAuth beta-header gap on subscription credentials, and the
inference-router/incoming-model interaction. These are real points but are
behavioral questions for @boazdavid to weigh in on, not findings I can fix
unilaterally without a product decision.
clawgenti
left a comment
There was a problem hiding this comment.
Summary
Thanks @boazdavid. I re-reviewed the one commit since 79024c3: c2c07ac (Fix 3 blocking review findings on the accountant PR). I also re-checked the open items from earlier rounds.
The three fixes in c2c07ac work as described:
- Negative net savings.
pricing.SignedMicrosOrZerokeeps the sign through the same NaN/Inf/bound guards, andevent.Figuresuses it forAvoidedAPIEquivalentMicrosandAvoidedUnknownMicros. The places that add these figures (Counts.addIntothroughevent.AddSat,session/figures.go,ledger.CurrenciesIn's!= 0test, agentop'sSigned) already accept negatives.docs/pricing.mdnow says "net". - Credential-hold sweep.
startSweepruns fromInitandstopSweepruns beforereleaseAllinShutdown.Pipeline.Startunwinds withShutdownwhen a later plugin'sInitfails, so the goroutine does not leak on that path. The threeDELETEretention texts now name the hold and the stash. - Received body per request. The received body is now stored with
pipeline.SetStateon the request's ownpctx, so two requests that overlap on one session can no longer swap bodies.
Still blocking:
- The
stale_prefixmust-fix from the8606e3dround is not fixed. Moving the received body ontopctxfixes the mix-up between two overlapping requests. It does not stop a one-shot from replacing the main conversation's stash entry. I re-ran the probe on this head. It is inline. - New: the
Rust (praxis)tests fail.inference.cacheWrite1hTokenswas added tocore/pipeline/testdata/parsed-request.fields, but the Rust model does not have it. The CI job turned green only because its step says "cargo test failed (does not block: no praxis-mode changes)". It is inline. - CodeQL alert #365 (
go/clear-text-logging,core/accounting/savings.go:430) is still open and has not been dismissed (see the existing thread). - CI has not run on this head. The PR still conflicts with
main(3847526e) in the same four files:core/reloader/reloader_test.go,core/session/fold.go,docs/session-api.mdandscripts/profile-tags/profiles_test.go. Only DCO (pass) and CodeRabbit (skipped) reported.
Not blocking, still open: the on_error: observe model-call suggestion (cmd/cortex/local.go:353). Your reply says this needs a product decision, and I agree. The context-guru v0.7.4-beta.1 → v0.7.4 pin also has to move before merge.
Author: boazdavid (FIRST_TIME_CONTRIBUTOR association, but repo permission admin, so treated as a maintainer)
Areas reviewed: Go (core/plugins/contextguru incoming_anthropic.go and plugin.go, core/cost/event, core/cost/pricing, and the consumers of the two signed fields in core/cost/usage, core/cost/ledger, core/session and cmd/agentop), docs (CLAUDE.md, docs/context-guru-plugin.md, docs/laptop-service.md, docs/session-api.md, docs/pricing.md), and the praxis field-parity test. I reviewed the delta since 79024c3 and re-checked the earlier open threads against the whole PR.
Agent/IDE config (.claude/.vscode): none
Commits: 47 commits. DCO passes. Only the upstream merge commit caceb14 has no sign-off.
CI status: not run on this head (merge conflicts). On the last head where CI ran (9a12e46), Rust (praxis) showed green, but its annotation says cargo test failed.
Verified by: go test -race -tags include_plugin_contextguru passes on plugins/contextguru, cost/event, cost/pricing, session, pipeline and accounting/.... In cost/usage and cost/ledger, only the known America/Havana DST tests fail. go vet and gofmt -l are clean. cargo test -p cortex-praxis-filters --lib (Rust 1.96.0): 142 pass, 1 fails (below). I also re-ran the one-shot probe described inline.
Generated by RepoMan github-pr-review.
| // is still pctx.Body, so the stash matches what upstream cached in that case too. | ||
| func (p *ContextGuru) stashSent(pctx *pipeline.Context, sid string) { | ||
| pre := pipeline.GetState[pendingBody](pctx, pendingBodyStateKey) | ||
| if pre == nil || p.stash == nil || isSubagent(pctx) || pctx.StatusCode != 200 { |
There was a problem hiding this comment.
must-fix (still open from the 8606e3d round): this guard still lets a Claude Code one-shot replace the main conversation's stash entry. c2c07ac fixed the overlap case (two requests in flight). It did not fix the sequential case that this thread was about.
A one-shot (title, permission monitor, auto-mode classifier) declares role main and has a 200 status. It now has its own pendingBody on its pctx, so it passes every condition here. p.cgSessions.get(sid) returns the same engine key as the main turn, so put replaces the main turn's entry.
Probe on c2c07ac. Using configured, anthropicPctx, invokeReq and OnFinish, on session s1:
- A main turn (3 messages,
Extensions.Inference.Tools = [Bash]) finishes with 200.p.stash.CoversSpan(key, 2, SpanHash(NormalizeMessages(mainBody)[:2]))istrue. - A one-shot (
claude-haiku-4-5, 1 message, no tools) on the same session finishes with 200. The sameCoversSpanis nowfalse.
So on the next main turn, cache_aware_summarizer and extract_llm_sweep still decline with ErrStalePrefix on any turn that follows a one-shot. With 79024c3 that is the default path on a local install. The new TestStashedBodyIsNotMixedUpBetweenOverlappingRequestsOnOneSession shows the same thing: it expects the one-shot B to be stashed for s1.
Suggested fix (as before): stash only requests that carry a tool manifest. That is the filter model.PromptContextOf uses: inf := pctx.Extensions.Inference; inf == nil || len(inf.Tools) == 0. Apply it here and at the pipeline.SetState in OnRequest. Please add a test with a main turn, then a one-shot, then CoversSpan for the main turn's span.
| inference.agentRole string | ||
| inference.anthropicBeta string | ||
| inference.cacheReadTokens number | ||
| inference.cacheWrite1hTokens number |
There was a problem hiding this comment.
must-fix (CI hides this failure): this line makes the praxis parity test fail. praxis/filters/src/parse/model.rs every_go_inference_field_is_set_or_listed reads this file. It requires every inference.* field either to be set by the Rust model or to be listed in NOT_SET_IN_PRAXIS_MODE. cacheWrite1hTokens is neither:
---- parse::model::tests::every_go_inference_field_is_set_or_listed stdout ----
panicked at filters/src/parse/model.rs:511:9:
Go fields the Rust model does not give: ["inference.cacheWrite1hTokens"]
test result: FAILED. 142 passed; 1 failed
(cargo test -p cortex-praxis-filters --lib on c2c07ac with Rust 1.96.0. On main, Rust (praxis) passes with no failure annotation.)
The Rust (praxis) job showed green on 9a12e46, the last head where CI ran, only because its step reports "cargo test failed (does not block: no praxis-mode changes)". The job's annotations show this. After the rebase it will look green again while this test fails.
Either fix works:
- Add
cache_write_1h_tokensto the RustInferenceExtension, and fill it fromusage.cache_creation.ephemeral_1h_input_tokensinpraxis/filters/src/parse/inference/anthropic.rs(next tocache_creation_input_tokens). Praxis-mode records then carry the 1h tier as Go's do. - Add
"inference.cacheWrite1hTokens"toNOT_SET_IN_PRAXIS_MODE, with a comment that praxis mode does not split the 1-hour tier yet.
v0.5.0 adds Provider.ReadSetsTTL and EntryFacts.PingTTL, opt-in support for a provider (AWS Bedrock, per upstream) where a read sets the TTL of the cache part it reads, so a keep-alive ping's return read gets credited its rescue. A host that sets neither sees no change: Cortex's host does not set ReadSetsTTL, so this bump is behavior-neutral here. Every module now pins v0.5.0. Co-Authored-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…t PR
Round 1 of the offload review raised 3 non-blocking points beyond the
3 blocking findings already fixed. All 3 are now closed:
- Under on_error: observe, modelsFor still built the static and
incoming models, so cgModel.Complete and meteredDispatcher sent the
real HTTP call regardless of dryRun, which only changed how the
resulting op is REPORTED (Projected, left out of every total). A
shadow pass is supposed to change nothing, the same line the
keep-alive keeper already holds ("UNDER on_error: observe NOTHING
IS HELD... that ping is real, billed spend"). modelsFor now returns
an empty ModelSpec under observe, so every model-backed component
degrades to deterministic/no-op and no credential hold is taken.
- A Claude subscription (OAuth) token can need an oauth-* Anthropic-
Beta value to authenticate directly against api.anthropic.com, and
cheapmodel.Anthropic's own headers never set one. Without it, an
incoming-model call on a subscription credential could 401 --
failing open, but silently (the summarizer does nothing that turn).
cortexDispatcher now holds the request's own oauth-* betas
(tooldefer.AuthBetas) alongside the credential and fills them in on
a call that set none, without overriding a caller that set its own
(tooldefer.RunProbeBeta's own beta argument).
- inference-router always runs after context-guru (agentop server add
appends it last), so the incoming-model hold is taken on the host
and credential the client named, before any redirect -- but
pctx.Body by OnFinish can be the redirected server's own rewrite.
Stashing it would have the next turn's prefix ask send that body, in
whatever shape the OTHER server expects, to the client's original
host. stashSent now skips a redirected request. Whether the incoming
model should instead follow the redirect is a product question this
does not answer; it only removes the concrete risk.
Tests: TestModelsForBuildsNeitherModelUnderObserve (both dialects, and
that no hold is taken), TestDoFillsTheRequestsOwnAuthBetaWhenTheCallerSetNone,
TestDoDoesNotOverrideACallerSetAuthBeta, TestDoSendsNoAuthBetaWhenTheRequestHadNone,
TestStashSentSkipsARedirectedRequest. Each confirmed to fail against
the reverted fix and pass with it. core/plugins/contextguru passes
with -race. cmd/cortex (local tags) builds and passes. gofmt and go
mod tidy -diff clean.
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
boazdavid
left a comment
There was a problem hiding this comment.
This replies to the 3 non-blocking points from round 1 (observe-mode
billed calls, the possible OAuth beta-header gap, the inference-router
interaction).
Fixed in 864a3f0, after a decision from @boazdavid to close all 3 now
rather than defer them.
-
Observe-mode billed calls: modelsFor now returns an empty ModelSpec
under on_error: observe, so every model-backed component degrades to
deterministic/no-op and no incoming-model credential hold is taken.
Test: TestModelsForBuildsNeitherModelUnderObserve (both dialects). -
OAuth beta-header gap: cortexDispatcher now holds the request's own
oauth-* Anthropic-Beta values (tooldefer.AuthBetas) alongside the
credential, and fills them in on a call that set none, without
overriding a caller that set its own. Tests:
TestDoFillsTheRequestsOwnAuthBetaWhenTheCallerSetNone,
TestDoDoesNotOverrideACallerSetAuthBeta,
TestDoSendsNoAuthBetaWhenTheRequestHadNone. -
inference-router interaction: stashSent now skips a redirected
request, so a prefix ask never sends a possibly-routed body to the
client's original host. Whether the incoming model should instead
follow the redirect is a separate product question this does not
answer; it only removes the concrete risk you flagged. Test:
TestStashSentSkipsARedirectedRequest.
Each new test is confirmed to fail against its fix reverted and pass
with it. core/plugins/contextguru passes with -race.
clawgenti
left a comment
There was a problem hiding this comment.
Summary
Thanks @boazdavid. I re-reviewed the two commits since c2c07ac: 6ab835d (accountant v0.5.0) and 864a3f0 (the 3 non-blocking points). I also re-checked the blocking items from the last round.
The three fixes in 864a3f0 work as described:
- Observe makes no model calls.
modelsForreturns an emptyModelSpecwhenpctx.Observing(), soanthropicIncomingis never called and no credential is held. The comment incmd/cortex/local.goand the text indocs/plugin-catalog.md/docs/context-guru-plugin.mdnow say so. - OAuth beta.
heldTarget.authBetacarries only theoauth-*values (tooldefer.AuthBetas), andDofills it in only when the caller set noAnthropic-Beta. One small gap is noted inline (nit). - Redirected requests.
stashSentnow skips a request wherepctx.Redirected()is true.
The accountant v0.5.0 bump builds in every module, and the accountant cases still pass through the host code.
Still blocking (no change and no reply since the last round):
- One-shot replaces the main turn's stash (thread).
864a3f0only adds theRedirected()check tostashSent. I re-ran the probe on864a3f0. A main turn ons1(withtools, 3 messages) finishes with 200, so the stash holds its body. Then aclaude-haiku-4-5one-shot (1 message, no tools, rolemain) ons1finishes with 200. After that, the stash'spreBodyis the one-shot's body. Socache_aware_summarizerandextract_llm_sweepwill still decline withErrStalePrefixon the main turn that follows any one-shot. This is the default path on a local install. The suggested filter (stash only whenpctx.Extensions.Inference.Toolsis non-empty, in bothOnRequestandstashSent) and a main → one-shot →CoversSpantest still apply. - The
Rust (praxis)parity test fails (thread).core/pipeline/testdata/parsed-request.fields:18still listsinference.cacheWrite1hTokens. Nothing underpraxis/changed, soevery_go_inference_field_is_set_or_listedstill fails. CI will hide this, because the job's step says "does not block". - CodeQL alert #365 (
go/clear-text-logging,core/accounting/savings.go:430) is stillopenand has not been dismissed (thread). - The PR still conflicts with
main(mergeable: CONFLICTING). CI has not run on this head: only DCO (pass) and CodeRabbit (skipped) reported.
Before merge, still open (not blocking): move context-guru v0.7.4-beta.1 to v0.7.4.
Author: boazdavid (FIRST_TIME_CONTRIBUTOR association, but repo permission admin, so treated as a maintainer)
Areas reviewed: Go (core/plugins/contextguru dispatcher.go, incoming_anthropic.go and plugin.go with their tests, cmd/cortex/local.go), the go.mod/go.sum bumps in all modules, and docs (docs/context-guru-plugin.md, docs/plugin-catalog.md). I reviewed the delta since c2c07ac and re-checked the open blocking threads against the head.
Agent/IDE config (.claude/.vscode): none
Commits: 49 commits. DCO passes.
CI status: not run on this head (merge conflicts).
Verified by: these all pass on 864a3f0 with GOWORK=off. In core: go build -tags include_plugin_contextguru ./..., go test -race -tags include_plugin_contextguru on plugins/contextguru, accounting/..., cost/event, cost/pricing and pipeline, plus go vet and gofmt -l. cmd/cortex builds and tests with the local profile tags. cmd/agentop (money, tui) and cmd/cortex-envoy build and test. I re-ran the one-shot stash probe as a throwaway test, and it fails as described in item 1.
Generated by RepoMan github-pr-review.
| auth = append(auth, heldHeader{name: name, val: b}) | ||
| } | ||
| } | ||
| authBeta := tooldefer.AuthBetas(reqHeaders.Values("Anthropic-Beta")) |
There was a problem hiding this comment.
nit: the held authBeta is fixed by the first request that creates a hold. credHolds.hold (incoming_anthropic.go:113-118) reuses the existing ref for a known credKey, and credKey hashes only the scheme, the host and authHeaderNames, not Anthropic-Beta. Each matching request also refreshes lastUsed, so that ref can live for the whole process.
Two cases follow from this:
- The first request on an OAuth credential has no
oauth-*beta (an older client, or a call type that leaves it out). Every later incoming-model call on that credential then goes out without the beta, even after the client starts sending it, and gets the silent 401 this change is meant to fix. - The client changes its
oauth-*beta version. The old value is still sent.
Two cheap fixes: add tooldefer.AuthBetas(pctx.Headers.Values("Anthropic-Beta")) to credKey, or update the held authBeta on each hold hit.
TestAccountantCases and TestSavingsAgreesWithTheAccountantCases could skip a case listed as "differs" in docs/accounting-differences.json. No listed id matched a real case id, so nothing was skipped, but the mechanism let a failing case be listed away instead of fixed. Remove it. Both tests now run every case in cases.All() (163 at accountant v0.5.0), and a case Cortex cannot meet fails. The differences file stays as documentation of Cortex-level differences from the proxy; no test reads it. The design spec now says every case must pass. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
clawgenti
left a comment
There was a problem hiding this comment.
Summary
Thanks @boazdavid. I re-reviewed the one commit since 864a3f0: b3851e5 (run every accountant case with no skips). It works as described. loadDifferences, skipDifference and logSkipped are gone. TestAccountantCases and TestSavingsAgreesWithTheAccountantCases now run every case in cases.All(). On b3851e5 with accountant v0.5.0, both pass with 163 subtests each (326 total), and none is skipped. Nothing in Go reads docs/accounting-differences.json any more. One stale sentence in that file is noted inline (nit).
Still blocking. This commit changes only tests and the spec, so none of the earlier blocking items has moved. None of their threads has a reply.
- A one-shot replaces the main turn's stash (thread). Nothing under
core/plugins/contextguruchanged since864a3f0, where the main → one-shot probe showed the stash holding the one-shot's body. So on a local install, which runs this path by default,cache_aware_summarizerandextract_llm_sweepstill decline withErrStalePrefixon the main turn after any one-shot. The fix suggested in that thread still applies: stash only whenpctx.Extensions.Inference.Toolsis non-empty, in bothOnRequestandstashSent, and add a main → one-shot →CoversSpantest. - The
Rust (praxis)parity test fails (thread).core/pipeline/testdata/parsed-request.fields:18listsinference.cacheWrite1hTokens.praxis/filters/src/parse/model.rshas no such field, and it is not inNOT_SET_IN_PRAXIS_MODE, soevery_go_inference_field_is_set_or_listedfails. The PR changes nothing underpraxis/. CI will not flag this, because that job's step says "does not block". Either addcache_write_1h_tokensto the RustInferenceExtension(andfull_sample), or list the field inNOT_SET_IN_PRAXIS_MODEwith a reason. - CodeQL alert #365 (
go/clear-text-logging,core/accounting/savings.go:430) is still open and has not been dismissed (thread). - The PR still conflicts with
main(mergeable: CONFLICTING). As a result, CI has not run on this head: only DCO (pass) and CodeRabbit (skipped) reported.
Before merge, still open (not blocking): move context-guru v0.7.4-beta.1 to v0.7.4.
Author: boazdavid (FIRST_TIME_CONTRIBUTOR association, but repo permission admin, so treated as a maintainer)
Areas reviewed: Go tests (core/accounting/cases_test.go, core/accounting/savings_agree_test.go), docs (docs/superpowers/specs/2026-11-17-accountant-integration-design.md, docs/accounting-differences.json). I reviewed the delta since 864a3f0 and re-checked the open blocking threads against this head.
Agent/IDE config (.claude/.vscode): none
Commits: 50 commits. DCO passes.
CI status: not run on this head (merge conflicts).
Verified by: on b3851e5 with GOWORK=off in core: go test -count=1 -tags include_plugin_contextguru ./accounting/... passes, a -v run of the two case tests shows 326 PASS subtests and no SKIP, and go vet ./accounting/ and gofmt -l accounting/ are clean. I checked the praxis parity gap by reading the code: the field list against model.rs and NOT_SET_IN_PRAXIS_MODE.
Generated by RepoMan github-pr-review.
| { | ||
| "id": "proxy.billing-mode-hardcoded", | ||
| "kind": "notCovered", | ||
| "reason": "The standalone context-guru proxy still hard-codes Billing{Mode: BillingAPI} for every request; it does not call accountant.BillingFrom yet (Cortex spec \u00a75.7). Remove this entry once the context-guru proxy calls accountant.BillingFrom. Not a case in github.com/rossoctl/accountant/test/cases, so this is a documentation-only note rather than a skip for TestAccountantCases." |
There was a problem hiding this comment.
nit: this note, and the same sentence at line 82, still says the entry is "a documentation-only note rather than a skip for TestAccountantCases". Since b3851e5, no test reads this file, and no entry of either kind is a skip. Consider dropping the "rather than a skip…" part from both notes. The same goes for the kind field's skip meaning, if you keep that field. Then nobody reading the file will think it still controls which cases run.
|
Closing: this PR is split into smaller
Merge order: branch The split was built from one source tree: this work merged with current Assisted-By: Claude (Anthropic AI) [email protected] |
Abstract
Cortex can make an agent's LLM requests smaller:
tool-pruneremoves tool definitions the agent does not use, andcontext-gurucompacts the conversation. Until now, Cortex reported what this saved with a rough byte ratio, and that figure did not match the context-guru proxy's figure for the same traffic.This PR makes Cortex count savings the same way the proxy does. Both now use one shared library,
accountant. Each saving is priced from real cache and token facts, and it is booked as dollars for an API key or as usage-limit units for a subscription. The figure appears in the ledger,/v1/usage, the sessions list and agentop. It can also be pushed to the central metrics collector. Model calls that context-guru makes, and keep-alive pings that keep an idle session's cache warm, are booked as spend, so the net saving is honest.The PR also turns
context-guruon by default for a new local install (presetxhigh).Why this PR is big
Against
mainit has 46 commits and 203 files, with +20,189 / −1,073 lines. Most of that is not production code:*_test.go)accountantcases, none skippedcore/accounting(new package) is most of itscripts/devdocs/superpowers/, plus user docsIt also carries several features that depend on each other, and three of them came in from #1412, which this PR supersedes:
core/accounting,core/cost).tool-prune,context-guru) and the pipeline hooks.xhigh(from Feat/contextguru keepalive #1412).metrics_pushOTLP export.If a smaller review unit is wanted, items 3–6 can each move to a follow-up PR on top of 1–2.
Design
docs/superpowers/specs/2026-11-17-accountant-integration-design.mddocs/superpowers/plans/2026-11-17-accountant-integration.mdWhat changes
core/accounting: Cortex's own host code. It parses the wire body, holds the cache facts, the W6.1 skip rules and the threads, and keeps oneTrackersper process (with a laptop snapshot, capped at 20 MiB). It also holds the pricing, the conversion of results to savings, keep-alive ping accounting, the metrics sink and the OTLP push. A boundary test keeps context-guru out of its imports. Accounting does not depend on context-guru: it works with tool-prune only, or with no context operator.pctx.ReportOpsand the client body as received.Pipeline.Runcalls a request start and end hook, so no listener changes. Hashing runs off the request goroutine. Accounting fails open.cache_controlmark. context-guru reports its engine operations, its envelope (tools and system) operations and its model-call spends.PingOpsandComputeStandalone. Its spend gets its own ledger columns, and its rescue is credited on the next request. Session state is kept on disk.8606e3d3): compacts OpenAI Responses requests (/v1/responsesis a default path). On Anthropic traffic,model.source: incomingcomponents get the request's own model (cheapmodel.Anthropicon the held credential, with the summarizer's prefix ask), and each call is aKindSpendop.marker_modeis capped atsummary. The engine default ispreset: xhigh.79024c3c): the--localconfig listscontext-guruaftertool-prune, withon_error: enforceandpreset: xhigh.contextgurumoves into thelocal,fullandfullcpexbuild profiles, because a binary that cannot load a plugin its config names refuses to start.lite,envoyandcpexstill leave it out.accountant.BillingFrom, read on the client's credential header before any plugin rewrites it. Each saving gets a basis (usd, subscriptionEquivalent or unknown) under accountant design §7.1. Money totals count only usd. A subscription saving is also shown in usage-limit units, with the API-equivalent dollars beside it./v1/usageand agentop switch to the accountant figure. New columns: penalty, units, unknown, plugin spend and keep-alive. The old byte-ratio pricing for tool-prune is removed.metrics_pushpushes OTLP over HTTP to the collector's Cortex receiver. Nothing is sent without a URL. A URL with credentials in it is refused.docs/accounting-differences.jsonlists every known difference from the proxy, with a reason and the spec section that covers it.Dependencies
github.com/rossoctl/accountant v0.5.0in every module. v0.4.0 addedPingWindowID, the active operation count and age inResult, and typedCheckFailurenumbers, and it fixed in-place position mapping after added content. v0.5.0 addsProvider.ReadSetsTTLandEntryFacts.PingTTL, opt-in support for a provider where a read sets the TTL of the cache part it reads. Cortex sets neither, so the v0.5.0 bump does not change behaviour. Noreplacelines are left.github.com/rossoctl/accountant/metricshas no tag upstream. It is pinned to the pseudo-version for commit6085d4661624(2026-11-11), which is the reviewed code.github.com/rossoctl/context-guru v0.7.4-beta.1. Againstv0.7.3,context-guru/proxydoes not compile with the new accountant.v0.7.4is now tagged upstream, so the pin should move to it before merge.modernc.org/sqlitev1.56.0 and itsmodernc.org/*toolchain are linked, since9d8ad9e0(context-guru session state on disk):core/plugins/contextguru/statedb.goimports it directly,core/go.modrequires it directly, andgo version -mon alocal-taggedcortexbinary lists it. It is pure Go, so it builds fine underCGO_ENABLED=0. (Corrected from an earlier, stale claim in this body that it was ingo.sumonly.)Behaviour changes
context-guruwith presetxhigh. It rewrites request bodies, and its LLM steps make extra model calls on the agent's own endpoint and key. Seton_error: observeto measure without changing any bytes. An existing~/.cortex/config.yamlis not rewritten.local,fullandfullcpexbinaries grow by about 16 MiB (alocalbuild is about 60 MB, afullbuild about 83 MB).accounting.enabled: false(or in praxis mode), tool-prune records no saving. The old byte-ratiosettle.Avoidedpath is gone (docs/tool-prune-plugin.md).enabled: auto, that is adding the first context operator. A reload that turns it off (for exampleon_error: offon the only operator) is accepted.Before merge
context-gurufromv0.7.4-beta.1tov0.7.4.scripts/dev/verify-contextguru-keepalive.sh.cmd/agentoproot-package tests with the laptop service stopped.scripts/dev/compare-contextguru-savings.py, the Cortex / proxy / control harness.Testing
core/cost/ledgerandcore/cost/usage, which also fail onmain.-race.accountanttest cases (cases.All()at v0.5.0) pass, with no case skipped or deferred.TestAccountantCaseschecks the libraryResult.TestSavingsAgreesWithTheAccountantCaseschecks Cortex's dollar conversion (SavingsBilled) on top of it.docs/accounting-differences.jsondocuments differences from the proxy. It is not a skip list.scripts/profile-tagsandcmd/cortex(built with thelocaltags) pass after the default-enable change. A freshlocalbinary started on a config from--write-configlistscontext-guruwithpreset: xhighin/v1/pipelineand logs no error.go mod tidy -diffare clean.Review round 1
Two independent reviewers found 3 blocking defects, now fixed:
core/cost/event/event.go):AvoidedAPIEquivalentMicrosandAvoidedUnknownMicrosran throughpricing.MicrosOrZero, which refuses any negative input by design. A request whose cache penalty exceeded its saving booked 0 instead of a negative net, overstating every total. Fixed with a newpricing.SignedMicrosOrZero, which preserves the sign; addedTestFigures_NegativeNetIsNegativeandTestSignedMicrosOrZero.core/plugins/contextguru/incoming_anthropic.go): an expired hold was only released on a later matching request, so on a quiet install it could stay held for the life of the process. Fixed with aholdSweepInterval(10m) ticker, started inInitand stopped inShutdown; added tests for the sweep itself and forInit/Shutdownwiring. Documented the hold (and the already-bounded forwarded-body stash) in the threeDELETE /v1/sessionsretention texts (CLAUDE.md,docs/laptop-service.md,docs/session-api.md).core/plugins/contextguru/plugin.go,incoming_anthropic.go): the pending body was kept in async.Mapkeyed by session id. Claude Code's one-shot calls share the main turn's session id, so two overlapping requests could clobber each other's entry, pairing one request's received body with a different request's forwarded body. Fixed by keeping it on the request's ownpctx(pipeline.SetState), which is single-threaded per request; addedTestStashedBodyIsNotMixedUpBetweenOverlappingRequestsOnOneSession, confirmed to fail against the old logic and pass with the fix.Also fixed:
docs/pricing.mdanddocs/context-guru-plugin.mddescribed these two figures as gross and the plugin as opt-in-at-build-time; both corrected.cmd/agentop/tui/sessions_pane.go's stale "gross" comment fixed too.Assisted-By: Claude (Anthropic AI) [email protected]