Repository navigation
feat(contextguru): [cg] Include the keep-alive pings' cost in spend, savings, sessions and budgets - #2114
Conversation
…tant Add the prompt-cache keep-alive: context-guru pings an idle session's upstream before its prefix cache expires, so the next turn is a cache hit rather than a full re-send. The keeper decides when to ping, how much, and when to stop; the dispatcher only sends and holds the caller's credential. Each ping is accounted through core/accounting.Host.Ping and booked to the cost ledger and /v1/usage apart from the agent's own requests: a ping is in no request, token, cost or latency figure. Its billing basis follows the thread's last request, and the thread's next request credits the cache the ping kept warm as a rescue. Model context windows resolve via the models the engine is given rather than proxyapp. The accountant state snapshot is capped at 20 MiB, dropping the threads seen longest ago. Keep-alive is on by default and each agent's cache is kept warm. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…at the keeper holds Review fixes for rossoctl#2059: - Pass the 1-hour cache-write count to the keeper. Without it every thread billed at the 1-hour tier ran on the 5-minute schedule: two pings that bought nothing, and no 59-minute ping. - Do not track a request that inference-router translated or gave upstream headers to. Its body, path and headers in the pipeline are not what went upstream, so a ping could not replay it. - Keep keep_alive on by default on every install, and add an upgrade note for clusters that already run context-guru: they start pinging on their callers' credentials with no config change. - Close the window where a request that finishes during Shutdown could hold a credential after the keeper's sweep. - Cap the accountant snapshot file at 20 MiB, not the raw state, which the file carries as base64. - Fetch the LiteLLM map on the plugin's model transport, so on a local install it ignores HTTPS_PROXY. - Show a subscription ping's API equivalent in agentop when its units round to zero. - Docs: a keeper entry holds the masked credential and the last request body; its hold is 12 minutes on a 5-minute thread and 118 minutes (at most 236) on a 1-hour thread. The snapshot leaves out the oldest threads past 20 MiB. Fold the duplicated session-api.md paragraph. - Pin context-guru to the v0.7.5 release, not v0.7.5-beta.2. - Drop the development-log references from comments, and fix the accountant version in snapshot_trim.go. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…ollow the wait plan
Two gaps against context-guru's own docs/how-to/cache-strategies.md:
1. keep_alive: had its own static policy (enabled/idle_seconds/max_pings/
max_usd_per_ping/min_prefix_tokens) and never touched context-guru's
named strategy table, so none of auto, none, 1-ping, 2-ping, 1-hour-head,
1-hour-on-wait, 1-hour-always or 30-min-ping could be picked.
2. The per-wait ping plan (keepalive.Policy.WaitPlan) was never turned on,
and recordFor filled none of the inputs it needs, so every wait got the
same flat ping count instead of following what the thread actually waits
for (its own tool, a person, background work, a teammate, done).
keepAliveConfig.policy now takes the engine's own resolved cache: block
(cgconfig.CacheConfig, already parsed by cgconfig.LoadBytes from engine:
in Configure -- context-guru's own config.applyStrategy resolves the named
strategy into it, so nothing here reimplements that table). Set
engine: {cache: {strategy: auto}} (or any other name) to pick one;
keep_alive: {enabled: false} still always wins as a kill switch. With no
cache.strategy set, policy() returns exactly what it always did -- the
per-wait plan's rossoctl#858 "no ping before the first tool call" rule changes
real scheduling, not just a tunable, so it only turns on through an
explicit strategy.
recordFor now carries Usage.StopReason (inf.FinishReason) and
ToolUseNames (inf.ToolCalls) so the keeper's WaitingFor can classify the
wait. ToolUseIncomplete is always false: that flag covers a host that
assembles ToolCalls from a spliced streaming-sniff window, which does not
describe this parser (inferenceparser fully assembles ToolCalls before
OnFinish runs). OpenTasks (background-task/teammate markers) is left
unset: that scanner lives in context-guru's internal/waitcause, which the
core does not export -- a background/teammate wait here falls back to
WaitingFor's unknown cause rather than a cortex-side approximation of a
scanner we cannot see.
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…dy does Left over from the modelclient.go conflict resolution two commits back: the Transport field moved to call modelTransport(localInstall) directly, but the local tr variable stayed, unused, so the build broke. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
Closes three gaps found comparing this plugin's config surface against context-guru-proxy's, now that engine.cache.strategy is wired (previous commit): 1. Discoverability: ConfigSchema's `engine` description never mentioned `cache:` at all, even after the strategy fix, so an operator had no way to learn the key exists except by reading source. Now names cache.strategy and its 8 values, and links context-guru's own docs/how-to/cache-strategies.md. docs/context-guru-plugin.md gets the same addition. 2. cache_mode: the proxy has CACHE_MODE=auto|on|off (process-wide override of whether the engine places prompt-cache breakpoints at all); this plugin had no equivalent. Added a top-level cache_mode field, validated at Configure, threaded straight into apply.Opts.CacheMode at the existing apply.BodyOpts call site in OnRequest -- the same field and the same three values as the proxy's env var, so a value means the same thing in both. resolveCacheAware's own decision (what each value actually changes) stays entirely in context-guru; nothing here reimplements it. 3. model.max_concurrent: the proxy bounds concurrent cheap-model calls with --cheap-model-concurrent (default 4); cgModel.Complete had no limiter at all, so an unbounded number of concurrent summarize/extract calls could fire. Added model.max_concurrent (default 4, same as the proxy), as a channel-based semaphore shared by every per-request copy of cgModel (staticModelFor copies the struct by value, but a channel is a reference type, so the copies share one semaphore). Complete acquires a slot or returns the request's own ctx.Err() if that context is canceled first while waiting. Not touched: dashboard, tenancy/auth, archiving, the upstream allow-list, --metrics-push*, listen address -- proxy-binary-only systems this plugin already covers differently (its own accountant, session layer, routing, metrics_push: block). Replicating proxy-shaped equivalents for them would duplicate decisions cortex already makes its own way. Tests: TestConfigure_RejectsBadCacheMode, TestConfigure_RejectsNegativeMaxConcurrent, TestCgModel_MaxConcurrentBoundsInFlightCalls (asserts the actual peak in-flight call count under -race, not just that Configure accepts the field). Co-Authored-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…e keep_alive Inference paths were never meant to be configurable - mirror context-guru-proxy's own hardcoded routes instead of a paths config key. Rename the cheap-model config key to cheap_model so it isn't confused with engine.cache or the request's own model. Retire the plugin-level keep_alive block: every one of its knobs is already a cache.keepalive_* key on context-guru's own engine.cache config, so keeping both kept two copies of the same decision. A config that still sends keep_alive gets one WARN naming the retired key and is otherwise unaffected. To keep keep-alive "on by default on every install" without a plugin-level default of its own, Configure now fills engine.cache.strategy: auto itself, but only when the operator's engine: YAML has no cache: key at all. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…TL1h through Two real must-fix bugs from review, still live after the keep_alive retirement (769ba92) changed the surrounding code's shape: - cachePolicy's resolved policy was only stored on p.kaPol inside the `if pol.KeepAlive` branch. cache.strategy: 1-hour-head resolves HeadTTL1h without turning KeepAlive on, so p.kaPol stayed at its zero value for that strategy — resolving a policy nothing read. Stored unconditionally now; the keeper is still built only when KeepAlive is on. - OnRequest's apply.Opts never passed HeadTTL1h/HeadTTLMinBytes through, so cache.strategy: 1-hour-head's whole effect was a silent no-op regardless of the above. Wired both fields from p.kaPol. - Found while testing the above: apply.BodyOpts's own Result.Changed misses the head-TTL relabel on a request that has a messages array (the library folds it into Changed on two early returns, but the full-pipeline path at the bottom overwrites Changed from the message rewrite alone, dropping the tools/system edit Result.Body still carries). Worked around in reportResult by ORing in Trace.HeadTTL1h, which is already correct regardless of which path set Changed. OneHourFirst (the 1-hour-always/-on-wait strategies' own effect) is not wired: the decision it needs is unexported from context-guru's keepalive package, so this layer has no way to ask it. Documented at the call site. Added tests for both fixes, plus one pinning that engine.cache.keepalive: false with no strategy named already stays off (769ba92's own fix, confirmed still correct, not changed here). Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…d fix the head-TTL change signal injectDefaultCacheStrategy concatenated raw YAML text onto the JSON-encoded engine config bytes. A JSON flow-mapping occupying the whole first line of a YAML document cannot be followed by further top-level block-mapping keys, so yaml.Unmarshal silently parsed only the first document and dropped the injected cache.strategy whenever engine was non-empty. Decode into a map[string]yaml.Node, insert the cache key, and marshal the whole map instead. keepalive.Keeper.OneHourFirst is exported since context-guru v0.7.7 (contrary to an earlier comment here claiming it wasn't) and is now wired into apply.Opts.OneHourFirst via a provider/endpoint-closed helper. reportResult's changed signal now also fires when Trace.HeadTTL1h is set but the library's own Result.Changed missed it, since apply.BodyOpts drops that signal on its full-pipeline path when a messages array is present (tracked upstream as rossoctl/context-guru#1348). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
… of wall time main now runs check-test-timing in pre-commit and CI (rossoctl#2080), which flags time.Sleep, time.After beside a wait, and polling loops in _test.go files. core/accounting/ping_test.go's barrier used a 1s time.After guard beside the wait; dropped it in favor of go test's own -timeout, which ends a genuinely broken barrier with every goroutine's stack rather than racing a short timer. TestCgModel_MaxConcurrentBoundsInFlightCalls used a fixed 200ms sleep to let goroutines "settle" before releasing them; replaced it with a channel the server closes once max_concurrent calls are actually in flight, which is the real event the sleep was approximating. keepalive_substitute_test.go and ping_test.go both construct their Keeper with Go: func(f func()) { f() }, so Sweep's ping already ran inline by the time it returns; the polling loops afterward were dead weight. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…read, and stop a null-engine crash Must-fix (clawgenti re-review at cd8e41b, carried from e21f17a): 1. oneHourFirstFor passed route="" and always threadID="" to keepalive.Keeper.OneHourFirst. recordFor records Route: pctx.Path (keepalive.go), and the keeper keys its one-hour route state (oneHourRoute) the same way, so passing "" made st.off (the gateway-downgrade stop) and st.costly (1-hour-on-wait's mode D) always miss. Separately, threadID came from the apply library's own res.Trace.Thread.ID, which stays "" because this plugin wires no Opts.ThreadOf -- so a named subagent's request was asked, and relabelled, as if it were the main thread, at the 2x one-hour write premium. Wiring the library's own Opts.ThreadOf/thread.Tracker would touch every other thread-keyed call this plugin makes (keeperKey, recordFor, RecordBilledInput) -- a much bigger change with its own key-mismatch risk. Instead, oneHourFirstFor now captures pctx.Path as route and, for threadID, the same agentThreadPrefix+pctx.Subagent() convention keeperKey already uses -- so this call and the keeper's own Arrive/Depart/Record for the same request key identically. TestOneHourAlwaysDoesNotRelabelASubagentsRequest pins the subagent case. 2. injectDefaultCacheStrategy panicked on an engine: key with no value (every child commented out, or no value at all): that reaches Configure as the JSON/YAML text "null", yaml.Unmarshal leaves doc nil with no error, and doc["cache"] = cache is an assignment to a nil map. A process startup crash, and a crash of a running proxy on config reload (no recover on that path). Treated the same as cgconfig.LoadBytes("null") already treats it: a no-op. TestConfigure_NullEngineDoesNotPanic pins it. Also: model and paths are retired top-level keys exactly like keep_alive, and json.Unmarshal silently drops them too -- cheap_model's rename from model, and the hardcoded paths list, were both silent. Extended the existing retired-key WARN (renamed warnOnRetiredTopLevelKeys) to cover both. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…ctually detect a missing cap Must-fix (clawgenti and huang195, re-review at cd8e41b): my own earlier test-timing fix (cd8e41b) replaced this test's fixed 200ms sleep with a channel that closes once max_concurrent calls are confirmed concurrently in the HTTP handler. That event is real, but observing it through a full network round trip left a timing gap: release fires the instant the handler's own counter reaches maxConc, with no guarantee the other calls (if a cap bug let them through too) have reached the handler by then — so the test could pass even with the cap fully disabled, confirmed by mutation testing (if false && m.sem != nil made the test pass 10/10 runs before this fix, and fail reliably after). cgModel gets a test-only onAcquire hook, called the instant a call's semaphore slot is taken (or immediately, unthrottled, when the cap is broken) — in-process, before the network call, with no round trip to race against. The test now tracks concurrency there instead of in the HTTP handler, which only holds calls open (via release) rather than timing them. Mutation-tested again: fails reliably with the cap disabled, passes consistently (20/20) with it intact. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
… the hold-duration docs huang195's review at a8ccd49: the earlier fix for {"engine":null} panicking stopped it from panicking, but left it turning keep-alive off while an absent engine: key turns it on -- the one difference between "I wrote engine: with nothing under it" and "I never wrote engine: at all" that an operator would not expect and could not see. engine: null (and every child commented out) decodes to the JSON literal "null", not an empty json.RawMessage; Configure now treats a trimmed "null" the same as empty, both defaulting to preset: balanced before injectDefaultCacheStrategy runs. TestConfigure_NullEngineDoesNotPanic now asserts a keeper is built, the same as TestKeepAliveOnByDefault's `{}` case. Also (clawgenti, doc accuracy): docs/context-guru-plugin.md, docs/session-api.md, CLAUDE.md, docs/laptop-service.md and the PR body all said a keeper entry's credential/content hold is "12 minutes" on a 5-minute cache. That is only the plain-default figure: cachePolicy sets WaitPlan on by default, which raises a tool-wait thread's ping count to cache.keepalive_tool_wait_max_pings (8 by default) instead of cache.keepalive_max_pings (2) -- so the real bound, (max_pings + 1) x idle_seconds, is up to 36 minutes for a thread waiting on its own tool call, not a flat 12. Corrected all four doc references and the PR body to state both figures. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…d pin it with a test clawgenti's re-review at 81125a5: the earlier doc fix said "up to 36 minutes for a tool wait" but left the figure for a background or human wait unstated, and the one test that pins the hold duration (TestKeepAliveHoldFollowsTheBilledTier) always runs with cache.keepalive_wait_plan disabled, specifically so it does not depend on wait classification -- which also means it cannot catch a docs/code mismatch on the wait-plan-on path, the real default. keepalive.Policy.WaitPings gives the exact per-cause ping counts: base (2, no particular wait), base+HumanExtraPings (2+1=3), base+BackgroundExtraPings (2+3=5), or ToolWaitMaxPings (8) for a tool wait -- 12, 16, 24 and 36 minutes at idle_seconds' default of 240. Updated docs/context-guru-plugin.md, CLAUDE.md, docs/laptop-service.md, docs/session-api.md and the PR body to state all four, not just the plain default and the tool-wait case. TestKeepAliveHoldIsLongerForAToolWaitUnderTheWaitPlan drives a tool-call response through the real plugin with the wait plan on (not keepAliveTestConfig's disabled one), and pins the resulting entry's MaxPings and hold at the tool-wait figures above. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
… hold figure
clawgenti's suggestion: Cortex's keeper is built with Dispatcher only
(keepalive.New(keepalive.Options{Dispatcher: p.disp})) and recordFor leaves
Record.OpenTasks nil deliberately -- the core does not export waitcause --
so WaitingFor never sees an open background count, and the library's
classifier returns human or unknown for an idle main thread here, never
background. A thread waiting on background work is classified unknown, so
it holds for the base 12 minutes, not the 24 the docs promised.
Dropped "24 waiting on background work" from docs/context-guru-plugin.md,
CLAUDE.md, docs/laptop-service.md, docs/session-api.md and the PR body,
keeping 12/16/36 and a note that the engine's background-wait count never
applies here.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
…lds its slot TestCgModel_MaxConcurrentBoundsInFlightCalls lowered its in-flight count after Complete returned. Complete frees its semaphore slot in a deferred receive before it returns, so a waiting call could acquire the slot and count itself first. A correct cap then reported a peak of 3, in about 2-3% of -race runs on 4 or more CPUs. Lower the count inside the HTTP handler instead, while the call is still inside Complete. With -race -count=300 -cpu 1,4,8 the test now has 0 failures in 900 runs, and with sem: nil it still fails 30 of 30 runs. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…savings, sessions and budgets rossoctl#2059 prices each keep-alive ping and books it apart, in keepAlive* fields that no total read. So the headline spend left out a real charge, and the net saving credited the keeper's rescue without the pings that earned it. - money.NetMicros and the subscription and unknown-billing nets subtract the pings of their basis; agentop names the keep-alive spend beside the penalty. - money.SpendMicros (costMicros + keepAliveMicros) is the headline and row cost in `agentop cost` and in every TUI spend figure. - accounting.Host.AddPingListener: Host.Ping notifies listeners after it records a ping. cmd/cortex registers session.Store.AddKeepAlive, which adds the spend to new keepAlive* / keepAlivePings fields on /v1/sessions rows without counting the ping as activity. - session-budget subscribes in Init and unsubscribes in Shutdown, and counts each ping's tokens by kind and one call. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 42 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
… the Redis write The check-test-timing hook refused waitWrites: it polled pendingWrites with a real 2s deadline and a 5ms sleep. count updates the local counters before it starts the Redis write, so the counters are final when Ping returns, and TestAccumulate_WritesToStore already covers the write itself. The Redis half of the test also raced that write on p.store under -race. 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
Reviewed this PR's own commit (17db976, the diff against cg/06-keepalive). The listener on Host.Ping, the keepAlive* figures in the session store, and the SpendMicros/NetMicros changes in agentop are well built and well tested. The new totals add up. Three things block it. Pre-commit Checks fails on the new session-budget test. A config reload counts every ping twice in session-budget while the old pipeline drains. And when a window has pings but no priced request (the idle case keep-alive exists for), the headline still says cost unavailable, while the new keep-alive line says the pings are in the total above.
Author: boazdavid (CONTRIBUTOR by association, admin permission on the repo — maintainer)
Areas reviewed: Go (core/accounting, core/session, core/plugins/sessionbudget, cmd/agentop money/TUI/cost, cmd/cortex wiring), docs, CLAUDE.md (repo-root doc text only)
Agent/IDE config (.claude/.vscode): none
Commits: 16 commits, all signed-off: yes (DCO passes)
CI status: failing. Pre-commit Checks fails on check-test-timing (inline below). Go CI (core peerproc, macOS) fails because no runner picked up the job (infra, not this PR). Several Go CI jobs were still pending when I checked.
Local runs at 17db976 (GOWORK on): gofmt -l on the changed Go files is clean. go vet is clean for cmd/agentop, cmd/cortex and the changed core packages. go test ./... passes in cmd/agentop except TestServiceInstall_RefusesABrokenConfig, which needs a systemd user bus this sandbox lacks. go test passes in core/accounting, core/session and core/plugins/sessionbudget. -race passes in accounting and sessionbudget. core/session/archive TestWriteSession_FailedEraseKeepsNumbering fails here because the sandbox runs as root, and this PR does not touch that package.
| # | File | Severity | Finding |
|---|---|---|---|
| 1 | core/plugins/sessionbudget/keepalive_test.go:44 | must-fix | check-test-timing fails CI (time.Sleep poll and a 2 s real deadline) |
| 2 | core/plugins/sessionbudget/plugin.go:270 | must-fix | A reload double-counts each ping in Redis for up to the 10 min drain window (probe: 1 ping, tokens=3670 calls=2) |
| 3 | cmd/agentop/cmd_cost.go:730 | must-fix | A window with only pings shows cost unavailable and claims the pings are "in the total above". The TUI strip and agents COST cell share the same gate |
| if done { | ||
| return | ||
| } | ||
| time.Sleep(5 * time.Millisecond) |
There was a problem hiding this comment.
must-fix: Pre-commit Checks fails on this file. The check-test-timing hook reports two lines:
- L44
time.Sleep(5 * time.Millisecond): "sleeps for a fixed time. Block on a channel the code or fake closes when it is done." - L35
time.Now().Add(2 * time.Second): "sets a real timeout."
waitWrites polls pendingWrites. count updates the local counters synchronously inside the listener call, so the local assertions need no wait. Only the Redis read needs one. One way to fix it: give the test memStore a channel that HashIncr signals, and have the test block on it, with time.Hour as the only bound, as the hook asks.
There was a problem hiding this comment.
Fixed in 4324334. waitWrites is removed. count updates the local counters before it starts the Redis write, so the test reads them when Ping returns, with no wait. TestAccumulate_WritesToStore covers the Redis write. scripts/dev/check-test-timing.py passes on the file.
| go p.refreshLoop(interval) | ||
| // Last, so a failed Init leaves nothing subscribed. Shutdown removes it, so the instance a | ||
| // reload replaces stops counting pings before the new one starts. | ||
| p.unsubPing = p.acct.AddPingListener(p.onPing) |
There was a problem hiding this comment.
must-fix: a config reload counts every keep-alive ping twice while the old pipeline drains.
The comment says Shutdown removes the old listener "before the new one starts". core/reloader does it the other way round. newIn.Start and newOut.Start run first, which calls this Init, which subscribes. After the swap, the old pipelines are stopped in the background by stopWhenUnheld, up to drainWindow later (10 min by default). Claude Code keeps a CONNECT tunnel open, so the old outbound pipeline usually stays up for the whole window. Both instances listen on the same long-lived Host and HashIncr the same Redis key, so each ping lands twice in the shared counters. The new instance's refresh loop then reads the doubled figure. With pings about every 4 minutes, that is roughly two extra pings per idle thread per reload, and the session's next request can hit max_tokens/max_calls early.
Probe at 17db976 in core/plugins/sessionbudget: two instances share one store and both subscribe as Init does. After one h.Ping("sess-1", ...), Redis reads tokens=3670 calls=2 (one ping is 1835 tokens and 1 call).
TestKeepAlivePing_ShutdownUnsubscribes only checks a single instance after Shutdown, so it does not cover the overlap. One possible fix: let the host keep one ping listener per key, with the newest registration replacing the previous one, and make the remover delete only its own registration. The new instance then takes over at Init, and the old instance's Shutdown is a no-op for it. Mind the case where a reload fails after this Init. Please add a test with two instances on one store.
There was a problem hiding this comment.
Fixed in 5403614. Host.AddKeyedPingListener(key, fn) calls only the newest live listener of a key. Removing the newest gives the pings back to the one before it. Removing an older one only drops it. session-budget registers in Init with the key "session-budget " + redis_url, so:
- During the drain, only the new instance counts a ping.
- If the reload fails after the new instance's
Init, itsShutdownhands the pings back to the old instance. - When the old instance stops later, its
Shutdownremoves an older registration and changes nothing.
Tests: TestKeepAlivePing_AReloadCountsAPingOnce (two instances on one host: old 0 / new 1 during the drain, then old counts again after the new one stops) and TestKeyedPingListener_NewestOfAKeyOnly. I also corrected the Init comment.
| case "plugin model calls": | ||
| fmt.Fprintf(stdout, " %-18s %s spend, not in the total above\n", l.Label, l.Figure) | ||
| case "keep-alive": | ||
| fmt.Fprintf(stdout, " %-18s %s spend; the API-key part is in the total above and off the net saving\n", l.Label, l.Figure) |
There was a problem hiding this comment.
must-fix: when a window has pings but no priced request, this line says something false. snap.Priced is Totals.PricedRequests > 0 (core/cost/usage/snapshot.go:874), and a ping is in no request counter. So the headline gate at L604 stays cost unavailable, and the pings' dollars are in no total. Pings fire while the session is idle, so this is the usual result for a short window after the agent stops: agentop cost --window 1h over an idle hour, or the TUI's short spans.
Probe at 17db976 (runCost against a fake /v1/usage returning {"window":"1h","totals":{"requests":0,"keepAliveMicros":20000,"keepAlivePings":3},"priced":false}):
COST — 1h
cost unavailable 0 requests 0 tokens
keep-alive $0.02 3 pings spend; the API-key part is in the total above and off the net saving
no priceable traffic in this window
Before this PR, the line said spend, not in the total above, which was true here. The same snap.Priced / PricedRequests gate keeps the pings out of the TUI spend strip (spend.go: Priced: snap.Priced feeds WindowUSD), the span readings, unitCosts, and agentCostCell (agents_pane.go:507, c.PricedRequests == 0 → empty cell). In this case, the PR's claim that headline spend includes the pings does not hold on any of those surfaces. Suggestion: wherever a spend figure is gated on Priced/PricedRequests, also treat KeepAliveMicros != 0 as money to show, through a helper beside money.SpendMicros. Please also add the ping-only case to the agentop cost tests and to a strip test.
There was a problem hiding this comment.
Fixed in 5403614. money.HasSpend(c) is PricedRequests > 0 || KeepAliveMicros != 0, and money.SpendPriced(snap) is snap.Priced || Totals.KeepAliveMicros != 0. They replace the Priced/PricedRequests gates on the agentop cost headline, its negative check, its "no priceable traffic" note and its breakdown rows. In the TUI, they replace the gates on the spend strip's Priced, the today figure, the span rows, unitCosts, the usage pane, the drawer and agentCostCell. Your probe is now TestRunCost_APingOnlyWindowShowsItsCharge: it shows $0.02, and neither cost unavailable nor no priceable traffic. TestSpendSummary_APingOnlyWindowHasAFigure covers the strip, including the case where subscription pings alone stay unpriced. The JSON priced field is unchanged, because it is the server's value.
|
CI on 17db976:
|
clawgenti
left a comment
There was a problem hiding this comment.
Summary
I reviewed this PR's own change, d32d3877..17db976d over #2059's head as the body asks, not the 65-file diff against main. The wiring matches the description: money.SpendMicros (costMicros + keepAliveMicros) is used on every agentop spend surface I could find (headline, breakdown rows, spend strip, today figure, span rows, drawer, usage pane, agents pane, sessions COST), money.NetMicros and the units/unknown nets subtract the pings of their own basis, session.Store.AddKeepAlive adds spend and a ping count while leaving events, UpdatedAt and the active session alone, and session-budget counts a ping's tokens by kind plus one call and never refuses it. go test passes for core/accounting, core/session, core/plugins/sessionbudget, cmd/agentop/money and cmd/agentop/tui (56 s); the two cmd/agentop failures (TestServiceInstall_RefusesABrokenConfig, TestReportSessionInterruption) reproduce identically at the stack base d32d3877, so they are this sandbox's missing systemd user bus, not this PR.
One must-fix: Pre-commit Checks is red, and the failing hook is check-test-timing on the new sessionbudget/keepalive_test.go (reproduced locally, exit 1). One suggestion on the agents pane.
Author: boazdavid (REST author_association says CONTRIBUTOR; repos/…/collaborators/…/permission reports admin, so — maintainer)
Areas reviewed: Go (core/accounting/ping.go, core/session, core/plugins/sessionbudget, cmd/agentop/*, cmd/cortex/main.go), docs, tests
Agent/IDE config (.claude/.vscode): none
Commits: 16 commits, all signed-off: yes
CI status: failing — Pre-commit Checks (see inline); 26 pass, 12 pending, 3 skipped
Not checked:
- The full
go test ./...forcore,cmd/cortexandcmd/cortex-envoythat the body reports — I ran the affected packages and all ofcmd/agentop/...instead. - Probe of the TUI's rendered output beyond the two cells quoted inline; the package's own tests cover the rest.
Generated by repoman github-pr-review@af425c8.
| t.Fatal("ping refused") | ||
| } | ||
| p.mu.RLock() | ||
| c := *p.cache["sess-1"] |
There was a problem hiding this comment.
must-fix — This is why Pre-commit Checks is red: the repo hook scripts/dev/check-test-timing.py rejects this helper, and it exits 1 on this file at the PR head (the failing GitHub step is Pre-commit Checks → Run pre-commit, run 45441143930):
core/plugins/sessionbudget/keepalive_test.go:35: sets a real timeout. Use time.Hour when the test does not exercise it, and 0 or a past deadline when the test is about it expiring.
deadline := time.Now().Add(2 * time.Second)
core/plugins/sessionbudget/keepalive_test.go:44: sleeps for a fixed time. Block on a channel the code or fake closes when it is done.
time.Sleep(5 * time.Millisecond)
Suggested fix: block on an event instead of polling. The package already asserts Redis state by calling p.accumulate(...) synchronously (plugin_test.go:341), so the Redis half can do that; for the local counters, a test hook that accumulate's defer closes would give the test something to wait on. If the poll is deliberate, CLAUDE.md ("Tests and time") allows a // timing: <reason> marker on each flagged line — but a channel is cheap here and keeps the test off the wall clock.
There was a problem hiding this comment.
Fixed in 4324334 (same finding as the thread above). The poll is removed, and the hook passes on the file.
| func agentCostCell(c usage.Counts) string { | ||
| if c.PricedRequests == 0 || negativeCost(c.CostMicros) { | ||
| // money.SpendMicros: the agent's requests plus its keep-alive pings on an API key. | ||
| if c.PricedRequests == 0 || negativeCost(money.SpendMicros(c)) { |
There was a problem hiding this comment.
suggestion — agentCostCell still gates on PricedRequests, so a row whose window holds only API-key keep-alive pings renders "—" even though the window total includes those dollars. Probe at this head:
c := usage.Counts{PricedRequests: 0, KeepAliveMicros: 20_000, KeepAlivePings: 1}
money.SpendMicros(c) // 20000
agentCostCell(c) // "—"
agentCostCellIn(c, nil, nil, agentsCostWidth) // "—"The sessions pane (sessionMoneyCellIn(spend, …)), the drawer (PricedRequests > 0 || money.SpendMicros(...) > 0) and agentop cost's headline all show $0.02 for that row, so this is the one surface in the body's list that can disagree with them. It is reachable when the ping lands in the window but the request that armed it does not — a request just before the window (or day) boundary and its ping just after.
Suggested fix: treat a priced ping as priced:
if (c.PricedRequests == 0 && c.KeepAliveMicros <= 0) || negativeCost(money.SpendMicros(c)) {
return emptyCell
}(agents_projects.go:317 has the same shape for the (other projects) row: other.CostMicros == 0 && count == 0.)
There was a problem hiding this comment.
Fixed in 5403614. agentCostCell gates on money.HasSpend, so your probe now renders $0.02 (TestAgentCostCell_APingOnlyAgentHasAFigure). The (other projects) row at agents_projects.go:317 now stays when money.SpendMicros(other.Counts) != 0.
…ping-only window's charge Review of rossoctl#2114 (clawgenti): - A config reload starts the new pipeline before the old one drains, so two session-budget instances listened at once and each ping landed twice in the shared Redis counters. Host.AddKeyedPingListener calls only the newest live listener of a key; removing it hands the pings back to the one before, so a reload that fails after Init leaves the old instance counting. session-budget keys on its redis_url. - A ping is in no request counter, so a window with only pings had Priced false and showed "cost unavailable" while the keep-alive line said the pings were in the total. money.HasSpend and money.SpendPriced treat usd keep-alive spend as a figure; agentop cost, the spend strip, today and span figures, unitCosts, the usage pane, the drawer, the agents COST cell and the "(other projects)" row use them. 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
Re-review at 5403614, the two commits since 17db976. All three earlier must-fixes hold. I re-ran each with a positive control at 17db976 rather than reading the diff:
check-test-timing—python scripts/dev/check-test-timing.pyexits 0 over the whole tree, and overcore/plugins/sessionbudget/keepalive_test.goalone. DroppingwaitWriteswas safe:countmoves the local counters under the lock beforePingreturns, so the tests read them without a poll.- The reload double count —
Host.AddKeyedPingListenerwithnotifyPing's newest-of-a-key rule is the right shape, and the handback case falls out of it correctly: removing the newest registration leaves the one before it as newest, so a reload that fails after the new instance'sInitgives the pings back. Probe, two live instances on one store and one ping:17db976→tokens=3670 calls=2;5403614→tokens=1835 calls=1. - The ping-only window —
money.SpendPriced/money.HasSpendare threaded through every surface that gates a figure:agentop cost's headline and--byrows, the spend strip, the today figure, span rows, the drawer, the usage pane and the agents COST cell. Probe, one ping-only window ($0.02, 3 pings): at5403614the summary reads$0.02 … keep-alive $0.02 3 pings … in the total above, the--by agentrow for that agent reads$0.02, and neithercost unavailablenorno priceable trafficappears; at17db976the same window printedcost unavailable,no priceable traffic in this window, and—for that row while the keep-alive line still said the spend was in the total above.
One non-blocking suggestion inline.
Author: boazdavid (REST author_association says CONTRIBUTOR; repos/…/collaborators/…/permission reports admin, so — maintainer)
Areas reviewed: Go (core/accounting/ping.go — AddKeyedPingListener, addPingListener, notifyPing; core/plugins/sessionbudget — pingKey, Init, Shutdown, count; cmd/agentop — money/savings.go, cmd_cost.go, tui/spend.go, spend_drawer.go, usage_render.go, agents_pane.go, agents_projects.go), docs (docs/session-budget-plugin.md), tests
Agent/IDE config (.claude/.vscode): none
Commits: 2 in this push (4324334, 5403614), all signed off: yes (DCO passes)
CI status: pending at review time (35 pending, 2 pass, 2 skipping); no failing check
Verified at this head (GOWORK=off): go vet ./... clean in cmd/agentop; go test -count=1 passes in core/accounting (1.6 s), core/plugins/sessionbudget, cmd/agentop/money and cmd/agentop/tui (55 s); gofmt -l empty on the touched files; scripts/dev/check-test-timing.py exits 0
Not checked:
core/plugins/contextguruand anything importing it — not touched by this push, andmodernc.org/sqlitecannot be fetched in this sandbox (the module proxy's CDN times out)- The full
go test ./...the body reports — I ran the affected packages instead - Inherited, not from this push: the sandbox's module cache holds a
GOPROXY=directcopy ofcontext-guru v0.7.7hashing to6j+87ku…whilego.sumrecordsdmVlQxu…, so Go refuses to verify it here. The entry predates this PR's commits; it matters only to a consumer that fetches that tag direct, since the proxy still serves the recorded zip
| # | File | Severity | Finding |
|---|---|---|---|
| 1 | core/plugins/sessionbudget/keepalive_test.go:75 | suggestion | The ping's Redis counters are no longer asserted end-to-end (inline) |
Generated by repoman github-pr-review@af425c8.
|
|
||
| // A keep-alive ping counts against its session like a response: its tokens by kind, and a call. | ||
| // The local counters move before Ping returns (count updates them before it starts the Redis | ||
| // write), so no wait is needed. The same delta goes to accumulate, whose Redis write |
There was a problem hiding this comment.
suggestion — this test asserted the ping's Redis counters (tokens=1835, calls=1) and now asserts only the local ones. The regression this push fixes lived in the Redis counters, and TestAccumulate_WritesToStore calls accumulate with a hand-built delta — it never exercises onPing → count → accumulate. So nothing now proves a ping reaches Redis once.
TestKeepAlivePing_AReloadCountsAPingOnce is the natural place to restore it, and its own comment already says "both write the same Redis counters": give the two instances one store (next.store = old.store, as two instances on one redis_url share one) and read the hash back. On this head that prints tokens=1835 calls=1; at 17db976 the same probe prints tokens=3670 calls=2, so the assertion has teeth.
Suggested fix: in the reload test, set next.store = old.store, and after each ping poll pendingWrites == 0 (no sleep) then assert HashGet(...)["tokens"]/["calls"]. A counter only a mock can see is the one that breaks.
There was a problem hiding this comment.
Done in 89b2168. TestKeepAlivePing_AReloadCountsAPingOnce now gives both instances one store and reads the hash back after the ping: tokens=1835, calls=1. The store signals each finished accumulate (on Expire, its last call), so the test blocks on a channel and does not poll. check-test-timing.py passes on the file. As a positive control, I switched the helper back to a plain AddPingListener, and the test failed ("old counted 1, new 1"). -race -count=10 passes.
clawgenti
left a comment
There was a problem hiding this comment.
Summary
I reviewed this PR's own change, d32d3877..54036146 (#2059 is merged, so this is now the whole diff against main: 31 files, +894/−96). The three must-fixes from the earlier reviews are fixed at this head:
- Pre-commit /
check-test-timing:scripts/dev/check-test-timing.pypasses on every changed test file (exit 0).waitWritesis gone, and the local counters are read afterPingreturns, which is correct becausecountupdates them synchronously. - Reload double count:
AddKeyedPingListenercalls only the newest live listener per key. Removing the newest hands the pings back to the previous one, and removing an older one only drops it.session-budgetregisters last inInitunder"session-budget " + redis_url, so a failedInitleaves nothing subscribed.pipeline.Start'sunwindStartshuts down the plugins that did start, which hands the pings back to the old instance as the comment says.TestKeepAlivePing_AReloadCountsAPingOncecovers both directions. - Ping-only window:
money.HasSpend/money.SpendPricedreplace thePriced/PricedRequestsgates. I probed the TUI at this head with a snapshot of{keepAliveMicros: 20000, keepAlivePings: 3}and no requests. The band rendersLAST 1H $0.02, the usage paneCOST $0.02, andagentCostCell$0.02. Subscription-only pings still render—.
I also checked the rest of the change. onPing uses the same pctx.SessionID the keeper captured (contextguru/ping.go), so a ping lands in the request's bucket. Its token total (Input + CacheRead + CacheWrite + Output) matches parsercommon.TokenUsage.Total, which feeds TotalTokens for requests. ListSessions and withPriorLocked both rebuild the figures from avoided + prior + keepAlive, so there is no double add, and Saturated covers the keep-alive sum. ListSessions is the only producer of /v1/sessions rows. The new SessionSummary fields are plain omitempty int64s, and no production decoder uses DisallowUnknownFields (only wire_fixture_test.go, which passes), so old and new agentop/server pairs decode both ways. I found no remaining Priced/CostMicros spend gate in agentop that misses the pings.
One doc gap for a follow-up, outside the diff hunks, so it is not inline: docs/session-budget-plugin.md still says, in the max_calls table row (L66) and in "max_calls enforcement scope." (L92), that only calls surfaced by inference-parser increment the counter. Keep-alive pings now do too, as the paragraph at the top of the file says.
Author: boazdavid (REST author_association CONTRIBUTOR; collaborators/…/permission is admin, so maintainer)
Areas reviewed: Go (core/accounting, core/session, core/plugins/sessionbudget, core/plugins/deps.go, cmd/cortex/main.go, cmd/agentop money/cost/TUI), docs, CLAUDE.md (doc text only)
Agent/IDE config (.claude/.vscode): none
Commits: 3 commits in this PR (18 incl. the merged stack), all signed off: yes (DCO pass)
CI status: pending. The run restarted after #2059 merged: 4 pass, 33 pending, 2 skipped, none failing when I posted. I ran the failing hook from last time locally (above).
Local runs at 5403614: gofmt -l on the changed Go files is empty, and go vet is clean for the changed core packages, cmd/agentop/... and cmd/cortex. scripts/dev/check-doc-links.py . passes. go test -race passes for core/accounting, core/session and core/plugins/sessionbudget. go test passes for cmd/agentop/money and cmd/agentop/tui. Two failures are not from this PR. core/cost/usage and core/cost/ledger fail only their America/Havana midnight tests, which the body notes fail on main too, and this PR does not touch those packages. cmd/agentop fails TestServiceInstall_RefusesABrokenConfig, which needs a systemd user bus this sandbox lacks.
…ed Redis counters once Review of rossoctl#2114 (clawgenti): the reload test checked only the local counters, and the double count it guards against lived in Redis. The two instances now share one store, as two on one redis_url share one Redis, and the test reads the hash back: tokens 1835, calls 1. The store signals each finished accumulate, so the test blocks on a channel and does not poll. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…calls Review of rossoctl#2114 (clawgenti): the max_calls table row, its "enforcement scope" note and the config description still said only inference-parser calls increment the counter. Keep-alive pings do too, where accounting is on. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
|
Thanks for the review. The doc gap from the approval is fixed in 4cbc631. The 89b2168 (after your approval) adds the Redis assertion from your suggestion to |
clawgenti
left a comment
There was a problem hiding this comment.
Summary
Re-review at 4cbc631, covering the two commits since my approval at 5403614: 89b2168 (test) and 4cbc631 (docs). Both answer the earlier review. The max_calls table row, the "enforcement scope" note and the max_calls config description now say that keep-alive pings count toward the limit where accounting is on. No generated schema or doc copies the description text, so nothing else needed to change. The reload test now gives both instances one shared store, as two instances on one redis_url share one Redis, and it reads the hash back after it blocks on a channel. That passes check-test-timing. I found nothing blocking. There is one nit inline: the new Redis read alone does not reliably catch the double count. The local-counter assertion above it still does, every time.
Author: boazdavid (REST author_association is CONTRIBUTOR; collaborators/…/permission reports admin, so maintainer)
Areas reviewed: Go test (core/plugins/sessionbudget/keepalive_test.go), config description (core/plugins/sessionbudget/plugin.go), docs (docs/session-budget-plugin.md)
Agent/IDE config (.claude/.vscode): none
Commits: 2 in this push (89b2168, 4cbc631), all signed off: yes (DCO passes)
CI status: pending at review time: 10 pass (DCO, CodeQL, Trivy, YAML Lint, action pinning, PR title, and others), 28 pending (Pre-commit Checks and the Go CI jobs among them), 2 skipped, none failing
Local runs at 4cbc631 (GOWORK=off): gofmt -l and go vet are clean for core/plugins/sessionbudget. go test -race -count=1 ./plugins/sessionbudget/ passes. scripts/dev/check-test-timing.py on keepalive_test.go exits 0. scripts/dev/check-doc-links.py . passes. git diff --check is clean.
Positive control: I gave each instance its own ping key, so both listeners fire, which is the pre-5403614 behaviour, and ran the test 10 times. The test failed 10/10 on the local-counter check (old counted 1, new 1). The new Redis assertion failed only 2/10. See the inline comment.
Not checked: anything outside these two commits. The rest of the PR is unchanged since the approval at 5403614.
| # | File | Severity | Finding |
|---|---|---|---|
| 1 | core/plugins/sessionbudget/keepalive_test.go:65 | nit | The Redis read races a second accumulate, so on its own it does not catch the double count |
| if o, n := calls(old, "sess-1"), calls(next, "sess-1"); o != 0 || n != 1 { | ||
| t.Errorf("during the drain: old counted %d, new %d; want 0 and 1", o, n) | ||
| } | ||
| <-store.done |
There was a problem hiding this comment.
nit: <-store.done returns after the first Expire. With the double-count bug, the old instance's accumulate goroutine runs at the same time, so this read often lands before its writes do. I gave each instance its own ping key to bring the bug back and ran the test 10 times. This assertion failed only 2/10 (once on a torn read, calls:1 tokens:3670). The calls(old) / calls(next) check above failed 10/10, so the test as a whole still guards the regression, and on correct code there is no flake.
No change is needed for this PR. If you want the Redis read to stand on its own, the comment could say it checks the content of the new instance's write, while the local counters guard against a second write. That split is sound, because count bumps the local counters (and launches accumulate) synchronously inside Ping.
huang195
left a comment
There was a problem hiding this comment.
Summary
I reviewed this PR's own change, d32d3877..4cbc631d (#2059 is merged). I read the full delta and checked two paths against the source at this head with probe tests. I did not commit the probes. The money arithmetic, the keyed ping listener and the session-store figures are correct and have tests. I found two gaps that the earlier rounds did not report. Neither one blocks the merge.
- The sessions pane UNITS column is not net of the subscription pings, but
agentop costis. On a subscription login, which is the usual Claude Code setup, the two surfaces show different net savings for one session. - In
on_exceed: pause, a ping that reaches a coldsession-budgetinstance (after a reload, or on a second pod) creates a local entry. The next request then skips the synchronous Redis hydrate that pause mode depends on, and goes through instead of pausing.
Author: boazdavid (MEMBER — maintainer)
Areas reviewed: Go (core/accounting, core/session, core/plugins/sessionbudget, cmd/cortex, cmd/agentop), Docs
Agent/IDE config (.claude/.vscode): none
Commits: 5 in this PR's delta, all signed-off: yes
CI status: passing
Assisted-By: Claude (Anthropic AI) [email protected]
| s.AvoidedUnits += f.units | ||
| s.PenaltyUnits += f.penaltyUnits | ||
| s.AvoidedAPIEquivalentMicros += f.apiEquivalent | ||
| s.KeepAliveMicros += f.keepAlive |
There was a problem hiding this comment.
suggestion: the UNITS column is not net of the subscription pings, but agentop cost and the drawer are.
This PR makes money.AccountantLines subtract KeepAliveUnits from the units net and KeepAliveAPIEquivalentMicros from its API equivalent. sessionUnitsCell (L704-711) still shows AvoidedUnits − PenaltyUnits and the gross AvoidedAPIEquivalentMicros. The fold here adds only KeepAliveMicros, and foldedFigure in linked.go carries no KeepAliveUnits or KeepAliveAPIEquivalentMicros. On a subscription, the keeper's rescue goes into AvoidedUnits, so this column shows the saving without the cost of the pings that earned it.
Probe at this head, with the same figures given to both functions:
sessions UNITS cell: "4.0 units (API equivalent $1.00)"
agentop cost line: 4.5 saved penalty 0.5 keep-alive 1.0 net 3.0 API equivalent net $0.70
The PR body and the new CLAUDE.md line say that every net saving subtracts the pings of its basis. A possible fix: fold KeepAliveUnits and KeepAliveAPIEquivalentMicros here and in linked.go, and compute the cell with the same net as money.netUnits (you can export it).
| return | ||
| } | ||
| u := s.Usage | ||
| p.count(s.Session, tokenDelta{ |
There was a problem hiding this comment.
suggestion: in on_exceed: pause, a ping on a cold instance stops the next request from hydrating, so that request goes through instead of pausing.
count creates &counters{startedAt: time.Now()} when the cache has no entry. OnRequest hydrates from Redis only on a cache miss (L313-347), and the comment there says pause is the mode where a one-request overshoot "would defeat the point". Before this PR, a new instance always saw OnRequest before it counted anything for a session. A ping comes for a session that is idle, which is the session that a new instance (after a reload, or on a second pod) has not seen. So the ping-seeded entry holds only the ping's counters, and evaluate checks the limit against them until refreshCache takes the max with Redis (refresh_interval, 5s by default). startedAt is also now for that time, so max_duration_seconds checks against the wrong start.
Probe at this head: Redis holds calls=5, max_calls=3, and the webhook returns 500 with pause_timeout_action: deny.
withPing=false action=Reject
withPing=true action=Continue
A possible fix: on a cache miss in onPing, do not create the local entry. Send only the Redis write (go p.accumulate(...)), so the next OnRequest takes the cold path. Another option is to call hydrateCache first. Note that accumulate's pendingWrites decrement already does nothing when there is no entry.
Stacked on: #2059
Required by: none. No PR in the series depends on this one. Merge it after #2059, at any point after that.
Review only this PR's change: boazdavid/cortex@cg/06-keepalive...cg/06b-keepalive-cost (the diff against
mainalso shows every PR below it until those merge)Part of the
[cg]series that replaces #1956, #1958 and #2053. See #2059 for the full merge order.What
#2059 prices each context-guru keep-alive ping and books it to the ledger and
/v1/usage, but only inkeepAlive*fields. No total uses those fields. This PR includes the ping cost in four places:rescueis inavoidedMicros, so the pings that earned it now come off the net.money.NetMicrosisavoided − penalty − keepAliveMicros. The subscription and unknown-billing nets subtract the pings of their own basis. agentop's "saved" line names the keep-alive spend beside the penalty.agentop cost(headline and breakdown rows) and the TUI (spend strip, today figure, span rows, drawer, usage pane, agents pane) showcostMicros + keepAliveMicros(money.SpendMicros). A window with only API-key pings (an idle hour) shows its charge, notcost unavailable(money.HasSpend,money.SpendPriced). Only pings on an API key are money. Subscription and unknown-billing pings stay out of the money totals, as before. Plugin model calls stay on their own line.accounting.Host.AddPingListeneris new:Host.Pingnotifies listeners after it records a ping.cmd/cortexregisterssession.Store.AddKeepAlive, which adds the ping's spend to newkeepAlive*andkeepAlivePingsfields on/v1/sessionsrows. A ping is not an event, so it does not changeeventCount,totalTokens,costMicros,updatedAtor the active session. The sessions pane COST column includes the pings, and its SAVED column is net of them.session-budgetis now anAccountingConsumer. It subscribes inInitand unsubscribes inShutdown, and counts each ping's tokens by kind and one call against the session. A ping is never refused. The session's next request is the one a reached limit stops. A reload starts the new instance before the old one drains, so the listener is keyed onredis_url(Host.AddKeyedPingListener): only the newest instance counts a ping, and a failed reload hands the pings back to the old one.Limits
session-budgetonly where accounting is on./v1/usagestill have them.cmd/cortex-envoyregisters no cost recorders on its host, so pings are in no envoy figure. This PR does not change that.litellm-budget-trackstill does not count pings. It reads the cost of pipeline requests. When a ping goes through the LiteLLM gateway, the gateway counts it itself.Upgrade note
With keep-alive on, which is the default,
session-budgetlimits are now reached sooner, because pings count toward them. Spend figures in agentop go up by the API-key ping spend, and net savings go down by the same amount.Testing
GOWORK=off, incore,cmd/cortex(plain and with thelocalprofile tags),cmd/cortex-envoyandcmd/agentop:gofmt -lempty,go vet ./...clean,go mod tidy -diffclean.go test ./...passes, except for the 3 America/Havana time-zone tests that fail onmaintoo (see feat(contextguru): [cg] Keep idle sessions' caches warm through the accountant #2059).go test -racepasses forcore/accounting,core/sessionandcore/plugins/sessionbudget.core/accounting/ping_listener_test.go,core/session/keepalive_test.go,core/plugins/sessionbudget/keepalive_test.go, plus new money, sessions-pane, drawer andagentop costcases. Three existing expectations changed on purpose (the net and headline now include the pings):TestAccountantLines,TestRunCost_ReportsTheAccountantsFiguresandTestDrawerFigures_ShowTheAccountantsFigures.🤖 Generated with Claude Code