Repository navigation
feat(contextguru): [cg] Keep the session state on disk - #2058
Conversation
|
Important Review skippedToo many files! This PR contains 102 files, which is 2 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.
|
974cb8b to
b483799
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
I reviewed only what this PR adds on top of cg/04-savings (#2057). The session state goes to a SQLite session_state table through context-guru v0.7.3's store.Disk. There is one shared *sql.DB per path, fail-open attach, and Shutdown flushes. I checked that against the library: Memory.AttachDisk, LoadSession (called by apply before every request), Disk.Close (idempotent, flushes), and the 30-day retention sweep. The wiring is correct. BuildWithDeps calls SetLocalInstall before Configure, and configuredPlugin forwards Shutdown, so the ~/.cortex path and the flush on drain both work. Locally, go vet and go test -race ./plugins/contextguru/ pass on this head, and gofmt is clean.
No blocking issues. Inline: two suggestions (a disk flusher that is never closed on failed builds or reloads, and DELETE routes that could actually erase the new on-disk content) and two nits.
Author: boazdavid (repo admin; GitHub association FIRST_TIME_CONTRIBUTOR, so a maintainer by permission)
Areas reviewed: Go (core/plugins/contextguru), go.mod/go.sum (modernc.org/sqlite v1.56.0 and its deps, the same versions context-guru v0.7.3 pins), Docs
Agent/IDE config (.claude/.vscode): none
Commits: all signed-off: yes
CI status: Go CI (all jobs), tidy, CodeQL analyses, Dependency Review and Trivy all pass. Two failures don't come from this PR's change. Pre-commit fails in check-doc-links on two missing anchors (docs/pricing.md → context-guru-plugin.md#where-its-own-model-calls-go, docs/configuration.md → laptop-service.md#the-metrics_push-configuration), and I reproduced the same failure on main and on cg/04-savings. The CodeQL gate's one high alert is in core/accounting/savings.go:413, which comes from #2057 and is not touched here.
b483799 to
ce97be9
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
The base is main, so the diff includes all of #2054–#2057 (and #2065). I reviewed only the commit unique to this PR, ce97be9 ("Keep the session state on disk"), against cg/04-savings (#2057 head f088aee). This head is a restack: ce97be9 is byte-for-byte the same change as b483799, which I approved earlier. The interdiff of the two commits is empty. My four earlier inline comments (the disk flusher leak on failed builds or reloads, DELETE routes that could call store.DeleteSessionState, the 24h TTL comment on the fail-open path, and Disk.Errors() in Metrics()) are still attached to this head and still apply. I haven't repeated them here.
New in this pass: one suggestion inline. The SQLite DSN is built from the raw path, so a # in the home or cache path sends the database to a different file with umask permissions. I reproduced this.
Re-verified on this head: go test -race and go vet in core/plugins/contextguru pass, and gofmt is clean. go mod tidy -diff is clean in core, cmd/cortex and cmd/cortex-envoy. Builds with include_plugin_contextguru succeed on Linux and on GOOS=windows for cmd/cortex. With HOME/XDG_CACHE_HOME pointed at a scratch dir, the tagged core config/plugins/pipeline/listener tests write no context-guru-state.db outside their temp dirs.
Author: boazdavid (repo admin; GitHub association FIRST_TIME_CONTRIBUTOR, so a maintainer by permission)
Areas reviewed: Go (core/plugins/contextguru), go.mod/go.sum (modernc.org/sqlite v1.56.0 and deps, the versions context-guru v0.7.3 pins), Docs
Agent/IDE config (.claude/.vscode): none
Commits: all signed-off: yes (DCO passes)
CI status: Several Go CI jobs (core, authbridge cortex, authbridge cortex-envoy) were still queued or running when I posted. I covered that ground with the local runs above. None of the failures comes from this commit:
- Pre-commit fails
check-doc-linksondocs/pricing.md→context-guru-plugin.md#where-its-own-model-calls-goanddocs/configuration.md→laptop-service.md#the-metrics_push-configuration. Both links come from lower in the stack, andcg/04-savingsfails the same way.mainpasses. - CodeQL's one high alert is
core/accounting/savings.go:413, from #2057. - Rust (praxis) is green but hides
cargo test failed (does not block: no praxis-mode changes). The same annotation appears on every PR from #2065 up, and #2065 changescore/pipeline/testdata/session-event.golden.json, so that is likely the source. Worth fixing in #2065, not here.
…Lite path Review fixes for rossoctl#2058: - Open the shared *sql.DB in Configure, and start the store.Disk (its flusher goroutine) in Init. A pipeline that a failed build or reload drops is never started, so it no longer leaks a flusher. - Set the 24h state-key lifetime only when the database opened. On the fail-open path the engine's default stays. - Report Disk.Errors() as the state_db_errors metric. - Escape '%', '#' and '?' in the file: URI. A '#' in the path made SQLite open another file, with the umask's mode, outside the 0700 directory. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
clawgenti
left a comment
There was a problem hiding this comment.
Summary
I re-reviewed the fix commit 0c4aea3 against ce97be9, which I approved earlier. Four of my five earlier comments are fixed, and each fix does what the replies say. The fifth (DELETE routes calling store.DeleteSessionState) is deferred to a follow-up, which is fine.
- Disk flusher leak:
Configurenow opens only the shared*sql.DBand starts no goroutine.Initstarts thestore.Disk. I traced both failure paths.Reloader.reloadOncereturns onvalidateReloadable/validateAccountingbefore anyStart, andnewOut.Startfailing at index N unwinds only[0..N-1], so a plugin whoseInitnever ran holds nothing.configuredPluginforwardsInit, andcmd/cortexandcmd/cortex-envoybothStarttheir pipelines. Theatomic.Pointerswap makes a repeatedInit/Shutdownsafe, and so isMetrics()reading it concurrently. - SQLite URI escaping: with the old
"file:"+pathput back,TestStateDB_PathWithURICharactersfails all three subtests:a#banda?bwrite elsewhere (a,a-wal,a-shmbeside the directory), anda%41bfails to open. WithsqliteURIthey all pass. The?that is now escaped no longer collides with modernc's own?_pragma=split. - 24h TTL only with a database: fixed for the path where no file can be opened. One leftover case: if
stateDBForopens the file butOpenDiskthen fails inInit(an unusable table), the 24h memory lifetime is already set while there is no disk copy. The pin cap bounds it and the case is rare, so I'm noting it here and not blocking on it. state_db_errorsmetric: added, documented and tested.
Verified locally on this head (GOWORK=off): go test -race ./plugins/contextguru/ passes. go vet is clean, gofmt -l is empty and go mod tidy -diff is clean in core. cmd/cortex and cmd/cortex-envoy build with include_plugin_contextguru. The tagged core plugins/..., pipeline/... and reloader/... tests pass, with HOME/XDG_CACHE_HOME pointed at a scratch dir, and they write no context-guru-state.db there. The one exception is plugins/tokenbroker/client, which hit the 10-minute test timeout in a network read in my sandbox. This PR doesn't touch it.
Author: boazdavid (FIRST_TIME_CONTRIBUTOR association, but repo admin, so a maintainer by permission)
Areas reviewed: Go (core/plugins/contextguru), Docs
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes (DCO passes)
CI status: Because the base is now cg/04-savings, only PR Verifier and DCO ran, and both pass. Go CI, pre-commit and CodeQL did not run on this head, so the local runs above stand in for them. The CodeQL alert at core/accounting/savings.go:413 belongs to #2057, as you noted.
0c4aea3 to
fa760c8
Compare
f088aee to
e11a7d2
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
This head restacks the PR onto the new cg/04-savings head (e11a7d2, previously f088aee). I diffed f088aee..0c4aea3, which I approved, against e11a7d2..fa760c8. Ignoring index lines and hunk offsets the two are identical, so the change itself is the same one I approved before. All my earlier findings still hold as resolved: the flusher starts in Init, sqliteURI escapes the path, the 24h TTL applies only with a database, and state_db_errors is reported. The DELETE follow-up is still deferred, as agreed.
The base delta touches core/plugins/contextguru/plugin.go: cgModel now holds a pipeline.OpReporter in place of pctx/dryRun. That code is separate from the state-disk code (struct fields, Configure's store setup, Init/Shutdown, Metrics), and the PR applies to it without conflict.
Verified locally on fa760c8 (GOWORK=off, with HOME/XDG_CACHE_HOME pointed at a scratch dir):
go test -race ./plugins/contextguru/passes incore.go vetis clean,gofmt -lis empty, andgo mod tidy -diffis clean.- With
include_plugin_contextguru, thesecoretests pass:plugins/contextguru/...,plugins/all/...,pipeline/...,reloader/...,config/...andaccounting/.... The taggedcmd/cortex./...tests pass too. cmd/cortexandcmd/cortex-envoyare tidy, and both build and vet cleanly with the tag.- The tests wrote no
context-guru-state.dbto the scratch home.
The one leftover I noted last time is unchanged and still not blocking: if the file opens but OpenDisk fails in Init, the 24h memory TTL is already set.
Author: boazdavid (FIRST_TIME_CONTRIBUTOR association, but repo admin, so a maintainer by permission)
Areas reviewed: Go (core/plugins/contextguru), go.mod/go.sum, Docs
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes (DCO passes)
CI status: On this base only DCO ran (it passes), and CodeRabbit skipped. Go CI, pre-commit and CodeQL did not run, so the local runs above stand in for them.
…Lite path Review fixes for rossoctl#2058: - Open the shared *sql.DB in Configure, and start the store.Disk (its flusher goroutine) in Init. A pipeline that a failed build or reload drops is never started, so it no longer leaks a flusher. - Set the 24h state-key lifetime only when the database opened. On the fail-open path the engine's default stays. - Report Disk.Errors() as the state_db_errors metric. - Escape '%', '#' and '?' in the file: URI. A '#' in the path made SQLite open another file, with the umask's mode, outside the 0700 directory. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
fa760c8 to
4c2e6e1
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
This head restacks the PR onto the new cg/04-savings head (4b6bdee, previously e11a7d2). The base now has its own localInstall field and SetLocalInstall (used for the HTTPS_PROXY bypass), so this PR drops its separate local field and reuses that one: stateDBFor(p.localInstall), with the field and setter comments merged. I compared e11a7d2..fa760c8, which I approved, with 4b6bdee..4c2e6e1, ignoring index lines and hunk offsets. Besides that change, the only differences are doc paragraphs (CLAUDE.md, docs/context-guru-plugin.md, docs/session-api.md) reflowed around text the base changed. The state-disk logic (statedb.go, Configure/Init/Shutdown, Metrics) and its tests are unchanged. BuildWithDeps still calls SetLocalInstall before Configure (core/plugins/deps.go:136), so the ~/.cortex path still applies on a local install.
No blocking issues. My earlier findings stay resolved. The DELETE follow-up is still deferred, as agreed, and the leftover I noted earlier (24h memory TTL when OpenDisk fails in Init) hasn't changed and is harmless.
The PR targets cg/04-savings, so Go CI, CodeQL and the security scans did not run (they trigger only on PRs to main). I ran the checks locally on 4c2e6e1 (GOWORK=off, with HOME/XDG_CACHE_HOME pointed at a scratch dir):
- In
core:go test -race ./plugins/contextguru/passes,go vetis clean,gofmt -lis empty andgo mod tidy -diffis clean. - With
include_plugin_contextguru, thecoretests forplugins/...,pipeline/...,reloader/...,config/...andaccounting/...pass, and so do thecmd/cortex./...tests. One exception:plugins/tokenbroker/clientTestClient_AcquireToken_DNSFailurehangs in my sandbox because of its egress proxy. This PR doesn't touch that package. cmd/cortexandcmd/cortex-envoyare tidy and vet cleanly with the tag.- The tests wrote no
context-guru-state.dbto the scratch home.
Author: boazdavid (repo admin; GitHub association FIRST_TIME_CONTRIBUTOR, so a maintainer by permission)
Areas reviewed: Go (core/plugins/contextguru), go.mod/go.sum (unchanged from the approved head), Docs
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes
CI status: DCO and the PR-title check pass. Go CI and the scans don't run on a stacked base, so I ran the checks locally (above).
…Lite path Review fixes for rossoctl#2058: - Open the shared *sql.DB in Configure, and start the store.Disk (its flusher goroutine) in Init. A pipeline that a failed build or reload drops is never started, so it no longer leaks a flusher. - Set the 24h state-key lifetime only when the database opened. On the fail-open path the engine's default stays. - Report Disk.Errors() as the state_db_errors metric. - Escape '%', '#' and '?' in the file: URI. A '#' in the path made SQLite open another file, with the umask's mode, outside the 0700 directory. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
4c2e6e1 to
466929f
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
This head is a re-push of 4c2e6e1, which I approved earlier. The tree is the same (f307bc6), the parent is the same (10dafd4 on 4b6bdee), and only the committer date changed. So the state-disk change itself is the one I reviewed before, and nothing in it needs fixing. The one thing that's new is the base: the PR now targets main, so the full CI ran for the first time. Two red results come from the layers below this PR, not from its own commits. Both are already fixed in the newer heads of those PRs, so a restack clears them:
- Go CI (core) fails. On the merge ref (
f438c6e),core/auditsTestTransportsSetIdleConnectionPoolfails withcore/plugins/contextguru/modelclient.go:19:9 builds an http.Transport without MaxIdleConnsPerHost. The test passes onmain. The literal comes from #2057, and #2057's current head31ceb90("Include MaxIdleConnsPerHost in the fallback transport literal") adds the field. This PR still sits on the older4b6bdee. I couldn't download the CI log because the log host timed out from my sandbox, but this is the only failure I get locally thatmaindoesn't also have. The other local failures (the America/Havana tzdata tests you list,tokenbroker/clientDNS, andsession/archiveTestWriteSession_FailedEraseKeepsNumbering) fail the same way onmainin my sandbox. They come from the environment (root user, egress proxy). - Rust (praxis) is green, but it hides
cargo test failed (does not block: no praxis-mode changes). Locally,every_go_inference_field_is_set_or_listedfails withGo fields the Rust model does not give: ["inference.cacheWrite1hTokens"]. The stack still carries the old589feae/f1a440bpricing commits, which add the Go field but not its Rust side. #2065's current head (69c7eac/0edbfcb) adds the praxis model, usage andparsed-request.fieldschanges, and its praxis job passes. I said in an earlier review that this came from #2065; to be precise, it comes from the stale copy of #2065 inside this stack.
So once this PR is restacked onto the current #2057 head (which carries the current #2065), both should go green. Neither is blocking for this PR's own change.
Other CI notes:
- Go CI (core peerproc, macOS) failed on
proxy.golang.orgi/o timeouts while downloading modules. That's a runner network flake, so a re-run should fix it. - CodeQL: the high alert at
core/accounting/savings.go:418and the new medium one atcore/accounting/host.go:245(log injection onpctx.Path) are both in #2055/#2057 code that this PR doesn't touch. Thehost.goone looks like a false positive:slogkey/value attributes are quoted by the handler, so a path can't forge a log line. - Every other job passes, including
Go CI (authbridge cortex),(authbridge cortex-envoy),(authbridge agentop),(plugin profiles),Verify module graph is tidyandPre-commit Checks. Thecheck-doc-linksfailure I noted earlier is gone.
Verified locally on this head (GOWORK=off, with HOME/XDG_CACHE_HOME pointed at a scratch dir): go test -race ./plugins/contextguru/ passes, go vet is clean and gofmt -l is empty. The merge ref merges cleanly with main. The tests wrote no context-guru-state.db to the scratch home. My earlier findings stay resolved, and the DELETE follow-up is still deferred, as agreed.
Author: boazdavid (repo admin; GitHub association FIRST_TIME_CONTRIBUTOR, so a maintainer by permission)
Areas reviewed: Go (core/plugins/contextguru), go.mod/go.sum, Docs, CI (core and praxis failures traced to lower layers)
Agent/IDE config (.claude/.vscode): none, in this PR's change or in the full diff against main
Commits: 22 commits against main (2 of them this PR's own), all signed-off: yes (DCO passes)
CI status: failing. Go CI (core) and Rust (praxis) fail because of the stale lower layers (see above), CodeQL flags lower-layer code, and macOS failed on a network flake. Everything else passes.
…Lite path Review fixes for rossoctl#2058: - Open the shared *sql.DB in Configure, and start the store.Disk (its flusher goroutine) in Init. A pipeline that a failed build or reload drops is never started, so it no longer leaks a flusher. - Set the 24h state-key lifetime only when the database opened. On the fail-open path the engine's default stays. - Report Disk.Errors() as the state_db_errors metric. - Escape '%', '#' and '?' in the file: URI. A '#' in the path made SQLite open another file, with the umask's mode, outside the 0700 directory. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
466929f to
1070d8e
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
This head restacks the PR's two commits onto the current #2057 head (f2ae82e). git range-diff 4b6bdee..466929f f2ae82e..1070d8e reports both patches identical (=) to 466929f, which I approved. So the state-disk change (statedb.go, Configure/Init/Shutdown, Metrics, the tests and docs) is the code I reviewed before. My earlier findings stay resolved, the DELETE follow-up is still deferred as agreed, and nothing in this PR's own change needs fixing.
I said last time that the two red CI results would clear on this restack, and they did:
- Go CI (core) passes.
core/auditsTestTransportsSetIdleConnectionPoolpasses now that415e825(MaxIdleConnsPerHost) is in the base. I also ran it locally. - Rust (praxis):
cargo testpasses, so theinference.cacheWrite1hTokensparity failure is gone.
CI notes:
- Rust (praxis) is green, but its annotations say
praxis end-to-end tests failed (does not block: no praxis-mode changes). This doesn't look related to this PR. The e2e test buildscmd/cortexwith thelocalprofile tags, which don't includeinclude_plugin_contextguru, so none of this PR's code is linked into it. Thego.modchanges only add new indirect modules and don't bump any existing ones. The same job on #2057's headf2ae82epasses with no annotations. I couldn't download the CI log because the log host timed out from my sandbox. Locally, I builtcortex-gatewayand ranTestPraxisE2Eon the merge reff784e80as a non-root user, and it passes. A re-run of the job should confirm this was a flake. - CodeQL fails on two alerts:
core/accounting/savings.go:419(clear-text logging) andcore/accounting/host.go:245(log injection). Both are in #2057's code, the same two alerts are open on #2057's merge ref, and this PR doesn't touchcore/accounting. - Dependency Review passes, with a warning that
github.com/remyoudompheng/bigffthas an OpenSSF Scorecard of 2.9, below the threshold of 3. It's a transitive dependency ofmodernc.org/libc(and already ofcontext-guruv0.7.3), brought in by the SQLite driver. This is for information only, not something to act on. - Every other job passes, including Windows, macOS peerproc, the authbridge builds, plugin profiles, module tidy and pre-commit.
Verified locally on 1070d8e (GOWORK=off, with HOME/XDG_CACHE_HOME pointed at a scratch dir):
- In
core:go test -race ./plugins/contextguru/ ./audits/...passes,go vetis clean,gofmt -lis empty andgo mod tidy -diffis clean. - With
include_plugin_contextguru, thesecoretests pass:plugins/contextguru/...,plugins/all/...,pipeline/...,reloader/...,config/...,accounting/...,plugins/inferenceparser/...andplugins/toolprune/.... The taggedcmd/cortex./...tests pass too. cmd/cortexandcmd/cortex-envoyare tidy and vet cleanly with the tag.- The tests wrote no
context-guru-state.dbto the scratch home.
Author: boazdavid (repo admin; GitHub association CONTRIBUTOR, so a maintainer by permission)
Areas reviewed: Go (core/plugins/contextguru), go.mod/go.sum, Docs, CI (praxis e2e, CodeQL, Dependency Review)
Agent/IDE config (.claude/.vscode): none
Commits: 6 commits against main (2 of them this PR's own), all signed-off: yes (DCO passes)
CI status: everything passes except CodeQL, whose two alerts are in #2057's code. Rust (praxis) has a non-blocking e2e failure that I couldn't reproduce locally.
…Lite path Review fixes for rossoctl#2058: - Open the shared *sql.DB in Configure, and start the store.Disk (its flusher goroutine) in Init. A pipeline that a failed build or reload drops is never started, so it no longer leaks a flusher. - Set the 24h state-key lifetime only when the database opened. On the fail-open path the engine's default stays. - Report Disk.Errors() as the state_db_errors metric. - Escape '%', '#' and '?' in the file: URI. A '#' in the path made SQLite open another file, with the umask's mode, outside the 0700 directory. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
1070d8e to
6ea82c3
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
I reviewed only this layer's change (cg/04-savings...6ea82c3): statedb.go, the Init/Shutdown lifecycle in plugin.go, the tests, docs and module updates. The design holds up. The shared *sql.DB is opened in Configure and starts no goroutine. The flusher starts in Init and is closed (flushed) in Shutdown, so the pipeline's Start/unwind/Stop contract owns it. configuredPlugin forwards both hooks, and the reloader calls Start on the new pipeline and Stop on the drained one. The stated fix works end to end: context-guru v0.7.3's apply.BodyOpts calls loadSessionState -> Memory.LoadSession before the pipeline reads the store, so a restarted or reloaded instance restores the session from the file. The file: URI escaping is correct for modernc v1.56.0. With the file: prefix, newConn passes the whole DSN to sqlite3_open_v2 with SQLITE_OPEN_URI. Because the path's ? is escaped to %3f, the first ? it splits on is the pragma query. I found no blocking issues. There are two non-blocking notes inline.
Out of scope for this layer: CodeQL's two open alerts (core/accounting/savings.go:422, core/accounting/host.go:247) come from #2057's code, not this diff.
Author: boazdavid (admin, author_association CONTRIBUTOR - maintainer)
Areas reviewed: Go (contextguru plugin, pipeline lifecycle, reloader interaction), go.mod/go.sum (modernc.org/sqlite and transitive deps), Docs
Agent/IDE config (.claude/.vscode): none
Commits: 7 commits, all signed-off: yes
CI status: Go CI jobs passing, no failure annotations; CodeQL failing on #2057's alerts; macOS peerproc pending. Locally: go vet clean, gofmt -l empty, go test -race ./plugins/contextguru/ passes.
…ge and sessions
Record the accountant's savings and the context operators' own model-call
spend in the cost ledger, /v1/usage, the sessions API and agentop, each split
by billing basis so only a true-dollar (API-key) figure is summed as money; a
subscription login's saving is valued in usage-limit units, and an
unknown-billing one is shown apart. Plugin model-call spend is kept out of
cost_usd so the existing spend totals keep their meaning.
Add core/accounting/{savings,price} and the savings-agreement tests that replay
every accountant case through Cortex's own conversion, core/cost/event, and the
savings parts of settle, usage and ledger (removing the old avoided/decode and
estimate paths). agentop shows the net, the penalty, the units and the spend,
each named.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
- Move the CodeQL suppression above the slog.Debug call in logTokens, where CodeQL reads it. - Log one DEBUG line when an operator reported ops on a path wire.FormatOf cannot read, and pin with a test that a saving on /chat/completions (no /v1) is recorded. - 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. - Say why Saving.TokensAvoided and operatorTokens count cache-effect tokens differently. - 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]>
…rt literal core/audits TestTransportsSetIdleConnectionPool checks the composite literal itself, not a later field assignment, so the fallback branch (http.DefaultTransport not an *http.Transport) failed the audit. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…ier value pricing.Tier has no TierCacheWrite1h constant — see pricing.Tier's own doc: the 1h premium is a subset of CacheWrite and is priced through pricing.Rates.CacheWrite1hRate, not a fifth tier slot. price.go and savings.go still referenced the old, pre-rossoctl#2065-rewrite constant, which no longer exists, so this layer did not build. USD1h prices those tokens directly, and largestTier names the 1h case as a literal "cache_write_1h" string instead of going through pricing.Tier.String(). Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…, correct Four real review findings on this layer: - OpenAI chat tools store their name in function.name, not the top-level name envelopeOps read. A removal among them matched nothing, fell back to the no-saving path, and lost the saving entirely. toolsOps now falls back to function.name before assigning the unnamed key. - A zero prompt-tier total (an error status with no prompt usage, or a context-guru call billed before an inference-router resend) dropped a completed operator spend along with the never-priced savings, because the gate in InferenceParser.accountant looked only at the prompt counters. Spend does not depend on them — each record prices from its own operator call. The gate now also asks when the request has a reported op. - One layer deeper: Host.Compute can refuse the whole request (a rejected status, or more than one upstream round) independent of the prompt total, which discarded the spend the same way. Host.Savings now reads the raw reported ops directly and prices any completed spend without going through Compute at all when it refuses — which also means a multi-round request's mismatched usage/body pair still cannot corrupt the thread's persisted cache-effect state for later requests, the actual reason Compute refuses. - A spend record carried no currency, so an operator's call to a different, differently-priced host (a credits-billed gateway beside a USD-endpoint call) was summed into the primary request's total as if it were the same unit. SpendRecord now carries Currency, SpendPrice returns it, and event.Figures skips a spend whose currency does not match the record's own rather than mixing units. Also dismissed 2 code-scanning alerts (clear-text-logging on the session id this package logs, log-injection on a request path it logs) as false positives, matching the repo's own precedent for the identical pattern (alerts rossoctl#359 and rossoctl#334 on main): the session id is validated before it is accepted, not a credential, and slog's TextHandler already quotes a value before it reaches the log. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…known, and fix a real regression in the zero-prompt-total gate Two more findings from clawgenti's re-review: - The currency fix only gated PluginSpendMicros (basis usd). PluginSpendUnknownMicros is "not money", but it is still one number, and a USD figure and a differently- priced currency's figure summed into it is just as mixed. Same gate now applies there. - The zero-prompt-total gate in InferenceParser.accountant asked whenever pctx.ReportedOps() was non-empty, reasoning that the pass before any data arrives has no ops either. That was wrong: a structural op (tool-prune's removal, say) reports during OnRequest, before the response exists, so that pass's ops list is not empty either — and asking there calls Host.Compute with an inference extension that is still all zeros, which Compute latches forever, so the real counts that arrive on a later pass are never priced at all. Reproduced by clawgenti; fixed by gating on pctx.StatusCode (set once, when the response is read) instead of on ReportedOps. Added a regression test pinning the exact two-pass sequence. Also dismissed the same 2 alerts' re-raised instances (rossoctl#365, rossoctl#370) after they shifted line following the rebase onto main — the earlier dismissal (rossoctl#372, rossoctl#373) stopped applying once that commit was superseded. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…tream broke clawgenti's re-review: the StatusCode-based gate in InferenceParser.accountant dropped a completed operator spend when a stream broke mid-body, because forwardproxy's classifyBrokenStream resets pctx.StatusCode to 0 there, same as a response that was never read — specifically so the outcome is not misread as a 200. That is right for the outcome, but a context-guru call already billed on the request is not undone by the break. The gate now also asks when pctx.ResponseDelivered() is true: every listener marks that once bytes actually reached the client, before a mid-stream break can zero StatusCode, so it is set and stays set in exactly the situation StatusCode alone could no longer tell apart. Added a test for the broken- stream case. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
Persist the per-session state the context-guru engine needs between turns — the summary checkpoint, the last billed input, freeze decisions — in the engine's session_state table, in a SQLite file (modernc.org/sqlite, pure Go). The state survives a restart and a config reload, so the prompt prefix the provider has cached stays valid. On a local install the file is ~/.cortex/context-guru-state.db; otherwise it lives in the user cache directory. It holds content, so it is mode 0600 in a 0700 directory, and a row is kept 30 days after its last write. The plugin fails open: with no usable file it keeps the state in memory and logs one WARN. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
…Lite path Review fixes for rossoctl#2058: - Open the shared *sql.DB in Configure, and start the store.Disk (its flusher goroutine) in Init. A pipeline that a failed build or reload drops is never started, so it no longer leaks a flusher. - Set the 24h state-key lifetime only when the database opened. On the fail-open path the engine's default stays. - Report Disk.Errors() as the state_db_errors metric. - Escape '%', '#' and '?' in the file: URI. A '#' in the path made SQLite open another file, with the umask's mode, outside the 0700 directory. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
6ea82c3 to
8c164cb
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
This layer (cbf36f5 + 8c164cb, reviewed against cg/04-savings) backs the context-guru store.Memory with context-guru's own store.Disk on a SQLite file. It opens a shared *sql.DB per path in Configure, starts the flusher in Init, flushes it in Shutdown, and fails open to memory. I verified the lifecycle against pipeline.Start/Stop and the reloader (a dropped build is never started, so it leaks no flusher), and checked that apply.BodyOpts calls LoadSession on the request path, so state written to disk really is reloaded after a restart. The file: URI escaping is correct for modernc: with a file: prefix the whole DSN goes to sqlite3_open_v2 with SQLITE_OPEN_URI. The -wal/-shm files inherit the 0600 mode. The file and its session_state table are both new, so no older on-disk format needs to stay compatible, and CREATE TABLE IF NOT EXISTS keeps an existing file. I found no must-fix issues, and the two suggestions below can go in a follow-up.
Locally at head 8c164cb (GOWORK=off):
go test ./plugins/contextguru/passes, and so do-tags include_plugin_contextgururuns ofplugins/all,config,pipeline,accounting/...andreloader. None of these tests left a state file in$HOMEor$XDG_CACHE_HOME.go mod tidy -diffis clean incore,cmd/cortex,cmd/cortex-envoyandcmd/agentop.go build -tags include_plugin_contextguruofcmd/cortexsucceeds, and so doesGOOS=windows go vetof the plugin.
Author: boazdavid (CONTRIBUTOR association, admin repo permission, so a maintainer)
Areas reviewed: Go (plugin, state DB, lifecycle), go.mod/go.sum, docs, CLAUDE.md
Agent/IDE config (.claude/.vscode): none
Commits: 2 in this layer, all signed off: yes
CI status: still pending (queued) when I posted; nothing has failed yet
huang195
left a comment
There was a problem hiding this comment.
Summary
I reviewed only this PR's own 2 commits (cbf36f5, 8c164cb). I found no must-fix problem. I checked these points and they are correct:
Disk.Closeflushes the writes but does not close the shared*sql.DB, so a draining instance and a new instance can use the same handle.- The engine calls
LoadSession(apply.go:1397). InitandShutdowngo throughconfiguredPlugin.~/.cortexis 0700.- No test outside the package builds the real plugin, so tests do not write to the user's real directories.
Four earlier comments still have no answer: TTL when OpenDisk fails (plugin.go:304), lost writes on a reload (plugin.go:359), and two about erase (session-api.md:422, :424). I agree that they are suggestions and not blockers. Before this PR, a reload lost all of the state, so the PR makes it better.
Author: boazdavid (MEMBER — maintainer)
Areas reviewed: Go, go.mod dependencies (modernc.org/sqlite, pure Go), docs, CLAUDE.md
Agent/IDE config (.claude/.vscode): none
Commits: all signed-off: yes
CI status: passing
Assisted-By: Claude (Anthropic AI) [email protected]
| } | ||
| db, err := openStateDB(path) | ||
| if err != nil { | ||
| slog.Warn("context-guru: session state stays in memory; its database could not be opened", |
There was a problem hiding this comment.
nit: The AuthBridge image runs as uid 1001 with no home directory, so $HOME is /. Then os.UserCacheDir gives /.cache and MkdirAll fails. Each sidecar that turns on context-guru logs this WARN at start and again at each config reload, because each Configure tries again. The feature cannot work in that pod, so a WARN each time is noise. You could log at INFO when localInstall is false, or remember the failure for each path.
Stacked on: #2057
Required by: #2059
Review only this PR's change: boazdavid/cortex@cg/04-savings...cg/05-contextguru-state-disk (the diff against
mainalso 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.main, not in this series)What
Persist the per-session state the context-guru engine needs between turns —
the summary checkpoint, the last billed input, freeze decisions — in the
engine's session_state table, in a SQLite file (modernc.org/sqlite, pure Go).
The state survives a restart and a config reload, so the prompt prefix the
provider has cached stays valid.
On a local install the file is ~/.cortex/context-guru-state.db; otherwise it
lives in the user cache directory. It holds content, so it is mode 0600 in a
0700 directory, and a row is kept 30 days after its last write. The plugin
fails open: with no usable file it keeps the state in memory and logs one WARN.
Testing
GOWORK=off, incore,cmd/cortex(plain and with thelocalprofile tags),cmd/cortex-envoy,cmd/agentop,scripts/profile-tagsandscripts/readme-demo:gofmt -lempty,go vet ./...clean,go mod tidy -diffclean,go test ./...passes.mainalike, from the local America/Havana time-zone data:TestMidnightTransitions_EveryFixtureIsStillTheDayItClaimsToBe(core/cost/ledger),TestStartOfLocalDay_PicksTheEarlierOfTwoMidnightsandTestParseWindowSpec_TodayStartsWhereTheLocalDayStartsInEveryZone(core/cost/usage).Assisted-By: Claude (Anthropic AI) [email protected]