Skip to content

feat: adapt compaction report and apply (hosted and local) - #528

Merged
amiddavid merged 3 commits into
mainfrom
feat/adapt-compaction
Oct 15, 2026
Merged

amiddavid merged 3 commits into
mainfrom
feat/adapt-compaction

Conversation

@OsherElhadad

@OsherElhadad OsherElhadad commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

Backend for /context-guru:adapt compaction (the plugin shell is a separate PR). Follows the plugin's adapt contract (docs/plugin/adapt.md in that PR).

What it does

GET /api/adapt/compaction?since=&until= (dashboard, tenant-scoped):

  • Lists the deterministic compaction components that can be tuned (format, dedup, toon, cmdfilter, searchfold, textclean, extract) and which the account runs.
  • Rebuilds each stored request from its captured blocks (real message indices, paired tool_use, placeholders elsewhere) and runs it through apply.BodyOpts with 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.
  • Searches options: which candidates run, their order, extract.min_tokens and dedup.min_tokens (greedy from the current config, plus the default and the lossless trio as seeds; bounded).
  • Prices each option gross over every covered request at the deployed rates: a block's first appearance at the tail rate (5m and 1h write tiers as billed), later appearances at the rate that turn paid (read on a hit, write on a full-prefix rewrite, fresh otherwise), a re-billed cache read when an option edits content it already sent, and the expand tool declaration when an option adds or drops the last offloader. Sessions the window cuts into are read from their start, so a re-send is not priced as new tail.
  • Reports current, default, the best few distinct options and "no deterministic compaction" for reference, with saved/spend/net, a recommendation only when the gain clears a floor, and coverage warnings.

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):

  • Identity. Hosted: the dashboard cookie, or the account's own proxy token, the token only for /api/adapt/* (report and apply), only for its own account, never as a manager. Single-tenant: loopback only.
  • Writing. Hosted: the registry's Update (validation, tenant_config_audit row, 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.
  • Rate limit: 6 applies per account per 10 minutes. Every apply and revert is logged with account, kind, option and before/after hashes.

Also: context-guru's own plugin output (a tool result whose call runs one of the plugin's scripts/*.py) is never compacted. components.Pipeline restores 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:

  • dollar figures cover only requests with stored content;
  • clipped blocks are not run; they are modelled from their stored sizes (keeping every component that rewrote one costs what was sent, dropping any of them costs the original size);
  • an option that drops a component is also charged the saving request_components booked 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 from saved_usd, which older rows store without the tokenizer correction;
  • content in cold storage is not read; LLM components are not replayed and stay as they are.

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; -race on the adapt tests passes.
  • Ran on a copy of a real dashboard database through an experimental proxy (hosted and single-tenant), including a real Claude Code session running the plugin command, and the apply round trip with a dashboard session.

@OsherElhadad OsherElhadad changed the title feat(dash): adapt compaction report and apply feat: adapt compaction report and apply (hosted and local) Oct 13, 2026

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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/../../me and compaction/../../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/stats and PUT /api/me all 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, or f.Cache = nil removed, TestAdaptApplyHostedStoresOnlyTheOfferedChange fails. With the base-hash check disabled, TestAdaptLocalOverrideYieldsToANewerStartConfig fails.
  • Clean code. request_components is deduplicated with MAX per (request, component), and the hot-reload swap keeps the store. gofmt and go vet are clean, and the Adapt tests in proxy and dash pass. All commits are signed off with no AI attribution.

Blocking:

  1. revert undoes ANY latest configuration change, including a manager's. I reproduced it: a manager PATCHes a user's config_yaml, then the user's proxy token POSTs {"option":"revert"}. It answers 200 and the manager's edit is gone. adaptRevert takes the newest config_yaml audit entry whatever produced it. Since reg.Update lets an account write its own config_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 equals after" guard is also untested: with it disabled, every test still passes.
  2. The single-tenant gate trusts RemoteAddr alone. adaptPrincipal treats 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. statsTrusted exists for exactly this: loopback and no X-Forwarded-*/X-Real-IP (#523's local apply uses it). Use it.
  3. The report is unbounded work reachable by every account's token. GET /api/adapt/compaction runs 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 same adaptAllow budget.

Non-blocking:

  • An empty basis applies "the latest offer". The config hash still protects against a moved document, but #523 now requires basis (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 whenever write > write1h.
  • Conflict with #523. Both turn h.static into an atomic.Pointer and add a single-tenant override (.adapt.json here, .toolfilter.json there). After both merge, reloadLocal rebuilds from the document and drops #523's swapped-in toolfilter, and #523's swap starts from h.pipe and 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 in reloadLocal.
  • Two commit titles start with wip:. Squash with a clean message.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 adapt audit 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, the statsTrusted rule. 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.
  • basis is now required, and tail writes are priced at the 5m tier.
  • gofmt and go vet are clean. The Adapt tests in proxy and dash pass, and the components/... 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 OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 ours makes 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 of statsTrusted: loopback, with no X-Forwarded-For, X-Real-IP, X-Forwarded-Proto or X-Forwarded-Host. With it disabled, TestAdaptApplyLocalHotReloadsAndPersists fails.
  • Reports are bounded. adaptReportSlot allows one running report per account and adaptReportBurst an 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.
  • basis is 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:

  1. Revert ignores the kind. adaptRevert(who, kind) uses kind only for the audit text, so /adapt tools revert undoes 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".
  2. 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.
  3. Two commits are titled wip:. Squash-merge with an explicit subject and body.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 kind from the audit-prefix match fails TestAdaptRevertIsPerKindAndOnce. Local: dropping the Log[last].Kind check 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 false fails 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-dir layouts. Removing apply|revert from the subcommand list fails TestOwnPluginOutputIsNeverCompacted.
  • gofmt and go vet are clean. go test ./components/... ./proxy passes, and so does go 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. adaptReportSlot records the start before acquireKVCache can fail, so on a busy host a client that honours Retry-After: 30 can 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 OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Osher-Elhadad added 2 commits October 14, 2026 20:13
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]>
@OsherElhadad
OsherElhadad force-pushed the feat/adapt-compaction branch from 8ace311 to 63dfba9 Compare October 14, 2026 20:17

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.go and the new proxy/clientsignal_test.go. That test now uses h.static.Store(...) for main's atomic static, 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. ownOutput is now only scripts/cg.py <adapt|home|savings|cache|waste|session|doctor> or scripts/tv.py. With the old broad regex restored, TestOwnPluginOutputIsNeverCompacted fails on the cat …/context-guru/…, other-plugin-script and cg.py apply cases. adaptX and cache_x do not match, and the Codex ../../scripts/cg.py form does.
  • gofmt and go vet are clean. Tests pass for components/..., cmd/..., tenant, and in full for ./proxy and ./dash. CI is green, and both commits are by Osher-Elhadad, signed off, with no AI attribution.

Non-blocking:

  1. \b after cache also matches cache-campaign, because - is a word boundary. So cg.py cache-campaign build and mode, 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 \b if the comment should hold exactly.
  2. Nothing tests the new recover in ownOutputs: removing it passes every components/... test. A test whose request makes the regex scan panic, or a direct call with a malformed request, would pin it.
  3. As before, a user command that merely names scripts/cg.py adapt (for example echo) is also exempt. That is fail-safe and accepted.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.)

  1. A read subcommand must now be followed by whitespace, an (escaped) quote or the end of the string, so cg.py cache-campaign build is compacted. With \b restored, TestOwnPluginOutputIsNeverCompacted fails on the new cache-campaign case.
  2. TestOwnOutputsFailsOpen makes toolCallsOf panic. With the recover removed, it fails with panic: 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 OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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), so cg.py cache-campaign build is no longer exempt. With \b restored, TestOwnPluginOutputIsNeverCompacted (components/all) fails.
  • ownOutputs' fail-open recover is pinned by TestOwnOutputsFailsOpen through the toolCallsOf seam.

gofmt and go vet are clean, and CI is green (build-test, purego, trivy, DCO). Signed off. This approval covers 9496607.

@amiddavid
amiddavid merged commit 4ada00e into main Oct 15, 2026
4 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants