Skip to content

feat(contextguru): [cg] Keep idle sessions' caches warm through the accountant - #2059

Merged
huang195 merged 24 commits into
rossoctl:mainfrom
boazdavid:cg/06-keepalive
Nov 24, 2026
Merged

huang195 merged 24 commits into
rossoctl:mainfrom
boazdavid:cg/06-keepalive

Conversation

@boazdavid

@boazdavid boazdavid commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on: #2058
Required by: #2060, #2114 (includes the pings' cost in spend, savings, sessions and budgets)
Review only this PR's change: boazdavid/cortex@cg/05-contextguru-state-disk...cg/06-keepalive (the diff against main also shows every PR below it until those merge)

Part of the [cg] series that replaces #1956, #1958 and #2053, split into reviewable layers. Merge in the order below.

# PR
— #2065 feat(pricing): Price 1-hour cache writes at the 1-hour rate (on main, not in this series) needed by #2055
1 #2054 feat(accounting): Add the accountant wire and facts packages and the dependency
2 #2055 feat(accounting): Host the accountant, with its config, pipeline hooks and case tests
3 #2056 feat(accounting): Report operators' context changes and model-call spend to the accountant
4 #2057 feat(accounting): Price the accountant's savings into the ledger, usage and sessions
5 #2058 feat(contextguru): Keep the session state on disk
6 #2059 feat(contextguru): Keep idle sessions' caches warm through the accountant this PR
7 #2060 feat(contextguru): Turn context-guru on by default on a local install
8 #2061 feat(contextguru): Port Responses, the Anthropic incoming model, the marker cap and xhigh from #1412
9 #2062 feat(accounting): Push the accountant's metrics to a central collector
10 #2063 feat(accounting): Add inference metrics for the time and bytes the proxy adds
— #2064 feat(central): Add the central metrics stack on OpenShift (on main alone, no Go)

What

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 file 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. A keeper entry holds the caller's credential and the thread's
last request body, both masked: on a 5-minute cache, (max_pings + 1) x idle_seconds --
12 minutes with no particular wait, 16 waiting on a person, or 36 waiting on its own tool call,
since the engine's wait plan (on by default) raises max_pings for the wait (its background-wait
count never applies here, since Cortex gives it no open-task data) -- and for 118 minutes (at
most 236) on a thread billed at
the 1-hour tier. A request that
inference-router translated, or gave upstream headers to, is not kept warm.

Upgrade note

Keep-alive is on by default on every install, clusters included. A cluster
that already runs context-guru (for compaction, for example) starts sending
billed pings on its callers' credentials after the upgrade, with no config
change. session-budget and litellm-budget-track do not count those pings,
and off a local install they go through HTTPS_PROXY. To keep the old
behaviour, set cache.strategy: none in the context-guru plugin's engine
config before you upgrade.

Testing

  • Built and tested on its own (this PR's tree), with GOWORK=off, in core, cmd/cortex (plain and with the local profile tags), cmd/cortex-envoy, cmd/agentop, scripts/profile-tags and scripts/readme-demo: gofmt -l empty, go vet ./... clean, go mod tidy -diff clean, go test ./... passes.
  • Review fixes (67ec6f8): go test -race passes for core/accounting/... and core/plugins/contextguru. The whole cmd/agentop package runs past the 10-minute test timeout on macOS, before and after the fixes, so CI covers it there.
  • 3 tests fail here and on main alike, from the local America/Havana time-zone data: TestMidnightTransitions_EveryFixtureIsStillTheDayItClaimsToBe (core/cost/ledger), TestStartOfLocalDay_PicksTheEarlierOfTwoMidnights and TestParseWindowSpec_TodayStartsWhereTheLocalDayStartsInEveryZone (core/cost/usage).

Assisted-By: Claude (Anthropic AI) [email protected]

@boazdavid
boazdavid requested a review from a team as a code owner November 22, 2026 13:55
@coderabbitai

coderabbitai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Too many files!

This PR contains 121 files, which is 21 over the limit of 100.

To get a review, reduce the PR to 100 files or fewer by splitting it into smaller PRs or changing its base branch.

Upgrade to a paid plan to raise the limit.

This review couldn't start because sufficient usage credits or metered capacity aren't available. Add credits or update usage-based reviews in the billing tab, then retry.

Check out review usage here.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 7bc239e4-06a1-44d1-8d5b-da29574c52e7
Commits

Reviewing files that changed from the base of the PR and between 82bfb96 and d32d387.

Files ignored due to path filters: 5

  • cmd/agentop/go.sum is excluded by !**/*.sum
  • cmd/cortex-envoy/go.sum is excluded by !**/*.sum
  • cmd/cortex/go.sum is excluded by !**/*.sum
  • core/go.sum is excluded by !**/*.sum
  • scripts/readme-demo/go.sum is excluded by !**/*.sum
Files selected for processing: 121

  • CLAUDE.md
  • cmd/agentop/cmd_cost.go
  • cmd/agentop/cmd_cost_test.go
  • cmd/agentop/go.mod
  • cmd/agentop/money/savings.go
  • cmd/agentop/money/savings_test.go
  • cmd/agentop/tui/cost_event.go
  • cmd/agentop/tui/cost_event_test.go
  • cmd/agentop/tui/events_column_sizing_test.go
  • cmd/agentop/tui/events_exchange_test.go
  • cmd/agentop/tui/events_pane.go
  • cmd/agentop/tui/events_rebuild_bench_test.go
  • cmd/agentop/tui/header_align_test.go
  • cmd/agentop/tui/linked.go
  • cmd/agentop/tui/local_preview_test.go
  • cmd/agentop/tui/prune_saving.go
  • cmd/agentop/tui/row_saving_test.go
  • cmd/agentop/tui/sessions_money_test.go
  • cmd/agentop/tui/sessions_pane.go
  • cmd/agentop/tui/sessions_server_test.go
  • cmd/agentop/tui/spend.go
  • cmd/agentop/tui/spend_drawer.go
  • cmd/agentop/tui/spend_drawer_test.go
  • cmd/agentop/tui/spend_test.go
  • cmd/cortex-envoy/go.mod
  • cmd/cortex-envoy/main.go
  • cmd/cortex/accounting.go
  • cmd/cortex/go.mod
  • cmd/cortex/main.go
  • core/accounting/host.go
  • core/accounting/host_test.go
  • core/accounting/options.go
  • core/accounting/options_test.go
  • core/accounting/ping.go
  • core/accounting/ping_basis_test.go
  • core/accounting/ping_test.go
  • core/accounting/price.go
  • core/accounting/price_test.go
  • core/accounting/savings.go
  • core/accounting/savings_agree_test.go
  • core/accounting/savings_test.go
  • core/accounting/snapshot.go
  • core/accounting/snapshot_test.go
  • core/accounting/snapshot_trim.go
  • core/config/accounting.go
  • core/config/accounting_test.go
  • core/cost/event/event.go
  • core/cost/event/event_test.go
  • core/cost/ledger/admission_test.go
  • core/cost/ledger/currency_test.go
  • core/cost/ledger/figures_test.go
  • core/cost/ledger/query.go
  • core/cost/ledger/writer.go
  • core/cost/pricing/cost.go
  • core/cost/pricing/cost_test.go
  • core/cost/pricing/estimate.go
  • core/cost/pricing/estimate_test.go
  • core/cost/settle/avoided.go
  • core/cost/settle/bound_agreement_test.go
  • core/cost/settle/decode.go
  • core/cost/settle/settle.go
  • core/cost/settle/settle_test.go
  • core/cost/usage/currency_test.go
  • core/cost/usage/pricing_test.go
  • core/cost/usage/rekey_test.go
  • core/cost/usage/replay_test.go
  • core/cost/usage/snapshot_test.go
  • core/cost/usage/usage.go
  • core/cost/usage/usage_test.go
  • core/go.mod
  • core/listener/forwardproxy/chainedwriters_test.go
  • core/plugins/contextguru/build_test.go
  • core/plugins/contextguru/dispatcher.go
  • core/plugins/contextguru/dispatcher_test.go
  • core/plugins/contextguru/envelope.go
  • core/plugins/contextguru/envelope_test.go
  • core/plugins/contextguru/keepalive.go
  • core/plugins/contextguru/keepalive_substitute_test.go
  • core/plugins/contextguru/keepalive_test.go
  • core/plugins/contextguru/keepalive_thread_test.go
  • core/plugins/contextguru/main_test.go
  • core/plugins/contextguru/mask.go
  • core/plugins/contextguru/modelclient.go
  • core/plugins/contextguru/modelclient_test.go
  • core/plugins/contextguru/ping.go
  • core/plugins/contextguru/ping_test.go
  • core/plugins/contextguru/plugin.go
  • core/plugins/contextguru/plugin_test.go
  • core/plugins/contextguru/statedb.go
  • core/plugins/contextguru/statedb_test.go
  • core/plugins/contextguru/windows.go
  • core/plugins/contextguru/windows_test.go
  • core/plugins/inferenceparser/accounting.go
  • core/plugins/inferenceparser/accounting_test.go
  • core/plugins/inferenceparser/cost.go
  • core/plugins/litellm_budgettrack/plugin_test.go
  • core/plugins/toolprune/accounting_test.go
  • core/plugins/toolprune/event.go
  • core/plugins/toolprune/plugin.go
  • core/plugins/toolprune/plugin_test.go
  • core/reloader/reloader.go
  • core/reloader/reloader_test.go
  • core/session/currencies_test.go
  • core/session/figures.go
  • core/session/fold.go
  • core/session/fold_test.go
  • core/session/history.go
  • core/session/store.go
  • core/session/store_test.go
  • core/session/summary.go
  • core/sessionapi/summary_test.go
  • docs/configuration.md
  • docs/context-guru-plugin.md
  • docs/laptop-service.md
  • docs/laptop-token-savings.md
  • docs/pricing.md
  • docs/proxy-contract.md
  • docs/session-api.md
  • docs/session-budget-plugin.md
  • docs/tool-prune-plugin.md
  • scripts/readme-demo/go.mod

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@boazdavid boazdavid changed the title [cg] feat(contextguru): Keep idle sessions' caches warm through the accountant feat(contextguru): [cg] Keep idle sessions' caches warm through the accountant Nov 22, 2026
@github-actions github-actions Bot added the ready-for-ai-review Request automated AI code review from clawgenti label Nov 22, 2026

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

I reviewed only what this PR adds on top of cg/05-contextguru-state-disk (the keeper and dispatcher, Host.Ping and the ping facts, the keep-alive split in event/ledger/usage/agentop, the 20 MiB snapshot trim, the window resolver and the docs). The split of ping spend from agent spend is consistent across the ring, the ledger and agentop, and the credential handling (masked hold, private copy per Do, no redirects, Release on Shutdown) is careful.

There is one must-fix. recordFor never passes the 1-hour cache-write count to the keeper, so the keeper treats every thread billed at the 1-hour tier as a 5-minute thread. Those threads get two pings that buy nothing and never get the 59-minute schedule. The other comments are a docs claim about what the keeper retains after DELETE /v1/sessions, two suggestions (keep-alive defaulting on in clusters, and the pre-release context-guru pin), and nits.

Author: boazdavid (admin collaborator, maintainer)
Areas reviewed: Go (core/accounting, core/plugins/contextguru, core/cost/{event,ledger,usage}, cmd/agentop/money), go.mod/go.sum, docs, CLAUDE.md
Agent/IDE config (.claude/.vscode): none (CLAUDE.md changes docs text only)
Commits: 7 commits on the stack, all signed off: yes (DCO passes)
CI status: pending when I reviewed it

Local verification on 735657b (GOWORK=off): go vet is clean on the touched packages. go test -race passes for core/accounting/..., core/plugins/contextguru, core/cost/event, cmd/agentop/money and cmd/agentop/tui. In core/cost/ledger and core/cost/usage the only failures are the three America/Havana time-zone tests the PR description already lists. cmd/agentop's TestServiceInstall_RefusesABrokenConfig fails here only because this box has no systemd user bus, and this PR does not touch it. I confirmed the must-fix with a scratch test (not pushed), described inline.

Comment thread core/plugins/contextguru/keepalive.go Outdated
Route: pctx.Path,
Status: pctx.StatusCode,
Usage: keepalive.Usage{FreshInput: int64(inf.InputTokens), CacheRead: int64(inf.CacheReadTokens),
CacheWrite: int64(inf.CacheWriteTokens), Output: int64(inf.OutputTokens)},

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

must-fix: the keeper never sees the 1-hour cache-write count, so it never puts a thread on the 1-hour schedule.

keepalive.Usage here leaves out CacheWrite1h, although inf.CacheWrite1hTokens is parsed (and pingFromReport maps it the other way). The keeper decides a thread's tier with keepalive.ResolveTier(body, u, usageOK, prev) → BilledOneHour(u.CacheWrite, u.CacheWrite1h, prev). Whenever the turn wrote cache, that check needs CacheWrite1h >= CacheWrite. With the field always 0, every turn that writes cache resolves to the 5-minute tier.

So a thread that asks for ttl: "1h" on every breakpoint and is billed at 1h never gets Policy.ForOneHour():

  • It is pinged at 4 and 8 minutes. That is billed spend on the caller's credential for a cache that would have lived an hour anyway, and keep-alive is on by default.
  • It never gets the 59-minute ping that would carry it past the hour.

I checked this with a scratch test on this head. The body was 1h-marked and had CacheWriteTokens = CacheWrite1hTokens = 90000. recordFor(...).Usage.CacheWrite1h came back 0 and keepalive.ResolveTier returned false. The same usage with the field set returned true.

Suggested change
CacheWrite: int64(inf.CacheWriteTokens), Output: int64(inf.OutputTokens)},
CacheWrite: int64(inf.CacheWriteTokens), CacheWrite1h: int64(inf.CacheWrite1hTokens), Output: int64(inf.OutputTokens)},

Please also pin it in TestRecordForMapsAFinishedRequest, or add a small test next to it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 67ec6f8. recordFor now passes CacheWrite1h. TestRecordForCarriesTheOneHourCacheWrite pins the mapping and checks that ResolveTier returns true. TestKeepAliveHoldFollowsTheBilledTier drives a 1h-asked, 1h-billed turn through OnFinish and asserts that the entry is TTL1h with a 118-minute hold. Both tests fail without the fix.

Comment thread docs/session-api.md Outdated
a local install), the billing mode of each thread's last request and any keep-alive
ping facts not yet credited (both in `core/accounting.Host`), and the context-guru
keeper's entries. They hold session and thread ids, content hashes and a billing
mode, never content; a keeper entry also holds the caller's credential, masked.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion: "never content" is not true of the keeper's entries, and the retention bound is wrong for 1-hour threads.

  • Content: a keeper entry holds more than ids and the masked credential. keepalive.Record.Body is documented as "exact bytes sent upstream; the keeper copies and masks it", which is the full forwarded conversation that each ping re-sends. After a DELETE, the erased session's transcript stays in memory (masked) and can still go upstream until the entry is released.
  • Retention bound: the bound depends on the entry's policy. For a 1-hour-tier thread, kaEntry.hold() is (MaxPings1h+1) × Idle1h, which is 118 min at the shipped defaults (the library's own doc comment says so), not about 12 min. You only see this once the 1h tier resolves (see the keepalive.go comment), but the docs should say it.
  • The copies disagree: line 412 says about 12 minutes, line 435 and docs/laptop-service.md say 13.5. At the defaults, (2+1) × 240s is 12 minutes.

The same wording is in CLAUDE.md (around line 270), docs/laptop-service.md (around line 691) and the "Credential retention" paragraph of docs/context-guru-plugin.md.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 67ec6f8. All copies now say that a keeper entry holds the caller's credential and the thread's last request body, both masked, and that a ping re-sends that body. The hold is 12 minutes on a 5-minute thread and 118 minutes (at most 236, keepalive.MaxHold1h) on a 1-hour thread. This is in CLAUDE.md, docs/session-api.md, docs/laptop-service.md and docs/context-guru-plugin.md. The duplicated session-api.md paragraph is now one copy, so the 13.5 figure is gone.

Comment thread core/plugins/contextguru/keepalive.go Outdated
// Every value is a knob on a decision the engine makes; none of them is a decision. A zero value
// takes the engine's own shipped default (config.DefaultKeepAlive*).
type keepAliveConfig struct {
Enabled bool `json:"enabled" description:"Ping an idle session's prompt cache before it expires. Each ping is billed to the caller's own credential." default:"true"`

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion: enabled defaults to true on every install, not only the local profile. A cluster that already runs context-guru for compaction will start sending billed pings on its callers' credentials after the upgrade. Those pings are outside session-budget/litellm-budget-track, and off a local install they go through the egress proxy. context_window.model_info already defaults differently on and off a local install for a similar reason. Consider defaulting keep-alive to p.local (#2060 turns context-guru on for local anyway), or at least call out the change in the release notes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The maintainer decided to keep keep-alive on by default on every install. In 67ec6f8 I added an upgrade note for clusters to docs/context-guru-plugin.md: a cluster that already runs context-guru starts pinging on its callers' credentials with no config change, and keep_alive: {enabled: false} before the upgrade keeps the old behaviour. The same note is in the PR description.

Comment thread core/go.mod Outdated
github.com/open-policy-agent/opa v1.22.4
github.com/rossoctl/context-guru v0.7.3
github.com/rossoctl/accountant v0.5.0
github.com/rossoctl/context-guru v0.7.5-beta.2

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion: context-guru v0.7.5-beta.2 is a pre-release. That is fine while the stack is in review, but please move to a tagged release before this merges to main, since this engine now decides when billed pings are sent. The same applies to the indirect pins in cmd/cortex and cmd/cortex-envoy.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 67ec6f8. The pin is now the v0.7.5 release in core, cmd/cortex and cmd/cortex-envoy. go mod tidy -diff is clean in each.

Comment thread core/plugins/contextguru/windows.go Outdated
// A standalone client, not one routed back through this proxy. The map refreshes in the
// background, so a lookup never waits on the network; until the first fetch lands the
// chain falls through and the fraction triggers decline, which is the safe direction.
chain = append(chain, litellm.New(c.ModelInfoURL, &http.Client{Timeout: 30 * time.Second}, 0))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit: the comment says this is "a standalone client, not one routed back through this proxy". But an http.Client with no Transport uses http.DefaultTransport, which honours HTTPS_PROXY. On a local install that variable points at Cortex itself, so the LiteLLM fetch goes back through Cortex's forward proxy, which is the case modelTransport(local) and newPingClient(local) are written to avoid. Either use &http.Client{Timeout: 30 * time.Second, Transport: modelTransport(p.local)} (with local passed in), or reword the comment.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 67ec6f8. The LiteLLM client now uses Transport: modelTransport(local), so on a local install it ignores HTTPS_PROXY. The comment says so.

Comment thread core/accounting/ping.go Outdated
CacheWriteTokens: p.Usage.CacheWrite,
// CacheWrite1h is the part of CacheWrite billed at the 1-hour rate, never an
// addition to it (p.Usage embeds accountant.Usage, whose own doc says the
// same). Task 7 (2026-11-17 accountant-integration): the 1h cache-write

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit: references to the development log ("Task 7 (2026-11-17 accountant-integration)" here and in the usageHook doc in host.go, and the "(review finding)" asides in ping.go, snapshot.go and plugin.go) will mean nothing to a later reader. The comments already explain why on their own, so these references can go.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 67ec6f8 for the files this PR adds or edits: ping.go, ping_test.go, snapshot.go, host.go (the usageHook doc and the others), plugin.go and build_test.go. A few remain in files that lower layers own (savings.go, boundary_test.go, host_test.go). I left those for their own PRs.

Comment thread core/accounting/snapshot_trim.go Outdated
)

// trimmableSnapshotVersion is the accountant snapshot format trimSnapshot knows (accountant
// v0.3.0, internal/engine/persist.go snapshotVersion). A snapshot of any other version is not

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit: the comment names accountant v0.3.0, but the module is now v0.5.0. I checked v0.5.0's internal/engine/persist.go: it is still snapshotVersion = 1 with the same {version, threads[{key, created, prevPrint{at}}]} shape, so the code is right and only the version in the comment is stale.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 67ec6f8. The comment now names v0.5.0.

Comment thread core/accounting/savings.go Fixed
@boazdavid
boazdavid changed the base branch from main to cg/05-contextguru-state-disk November 22, 2026 16:11

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

This PR's base is main, so its diff also carries the 9 commits of #2065 and #2054-#2058. This review covers only fab047b (the keep-alive commit, 47 files), compared with its parent ce97be9. The keep-alive wiring is careful. Credentials are masked, cloned for Do and zeroed. Redirects are refused, the arrive/depart bookkeeping covers every exit path, nothing is held under observe, and the Shutdown stop flag is in place. Pings stay out of every request, token and latency figure in both the ledger and the ring. I found one must-fix: the PR's documented credential-retention bound, and its "no content" claim, do not hold for the keeper the PR wires in. There are also a few suggestions.

Author: boazdavid (FIRST_TIME_CONTRIBUTOR, first-time by association; the repo permission API reports admin)
Areas reviewed: Go (core/plugins/contextguru, core/accounting, core/cost/{event,ledger,usage}, cmd/agentop/money), Docs, go.mod
Agent/IDE config (.claude/.vscode): none
Commits: 1 commit in scope (fab047b), signed off: yes
CI status: the failures are inherited from lower layers of the stack, not from this commit:

  • CodeQL: one high alert at core/accounting/savings.go:413 (logTokens). That line comes from f088aee (#2057).
  • Pre-commit Checks: check-doc-links fails on docs/configuration.md -> laptop-service.md#the-metrics_push-configuration, which comes from the #2055/#2057 layers. This commit fixes the other broken anchor its parent had (pricing.md -> context-guru-plugin.md#where-its-own-model-calls-go).
  • Rust (praxis) is green but has a non-blocking annotation: "cargo test failed (does not block: no praxis-mode changes)". It shows on every PR from #2055 up and not on main, so it most likely comes from the session-event golden change lower in the stack.
  • Several Go CI jobs were still pending when I posted this.

Local verification (head fab047b, GOWORK=off): go vet is clean on plugins/contextguru, accounting/... and cost/.... go test passes on plugins/contextguru and accounting, also with -race. In cost/..., only the 3 America/Havana tz-data tests the PR description lists fail.

Dependency: github.com/rossoctl/context-guru moves to a pre-release, v0.7.5-beta.2. Please move it to a final tag before this lands on main, or say in the description why a beta is acceptable.

Comment thread docs/context-guru-plugin.md Outdated

**Spend:** each ping is billed to the caller's credential and logged as `context-guru keep-alive ping`. Where accounting is on, the plugin also hands the ping to the accountant host (`core/accounting`'s `Host.Ping`). The host refuses a ping with no idle window, a status outside 200-299, or no usage. Otherwise it prices the ping with Cortex's rate table and writes it to the cost ledger and the usage aggregator as a response event, never through the session store: a ping is not agent activity. The event's cost record keeps `source` and `provenance` as for any request (how the cost was arrived at), carries `purpose: keep-alive`, and carries the `basis` of the thread's last request's billing mode, because a ping uses the same credential. The ledger and `/v1/usage` keep a ping out of every request figure: it counts in `keepAlivePings`, never in `requests`, `costMicros`, the tokens or the latency mean. Its spend is split by basis, as [pricing.md](pricing.md#cost-records) describes: only a ping on an API key is money (`keepAliveMicros`); a ping on a subscription login is booked in usage-limit units (`keepAliveUnits`, with its API-equivalent dollars beside them), and one whose billing mode is unknown is shown apart (`keepAliveUnknownMicros`). The metrics push books ping dollars on the same rule. The first ping after a restart has no last request to read, so it is `unknown`. The thread's next priced request then carries the ping's facts, so the accountant credits the cache it kept warm as a `rescue` under the ping's own `ChangeID` (`ka:<thread>:<window>`). A manual ping is priced but credits no rescue. Where accounting is off, the log line is the only record. Pings are not counted by `session-budget` or `litellm-budget-track`.

**Credential retention:** Cortex keeps the caller's credential in memory, masked, for up to `(max_pings + 1) × idle_seconds` per tracked thread — about 12 minutes at the defaults above. It is released on that thread's next request, on plugin `Shutdown` or a config reload, or at that deadline, whichever comes first.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

must-fix: this bound does not hold for the keeper this PR wires in.

  • One-hour-tier threads. keepalive.Keeper.Record swaps in Policy.ForOneHour() when ResolveTier sees a thread whose cache the provider billed at the 1-hour tier (context-guru v0.7.5-beta.2, keepalive/keeper.go ~L991). That uses Idle1h/MaxPings1h, by default 59 min and 1 ping. kaEntry.hold() is then (1+1) x 59 min = 118 min, with a cap of MaxHold1h = 236 min. It is not (max_pings + 1) x idle_seconds = 12 min. A Claude Code session that asks ttl: "1h" on its breakpoints reaches this path, and the plugin's keep_alive block has no knob for it.
  • OpenAI threads. These follow OpenAIIdle (default OpenAIMinimumCacheTTL - 2m), not idle_seconds, so their hold is also longer than stated.
  • Content. The keeper holds the request body as well as the credential: Record.Body is "exact bytes sent upstream; the keeper copies and masks it". That is the whole transcript, masked, for the same period. docs/session-api.md (both copies of the paragraph), docs/laptop-service.md and CLAUDE.md all say the keeper holds "never content" / "no content" beyond the masked credential.

These are the guarantees an operator reads to decide what DELETE /v1/sessions leaves behind, so they need to be correct. Either:

  • (a) bound the hold from the plugin: set Idle1h/MaxPings1h (and OpenAIIdle) in keepAliveConfig.policy(), or refuse the 1h swap, so the documented formula is true; or
  • (b) document the real bounds (about 12 min on a 5-minute thread, about 118 min and at most 236 min on a 1-hour thread, the OpenAI figure), and say that the keeper holds the last request body, masked, along with the credential.

A test that records a 1h-billed thread and asserts the entry's release time would keep the docs honest.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 67ec6f8 with option (b). The docs now give the real bounds: 12 minutes on a 5-minute thread, and 118 minutes (at most 236) on a thread billed at the 1-hour tier. They also say that the keeper holds the last request body, masked, with the credential. TestKeepAliveHoldFollowsTheBilledTier records a 5-minute thread and then a 1h-billed thread, and asserts each entry's hold, so the docs stay correct if the engine's defaults move.

I did not add an OpenAI figure. In the plugin, the keeper does not read OpenAIIdle. In context-guru v0.7.5 only the standalone proxy reads it (proxy/keepalive.go swaps pol.Idle = pol.OpenAIIdle), and keepalive/keeper.go never does. So an OpenAI thread here follows idle_seconds and has the 12-minute bound.

if p.keeper == nil || pipeline.GetState[kaShadow](pctx, kaShadowStateKey) != nil {
return
}
hdr := pctx.Headers

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion: when inference-router translated the request, the ping does not replay what went upstream.

Translate leaves pctx.Body in the client's protocol and pctx.Path at the client's path. The listener converts the body and applies the translate path on the wire only (listener/forwardproxy/translate.go, "pctx.Path does not change"). pctx.Host, however, is the routed target, and pctx.Headers carries the target's key (setAuth). So recordFor hands the keeper an Anthropic /v1/messages body, for example, to ping at https://<openai-compatible target>/v1/messages with the target's credential. That ping cannot succeed, and Cred is fed into the keeper's dead-credential mark. Headers the router sets with SetUpstreamHeaders (srv.headers) are not replayed either.

The simplest fix: skip Record when pctx.TranslateTarget() reports ok, and add pctx.UpstreamHeaders() to the ping header set (or skip when it is non-empty). Then add a test that drives a translated request through OnFinish and asserts nothing is held.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 67ec6f8. recordFor now skips a request when pctx.TranslateTarget() reports ok or pctx.UpstreamHeaders() is non-empty (replayable). TestKeepAliveHoldsNothingForARequestTheRouterRewrote runs a real WritesDestination plugin through pipeline.Run for both cases, then OnFinish, and asserts that no entry and no credential are held. It also checks that a plain redirect is still recorded.

Comment thread core/plugins/contextguru/keepalive.go Outdated
// Every value is a knob on a decision the engine makes; none of them is a decision. A zero value
// takes the engine's own shipped default (config.DefaultKeepAlive*).
type keepAliveConfig struct {
Enabled bool `json:"enabled" description:"Ping an idle session's prompt cache before it expires. Each ping is billed to the caller's own credential." default:"true"`

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion: consider defaulting enabled to the local install only, as context_window.model_info already does (modelInfoOn). With this default, a cluster operator who turns context-guru on for compaction also gets, with no further opt-in, Cortex holding every tenant's credential and transcript, masked, and spending on those credentials. The INFO/WARN at Configure is the only signal. The laptop case, which #2060 turns on, keeps its default.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The maintainer kept the default on for every install. I added an upgrade note instead; see the reply on the other comment about this line.

Comment thread docs/laptop-service.md Outdated
newer sessions push it out (at most 10,000 threads are kept), and a state file older than 1 hour
is not read at startup (see [session-api.md](session-api.md#delete-v1sessions)).
billing mode, no content, in memory and in `~/.cortex/accountant-state.json`, plus the
keep-alive keeper's masked credential. The keeper's entries go within about 13.5 minutes at its

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit: "about 13.5 minutes" here, and in the second copy of the paragraph in docs/session-api.md (L435), while context-guru-plugin.md, the first session-api.md copy and CLAUDE.md say 12 minutes ((2+1) x 240 s). Please pick one figure, which depends on the must-fix above. The duplicated session-api.md paragraph predates this commit, but this commit edits both copies, so it may be worth folding them into one.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 67ec6f8. Every copy now says 12 minutes on a 5-minute thread, plus the 1-hour figure, and the duplicated session-api.md paragraph is now one copy.

@clawgenti clawgenti left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Reviewed at fab047b, base cg/05-contextguru-state-disk. No must-fix findings: the keeper wiring is careful — the credential is held masked and zeroized on release, the ping client has the proxy pinned off and redirects refused, pings are accounted as their own purpose and kept out of every request/token/cost/latency figure, the snapshot save is dirty-gated, and the ping-facts map is capped and trimmed like threadBilling. The findings below are documentation-versus-code mismatches and one narrow shutdown window.

Suggestions

  • The 20 MiB cap does not bound the file, and the doc says it does. snapshotMaxBytes = 20 << 20 (core/accounting/snapshot.go) is applied to the raw state before encoding, and the code's own comment notes that State is JSON "which encoding/json writes as base64 for a []byte" — so the file lands at up to ~4/3 the cap. Probe with a state just over the cap (throwaway, deleted): cap=121332 trimmed State=117301 file=156459 ratio=1.290x, i.e. a 20 MiB state budget can produce a ~26 MiB file. docs/laptop-service.md says the file "stays under 20 MiB". Either budget the encoded length (4*((n+2)/3)) when trimming, or reword the doc to say the state is capped and the file may be a third larger.
  • The keeper-retention figure contradicts itself across the docs this PR touches. The same formula (max_pings + 1) × idle_seconds is glossed as "about 12 minutes" in docs/session-api.md and "about 13.5 minutes" in docs/session-api.md and docs/laptop-service.md. With the shipped defaults (idle_seconds 240, max_pings 2) it is 3 × 240 s = 720 s = 12 minutes; 13.5 matches no default. Make all three say 12.
  • "The snapshot file, rewritten every 60s, holds what memory holds" is now false past the cap. save deliberately leaves the oldest threads out of the file while memory keeps them. The sentence survives in CLAUDE.md and in docs/session-api.md (twice) and now contradicts this PR's own new paragraph about trimming.
  • A request finishing during a hot-reload drain can install a held credential after Shutdown has swept the keeper. OnFinish checks p.stopped.Load(), then does a store write (recordBilled), then calls keeper.Record; Shutdown sets stopped and then calls keeper.Shutdown, so an OnFinish that passed the check before the store can reach Record after the sweep. Bounded — the keeper arms a per-entry expiry so the credential is still zeroized at the hold deadline — but the comment "releases every held credential before returning" is stronger than the code. A small RWMutex around Arrive/Record/Depart and Shutdown closes it.

Nit — cmd/agentop/money/savings.go: the keep-alive line's guard omits KeepAliveAPIEquivalentMicros, so a subscription ping whose milli-units round to zero shows a ping count with neither units nor the API-equivalent beside it.

Author: boazdavid (FIRST_TIME_CONTRIBUTOR — first-time)
Areas reviewed: Go (core/plugins/contextguru, core/accounting, core/cost/{event,ledger,usage,settle}, cmd/agentop/money), docs
Agent/IDE config (.claude/.vscode): none. The repo-root CLAUDE.md is modified (documentation only); no .claude/ or .vscode/ path is touched.
Commits: 1 commit, all signed-off: yes
CI status: failing, both inherited rather than caused here — Pre-commit Checks fails on docs/configuration.md → laptop-service.md#the-metrics_push-configuration (an anchor added by a lower layer, reproduced locally with scripts/dev/check-doc-links.py), and CodeQL flags core/accounting/savings.go:413, a file outside this PR's 47-file diff. All Go CI jobs pass.

Verified by: at head, go test ./accounting/... ./cost/... ./accounting/... and the targeted new tests (TestRow_AKeepAlivePingIsItsOwnColumn, TestAggregator_AKeepAlivePingIsNotARequest, TestAggregator_ASubscriptionPingBooksUnitsNotMoney, the snapshot/trim tests) all pass; the only failures are the three America/Havana time-zone tests the body names as pre-existing. gofmt -l empty. The keeper's defaults (DefaultKeepAliveIdle = 240, DefaultKeepAliveMaxPings = 2) were read from the vendored context-guru source at the PR's pin to check the 12-minute arithmetic. Snapshot probe as quoted, deleted afterwards. Not run here: the context-guru plugin integration tests — its modernc.org/sqlite dependency resolves through a host this sandbox blocks — so CI's plugin jobs are the evidence for those.

Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).

boazdavid added a commit to boazdavid/cortex that referenced this pull request Nov 23, 2026
- Move the CodeQL suppression above the slog.Debug call in logTokens, where CodeQL reads it.
- Match wire.FormatOf and facts.Classify on the parser's suffixes (/chat/completions,
  /responses), so a saving on a path without /v1, on Azure or on Codex is recorded. Log one
  DEBUG line when an operator reported ops on a path the accountant cannot read.
- Keep HTTPS_PROXY for context-guru's own model calls outside a local install; pin it off only
  on a local install, where it points back into Cortex.
- Count a row whose only accountant figure is a negative net, or is in units, in
  ledger.CurrenciesIn, as the ring does.
- Drop the metrics_push docs (rossoctl#2062) and the keep-alive purpose row and agentop label (rossoctl#2059).
- Add the context-guru-plugin.md section the pricing.md link points to.
- Restore the session-api.md and CLAUDE.md paragraph a rebase duplicated.
- Document how the billing basis is chosen from the client's credential (follow-up: rossoctl#2074).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
@boazdavid
boazdavid force-pushed the cg/05-contextguru-state-disk branch from ce97be9 to fa760c8 Compare November 23, 2026 08:00
boazdavid added a commit to boazdavid/cortex that referenced this pull request Nov 23, 2026
…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]>

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Re-review at 20622ee8, this layer only (cg/05-contextguru-state-disk...cg/06-keepalive: 7 commits, 47 files). The stack is now rebased on main (82bfb968), and context-guru is bumped to v0.7.7. The range-diff against 769ba92e shows no changes beyond the go.mod/go.sum bump, apart from the new commit.

The new commit fixes what it says it fixes for 1-hour-head. p.kaPol is now stored even when keep-alive is off, HeadTTL1h/HeadTTLMinBytes reach apply.Opts, and the Changed || Trace.HeadTTL1h OR covers the library paths that drop the relabel (apply.go:921 and :1121). TestOnRequest_HeadTTL1hStrategyRelabelsAnExistingHeadBreakpoint is a real test: without the OR it fails with "expected the tools breakpoint to be relabelled". TestKeepAliveFalseWithNoStrategyStaysOff pins the round-1 fix.

Two must-fixes remain:

  1. must-fix (unchanged, open threads on plugin.go:521/:530): injectDefaultCacheStrategy appends YAML after an engine that is always JSON by the time Configure sees it, so keep-alive is off for every config that sets engine at all. Re-probed at this head (configured(t, ...), then p.keeper != nil):

    {}                                                      keeper=true
    {"engine":{"preset":"xhigh"}}                           keeper=false
    {"engine":{"preset":"balanced"}}                        keeper=false
    {"engine":{"preset":"xhigh","cache":{"strategy":"auto"}}} keeper=true
    

    The PR body ("Keep-alive is on by default and each agent's cache is kept warm"), the upgrade note and the docs all still state the default as if it reached these configs. #2060's local config (engine: {preset: xhigh}) is one of them.

  2. must-fix (narrowed, inline on plugin.go:602): OneHourFirst is still not wired, and the reason in the comment and the commit message is not right: keepalive.Keeper.OneHourFirst is exported in v0.7.7. As a result, 1-hour-always behaves exactly like auto (5-minute writes, pings every 240s), while the docs offer it and say strategies behave "identically" to context-guru-proxy. A wiring sketch that I compiled and probed is inline.

New in this round: one suggestion, inline on plugin.go:686. A body that already carries ttl: "1h" is reported as rewritten, with identical bytes.

Still open from the last round, with the tree unchanged, so not repeated inline:

  • suggestion: the model → cheap_model rename and the removal of paths are silent (threads on plugin.go:142).
  • suggestion: the PR body's Upgrade note still says to set keep_alive: {enabled: false}. That key is retired and only WARNs now. The docs say engine.cache.strategy: none.
  • nit: docs/context-guru-plugin.md:26 still says "uses the model block". It should say cheap_model.
  • nit: the field comment at plugin.go:294 ("all nil/zero when keep_alive.enabled is false") is now wrong twice: the key is retired, and kaPol is no longer zero when the keeper is nil.

Author: boazdavid (CONTRIBUTOR by author_association; the permission API reports admin, so maintainer)
Areas reviewed: Go: core/plugins/contextguru (new commit: Configure, OnRequest's apply.Opts, reportResult, tests), checked against context-guru v0.7.7 apply, keepalive, config/strategy.go and proxy; docs; stack ancestry and rebase
Agent/IDE config (.claude/.vscode): none (the gate found no matches in the PR diff or in this layer)
Commits: 7 in this layer, all signed off: yes (DCO passes)
CI status: the PR is now MERGEABLE. Workflows were queued for this head but had not finished when this review was posted: 36 checks pending, DCO passing. Locally at 20622ee8: go vet ./plugins/contextguru/ is clean, go build ./... in core and cmd/cortex and go vet ./... in cmd/cortex pass, and go test -race passes for core/plugins/contextguru, core/accounting/... and core/config.

Not checked: live pings against a real upstream (no gateway or credential in this sandbox), and cmd/agentop.

Verified by: scratch tests in core/plugins/contextguru (deleted afterwards) for the default-strategy table above, 1-hour-always/1-hour-on-wait at head (body unchanged, no "1h") and with the inline sketch applied (1-hour-always relabels, package tests pass), and the already-1h body. Also a mutation check: with the || res.Trace.HeadTTL1h removed, the new HeadTTL1h test fails.

Comment thread core/plugins/contextguru/plugin.go Outdated
// without them here, that strategy resolved a policy nothing read, and OnRequest asked for
// the plain 5-minute tier regardless (review finding). OneHourFirst, the 1-hour-always/
// -on-wait strategies' own effect (p.kaPol.OneHourAlways/OneHourOnWait), is not wired here:
// the decision it needs (keepalive.Keeper's own oneHourFirstThread) is unexported, so this

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

must-fix: the reason given here does not hold, and 1-hour-always still has no effect at this head.

Keeper.OneHourFirst is exported in the version this PR pins (context-guru v0.7.7 keepalive/onehour.go:410, and v0.7.6 too). It is where the decision is made: the unexported oneHourFirstThread only reads the map that OneHourFirst fills. context-guru's own proxy wires it as apply.Opts.OneHourFirst (proxy/modes.go:76, built by oneHourFirstFor in proxy/keepalive.go:486-500).

What happens today (scratch probe at this head, deleted afterwards): with engine: {cache: {strategy: 1-hour-always}} and a /v1/messages body with tools and a 5m breakpoint, OnRequest leaves the body unchanged, with no "1h". The keeper is built on the auto schedule. Because nothing calls OneHourFirst, k.oneHourFirst stays empty and keeper.go:919 never puts the thread in the 1-hour mode. So 1-hour-always behaves like auto: the main thread writes at 5 minutes and is pinged every 240s. The strategy's own description says the opposite: it writes at 1 hour and gets no pings. For 1-hour-on-wait, the ping-side switch lives in the keeper (keeper.go:1065) and works. Only its costly-route fallback (mode D) needs this hook.

Meanwhile docs/context-guru-plugin.md:24 and the ConfigSchema text still list both strategies, and the docs say a strategy "behaves identically" here and in context-guru-proxy.

The wiring fits in this layer. I tried this sketch locally. It keys on the same session, endpoint and route that recordFor gives the keeper, and it skips subagent and observe requests, as the keeper does. With it, 1-hour-always relabels the tools breakpoint to 1h, auto and 1-hour-on-wait leave a first request alone, and go test ./plugins/contextguru/ still passes:

var oneHourFirst func(session, threadID, model string, toolsDeclared bool) bool
if p.keeper != nil && !pctx.Observing() && (p.kaPol.OneHourAlways || p.kaPol.OneHourOnWait) {
	if key, ok := keeperKey(pctx, sid); ok && key.Thread == "" {
		oneHourFirst = func(_, _ string, model string, toolsDeclared bool) bool {
			return p.keeper.OneHourFirst("", sid, "", provider, pctx.Host, pctx.Path, model, toolsDeclared,
				keepalive.OneHourMode{Always: p.kaPol.OneHourAlways, RebuildTokens: int64(p.kaPol.OneHourRebuildTokens)})
		}
	}
}
// ... apply.Opts{..., OneHourFirst: oneHourFirst}

(The hook's own session argument is the engine's derived key, not sid, so it is ignored. threadID is always "" here because no ThreadOf is wired, which is why the subagent check uses keeperKey.) If you would rather leave this for a later layer, the docs and ConfigSchema should then stop offering 1-hour-always (and should state the on-wait gap), and Configure should WARN when either strategy is picked. A test like TestOnRequest_HeadTTL1hStrategyRelabelsAnExistingHeadBreakpoint for 1-hour-always would pin it either way.

Comment thread core/plugins/contextguru/plugin.go Outdated
// authoritative here regardless of which path set Changed, so ORing it in recovers exactly
// the one case this library gap drops; it is already true, so this is a no-op, on every path
// that already counted it.
out, changed = res.Body, res.Changed || res.Trace.HeadTTL1h

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion: Trace.HeadTTL1h is also true when nothing was relabelled. upgradeHeadTTL (context-guru apply/headttl.go) sets upgraded = true for a breakpoint that already says ttl: "1h", and leaves the bytes unchanged. A client that already sends 1-hour markers, which Claude Code does on some setups, then gets changed = true on every request at or above the size gate. The result is SetBody with identical bytes, BodyMutated() true, a body-mutation session event, and an INFO line "context-guru rewrote request body" with pctSaved 0.

Probe at this head: 1-hour-head with head_ttl_min_bytes: 1 and a tools breakpoint already at "1h" gives BodyMutated=true and bytes.Equal(out, in)=true.

Something like res.Changed || (res.Trace.HeadTTL1h && !bytes.Equal(res.Body, pctx.Body)) keeps the fix for the case you reproduced and drops this one. It also covers the 1-hour-first defer (apply.go:436-439), which sets HeadTTL1h before its own bytes.Equal check, once that hook is wired.

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed the keep-alive layer only: the 7 commits from cg/05-contextguru-state-disk to cg/06-keepalive (47 files). The diff against main also contains the lower stack. Focus: the keeper wiring in core/plugins/contextguru, ping accounting in core/accounting, and the ledger/usage split.

The implementation reads carefully and the money split is consistent across the ledger and /v1/usage. The findings are documentation and an upgrade hazard, not a defect in the ping path.

Author: boazdavid (CONTRIBUTOR — returning external)
Areas reviewed: Go (context-guru plugin, accounting ping/snapshot, cost/event, cost/ledger, cost/usage, agentop money), docs
Agent/IDE config (.claude/.vscode): none
Commits: 16 vs main (7 in this layer), all signed-off: yes
CI status: pending at review time
Not checked:

  • core/plugins/contextguru build and tests — the module cache holds context-guru v0.7.6, the PR needs v0.7.7, and the module-zip host (storage.googleapis.com) is unreachable from this sandbox; modernc.org/sqlite and modernc.org/libc zips are absent too. §3.12 forbids installing a toolchain, so no head-vs-base probe of that package.
  • go mod tidy -diff — same network requirement.

Verified by: gofmt -l over the 35 changed Go files (clean); go vet on accounting, cost/event, cost/ledger, cost/usage (clean); go test ./core/accounting/... ./core/cost/... (pass, except the three America/Havana DST fixtures the PR body already names as failing on main too); source cross-checks of the keeper/dispatcher against context-guru v0.7.7's keepalive and dispatch packages.

Generated by repoman github-pr-review@af425c8.


There used to be a plugin-level `keep_alive` block here (`enabled`, `idle_seconds`, `max_pings`, `max_usd_per_ping`, `min_prefix_tokens`), predating `engine.cache` support. It is retired: every one of its knobs is a `cache.keepalive_*` key on the engine's own config already, so keeping both was keeping two copies of the same decision. A config that still sends a `keep_alive` block gets one `WARN` naming the retired key and is otherwise unaffected — the key is accepted and ignored, not refused, so an old document keeps loading.

**Upgrade note for clusters:** a cluster that already runs context-guru (for compaction, for example) gets keep-alive with no config change. From then on Cortex holds each tracked thread's credential and last request, masked, and sends billed pings on those credentials. `session-budget` and `litellm-budget-track` do not count the pings, and off a local install they go through `HTTPS_PROXY`. To keep the old behaviour, set `engine.cache.strategy: none` before you upgrade. Every decision (whether to ping, how much, when to stop) stays inside the context-guru engine, not this plugin.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

must-fix — the PR description's upgrade note contradicts this line and the code.

The body says: "To keep the old behaviour, set keep_alive: {enabled: false} in the context-guru plugin config before you upgrade." This PR retires that key: warnOnRetiredKeepAliveKey (core/plugins/contextguru/plugin.go) logs one WARN and ignores it, and injectDefaultCacheStrategy still appends cache.strategy: auto when the engine YAML has no cache: key.

Concrete case: an operator who already runs keep_alive: {enabled: false} upgrades, sees the WARN, and keep-alive is on — billed pings leave on callers' own credentials while nobody is at the keyboard. Following the PR body reproduces exactly the behaviour it says it prevents.

Suggested fix: correct the PR body to point at engine.cache.strategy: none. Consider also honouring an explicit enabled: false (map it to the off strategy) rather than only warning, since that was the documented off-switch before this PR.

Second, smaller correction in the same paragraph: "gets keep-alive with no config change" holds only when the engine YAML has no cache: key at all. Any operator-authored cache: block — even one that only sets keepalive_* without keepalive: true — skips the injected default and stays off. Worth one sentence so the scope is accurate.

engine pulls a large transitive dependency set.
pass-through; model-driven expand/restore is a later integration. The
plugin also implements `OnFinish`, `Init`, and `Shutdown` for the
keep-alive feature below. It ships in the `local`, `full` and

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion — this paragraph describes #2060's state, not this PR's.

At this head, scripts/profile-tags/profiles.go still has "contextguru": {}, core/plugins/all/plugins_contextguru.go still says "context-guru belongs to no shipped profile", and cmd/cortex/local.go does not enable it. So between merging this PR and #2060 the docs claim a local install ships and enables context-guru when it does not, and if #2060 is dropped they stay wrong.

Suggested fix: move the "ships in the local, full and fullcpex build profiles … the local config enables it by default (preset xhigh)" sentence to #2060, or land the profile/local change in this PR.

Comment thread core/go.sum
github.com/rossoctl/accountant v0.5.0/go.mod h1:AA9aM/QvO3AksXUGjOJiunMSxiZ1PqRsCxqKvq4IsrI=
github.com/rossoctl/context-guru v0.7.4 h1:q7X2OmVkBGKqrg8LZje11m3/8dY0572ih2BXMQoxT88=
github.com/rossoctl/context-guru v0.7.4/go.mod h1:aGG2sHz8n6K0JOrDQd1CMqOV89qTu2kHlnRrzCB4i/Q=
github.com/rossoctl/context-guru v0.7.7 h1:dmVlQxu3vZtaHe1OuBy80RWnyt+dzxr36skd+IO+IYg=

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit — go.sum matches the published module (sum.golang.org records h1:dmVlQxu3…), but the v0.7.7 tag on GitHub was re-pointed after publication: the proxy published v0.7.7 from 23a4b03 (2026-11-23 10:47Z), while the tag now resolves to 30a8076 (14:55Z). The two differ only in .gitignore and proxy/accountant_wire_test.go.

Concrete case: GOPROXY=direct go mod download github.com/rossoctl/[email protected] fails with checksum mismatch: downloaded h1:6j+87kuCN780fTDykq9aiG8gNmG3omVC4rmGG0a01/0=. CI uses the module proxy, so it is unaffected; a direct build is not. Pinning a pseudo-version of 23a4b03, or re-tagging immutably upstream, removes the surprise.

…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]>

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Re-review at e21f17a1, this layer only (cg/05-contextguru-state-disk...cg/06-keepalive: 8 commits, 47 files). The range-diff against 769ba92e shows the rebase onto main (82bfb968) and the context-guru v0.7.7 bump, plus two new commits: 20622ee8 and e21f17a1.

Three findings from the last two rounds are fixed, and I checked each one at this head:

  • Default strategy injection. injectDefaultCacheStrategy now re-marshals the document. {"engine":{"preset":"xhigh"}}, {"engine":{"preset":"balanced"}}, {"engine":{}} and a pipeline:-style engine all build the keeper. cache: {keepalive: false} and cache: {strategy: none} still leave it off.
  • 1-hour-head. HeadTTL1h/HeadTTLMinBytes reach apply.Opts, and the bytes.Equal guard drops the already-1h false positive. TestOnRequest_HeadTTL1hStrategyIsANoOpWhenAlreadyRelabelled is a real test: it fails once the guard is removed.
  • PR body upgrade note. It now points at cache.strategy: none.

OneHourFirst is now wired, and TestOnRequest_OneHourAlwaysStrategyRelabelsEveryExistingMark fails once the wiring is removed. Two problems block this head, though.

Must-fix

  1. oneHourFirstFor asks the keeper about a different route, and a different thread, than the one recordFor records (inline on plugin.go:868). It passes route "", but recordFor records Route: pctx.Path. So the keeper's route state (off after a silent downgrade, costly after a probe) never reaches this hook. That has three effects:
    • Under 1-hour-always, the downgrade stop never takes effect. The keeper logs "the threads fall back to the plain schedule", but every later request is still relabelled to 1h.
    • Mode D of 1-hour-on-wait can never fire, so that strategy's request-side half is still a no-op.
    • A named subagent's request is relabelled to 1h too, because threadID is always "" here.
  2. injectDefaultCacheStrategy panics on engine: null (inline on plugin.go:542). An engine: key whose children are all commented out reaches Configure as {"engine":null}. That panics with assignment to entry in nil map, and plugins/deps.go:143 does not recover it, so Cortex fails to start. At the base (8c164cb) the same config loads.

Still open from earlier rounds (unchanged at this head, so not repeated inline):

  • suggestion: the model → cheap_model rename and the removal of paths are silent (json.Unmarshal ignores both). keep_alive gets a WARN for the same situation.
  • suggestion: docs/context-guru-plugin.md:7 describes #2060's profile and local-config state, not this PR's.
  • nit: docs/context-guru-plugin.md:23 says "passed through verbatim", which the next bullet contradicts (the cache.strategy: auto injection). Line 26 still says "uses the model block".
  • nit: the field comment at plugin.go:295 ("all nil/zero when keep_alive.enabled is false") is stale: the key is retired, and kaPol is now set even when the keeper is nil.

Author: boazdavid (CONTRIBUTOR by author_association; the permission API reports admin, so maintainer)
Areas reviewed: Go: core/plugins/contextguru (Configure, injectDefaultCacheStrategy, OnRequest's apply.Opts, oneHourFirstFor, reportResult, and the new tests), checked against context-guru v0.7.7 apply, keepalive/onehour.go and proxy/keepalive.go; stack ancestry and range-diff
Agent/IDE config (.claude/.vscode): none (the gate found no matches in the PR diff)
Commits: 8 in this layer, all signed off: yes (DCO passes)
CI status: queued at review time (36 checks pending, DCO passing). Locally at e21f17a1 (GOWORK=off): gofmt -l is empty, go vet ./plugins/contextguru/ is clean, go build ./... in core passes, and go test -race passes for core/plugins/contextguru, core/accounting/... and core/config.

Verified by: scratch tests (deleted afterwards). One table-probes Configure over the engine shapes above plus {"engine":null}, at head and at the base. Another drives OnRequest/OnFinish under 1-hour-always with a downgraded response and a request carrying X-Claude-Code-Agent-Id. A third parses a PluginEntry with an empty engine: through core/config. I also ran mutation checks on the two new OnRequest tests.

Not checked: live pings or 1-hour probes against a real upstream (no gateway or credential in this sandbox), and cmd/agentop.

Comment thread core/plugins/contextguru/plugin.go Outdated
}
mode := keepalive.OneHourMode{Always: p.kaPol.OneHourAlways, RebuildTokens: int64(p.kaPol.OneHourRebuildTokens)}
return func(session, threadID, model string, toolsDeclared bool) bool {
return p.keeper.OneHourFirst("", session, threadID, provider, endpoint, "", model, toolsDeclared, mode)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

must-fix: these arguments do not match what recordFor gives the keeper, so the keeper's per-route and per-thread state never reaches this hook.

The route is not the proxy's cost-routing concept. oneHourRoute(provider, endpoint, route, model) keys oneHourRoutes, and recordFor fills Record.Route with pctx.Path. So everything the keeper learns for the route is stored under anthropic|<host>|/v1/messages|<model>: checkOneHourFirstDowngrade's off (onehour.go:494) and the probe's costly (onehour.go:167/197, from the ping job's route). This hook then reads anthropic|<host>||<model>, where nothing is ever stored. context-guru's own proxy passes the same route to both (proxy/keepalive.go:464 and :498).

I probed it at this head with 1-hour-always. I drove OnRequest, then OnFinish with a downgraded response (CacheWriteTokens: 50000, CacheWrite1hTokens: 0), three turns in a row:

turn 1: request relabelled to 1h=true
WARN ... no more 1-hour keep-alive pings on this route; the threads fall back to the plain schedule: a request with 1-hour markers wrote tokens and was billed at 5 minutes (a silent downgrade) route=/v1/messages
  after finish: OneHourFirst(route=/v1/messages)=false  OneHourFirst(route="" as plugin wires)=true
turn 2: request relabelled to 1h=true
turn 3: request relabelled to 1h=true

The effects:

  • 1-hour-always: the downgrade stop never takes effect, even though the WARN says the threads fall back.
  • 1-hour-on-wait: mode D can never fire, because st.costly is never found. The strategy's request-side half is therefore still a no-op, which is the gap this commit says it closes.
  • Subagents: threadID comes from res.Trace.Thread.ID, which is always "" here (no ThreadOf is wired). So a named subagent's request is treated as the main thread. Probe: with X-Claude-Code-Agent-Id set, 1-hour-always relabels it to 1h (keeperKey gives Thread: "a:<id>"), while auto leaves it alone. The library keeps this mode to the main thread, and 1-hour writes are billed at 2x base input instead of 1.25x. The request also sets oneHourFirst on the main thread's key.
  • Session: session is the engine's derived id. It equals sid only when sid passes session.safeExplicit. A sid from the Identity.Subject() fallback with / in it does not, and then the hook and Record key different threads.

A fix is to build the hook per request from what recordFor uses:

func (p *ContextGuru) oneHourFirstFor(pctx *pipeline.Context, sid string, provider bschemas.ModelProvider) func(string, string, string, bool) bool {
	if p.keeper == nil || pctx.Observing() || (!p.kaPol.OneHourOnWait && !p.kaPol.OneHourAlways) {
		return nil
	}
	if key, ok := keeperKey(pctx, sid); !ok || key.Thread != "" {
		return nil // main thread only, as the keeper keys it
	}
	mode := keepalive.OneHourMode{Always: p.kaPol.OneHourAlways, RebuildTokens: int64(p.kaPol.OneHourRebuildTokens)}
	host, route := pctx.Host, pctx.Path
	return func(_, _ string, model string, toolsDeclared bool) bool {
		return p.keeper.OneHourFirst("", sid, "", provider, host, route, model, toolsDeclared, mode)
	}
}

pctx.Observing() matches the keeper's own kaShadow rule. A request whose rewrite is discarded should not put the thread in the mode. Please add two tests: a downgraded OnFinish followed by a request that is no longer relabelled, and a subagent-header request that is not relabelled.

if err := cache.Encode(map[string]string{"strategy": cgconfig.DefaultStrategy}); err != nil {
return engine // cgconfig.DefaultStrategy is a constant string; this does not fail in practice
}
doc["cache"] = cache

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

must-fix: doc is a nil map when engine is JSON null, so this assignment panics.

yaml.Unmarshal([]byte("null"), &doc) returns no error and leaves doc nil. The cache lookup above then misses, and doc["cache"] = cache panics. This is reachable from an ordinary config file. An engine: key whose children are all commented out:

- name: context-guru
  config:
    engine:
      # preset: xhigh

reaches Configure as {"engine":null}. I checked that with PluginEntry in core/config. Probe: New().Configure({"engine":null}) panics with assignment to entry in nil map at this head, and configures cleanly at the base 8c164cb. plugins/deps.go:143 calls Configure without a recover, so Cortex fails to start (or a reload panics) instead of returning a config error.

Either initialise the map (if doc == nil { doc = map[string]yaml.Node{} }), or treat null like an absent engine in Configure (len(engine) == 0 || string(bytes.TrimSpace(engine)) == "null" → preset: balanced). The second keeps the documented default. Please add {"engine":null} to TestKeepAliveOnByDefaultWithANonEmptyEngine.

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Re-review at e21f17a, this layer only (cg/05-contextguru-state-disk...cg/06-keepalive: 8 commits, 47 files). Only the top commit is new since the last round (20622ee8..e21f17a, plugin.go + tests). It does what two of its three claims say: the cache.strategy: auto injection now survives a non-empty engine: (verified with the head's own injectDefaultCacheStrategy against cgconfig.LoadBytes v0.7.7, table below), and the head-TTL change signal no longer calls SetBody on identical bytes. The third claim — wiring apply.Opts.OneHourFirst — lands on a route key the keeper never writes, so 1-hour-on-wait still does nothing at the request's breakpoints, and the hook has no subagent guard, so 1-hour-always relabels subagent requests at the 1-hour write premium. Both are inline.

engine: input before (append) after (re-marshal)
preset: balanced auto, keepAlive=true auto, keepAlive=true
{"preset":"xhigh"} "", keepAlive=false auto, keepAlive=true
{"preset":"xhigh","cache":{"strategy":"none"}} none, false none, false
{"preset":"xhigh","cache":{"keepalive":false}} "", false "", false
{"preset":"xhigh","cache":{"strategy":"1-hour-head"}} 1-hour-head, headTTL1h=true same

The keeper's own probe confirms the route-key half of the gap (context-guru v0.7.7, Record → Sweep → judgeOneHour, scratch test deleted afterwards): after a costly 1-hour probe recorded on route /v1/messages, a fresh main thread with an aged 49k-token prefix gets OneHourFirst(route="/v1/messages")=true and OneHourFirst(route="")=false. The new 1-hour-always test passes because C (mode.Always) never reads the route state — D (1-hour-on-wait) does, and nothing tests it.

Must-fix

  1. plugin.go:868 — OneHourFirst is asked with route=""; the keeper keys its route state by the record's pctx.Path, so 1-hour-on-wait never enters and the gateway-downgrade stop never reaches this question. Inline.
  2. plugin.go:862 — no subagent guard: apply.Opts.ThreadOf is unset, so threadID is always "", and a named-agent request is asked as the main thread and relabelled under 1-hour-always. Inline.

Suggestions

  • docs/context-guru-plugin.md:24 still tells operators a strategy "behaves identically in both" hosts, and lists 1-hour-on-wait. With must-fix 1 that sentence is false for the wait strategies; please either wire them or say which ones differ here.
  • docs/context-guru-plugin.md:26 still says "On other dialects the component uses the model block"; the key is cheap_model now (raised last round, unchanged).
  • The PR body's Testing section still cites 67ec6f83, which is no longer in this branch.

Author: boazdavid (CONTRIBUTOR by author_association; repo permission admin — maintainer, returning external)
Areas reviewed: Go (core/plugins/contextguru: Configure, injectDefaultCacheStrategy, OnRequest's apply.Opts, reportResult, oneHourFirstFor) against context-guru v0.7.7 (apply, keepalive), the new tests, docs
Agent/IDE config (.claude/.vscode): none (gate run over the layer diff: no matches)
Commits: 8 in this layer, all signed off: yes (DCO passes)
CI status: every job QUEUED at review time except DCO (success); the PR is MERGEABLE again after the rebase

Not checked:

  • go test for core/plugins/contextguru — modernc.org/sqlite v1.56.0 is unreachable from this sandbox (storage.googleapis.com TLS handshakes time out), so the package and its tests cannot be compiled here; the new TestOnRequest_* cases therefore run in CI, not in this review.
  • head-vs-base probes against a live upstream — no gateway or credential in this sandbox.

Verified by: the injectDefaultCacheStrategy probe over cgconfig.LoadBytes v0.7.7 quoted in the table (old vs head implementations, same inputs); keepalive in-package probes at v0.7.7 through Record/Sweep/judgeOneHour and through OneHourFirst directly, quoted inline; git diff 20622ee8..e21f17a (three files); gofmt -l over core/plugins/contextguru (empty); the §3.5a grep over the layer diff. Scratch worktrees and probe files were deleted afterwards.

Generated by repoman github-pr-review@af425c8.

Comment thread core/plugins/contextguru/plugin.go Outdated
}
mode := keepalive.OneHourMode{Always: p.kaPol.OneHourAlways, RebuildTokens: int64(p.kaPol.OneHourRebuildTokens)}
return func(session, threadID, model string, toolsDeclared bool) bool {
return p.keeper.OneHourFirst("", session, threadID, provider, endpoint, "", model, toolsDeclared, mode)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

must-fix — route must be the request's path, not "", or the wait strategies never fire.

keepalive.Keeper keys its one-hour route state by oneHourRoute(provider, endpoint, route, model) (onehour.go:59), and every write to that map comes from the record and ping path: Record.Route — which this plugin sets to pctx.Path (keepalive.go:145) — and pingJob.route, copied from the entry. OneHourFirst reads that map twice: st.costly gates D (1-hour-on-wait), and st.off stops the mode after a silent gateway downgrade (checkOneHourFirstDowngrade, keyed by r.Route). Asking with "" asks about a route that is never written, so both reads always miss.

It is not that the route is "unresolved": the plugin already resolves it, and already puts it in every Record. The parenthetical above ("a route this plugin does not resolve either") is what makes it look deliberate.

Evidence at context-guru v0.7.7, through the keeper's own Record → Sweep → judgeOneHour path (scratch in-package test, deleted afterwards): a request recorded with Route: "/v1/messages" leaves a 1-hour probe ping answered with a rewrite (CacheRead: 0, CacheWrite: 49000), so the route becomes costly=true; then for a fresh main thread with a 10-minute-old 49k-token prefix:

OneHourFirst(..., route="/v1/messages") = true
OneHourFirst(..., route="")             = false

1-hour-always works only because C (mode.Always) never consults the route state — which is why the new test at plugin_test.go:166 passes over the gap.

Suggested fix: close over pctx.Path the way pctx.Host is closed over, and pass it as route. Add a 1-hour-on-wait case driven through Configure (the new test covers 1-hour-always only), and, if you want the downgrade stop covered too, one where the keeper has marked the route off.

Comment thread core/plugins/contextguru/plugin.go Outdated
// plugin does not resolve either (the proxy's own cost-routing concept) -- both passed "", which
// OneHourFirst's own doc does not require non-empty. endpoint is the request's host, closed over
// once per request rather than threaded through apply.Opts a second way.
func (p *ContextGuru) oneHourFirstFor(provider bschemas.ModelProvider, endpoint string) func(session, threadID, model string, toolsDeclared bool) bool {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

must-fix — a subagent request is asked as the main thread, so 1-hour-always relabels it too.

keepalive.Keeper.OneHourFirst refuses any non-empty threadID (onehour.go:411: threadID != "" returns false) because the library relabels only the main thread — a subagent does not wait long enough for a 1-hour write to pay for itself, and that write costs 2x. apply passes res.Trace.Thread.ID, and this plugin wires no apply.Opts.ThreadOf, so that value is always "" (reportResult's own comment says so). oneHourFirstFor never sees pctx and never calls pctx.Subagent(), so a Claude Code subagent or agent-team teammate request is indistinguishable from the main thread at this hook.

Evidence at v0.7.7:

OneHourMode{Always:true}: threadID=""      -> true
OneHourMode{Always:true}: threadID="a:ag7" -> false

Under cache.strategy: 1-hour-always the subagent's request therefore comes back true, apply relabels every existing breakpoint at 1h, and the mode is recorded under the main thread's key.

Suggested fix: take pctx (or a small predicate) into oneHourFirstFor and return nil when pctx.Subagent() != "" — the same identity keeperKey's first branch uses for the agent's own thread. A test with a subagent pctx would pin it.

… 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]>

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Re-review at cd8e41be, this layer only (cg/05-contextguru-state-disk...cg/06-keepalive: 9 commits, 47 files). The only new commit since e21f17a1 is cd8e41be. It changes four test files and no production code, to satisfy check-test-timing (#2080). Two of its three changes are sound. The third weakens the test it touches: with the concurrency cap removed, that test now passes almost every run. The two must-fixes from the last round are unchanged.

Checked at this head:

  • core/accounting/ping_test.go: the barrier now blocks on <-release alone, and go test's -timeout ends a hang. TestPing_ConcurrentRequestsCreditOneRescue passes 20/20 under -race.
  • keepalive_substitute_test.go and ping_test.go: both keepers are built with Go: func(f func()) { f() } (lines 78 and 159), so Sweep has already finished the ping when it returns, and the polling loops were dead code. Removing them is correct.
  • scripts/dev/check-test-timing.py passes over every _test.go file in this layer.

Must-fix

  1. New in cd8e41be: TestCgModel_MaxConcurrentBoundsInFlightCalls no longer detects a missing cap (inline on plugin_test.go:675).
  2. Still open: oneHourFirstFor asks the keeper about route "" and never checks for a subagent (plugin.go:862-869, unchanged). The keeper's off/costly route state never reaches this hook, so 1-hour-on-wait never fires, the downgrade stop doesn't take effect, and 1-hour-always relabels subagent requests. See #2059 (comment) and #2059 (comment).
  3. Still open: injectDefaultCacheStrategy panics on {"engine":null} (plugin.go:542, unchanged). I re-ran the probe at this head: New().Configure({"engine":null}) panics with assignment to entry in nil map. See #2059 (comment).

The earlier suggestions and nits (the silent model→cheap_model/paths rename, the stale docs/context-guru-plugin.md lines 7/23/24/26, the stale field comment at plugin.go:295, and the PR body's Testing section citing 67ec6f83) are also unchanged, so I have not repeated them inline.

Author: boazdavid (CONTRIBUTOR by author_association; repo permission admin, so maintainer)
Areas reviewed: Go tests (core/accounting/ping_test.go, core/plugins/contextguru/{plugin,ping,keepalive_substitute}_test.go); re-checked oneHourFirstFor and injectDefaultCacheStrategy at this head
Agent/IDE config (.claude/.vscode): none (gate run over the layer diff and the full PR diff: no matches)
Commits: 9 in this layer, all signed off: yes (DCO passes)
CI status: every job except DCO (success) was QUEUED at review time. Locally at cd8e41be (GOWORK=off): gofmt -l is empty, go vet is clean, and go test -race passes for core/accounting/... and core/plugins/contextguru.

Verified by: a mutation run that set cgModel.sem to nil in Configure and ran the max-concurrent test at -count=30, with this head's test and with e21f17a1's; an in-package {"engine":null} probe; the timing hook. All scratch files were deleted afterwards.

Not checked: live pings against a real upstream, and cmd/agentop.

}
// Wait for the cap to actually bind before releasing, so the peak this observes is the
// steady state, not a race against goroutine scheduling.
<-atCap

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

must-fix: atCap is not the event the 200 ms sleep stood for, so this test no longer catches a missing cap.

The sleep waited until all n goroutines had reached either the server or the semaphore. atCap closes as soon as maxConc calls are in flight, and with a working cap those are the first two to arrive. The test then releases at once. If the cap is broken, the other four calls are usually still starting up at that point, so peak stays at 2 and the test passes.

Mutation probe: in Configure, set sem: nil instead of make(chan struct{}, maxConcurrent), so the model is unbounded. Then run go test -count=30 -run 'TestCgModel_MaxConcurrentBoundsInFlightCalls$':

test version failures with the cap removed
e21f17a1 (200 ms sleep) 30/30 (peak concurrent calls = 6)
this head (<-atCap) 5/30 on one run, 0/30 on a second

So the commit message's claim that atCap is "the real event the sleep was approximating" doesn't hold. A regression in max_concurrent would now pass CI almost every time.

There is no event for "the other calls are blocked on the semaphore", so a fix has to check the cap directly or keep a wait that the hook allows:

  • Deterministic (preferred): this is an in-package test, so after <-atCap, also assert on the semaphore itself, e.g. s := m.(cgModel).sem; if cap(s) != maxConc || len(s) != maxConc { t.Fatalf(...) }. That fails every time with the cap removed or mis-sized, and the peak assertion stays as a behavioural check.
  • Or keep a settle wait after <-atCap, annotated with // timing: <reason> as check-test-timing.py allows, so a broken cap still lets all six calls reach the server before the release.

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Re-review at cd8e41be, this layer only (cg/05-contextguru-state-disk...cg/06-keepalive). Only one commit is new since the e21f17a1 round: cd8e41be, which is test-only (4 files, no production code). It does what it says — the time.Sleep/polling loops are replaced by the events they were approximating (Sweep with Go: func(f func()) { f() } runs the ping inline; atCap closes when max_concurrent calls are actually in flight), which is what check-test-timing and the repo's test rules ask for. I found nothing wrong with it.

The two must-fixes from the e21f17a1 round are unchanged at this head, because cd8e41be touches no production code. Both still have their inline comments from that round (plugin.go:868 and plugin.go:542), so I am not duplicating them inline here.

Must-fix (carried, still open at cd8e41be)

  1. oneHourFirstFor asks the keeper about a route and a thread it never recorded (plugin.go:868, plugin.go:862). recordFor records Route: pctx.Path (keepalive.go:137), and the keeper keys its one-hour route state by oneHourRoute(provider, endpoint, route, model); the hook passes route="", so st.off (the gateway-downgrade stop, checkOneHourFirstDowngrade, keyed by r.Route) and st.costly (mode D of 1-hour-on-wait) always miss. Separately, apply.Opts.ThreadOf is unset, so threadID is always "", and Keeper.OneHourFirst refuses only a non-empty threadID — a named subagent's request is asked as the main thread and relabelled under 1-hour-always at the 2x 1-hour write premium. plugin.go:678 already documents that res.Trace.Thread.ID is empty with no ThreadOf wired.
  2. injectDefaultCacheStrategy panics on an engine: key with no value (plugin.go:542). I reproduced the whole path independently: an engine: whose children are all commented out reaches Configure as {"engine":null} (yamlNodeToJSON → null; json.Unmarshal into the json.RawMessage field keeps null, len 4), yaml.Unmarshal([]byte("null"), &doc) leaves doc nil without an error, and doc["cache"] = cache panics with assignment to entry in nil map. At the base (8c164cbb, where the plugin has no injection at all) the same input is cgconfig.LoadBytes("null"), which returns a zero config and no error; on the layer before e21f17a1 it produced a clean config error. plugins/deps.go:143 calls Configure without a recover, and the reload path builds plugins on the reload goroutine, so this is a process start-up crash, and a crash of a running proxy on reload. Suggested fix: if doc == nil { doc = map[string]yaml.Node{} }, or treat a trimmed null like an absent engine (then the documented preset: balanced default applies).

Still open from earlier rounds (suggestions/nits, unchanged, not repeated inline)

  • suggestion: model → cheap_model and the removal of paths are silent (json.Unmarshal ignores both); keep_alive gets a WARN for the same situation.
  • suggestion: docs/context-guru-plugin.md:7 describes #2060's profile and local-config state, not this PR's.
  • nit: docs/context-guru-plugin.md:23 says "passed through verbatim", which the next bullet contradicts; line 26 still says "uses the model block".
  • nit: the field comment at plugin.go:295 ("all nil/zero when keep_alive.enabled is false") is stale: the key is retired and kaPol is now set even when the keeper is nil.
  • suggestion: the PR body's Testing section still cites 67ec6f83, which is no longer in this branch.

Author: boazdavid (CONTRIBUTOR by author_association; the permission API reports admin, so maintainer)
Areas reviewed: Go (core/plugins/contextguru: Configure, injectDefaultCacheStrategy, oneHourFirstFor, reportResult; the four test files in cd8e41be), checked against context-guru v0.7.6 apply, keepalive/onehour.go and keepalive/keeper.go, and against the cycle's stack ancestry
Agent/IDE config (.claude/.vscode): none (gate run over the layer diff: no matches)
Commits: 9 in this layer, all signed off: yes (DCO passes)
CI status: queued at review time (all jobs pending except DCO, which passes)

Not checked:

  • Compiling core/plugins/contextguru or running its tests here — modernc.org/sqlite v1.56.0 and context-guru v0.7.7 are absent from this sandbox's module cache and both module-zip hosts time out, so the package cannot be built. The findings above are source-level and probe-level, not test-run results.
  • context-guru v0.7.7 internals — I read v0.7.6, the newest cached copy; the oneHourRoute/recordFor/OneHourFirst code the findings rest on is present identically there.
  • live pings or 1-hour probes against a real upstream — no gateway or credential in this sandbox.

Verified by: a standalone probe of the head's injectDefaultCacheStrategy (both the pre-e21f17a1 append form and the head's re-marshal form) against yaml.v3 and cgconfig.LoadBytes (v0.7.6): {"preset":"xhigh"} and {"pipeline":["collapse"]} now resolve cache.strategy: auto, {"preset":"xhigh","cache":{"strategy":"none"}} stays none, {"cache":{"keepalive":false}} stays off, and null panics with assignment to entry in nil map while {} does not; a second probe confirming the YAML→JSON path (engine: → null → RawMessage("null"), len 4) and that LoadBytes("null") returns ok at the base; git diff --stat e21f17a1 cd8e41be (test files only) and git range-diff over the cycle's layer; source reads of keepalive.Keeper.OneHourFirst (refuses a non-empty threadID), oneHourRoute, checkOneHourFirstDowngrade, and apply.Opts.ThreadOf. All probe files were written outside the checkout and deleted afterwards.

Generated by repoman github-pr-review@af425c8.

@huang195 huang195 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Summary

I reviewed this layer only (cg/05-contextguru-state-disk...cg/06-keepalive at cd8e41be, 9 commits, 47 files). I read the production code of this layer: the plugin wiring, the dispatcher, credential masking, Host.Ping, the snapshot trim, and the event, ledger and usage split. I checked each claim against context-guru v0.7.7. The credential custody is careful. A ping's headers come from PingHeaders' allow-list. The ping client refuses redirects. A pingTimeout of 60 s bounds each ping, and the keeper's MaxBytes (128 MiB) bounds what it holds.

I confirm clawgenti's three open must-fix items at this head, so I do not repeat them inline:

  • oneHourFirstFor passes route "". In v0.7.7, OneHourFirst keys its off/costly state by oneHourRoute(provider, endpoint, route, model), and Record writes pctx.Path. So 1-hour-on-wait never starts. The session id does match: sessionIDFrom returns sid unchanged.
  • The {"engine":null} panic in injectDefaultCacheStrategy.
  • TestCgModel_MaxConcurrentBoundsInFlightCalls.

Author: boazdavid (MEMBER, maintainer)
Areas reviewed: Go (core/plugins/contextguru, core/accounting, core/cost/{event,ledger,usage}), docs
Agent/IDE config (.claude/.vscode): none
Commits: 9 in this layer. DCO passes.
CI status: pending. Only DCO has finished.
Not checked: go test (I ran no build), live pings, cmd/agentop, envoy-sidecar mode.

Assisted-By: Claude (Anthropic AI) [email protected]

Comment thread docs/context-guru-plugin.md Resolved
Comment thread docs/laptop-service.md
newer sessions push it out (at most 10,000 threads are kept), and a state file older than 1 hour
is not read at startup (see [session-api.md](session-api.md#delete-v1sessions)).
billing mode, no content, in memory and in `~/.cortex/accountant-state.json`. Nor does either
erase the keep-alive keeper's entries, which hold the caller's credential and the thread's last

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

suggestion: After DELETE /v1/sessions/{id} (agentop x), the keeper still holds the erased conversation and the credential. It also continues to send that conversation upstream until the hold ends. A user who erases a session does not expect this. The keeper has RetireSession(tenant, session) in v0.7.7. A hook from the two DELETE routes could call it with tenant "". If you keep the current behaviour, please say in this paragraph that pings continue after an erase.

Comment thread core/accounting/ping.go
Duration: info.Duration,
Client: client,
}
r.Record(sessionID, ev)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

suggestion: Ping events go only to the usage aggregator and the ledger (cmd/cortex/main.go:749, :799). They do not go to the archive. At startup, /v1/usage replays the last 6 hours from the archive (cmd/cortex/archive.go:156). After a restart, /v1/usage therefore loses keepAlivePings and ping spend for that window, but the ledger keeps them, so the two views disagree. Please write ping events to the archive too, or document the gap.

Comment thread CLAUDE.md Outdated
credential and the thread's last request body (the whole forwarded conversation), both masked,
and a ping re-sends that body. The context-guru state DOES
hold content (the summary checkpoint and other text the plugin made), and its rows stay 30 days
after their last write. A keeper entry goes at `(max_pings + 1) × idle_seconds` (12 minutes

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: The root CLAUDE.md loads in every session, and these new lines repeat docs/session-api.md#delete-v1sessions. Please keep only the pointer. This is the same request as the nit on #2055.

…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]>

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Re-review at a8ccd49d, this layer only (cg/05-contextguru-state-disk...cg/06-keepalive). The only commit since cd8e41be is a8ccd49d, which changes plugin.go and three test files. Its three stated fixes all work at this head:

  • OneHourFirst route and thread. oneHourFirstFor now passes pctx.Path (what recordFor records as Route) and agentThreadPrefix + pctx.Subagent() (what keeperKey uses). I checked this against context-guru v0.7.7 Keeper.OneHourFirst/oneHourRoute/checkOneHourFirstDowngrade. The session passed (oneHourSession = sessionIDFrom(...)) matches the keeper's Key.Session. A scratch probe under 1-hour-always sent a request, finished it billed at 5 minutes (a silent downgrade), and then sent a new session's request. At head that request is not relabelled. With route := "" it is. So the gateway-downgrade stop now reaches this hook. TestOneHourAlwaysDoesNotRelabelASubagentsRequest is a real test: it fails once the threadID line is reverted.
  • {"engine":null} panic. Fixed. TestConfigure_NullEngineDoesNotPanic panics with assignment to entry in nil map once the doc == nil guard is removed.
  • Retired model/paths keys now WARN. No current top-level field is named model or paths (the model json tag belongs to modelConfig, under cheap_model), so this cannot fire on a valid config.

Two must-fixes from the cd8e41be round are still open, because this commit does not touch them:

  1. must-fix: TestCgModel_MaxConcurrentBoundsInFlightCalls still does not detect a missing cap (#2059 (comment)). plugin_test.go only gained a new test in this commit. I re-ran the mutation at this head (sem: nil at plugin.go:489, -count=30): 4 of 30 runs fail, so a max_concurrent regression would pass CI almost every time.
  2. must-fix: the "12 minutes" credential/conversation hold is still stated in docs/context-guru-plugin.md:78, docs/session-api.md:419, CLAUDE.md:275, docs/laptop-service.md:708 and the PR body (#2059 (comment)). I confirmed this against v0.7.7 at this head. cachePolicy sets WaitPlan: resolved.WaitPlanOn(), which is true when unset. On a planned wait, Record sets pol.MaxPings to the plan's ping count (keeper.go:1060, pol.MaxPings = pings), and hold() is (MaxPings+1) × Idle (keeper.go:287-289). With DefaultToolWaitMaxPings = 8, a tool wait holds the credential for up to 36 minutes under auto.

Two new suggestions are inline: the route half of the fix has no test, and the null-engine comment says one thing while the code does another.

Still open from earlier rounds (unchanged, not repeated inline):

  • nit: docs/context-guru-plugin.md:26 still says "the component uses the model block". The new WARN now tells operators that model is retired and points them to this same doc.
  • nit: docs/context-guru-plugin.md:23 says "passed through verbatim", which the cache.strategy: auto bullet below it contradicts.
  • nit: the field comment at plugin.go:295 ("all nil/zero when keep_alive.enabled is false") is stale: the key is retired, and kaPol is set even when the keeper is nil.
  • suggestion: the PR body's Testing section still cites 67ec6f83, which is no longer in this branch.

Author: boazdavid (CONTRIBUTOR by author_association; the permission API reports admin, so maintainer)
Areas reviewed: Go: core/plugins/contextguru (oneHourFirstFor, injectDefaultCacheStrategy, warnOnRetiredTopLevelKeys, the three test files), checked against context-guru v0.7.7 apply/apply.go (the OneHourFirst defer and oneHourSession) and keepalive/{onehour,keeper,waitplan}.go
Agent/IDE config (.claude/.vscode): none (the gate found no matches in the PR diff)
Commits: 10 in this layer, all signed off: yes (DCO passes)
CI status: every workflow job was pending at review time; only DCO had finished (pass). There were no annotations to read yet. Locally at a8ccd49d (GOWORK=off): gofmt -l is empty, go vet is clean and go test -race passes for core/plugins/contextguru.

Verified by: mutation runs at this head (route reverted to "": no package test fails. threadID reverted: the new subagent test fails. doc == nil guard removed: the new null-engine test panics. sem: nil: 4 of 30 runs fail). Also a scratch downgrade probe through OnRequest/OnFinish, run at head and with the route mutation. Scratch files were deleted afterwards.

Not checked: live pings or 1-hour probes against a real upstream (no gateway or credential in this sandbox), and cmd/agentop.

if agent := pctx.Subagent(); agent != "" {
threadID = agentThreadPrefix + agent
}
route := pctx.Path

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion: The route half of this fix works, but no test covers it. With route := "" restored here, the whole package still passes. Only the subagent half is pinned, by TestOneHourAlwaysDoesNotRelabelASubagentsRequest.

Here is a test that fails with route := "" and passes at head. I ran it as a scratch file in this package and then deleted it:

func TestOneHourAlwaysStopsOnARouteTheGatewayDowngraded(t *testing.T) {
	p := configured(t, `{"engine":{"cache":{"strategy":"1-hour-always"}}}`)
	if err := p.Init(t.Context()); err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { _ = p.Shutdown(t.Context()) })
	body := func() []byte { /* same tools+cache_control body as the subagent test */ }
	r1 := inferencePctx("/v1/messages", body())
	r1.Headers = http.Header{"Authorization": {"Bearer caller"}, "Anthropic-Version": {"2023-06-01"}}
	invokeReq(p, r1) // relabelled to 1h
	r1.StartedAt, r1.StatusCode = time.Now(), 200
	r1.Extensions.Inference = &pipeline.InferenceExtension{Model: "claude-sonnet-4-5",
		InputTokens: 3, CacheWriteTokens: 30_000, OutputTokens: 10, // billed at 5m: a silent downgrade
		PresentKinds: 1 | 2 | 4 | 8, AgentRole: pipeline.AgentRoleMain}
	p.OnFinish(t.Context(), r1)

	r2 := inferencePctx("/v1/messages", body())
	r2.Session, r2.SessionID = &pipeline.SessionView{ID: "s2"}, "s2"
	invokeReq(p, r2)
	if strings.Contains(string(r2.Body), `"ttl":"1h"`) {
		t.Fatalf("the downgrade stop did not reach OneHourFirst: %s", r2.Body)
	}
}

At head the keeper logs no more 1-hour keep-alive pings on this route ... route=/v1/messages and r2 keeps its 5-minute mark. With route := "", r2 is relabelled to 1h.

if err := yaml.Unmarshal(engine, &doc); err != nil {
return engine // malformed YAML: let cgconfig.LoadBytes produce the real error
}
if doc == nil {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion: The crash is fixed, but this comment says "Treat it as an absent engine", and the code does not do that. An absent engine (len(p.cfg.Engine) == 0 in Configure) becomes preset: balanced plus cache.strategy: auto, so it gets a keeper. A null engine is passed to cgconfig.LoadBytes("null") as-is and gets no keeper. TestConfigure_NullEngineDoesNotPanic pins that: p.keeper != nil is a failure.

The case this handles is an engine: key whose children are all commented out. An operator who writes that most likely means "use the defaults", and the docs say Default: preset: balanced and keep-alive "on by default on every install". The base behaves the same way, so this is not a regression. Still, please pick one:

  • Treat null like an absent engine in Configure, for example if len(engine) == 0 || bytes.Equal(bytes.TrimSpace(engine), []byte("null")) { engine = []byte("preset: balanced") }, and flip the test to expect a keeper.
  • Or keep the current behaviour and fix the comment and the docs, so they say that an empty engine: turns off both the preset and keep-alive.

@huang195 huang195 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Summary

Delta review of a8ccd49d over cd8e41be, this layer only (cg/05-contextguru-state-disk...cg/06-keepalive). The new commit changes plugin.go and three test files. It closes two of the three must-fix items from my last review. The third item is still open.

Results at this head:

  • Subagent thread: fixed. oneHourFirstFor now uses agentThreadPrefix + pctx.Subagent(), which is the same key that keeperKey uses. TestOneHourAlwaysDoesNotRelabelASubagentsRequest is a real test. With threadID set back to "", it fails.
  • Route: fixed, but no test. route is now pctx.Path, which is the value that recordFor writes. But with route := "" put back, the full package passes. See the inline comment.
  • {"engine":null} panic: fixed. With the doc == nil guard removed, TestConfigure_NullEngineDoesNotPanic panics. But a null engine now turns keep-alive off, and an absent engine turns it on. See the inline comment.
  • Retired model and paths keys: they now get a WARN. This closes the earlier suggestion.

Must-fix

  1. TestCgModel_MaxConcurrentBoundsInFlightCalls still does not find a missing cap. This commit does not change it. Inline on plugin_test.go:675.

Still open from earlier rounds (unchanged, so not repeated inline):

  • nit: docs/context-guru-plugin.md:23 says "passed through verbatim". The next bullet says that the plugin injects cache.strategy: auto. Line 26 still says "uses the model block". The key is now cheap_model.
  • nit: the field comment at plugin.go:295 still says "all nil/zero when keep_alive.enabled is false". That key is retired, and kaPol is now set when the keeper is nil.
  • suggestion: the PR body's Testing section still cites 67ec6f83. That commit is not on this branch.

FYI, not this PR: the v0.7.7 tag of rossoctl/context-guru moved after its release. proxy.golang.org and sum.golang.org have v0.7.7 at 23a4b03. The tag now points at 30a8076, which is 2 commits later. Those 2 commits change only tests and .gitignore. CI uses the default proxy and is not affected. A build with GOPROXY=direct fails with checksum mismatch on the go.sum line of this PR. Please ask the context-guru maintainers to put the tag back, or to release v0.7.8.

Author: boazdavid (MEMBER, maintainer)
Areas reviewed: Go (core/plugins/contextguru: oneHourFirstFor, injectDefaultCacheStrategy, warnOnRetiredTopLevelKeys, and the new tests)
Agent/IDE config (.claude/.vscode): none
Commits: 10 in this layer, all signed off: yes (DCO passes)
CI status: pending. Only DCO has finished.

Verified by: at a8ccd49d, with GOWORK=off and the module copy from proxy.golang.org: go vet ./plugins/contextguru/ is clean, gofmt -l is empty, and go test -race passes for core/plugins/contextguru and core/config. Four mutation checks: threadID = "" (one test fails), route := "" (all tests pass), no doc == nil guard (one test panics), and sem: nil (the max-concurrent test passes 30 of 30 runs). A scratch probe of Configure gave keeper=true for {} and for {"engine":{}}, and keeper=false for {"engine":null}. I deleted the scratch files after the checks.

Not checked: live pings against a real upstream, cmd/agentop, and envoy-sidecar mode.

Assisted-By: Claude (Anthropic AI) [email protected]

break
}
}
if cur >= maxConc {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

must-fix (still open from the cd8e41be round; this commit does not change it): this test does not find a missing cap. I set sem: nil in Configure (plugin.go:489) and ran this test with -count=30. It passed 30 of 30 runs. atCap closes when the 2nd call arrives, and close(release) follows at once, so the other 4 calls usually arrive after the first 2 are released. Thus peak stays at 2 with no cap.

The test must look at the cap itself while the handler holds the calls. For example, after <-atCap, check that the model's sem is full (len == cap == maxConc) before close(release). Then do the sem: nil mutation again and make sure that the test fails.

if agent := pctx.Subagent(); agent != "" {
threadID = agentThreadPrefix + agent
}
route := pctx.Path

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

suggestion: this line is correct, but no test pins it. I set it back to route := "" and the full package passes. This is the line that makes the gateway-downgrade stop and mode D of 1-hour-on-wait work. Please add a test: under 1-hour-always, record a downgraded response on /v1/messages, and then make sure that the next main-thread request is not relabelled to 1h. The test must fail with route := "".

// nil map (review finding, reproduced). Treat it as an absent engine: cgconfig.LoadBytes
// already gives a config with no error for "null", so this stays a no-op rather than
// also setting cache.strategy on an engine that names nothing else.
return engine

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

suggestion: the comment says "Treat it as an absent engine", but the result is different from an absent engine. An absent engine gets preset: balanced plus cache.strategy: auto. A null engine gets a zero config: no preset and no keep-alive. I probed Configure at this head:

{}                 keeper=true
{"engine":{}}      keeper=true
{"engine":null}    keeper=false

Thus an engine: key with all its children commented out turns keep-alive off with no WARN, and engine: {} keeps it on. The fix is in Configure: treat a trimmed null the same as len(engine) == 0. Then this guard is only a safety check, and TestConfigure_NullEngineDoesNotPanic must expect p.keeper != nil.

…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]>

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Reviewed this layer only — cg/05-contextguru-state-disk...cg/06-keepalive at a8ccd49d (1 commit, 4 files) — against context-guru v0.7.7 (tag 30a8076). The two fixes are right, and I checked them against the library rather than the comments.

  • OneHourFirst refuses a non-empty threadID (keepalive/onehour.go:411), and agentThreadPrefix + pctx.Subagent() is the convention keeperKey already uses (keepalive.go:72), so a named subagent's request can no longer be relabelled as the main thread. The new test's negative assertion is paired with the existing positive control (TestOnRequest_OneHourAlwaysStrategyRelabelsEveryExistingMark), so it fails on the old code and passes now.
  • route := pctx.Path is the key the keeper's own bookkeeping uses: oneHourRoute is provider|endpoint|route|model (keepalive/onehour.go:59) and recordFor writes Endpoint: pctx.Host, Route: pctx.Path (keepalive.go:136-137). Before this, the st.off/st.costly and lastTouch lookups were keyed on "" and could never match the route the keeper recorded.
  • The doc == nil guard is the right shape for engine: null (and for a comments-only engine): yaml.Unmarshal leaves the map nil with no error, so the doc["cache"] = cache write was an assignment to a nil map — a startup crash, and a crash on config reload too. cgconfig.LoadBytes("null") is a clean no-op, and the test covers it. One suggestion inline on what "absent" means there.

Still open from earlier rounds, in this PR's diff but not in this commit, so not raised again inline:

  • must-fix — the "12 minutes" hold claim in docs/context-guru-plugin.md, CLAUDE.md, docs/laptop-service.md, docs/session-api.md and the PR body. Verified independently: WaitPlan is on by default (keepalive.go:43), MaxPings is raised to the plan count (context-guru keepalive/keeper.go:1718) and hold() is (MaxPings+1) × Idle (keeper.go:288). At 240 s idle that is 36 min on a tool wait, 24 min background, 16 min human. TestKeepAliveHoldFollowsTheBilledTier pins 12 minutes on a policy with no wait plan, so it cannot catch it.
  • suggestion (huang195) — RetireSession on the two DELETE routes, or say in the paragraph that pings continue after an erase; ping events missing from the archive that /v1/usage replays.

Author: boazdavid (CONTRIBUTOR — returning external)
Areas reviewed: Go (core/plugins/contextguru)
Agent/IDE config (.claude/.vscode): none
Commits: 1 in this layer (19 in the PR), signed off, DCO passing
CI status: pending at a8ccd49 (DCO passed; every other job still queued)
Not checked:

  • go build, go vet, go test — the Go module CDN is unreachable from this sandbox (proxy.golang.org zips redirect to storage.googleapis.com, which times out; modernc.org/[email protected] likewise), so core/plugins/contextguru cannot compile here. gofmt -l core/plugins/contextguru is empty at this head.
  • A live keep-alive ping against an upstream.

Generated by repoman github-pr-review@af425c8.

// that combined text (it reads the first document and stops), which is exactly why this went
// unnoticed -- LoadBytes got no error, just a cache.strategy of "" (review finding: keep-alive
// off for every config that sets engine at all, including the plain preset case).
func injectDefaultCacheStrategy(engine []byte) []byte {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion: The guard is right, but calling a null engine "an absent engine" is not what the code does. An absent engine: key falls back to the default preset (plugin.go:386: preset: balanced at this head, xhigh higher in the stack), while engine: with no value loads a zero config — no components, no keeper, no keep-alive — and logs nothing.

Concrete case: an operator writes

engine:
  # preset: balanced
  # pipeline: ...

intending to keep the default, and context-guru silently turns itself off, while deleting those two lines entirely turns it on.

Suggested fix: either build the default preset when doc == nil (so "absent" is true), or keep the no-op and log one WARN naming the empty engine — the same "never refuse the document, always say so" rule warnOnRetiredTopLevelKeys follows.

… 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]>

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Reviewed this layer only — 81125a5d (1 commit, 2 files). The change does what its message says: onAcquire fires the instant this call's semaphore slot is taken, in-process, so a missing cap is visible without racing an HTTP round trip, and the two assertions (peak ≤ max_concurrent, all 6 calls complete) are the right ones. I read the engine at the exact content CI builds — context-guru v0.7.7 as the checksum database pins it (commit 23a4b03).

One suggestion inline, on the counter's lifetime. The still-open items from earlier rounds are below; the code they concern is not in this commit, so they are not repeated inline.

Still open from earlier rounds:

  • must-fix — the "12 minutes" hold claim in docs/context-guru-plugin.md, CLAUDE.md:280, docs/laptop-service.md and docs/session-api.md. Re-verified at this head against 23a4b03: WaitPlan is on by default (keepalive.go:43), the keeper raises MaxPings to the plan count (keepalive/keeper.go:1718) and hold() is (MaxPings+1) × Idle (keeper.go:288). At the 240 s idle default that is 36 min for a tool wait (8+1), 24 min for background work (5+1) and 16 min for a human wait (3+1) — not 12. This PR's body states it correctly ("up to 36 minutes for a thread waiting on its own tool call"); the docs still say 12 minutes flat, and TestKeepAliveHoldFollowsTheBilledTier pins 12 minutes on a policy with no wait plan, so it cannot catch it.
  • suggestion (huang195) — RetireSession on the two DELETE routes, or say in the paragraph that pings continue after an erase; ping events missing from the archive that /v1/usage replays.

Author: boazdavid (CONTRIBUTOR — returning external, elevated scrutiny)
Areas reviewed: Go (core/plugins/contextguru/plugin.go, plugin_test.go), and the engine's cap/hold code at 23a4b03
Agent/IDE config (.claude/.vscode): none (gate run over the PR diff: no matches, including renames)
Commits: 1 in this layer (19 in the PR), signed off, DCO passing
CI status: pending at 81125a5d — DCO success, 35 queued, 2 skipped, 1 neutral; no Go job has finished
Not checked:

  • go test, go vet, -race on core/plugins/contextguru — modernc.org/sqlite v1.56.0's zip is absent from the module cache and proxy.golang.org's zip endpoint fails TLS from this sandbox (unexpected eof while reading), so the package cannot compile here; §3.12 rules out fetching a toolchain to make a probe run.
  • The handoff race described inline is a scheduling argument, not a reproduced failure — without a build there is no -race or stress run to demonstrate it.

Verified by: gofmt -l core/plugins/contextguru (empty); go doc/source read of the library at 23a4b03 (keepalive/keeper.go:288,1718, config/config.go:288,308-310); sum.golang.org lookup of v0.7.7; git grep for .claude/.vscode in the diff. The worktrees were deleted afterwards.

Generated by repoman github-pr-review@af425c8.

Comment thread core/plugins/contextguru/plugin_test.go Outdated
if _, err := cm.Complete(context.Background(), "summarize"); err != nil {
t.Errorf("Complete: %v", err)
}
inFlight.Add(-1)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion — the counter is decremented after the semaphore slot is released, so a correct cap can read maxConcurrent+1 and fail the test.

onAcquire increments inFlight while the slot is held, but this goroutine decrements only after Complete returns — and Complete's deferred <-m.sem has already freed the slot by then. At a handoff the next waiter can therefore acquire the freed slot and run onAcquire (inFlight+1) before this line runs. With maxConc = 2 and 6 calls there are four handoffs, each able to produce a transient inFlight == 3: peak becomes 3 and the test reports peak concurrent calls = 3, want at most 2 on an implementation that is correct. It needs a second P to steal the woken sender, so it will be rare and hard to reproduce — but it is a failure mode the test itself creates.

Second, milder: if the cap resolves tighter than configured (say max_concurrent ends up 1), inFlight never reaches maxConc, atCap never closes, and <-atCap hangs until the package's go test timeout — a 10-minute stall rather than a failure. The comment's "never hangs waiting for a release only a bug would need" does not cover an over-tight cap.

Suggested fix: decrement while the slot is still held, so peak means what it says. Add an onRelease func() beside onAcquire and fold both under the same defer — defer func() { if m.onRelease != nil { m.onRelease() }; <-m.sem }() — with the test's inFlight.Add(-1) in onRelease. And bound the wait: select { case <-atCap: case <-time.After(30 * time.Second): t.Fatal("the cap never reached max_concurrent; it may be tighter than configured") }.

…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]>

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Reviewed the layer only (cg/05-contextguru-state-disk...cg/06-keepalive) at 323778fd — the two commits since the last pass, 6c7cbc6d and 323778fd. Both close what the earlier rounds left open: engine: null now takes the same path as an absent engine: and the test asserts a keeper rather than only the absence of a panic; the hold paragraph now gives the wait plan's counts instead of a flat 12 minutes, and TestKeepAliveHoldIsLongerForAToolWaitUnderTheWaitPlan pins 36 minutes on the one path no earlier test could disprove (every fixture in TestKeepAliveHoldFollowsTheBilledTier sets keepalive_wait_plan: false).

I checked the arithmetic against v0.7.7 rather than the comments: WaitPings raises the count (keepalive/waitplan.go:81-101), hold() is (MaxPings+1) × Idle (keepalive/keeper.go:288), and the defaults are 2 / +1 / +3 / 8 at 240 s — so 12 / 16 / 24 / 36 is right. One of those four cannot occur in this integration; that is the one suggestion inline.

Still open from earlier rounds (unchanged, so not repeated inline):

  • suggestion (huang195) — RetireSession on the two DELETE routes, or say in the paragraph that pings continue after an erase.
  • nit — docs/context-guru-plugin.md:26 still says a component "uses the model block"; the key is now cheap_model.
  • nit — core/plugins/contextguru/plugin.go:304 still says the keep-alive fields are "all nil/zero when keep_alive.enabled is false"; that key is retired, and kaPol is set even when the keeper is nil.
  • suggestion — the PR body's Testing section still cites 67ec6f83, which is not on this branch.

Author: boazdavid (CONTRIBUTOR — returning external)
Areas reviewed: Go (core/plugins/contextguru: plugin.go Configure, keepalive_test.go), docs (context-guru-plugin.md, session-api.md, laptop-service.md, CLAUDE.md), against rossoctl/context-guru v0.7.7
Agent/IDE config (.claude/.vscode): none (checked the PR's changed-file list)
Commits: 22 in the PR, all signed off: yes (DCO passes)
CI status: pending at 323778fd — DCO passed, every other job queued
Not checked:

  • go build, go vet, go test, -race — modernc.org/sqlite v1.56.0's zip is not in the module cache and proxy.golang.org's zip endpoint fails from this sandbox (net/http: TLS handshake timeout), so the package cannot compile here; §3.12 rules out fetching a toolchain to make a probe run
  • A live keep-alive ping, and the two wait causes the suggestion below is about

Verified by: gofmt -l core/plugins/contextguru core/accounting (empty at this head); source read of the library at v0.7.7 (keepalive/waitplan.go:81-101, keepalive/keeper.go:288, config/config.go:208-227,308-310); git grep for .claude/.vscode over the PR's file list. The worktrees were deleted afterwards.

Generated by repoman github-pr-review@af425c8.

Comment thread docs/context-guru-plugin.md Resolved

@huang195 huang195 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Summary

Round 3. I read the delta since my last review (a8ccd49d..323778fd: 81125a5d, 6c7cbc6d, 323778fd). go vet and go test -race pass in core/plugins/contextguru.

Status of my earlier threads:

  • Fixed: the hold-time must-fix. The 12/16/24/36-minute breakdown is now in the 4 docs and in the PR body, and TestKeepAliveHoldIsLongerForAToolWaitUnderTheWaitPlan pins the 36 minutes.
  • Fixed: the cap-test must-fix. With sem: nil the test now fails 30 of 30 runs.
  • Fixed: the null-engine suggestion. engine: null now builds a keeper, the same as an absent engine.
  • Still open, not blocking: the route := "" test (plugin.go:913), pings after an erase, ping events missing from the archive, and the root CLAUDE.md nit.

One new suggestion is inline: the new cap test is flaky when the cap works.

Author: boazdavid (MEMBER — maintainer)
Areas reviewed: Go (contextguru plugin and tests), docs
Agent/IDE config (.claude/.vscode): none
Commits: DCO check passes
CI status: pending

Assisted-By: Claude (Anthropic AI) [email protected]

Comment thread core/plugins/contextguru/plugin_test.go Outdated
if _, err := cm.Complete(context.Background(), "summarize"); err != nil {
t.Errorf("Complete: %v", err)
}
inFlight.Add(-1)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

suggestion: This test can fail when the cap works. Complete frees its slot in a defer, before it returns. inFlight drops only after the return. So after close(release), a waiting call can take the freed slot, and onAcquire can count 3 before this line runs. I ran it at this head with go test -race -count=500 -cpu 1,4,8: 2 of 1,500 runs failed with peak concurrent calls = 3, want at most 2.

Fix: lower inFlight in the HTTP handler, after <-release. The handler runs while the call still holds its slot. Then remove this line. I tried that change: 0 of 1,500 race runs failed, and with sem: nil the test still fails 30 of 30 runs.

… 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]>

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Re-review at 9e4d32f0, this layer only (8c164cb..9e4d32f0; #2058 is merged, so the merge base is 8c164cbb). The only commit since my last pass at 323778fd is 9e4d32f0. It changes docs only (CLAUDE.md, docs/context-guru-plugin.md, docs/laptop-service.md, docs/session-api.md) and the PR body.

Resolved since 323778fd:

  • The 24-minute background-wait figure is gone from all four docs and the PR body. I checked the reason given against context-guru v0.7.7. plugin.go:452 builds the keeper with keepalive.Options{Dispatcher: p.disp} only, so Options.OpenTasks is nil, and recordFor leaves Record.OpenTasks nil. Keeper.WaitingFor (keepalive/waitplan.go:159-176) then passes bg = 0 to the classifier, which can never return background. The remaining 12 / 16 / 36 figures match WaitPings (base 2, +1 for a person on the main thread, 8 for a tool wait) at the 240 s default. git grep finds no other copy of the old figure.

All must-fix items from earlier rounds are still closed at this head. I spot-checked these in code:

  • HeadTTL1h, HeadTTLMinBytes and OneHourFirst are wired into apply.Opts (plugin.go:661-663).
  • injectDefaultCacheStrategy edits a decoded node map, so a JSON engine: gets the default strategy. A probe of {"engine":{"preset":"balanced"}} gives keeper=true.
  • {"engine":null} builds a keeper, the same as an absent engine.
  • The upgrade note names cache.strategy: none.
  • The hold-time breakdown is correct.
  • With sem: nil the cap test still fails 30 of 30 runs.

must-fix (new evidence on an open thread): TestCgModel_MaxConcurrentBoundsInFlightCalls fails about 2-3% of the time on a correct cap, under the flags CI uses (go test -race). Earlier rounds rated this a suggestion because the failure looked rare. It is not rare. The details, a measured rate and a verified 2-line fix are inline.

Still open from earlier rounds (unchanged, not blocking, not repeated inline):

  • suggestion: no test pins route := pctx.Path (plugin.go:913). With route := "" back in place, the package still passes.
  • suggestion (huang195): RetireSession on the two DELETE routes, or say that pings continue after an erase. Also, ping events are missing from the archive that /v1/usage replays.
  • nit: docs/context-guru-plugin.md:23 says "passed through verbatim", but the plugin injects cache.strategy: auto. Line 26 still says "uses the model block", but the key is now cheap_model.
  • nit: the plugin.go:304 field comment still names keep_alive.enabled.
  • nit (huang195): the root CLAUDE.md repeats docs/session-api.md#delete-v1sessions instead of only linking to it.
  • suggestion: the PR body's Testing section still cites 67ec6f83, which is not on this branch.

Author: boazdavid (CONTRIBUTOR — returning external)
Areas reviewed: Docs (the 9e4d32f0 delta), Go (core/plugins/contextguru, core/accounting, core/cost/*), checked against context-guru v0.7.7
Agent/IDE config (.claude/.vscode): none (the gate found no matches in the PR diff or the layer diff, renames included)
Commits: 1 since the last review (14 in the layer), all signed off: yes (DCO passes)
CI status: every job except DCO was still queued at 9e4d32f0, so there are no results or annotations to read. Local results are below.

Verified by (at 9e4d32f0, with GOWORK=off and the local module cache):

  • go vet is clean for ./plugins/contextguru/, ./accounting/... and ./config/.
  • gofmt -l is empty on the changed Go files.
  • scripts/dev/check-test-timing.py passes on every changed _test.go file.
  • go test -race passes for plugins/contextguru, accounting/..., config and cost/event, pricing and settle. Three tests fail in cost/ledger and cost/usage: the America/Havana time-zone tests the PR body lists. They fail the same way on main.
  • A Configure probe of the retired model, paths and keep_alive keys: each one logs a WARN and none fails the decode.
  • Stress runs of the cap test, with the mutation and with the fix (see inline).

All scratch files were deleted afterwards.

Not checked: live pings against a real upstream, cmd/agentop, and envoy-sidecar mode.

Comment thread core/plugins/contextguru/plugin_test.go Outdated
if _, err := cm.Complete(context.Background(), "summarize"); err != nil {
t.Errorf("Complete: %v", err)
}
inFlight.Add(-1)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

must-fix: this test fails on a correct cap often enough to break CI. This is the same race as #2059 (comment) and #2059 (comment), and I measured it at this head.

Complete frees its slot in its deferred <-m.sem before it returns, but inFlight drops only here, after the return. In that gap a waiting call can take the freed slot and run onAcquire, which counts 3. The test then reports peak concurrent calls = 3, want at most 2 even though the code is correct.

Runs at 9e4d32f0 with -race, which is how ci.yaml runs core:

run failures
-count=400 -cpu 1 0 / 400
-count=400 -cpu 4 13 / 400 (3.3%)
-count=400, default GOMAXPROCS (8) 7 / 400 (1.8%)
-count=500 -cpu 1,4,8 34 / 1,500

GitHub's Linux runners have 4 vCPUs, so after this merges, about one Go CI (core) run in 30 would go red on a PR that does not touch this code.

Fix (huang195's suggestion, which I tried): lower the counter inside the HTTP handler, while the call still holds its slot, and delete this line.

	release := make(chan struct{})
	var inFlight, peak atomic.Int64
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		<-release
		inFlight.Add(-1) // still inside Complete, so before its deferred <-m.sem
		_, _ = io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"ok"}}]}`)
	}))

With that change, a run with -race -count=600 had 0 failures. With sem: nil at plugin.go:505, the test still failed 30 of 30 runs, so it still catches a missing cap.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in d32d387. The in-flight count now drops inside the HTTP handler, while the call still holds its slot. With -race -count=300 -cpu 1,4,8 the test had 0 failures in 900 runs. With sem: nil it still failed 30 of 30 runs.

…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]>
@boazdavid
boazdavid requested a review from clawgenti November 24, 2026 14:01

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Reviewed the one commit since the pass at 9e4d32f0: d32d3877 is test-only (core/plugins/contextguru/plugin_test.go, +6/−2) and it closes the flake must-fix from that pass.

The fix is the right one. Complete releases its semaphore slot in a deferred receive (core/plugins/contextguru/plugin.go:214-225), so a call that returns can have its slot re-acquired — and the new call counted — before the returning goroutine runs any code after Complete. Moving inFlight.Add(-1) into the test server's handler, which runs while the call is still inside Complete and still holds the slot, removes that window: no more than max_concurrent goroutines can be between onAcquire and the handler at once, so a correct cap can no longer report maxConc+1. The comment states the reason, which is what keeps the next reader from moving it back.

I traced that ordering in cgModel.Complete at head rather than taking the comment's word for it; the defer func() { <-m.sem }() is exactly where the comment says.

Nothing blocking. The non-blocking items from earlier rounds still stand and are not repeated inline (no test pins route := pctx.Path; huang195's RetireSession/ping-archive and CLAUDE.md points; the plugin.go:304 field comment; the PR body's Testing section citing a SHA not on the branch).

Author: boazdavid (CONTRIBUTOR — returning external)
Areas reviewed: Go test (plugin_test.go cap test) against cgModel.Complete's semaphore path
Agent/IDE config (.claude/.vscode): none (no matches in the PR diff or this delta, renames included)
Commits: 24 in the PR, all signed off: yes (DCO passes)
CI status: queued at d32d3877 — DCO passed, 35 jobs queued, 2 skipped, 1 neutral
Not checked:

  • go test -race at head, including the stress runs that measured the old flake rate — the local module cache's context-guru v0.7.7 zip does not match go.sum (checksum mismatch, SECURITY ERROR), and §3.12 forbids fetching a replacement
  • Live pings against a real upstream, cmd/agentop, envoy-sidecar mode

Verified by: read of cgModel.Complete (plugin.go:214-225) and the new handler/onAcquire pairing at head; git diff 9e4d32f0 d32d3877 to confirm the commit is test-only. The worktree was removed afterwards.

Generated by repoman github-pr-review@af425c8.

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Re-review at d32d3877, this layer only (8c164cb..d32d3877; #2058 is merged and 8c164cb is on main, so origin/main..d32d3877 is exactly this layer's 15 commits). The one commit since 9e4d32f0 is test-only, and it fixes the cap-test flake that was the last open must-fix. I ran the checks myself instead of relying on the earlier rounds:

  • The flake is fixed. go test -race -count=300 -run TestCgModel_MaxConcurrentBoundsInFlightCalls$ passes 300 of 300 runs at head. The same run with 9e4d32f0's test against head's code fails 10 of 300. So the stress run does catch the race, and moving inFlight.Add(-1) into the handler, while the call still holds its slot, removes it. llmclient has no retry path, so the handler runs once per Complete and the decrement stays paired with its onAcquire.
  • The test still catches a missing cap. With sem: nil in Configure, it fails 30 of 30 runs.

Earlier must-fixes, all resolved at this head (each re-read in code):

  1. recordFor passes CacheWrite1h to the keeper, so 1-hour threads stay on the 1-hour schedule (735657b round).
  2. The retention docs now say the keeper holds the whole forwarded body, and give the 118 / 236-minute bound for 1-hour threads (fab047b round).
  3. Rebase: the layer sits on merged #2058, and GitHub reports MERGEABLE (b0dcc87 and be34b22 rounds).
  4. engine.cache.keepalive: false is honoured with no strategy, because cachePolicy always uses cache.Resolved() (be34b22 to e9641ea).
  5. The 1-hour strategies' request-side half (HeadTTL1h, HeadTTLMinBytes, OneHourFirst) reaches apply.Opts (be34b22 to 20622ee).
  6. injectDefaultCacheStrategy now re-marshals instead of appending YAML after JSON (769ba92 and 20622ee).
  7. oneHourFirstFor keys on pctx.Path and the subagent thread (e21f17a).
  8. {"engine":null} no longer panics, and is handled like an absent engine (e21f17a).
  9. The cap test detects a missing cap (cd8e41b).
  10. The hold time reads 12 / 16 / 36 minutes, not a flat 12 (cd8e41b to 6c7cbc6).
  11. The cap test no longer flakes on a correct cap (9e4d32f).

No must-fix is left, so I am approving. I have one new nit, inline on query.go. The non-blocking items from earlier rounds still stand, and I have not repeated them inline:

  • no test pins route := pctx.Path.
  • @huang195's RetireSession / ping-archive points, and his root CLAUDE.md point.
  • the stale keep_alive.enabled field comment in plugin.go.
  • docs/context-guru-plugin.md's "passed through verbatim" line, and its "uses the model block" line.
  • the Testing section of the PR body cites 67ec6f83, which is not on this branch.

Author: boazdavid (CONTRIBUTOR by author_association; the permission API reports admin, so maintainer)
Areas reviewed: Go (core/plugins/contextguru, core/accounting ping/snapshot/host, core/cost/{event,ledger,usage}, cmd/agentop/money), docs. JSON decoders: the new Event fields (purpose, basis, units, estimated) and the usage.Counts keepAlive* fields are additive and omitempty. No tag collides with an existing one, and no strict decoder reads them, so an older record or response still decodes.
Agent/IDE config (.claude/.vscode): none (the gate found no matches in the layer diff, renames included)
Commits: 15 in this layer (24 in the PR), all signed off: yes (DCO passes)
CI status: 36 checks pass. No Go CI job has a continue-on-error step, and the annotations are only cache, Node 20, hadolint and line-length warnings. The job logs themselves could not be downloaded here (their blob host timed out), so I read the step conclusions instead: all are success.

Verified by (at d32d3877, GOWORK=off, go mod verify clean):

  • gofmt -l is empty on every changed Go file, and scripts/dev/check-test-timing.py passes on every changed _test.go file.
  • go vet is clean for plugins/contextguru, accounting/..., config, cost/... and cmd/cortex.
  • go test -race passes for plugins/contextguru, accounting/..., config, cost/event, cost/pricing, cost/settle and cmd/agentop/{money,tui}. cost/ledger and cost/usage fail only the three America/Havana tz-data tests the PR body lists.
  • cmd/cortex and cmd/cortex-envoy build.
  • The stress and mutation runs above, in a scratch worktree that I deleted afterwards.

Not checked: live pings against a real upstream, and envoy-sidecar mode.

Comment thread core/cost/ledger/query.go
return r.AvoidedMicros != 0 || r.PenaltyMicros != 0 || r.AvoidedUnits != 0 || r.PenaltyUnits != 0 ||
r.AvoidedAPIEquivalentMicros != 0 || r.AvoidedUnknownMicros != 0 ||
r.PluginSpendMicros != 0 || r.PluginSpendUnits != 0 || r.PluginSpendUnknownMicros != 0 ||
r.KeepAliveMicros != 0 || r.KeepAliveAPIEquivalentMicros != 0 || r.KeepAliveUnknownMicros != 0

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit: KeepAliveUnits is missing here, unlike its plugin-spend counterpart PluginSpendUnits two lines up. The doc comment also still says "nine figures". event.Figures has thirteen now.

This function is documented as "the ledger's form of the ring's !avoided.IsZero()". The ring's check counts Figures.KeepAliveUnits, so the two can disagree on a subscription ping whose units are nonzero while its API-equivalent dollars round to zero (a zero-rate model, for example). The ring then reports a currency for that window and the ledger does not. This is an edge case, but the fix is one term:

Suggested change
r.KeepAliveMicros != 0 || r.KeepAliveAPIEquivalentMicros != 0 || r.KeepAliveUnknownMicros != 0
r.KeepAliveMicros != 0 || r.KeepAliveUnits != 0 || r.KeepAliveAPIEquivalentMicros != 0 || r.KeepAliveUnknownMicros != 0

@huang195
huang195 merged commit e580666 into rossoctl:main Nov 24, 2026
43 of 47 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 24, 2026
huang195 pushed a commit that referenced this pull request Nov 24, 2026
…savings, sessions and budgets

#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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants