Repository navigation
feat: adapt compaction report and apply (hosted and local) - #528
Conversation
OsherElhadad
left a comment
There was a problem hiding this comment.
Review: REQUEST CHANGES at 8a11bf3. (Posted as a comment: GitHub does not let the author account request changes.) This is mostly a security review of the token scope, as requested.
Verified:
- The token reaches only
/api/adapt/*. With the account's proxy token I tried/api/adapt/../stats,//../prompt,x/../../meandcompaction/../../stats. The mux cleans each path and redirects (307), and the redirected request gets no token auth. The encoded forms (%2e%2e,..%2f,/api/adaptX) match no dash route and fall through to the upstream catch-all, so no dashboard data is served for them./api/me,/api/me/audit,/api/statsandPUT /api/meall refuse the token. - The token never acts as a manager.
?tenant=<other>is ignored for a token caller (it is not a manager), so the report stays on the token's own account. - The rate limit is keyed by account, the same key for cookie and token.
- Apply only takes a server-offered option. It requires a fresh offer (
kind|tenant, 30-min TTL), and its config-hash check gives 409 when the configuration moved. With the hash check disabled, the basis check disabled, orf.Cache = nilremoved, TestAdaptApplyHostedStoresOnlyTheOfferedChange fails. With the base-hash check disabled, TestAdaptLocalOverrideYieldsToANewerStartConfig fails. - Clean code.
request_componentsis deduplicated with MAX per (request, component), and the hot-reload swap keeps the store.gofmtandgo vetare clean, and theAdapttests inproxyanddashpass. All commits are signed off with no AI attribution.
Blocking:
revertundoes ANY latest configuration change, including a manager's. I reproduced it: a manager PATCHes a user'sconfig_yaml, then the user's proxy token POSTs{"option":"revert"}. It answers 200 and the manager's edit is gone.adaptReverttakes the newestconfig_yamlaudit entry whatever produced it. Sincereg.Updatelets an account write its ownconfig_yaml, this lets a plain account (or any holder of its proxy token) restore an arbitrary earlier document, which bypasses the manager-only YAML gate on PUT /api/me. Restrict revert to a change this route made: for example, keep the last adapt apply's before/after per account, and revert only when the newest audit entry is that same after-state by the same actor. Add a test with a manager edit in between. The "current equalsafter" guard is also untested: with it disabled, every test still passes.- The single-tenant gate trusts
RemoteAddralone.adaptPrincipaltreats any loopback peer as local. A single-tenant proxy behind a reverse proxy on the same host would therefore let every remote client read and apply.statsTrustedexists for exactly this: loopback and noX-Forwarded-*/X-Real-IP(#523's local apply uses it). Use it. - The report is unbounded work reachable by every account's token.
GET /api/adapt/compactionruns up to 30 replay arms for up to 5 minutes on the production host. Any proxy token, which sits in every client's environment, can start one, repeatedly and concurrently, with no limit. Add a per-account single-flight (or cache the last report for its TTL) and a global concurrency cap, or put the GET under the sameadaptAllowbudget.
Non-blocking:
- An empty
basisapplies "the latest offer". The config hash still protects against a moved document, but #523 now requiresbasis(400 without it). One rule for every adapt kind would be easier to reason about. - The 1h write blend in
adaptRates. A 1h breakpoint precedes every 5m one, so the tail blocks this prices are at the 5m end of the prefix. Blending in the 1h share over-prices tail writes when the head is 1h. Price the tail at the 5m write rate wheneverwrite > write1h. - Conflict with #523. Both turn
h.staticinto anatomic.Pointerand add a single-tenant override (.adapt.jsonhere,.toolfilter.jsonthere). After both merge,reloadLocalrebuilds from the document and drops #523's swapped-in toolfilter, and #523's swap starts fromh.pipeand drops an applied adapt pipeline. Whichever merges second needs one owner of the running pipeline, for example by applying the local removal list on top inreloadLocal. - Two commit titles start with
wip:. Squash with a clean message.
OsherElhadad
left a comment
There was a problem hiding this comment.
Re-review: APPROVE at 1521573. (Posted as a comment: GitHub does not let the author account approve.)
- Revert (1) is fixed. It now undoes only a change that has a matching
adaptaudit row (same stored before/after hashes, not a revert) and that is still the stored document. A manager's edit in between gets 409. With the guard disabled, TestAdaptRevertNeverUndoesAManagersEdit and TestAdaptApplyHostedStoresOnlyTheOfferedChange both fail. - The single-tenant gate (2) is fixed. It now uses
directLoopback, thestatsTrustedrule. With that check disabled, TestAdaptApplyLocalHotReloadsAndPersists fails. - The report cost (3) is bounded. Each account gets one report at a time and 12 per hour (429 beyond that), inside the global KV-cache slots.
basisis now required, and tail writes are priced at the 5m tier.gofmtandgo vetare clean. TheAdapttests inproxyanddashpass, and thecomponents/...tests pass. Both commits are signed off with no AI attribution.
Nit: when acquireKVCache fails (the context was cancelled, or no slot came free in time), the handler returns without writing anything, so the client sees an empty 200. Answer 503 there. Squash at merge with an explicit subject and body, as planned.
Approved.
OsherElhadad
left a comment
There was a problem hiding this comment.
Re-review: APPROVE at 9b6a830. (Posted as a comment: GitHub does not let the author account approve.)
All three earlier blockers are fixed. I checked each by disabling the fix and confirming a test fails:
- Revert undoes only the caller's own adapt apply, and only while it is still the latest change. Removing the actor match makes TestAdaptRevertIsOnlyTheCallersOwnApply fail. Disabling
oursmakes TestAdaptRevertNeverUndoesAManagersEdit fail. Dropping the "still the latest change" comparison (e.After != t.ConfigYAML) makes TestAdaptRevertIsOnlyTheCallersOwnApply fail. - The single-tenant gate is
directLoopback. That is the shared body ofstatsTrusted: loopback, with no X-Forwarded-For, X-Real-IP, X-Forwarded-Proto or X-Forwarded-Host. With it disabled, TestAdaptApplyLocalHotReloadsAndPersists fails. - Reports are bounded.
adaptReportSlotallows one running report per account andadaptReportBurstan hour, taken before the global KV-cache slot. With it disabled, TestAdaptReportSlotIsOnePerAccountAndBudgeted fails. A cancelled replay returns an error rather than numbers, and the client-goes-away test passes. basisis required (400). Tail blocks are priced at the 5m write rate unless the request wrote everything at 1h.
Token scope still holds:
- DashAuth accepts the proxy token only under
/api/adapt/, as a plain tenant principal.?tenant=widens scope only for a cookie-authenticated manager. - The token also reaches
POST /api/adapt/tools/apply(#523), with the same constraints: only an option the server offered in that account's latest report, within 30 minutes, matched by basis. The offers store is keyed by kind and tenant, one entry each, so it is bounded.
Checks: gofmt and go vet are clean. go test passes for proxy, components/... and cmd/.... In dash, 2 tests failed with SQLITE_BUSY under host load and passed on rerun; neither is an adapt test. go test -race ./proxy ./dash -run Adapt passes.
Non-blocking:
- Revert ignores the kind.
adaptRevert(who, kind)useskindonly for the audit text, so/adapt tools revertundoes a compaction apply if that was the caller's latest adapt change (the local revert is the same). Either match the adapt row's kind, or say so in the answer. The tools route already says "whatever made it". - The " revert via " exclusion is untested. Removing it still passes every test, so "a second revert is 409" is not actually checked. The cancel check after
wg.Wait()(line 836) is also unpinned, because only the dispatch-loop check is exercised. - Two commits are titled
wip:. Squash-merge with an explicit subject and body.
OsherElhadad
left a comment
There was a problem hiding this comment.
Re-review: APPROVE at d6b3147 (the delta from 9b6a830: 3522489, db77556, d6b3147). (Posted as a comment: GitHub does not let the author account approve.)
Verified by disabling each change; the named test then fails:
- Revert is per kind. Hosted: dropping
kindfrom the audit-prefix match fails TestAdaptRevertIsPerKindAndOnce. Local: dropping theLog[last].Kindcheck fails TestAdaptApplyLocalHotReloadsAndPersists. This resolves the earlier note that a tools revert could undo a compaction apply. - The tie-break is a total order. Fewer moves, then fewer components, then the key. Making the last step
falsefails TestAdaptTieBreakIsATotalOrder and TestAdaptReportIsDeterministicOnTies. Per-session slots summed in session order make the totals the same float on every run. - A busy report gets a 503 with Retry-After. Removing the header fails TestAdaptReportBusyIs503.
- The own-output match covers the Codex and
--plugin-dirlayouts. Removingapply|revertfrom the subcommand list fails TestOwnPluginOutputIsNeverCompacted. gofmtandgo vetare clean.go test ./components/... ./proxypasses, and so doesgo test -race ./dash -run Adapt. One dash test failed with SQLITE_BUSY under host load and passed when rerun alone. All three commits are signed off with no AI attribution.
On spoofing the own-output exemption: the match runs on the tool call's argument text, so any command that names scripts/cg.py <subcommand> (for example echo scripts/cg.py session, or a user's own repo with a scripts/cg.py cache), or any scripts/tv.py, is exempt. I looked for an exploit and found none. The exemption only restores that tool result verbatim after a component changed it (restoreOwn). It never alters content, never touches another account, and the live path and the replay apply it the same way, so it cannot skew the report against live behaviour. The worst a spoof does is leave the caller's own output uncompacted. Accepted as is. If false positives on users' own cg.py scripts start to matter, anchor the match on the plugin root.
Non-blocking:
- A 503 still uses up hourly quota.
adaptReportSlotrecords the start beforeacquireKVCachecan fail, so on a busy host a client that honoursRetry-After: 30can use all 12 hourly starts within about six minutes and then gets 429 for the rest of the hour. Take the global slot first, or drop the recorded start on 503. - The two
wip:commit titles from earlier: squash-merge with an explicit subject and body.
OsherElhadad
left a comment
There was a problem hiding this comment.
Re-review: APPROVE at 8ace311. (Posted as a comment: GitHub does not let the author account approve.) The handler now takes the global dashboard slot before the per-account report slot, so a busy 503 no longer spends the account's hourly budget, and the new test assertion pins that. go vet is clean and the dash Adapt tests pass. Signed off, no AI attribution. Non-blocking: acquireKVCache waits rather than failing fast, so an account's extra concurrent requests queue for a global slot before they get 429. It might be cheaper to check whether a report is already running for the account before waiting. This approval covers 8ace311.
GET /api/adapt/compaction replays the deterministic compaction components on an account's stored requests through apply.BodyOpts, searches which run, their order and two thresholds, and prices each option gross per request at the deployed rates. Coverage is stated in every report; clipped blocks are modelled from stored sizes, and dropping a component is charged the saving request_components booked for it that the replay cannot see. Reports are bounded per account, cancellable, and answer 503 when the dashboard is busy. POST /api/adapt/compaction/apply stores an option the account's latest report offered. proxy/adaptapply.go is the shared helper for every adapt kind: dashboard cookie or the account's own proxy token (adapt routes only), loopback-only on a single-tenant proxy, a rate limit, audit rows, a per-kind revert of the caller's own latest apply, and an in-process pipeline swap with a persisted override on a single-tenant proxy. The pipeline never changes context-guru's own plugin read output. Signed-off-by: Osher-Elhadad <[email protected]>
…mpaction The own-output exemption matched any plugin script and any path naming context-guru. It now matches only scripts/cg.py with a read subcommand (adapt, home, savings, cache, waste, session, doctor) and scripts/tv.py, in the Claude Code and Codex layouts. cg.py apply and revert, other plugins' scripts and paths that merely contain context-guru are compacted as before. The match also fails open on a panic, since it runs outside the per-component recover. Signed-off-by: Osher-Elhadad <[email protected]>
8ace311 to
63dfba9
Compare
OsherElhadad
left a comment
There was a problem hiding this comment.
Re-review: APPROVE at 63dfba9 (00f8d08 is the squash of the work approved through 8ace311, rebased on main; 63dfba9 narrows ownOutput). (Posted as a comment: GitHub does not let the author account approve.)
- Squash and rebase. I compared the PR's per-file diff at 8ace311, against its old base, with the diff at 00f8d08, against main. Every file is identical except one dropped comment in
cmd/context-guru-proxy/main.goand the newproxy/clientsignal_test.go. That test now usesh.static.Store(...)for main's atomicstatic, which is correct. So the approved behaviour is all still there: the revert actor and kind guard,directLoopback, the global-slot-first report ordering, the required basis, 5m tail pricing, the deterministic tie-break and the token scope. - 63dfba9.
ownOutputis now onlyscripts/cg.py <adapt|home|savings|cache|waste|session|doctor>orscripts/tv.py. With the old broad regex restored, TestOwnPluginOutputIsNeverCompacted fails on thecat …/context-guru/…, other-plugin-script andcg.py applycases.adaptXandcache_xdo not match, and the Codex../../scripts/cg.pyform does. gofmtandgo vetare clean. Tests pass forcomponents/...,cmd/...,tenant, and in full for./proxyand./dash. CI is green, and both commits are by Osher-Elhadad, signed off, with no AI attribution.
Non-blocking:
\baftercachealso matchescache-campaign, because-is a word boundary. Socg.py cache-campaign buildandmode, which are changes, are exempt from compaction, despite the comment's "not cg.py's … which change a setting". It fails safe, since the output is only left uncompacted. Use(\s|\\?["']|$)instead of\bif the comment should hold exactly.- Nothing tests the new
recoverinownOutputs: removing it passes everycomponents/...test. A test whose request makes the regex scan panic, or a direct call with a malformed request, would pin it. - As before, a user command that merely names
scripts/cg.py adapt(for exampleecho) is also exempt. That is fail-safe and accepted.
…put fail-open Signed-off-by: Osher-Elhadad <[email protected]>
OsherElhadad
left a comment
There was a problem hiding this comment.
Re-review: APPROVE at 9496607. This closes both non-blocking notes from my 63dfba9 review. (Posted as a comment: GitHub does not let the author account approve.)
- A read subcommand must now be followed by whitespace, an (escaped) quote or the end of the string, so
cg.py cache-campaign buildis compacted. With\brestored, TestOwnPluginOutputIsNeverCompacted fails on the new cache-campaign case. - TestOwnOutputsFailsOpen makes
toolCallsOfpanic. With therecoverremoved, it fails withpanic: boom.
gofmt and go vet are clean, and components/... passes. CI is green, and the commit is signed off with no AI attribution. This approval covers 9496607.
OsherElhadad
left a comment
There was a problem hiding this comment.
Re-review: APPROVE at 9496607 (on top of 63dfba9). (Posted as a comment: GitHub does not let the author account approve.)
Both nits are fixed:
- The read subcommand must now end its word (
(\s|\\?["']|$)instead of\b), socg.py cache-campaign buildis no longer exempt. With\brestored, TestOwnPluginOutputIsNeverCompacted (components/all) fails. ownOutputs' fail-open recover is pinned by TestOwnOutputsFailsOpen through thetoolCallsOfseam.
gofmt and go vet are clean, and CI is green (build-test, purego, trivy, DCO). Signed off. This approval covers 9496607.
Backend for
/context-guru:adapt compaction(the plugin shell is a separate PR). Follows the plugin's adapt contract (docs/plugin/adapt.mdin that PR).What it does
GET /api/adapt/compaction?since=&until=(dashboard, tenant-scoped):format, dedup, toon, cmdfilter, searchfold, textclean, extract) and which the account runs.tool_use, placeholders elsewhere) and runs it throughapply.BodyOptswith a per-session store and the request's own clock, so the product's own cache-aware freeze, sticky replay and never-worse guard decide. Nothing re-implements a component.extract.min_tokensanddedup.min_tokens(greedy from the current config, plus the default and the lossless trio as seeds; bounded).POST /api/adapt/compaction/apply {"option","basis"}stores an option for the caller's own account. Options have short ids (current,default,none,c1...); the server keeps each account's latest report's options for 30 minutes, and an apply may only name one of those (409 otherwise, and 409 when the configuration changed since the report). Only candidate components and the searched settings move; every other component keeps its place; the cache block is not touched.{"option":"revert"}restores the configuration from before the last change, only if nothing changed it since.Shared apply helper (
proxy/adaptapply.go, meant for every/api/adapt/*kind):/api/adapt/*(report and apply), only for its own account, never as a manager. Single-tenant: loopback only.Update(validation,tenant_config_auditrow, pipeline rebuilt on the next request). Single-tenant: an override document beside the dashboard database, and the running pipeline is rebuilt and swapped in-process (no restart), keeping the state store so existing markers still expand. An override written against a different start configuration is ignored at start, so a later preset or config-file change wins.Also: context-guru's own plugin output (a tool result whose call runs one of the plugin's
scripts/*.py) is never compacted.components.Pipelinerestores it after every component, so an agent never prints a report with lines elided out of it.Data limits, stated in every report
The dashboard stores only the blocks a component rewrote, capped per request, each clipped at capture. So:
request_componentsbooked for it that the replay cannot see (blocks past the capture cap, content never stored). That booking is re-priced from its token counts at the replay's rates, not read fromsaved_usd, which older rows store without the tokenizer correction;Tests
dash/adaptcompaction_test.go: per-appearance pricing by hand (tail write, read, full rewrite), bust and 1h-tier rates, coverage of clipped and content-less requests, modelled blocks, the unseen-saving charge, lead-in before the window, option id round trip and rejection, pipeline merge, the route's tenant scoping (user, manager default, manager naming an account).proxy/adaptctl_test.go: hosted apply of an offered option (stored pipeline and setting, no cache block, stale basis, moved configuration, another account's offer, revert, audit); the proxy token reaches the adapt report and apply and nothing else, and applies are rate-limited; single-tenant apply hot-reloads the running pipeline, persists, survives a restart, reverts, refuses off-loopback callers, and ignores an override made against an older start configuration.go test ./dash/ ./proxy/ ./tenant/ ./config/ ./apply/ ./components/... ./cmd/... ./context-guru-plugin/...passes;-raceon the adapt tests passes.