Skip to content

feat(cache): /context-guru:adapt cache: replay keep-alive strategies on your history and enforce through the auto builder - #530

Merged
amiddavid merged 7 commits into
mainfrom
feat/adapt-cache
Oct 15, 2026
Merged

amiddavid merged 7 commits into
mainfrom
feat/adapt-cache

Conversation

@OsherElhadad

@OsherElhadad OsherElhadad commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

This is the backend of /context-guru:adapt cache. It follows the plugin's /context-guru:adapt contract (#526) and uses the shared adapt principal, rate limit and audit in proxy/adaptapply.go (#528, merged into this branch). It is stacked on the re-landed #521 (port/predictive-campaigns-main). The branch also contains #528 through one merge commit, because this PR uses its shared helper; that part leaves the diff once #528 is on main and the base is rebased. Design: docs/proposals/adapt-cache.md (excluded from the site nav, like the other proposals).

What it does

GET /api/adapt/cache?since=&until= replays keep-alive options on the caller's own history:

  • never;
  • the shipped default (K2 at 270 s, >= 80K prefix, <= $0.50 a ping, SessionEnd);
  • the current setting;
  • blanket K1, K2 and K3;
  • adapted plans: auto, and one plan per segment of day of week, hour, prompt-size band, model, client or stop reason.

The report leads with a relative comparison: best vs the default vs the current setting, held out, paired by session (relative, summary).

  • Table: the last 30% of decisions, with plans tuned only on what came before. The whole window is under in_sample.
  • Money: in gateway dollars, from the closed form taken in expectation over default model parameters (adaptreplay.go). A ping that rewrites stops the span; a rescued request can still miss; the cliff has a spread; the shared head and hits from other sessions are fitted on the caller's own history; a ping stops when its keeper entry (one per thread of a session) sees a new request. The money is always labelled an upper bound (upper_bound, a warning, calibration).
  • Gate verdict: each adapted option carries the builder's own verdict, computed by the same shipGate function on the same rows and units. It must beat the default, blanket K3 and the fleet plan.
  • Recommendation: only an adapted option that passes the gate is recommended. Otherwise the summary says to keep the default. disagreement gives one line when money and the gate disagree.

For /context-guru:save-more cache the report also returns:

  • to_date: what the current keep-alive saved so far, observed from the ledger;
  • gain: the change on offer against the default and the current setting, held out, paired by session, and per held-out week;
  • heatmap: a Monday..Sunday x 00..23 grid of that gain in the account's strategy timezone (heatmap_tz), with one grid per option under option_heatmaps;
  • ci95 and per_week_usd on the recommendation.

POST /api/adapt/cache/apply {"option","basis","force"}:

  • default switches the caller's campaign off. revert undoes only the caller's own adapt campaign (one an adapt apply by the same actor started and last set); anything else is 409.
  • A non-manager (session or token) never overrides a campaign a manager last set: apply, force, default and revert all return 409 "campaign managed by your account admin", and nothing changes. A manager can.
  • An adapted option runs the auto build in-process. If the gate passes (ship), the campaign goes active. Otherwise it runs in shadow, and the response carries ok: false and force_available: true.
  • "force": true (apply anyway) activates the caller's own tuned plan (own_policy), not the fleet plan, and the note says the campaign is not rebuilt daily.
  • An adapted apply needs the basis of the caller's own latest report: an empty basis, another caller's basis (a manager's ?tenant= read keeps its own) or one older than 1 h returns 409. Applies are rate-limited and audited; a forced apply's audit row says "forced, gate failed".
  • Policy: an account (dashboard session or its own proxy token) can switch off, build and force a campaign on its own account only, and only when no manager set the live one. A campaign never turns the keep-alive on for an account that has it off, and never widens the per-ping ceiling.

Data: the report makes the same reads as the auto builder (autoFleet for the prior, autoOwn for the account's own rows, rowsWith to combine them). The fleet's rows are read for the prior, and the account's own rows are read on their own, so a busy fleet never pushes them past the row cap. If the account's own window is over the cap, the report answers 422 rather than a shortened report. If the fleet prior was cut, a warning says so.

Scope:

  • Hosted: the dashboard cookie, where a manager may pass ?tenant=, or the account's own proxy token.
  • Single-tenant: direct loopback only, no forwarding headers (the /stats rule).

Changes outside the new files (reviewers: please check)

  • SessionEnd scoring (the auto builder too). With session_end, a ping is cancelled if it would start after the end of the session's last response, in ANY model's conversation of that session. Before, only the session's final row lost its pings. Test: TestSessionEndStopsPingsAcrossModels.
  • Successors per thread. KVCacheOptions.ByThread links each request to the next one on its own thread_id. The report and the builder both use it, and turns are counted per thread. Rows written before threads existed ('') link as before. kvcache.Request.ThreadID is not on the JSON wire.
  • Builder:
    • segment_by, kept on refresh;
    • the shipped default added to the ship gate;
    • own_policy stored in every evaluated spec;
    • the shared shipGate;
    • runtime facts hour_utc and dow_utc.
  • Refactors. startCacheBuild and setCampaignMode are factored out of the manager handlers; the handlers behave the same.

Evidence

  • proxy/adaptcache_test.go covers:
    • the report gate equals the builder's verdict, and an apply then switches the campaign on;
    • apply anyway activates the chosen plan, on disk and over HTTP;
    • shadow carries force_available, insufficient history stays off, and revert works;
    • a per-segment plan ships where one plan cannot;
    • segment predicates select the same requests live;
    • SessionEnd works across models, and a ping's span is its own thread's (TestPingSpanIsPerThread);
    • a manager's campaign is untouchable by the account's session and token (TestAdaptCacheNeverOverridesAManagersCampaign); a forced apply on the account's own campaign goes live and is audited, and revert undoes only the caller's adapt campaign (TestAdaptCacheForceOnTheAccountsOwnCampaignIsAudited);
    • the expected-value replay charges failures and other sessions' hits;
    • single-tenant routes refuse non-loopback and relayed callers;
    • the caller's 4 requests among a busier fleet over the row cap still give a full report, and an own window over the cap gives 422 (TestAdaptReportReadsTheCallersRowsPastTheFleetCap); reports are bounded per account per hour (TestAdaptCacheReportsAreRateLimitedPerAccount);
    • a manager's ?tenant= reads the account without replacing its basis, a non-manager's is ignored, accounts are isolated, and a missing, foreign, stale or expired basis returns 409;
    • the shared ship gate fails a plan that ties any of its legs (TestShipGateNeedsToBeatK3TheFleetAndTheDefault).
  • dash: TestKVCacheDatasetByThreadLinksWithinTheThread.
  • go test ./proxy ./dash ./kvcache ./predictive ./components/... ./cmd/... pass, and mkdocs build --strict passes. With -race, ./proxy takes 527 s on our box against 500 s for the base without this PR. The three adapt tests that took about 166 s now use a small fixture and take about 13 s together. Some older proxy and dash tests fail now and then under full-package load on a busy box and pass on rerun; none of them is in code this PR changes.
  • I ran the report on a copy of a real account's history and in a real Claude Code session through the plugin, and checked it against the offline research replay engine. The numbers stay in the private research repo.

Release notes

The keep-alive builder and this report start every account's plan from a shared prior: aggregate keep-alive outcomes (request timing, token counts, cache hits) of all accounts on the same service, shrunk toward the account's own history. No account's content is read.

@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 d7edfd8. (Posted as a comment: GitHub does not let the author account request changes.)

Verified:

  • The PR is stacked on #521. All 6 commits are by Osher-Elhadad and signed off, with no AI attribution. gofmt and go vet are clean.
  • go test ./predictive and ./dash pass. ./proxy passes except TestDashboardAddsNoRequestLatencyWithContentCapture, which failed once under host load and passes when rerun alone.
  • The refresh gate from before is intact. refreshAutoCampaigns keeps segment_by (it is in request.json), still skips a non-ship rebuild of an ACTIVE campaign, and still swaps through swapSpec under the campaign lock.
  • The SessionEnd change matches the keeper. toEnd is measured to the end of the session's last response on any model (ConversationID is the session), and the live SessionEnd retireSession retires every entry under the session prefix, whatever its model. With stop = f.toEnd reverted to the old stop = 0, TestAutoSpecSegmentedShipsAPlanPerSegment and TestAdaptCacheReportAndApply fail.
  • The basis check is tested. Ignoring the basis makes TestAdaptCacheReportAndApply fail. Loosening the builder's ship gate makes three tests fail.

Blocking:

  1. Single-tenant routes have no access check. adaptCaller returns h.static for anyone when registry() == nil. mountAdapt puts both routes on the proxy's main mux, which listens wherever the proxy listens. So on a single-tenant proxy bound beyond loopback (a container or a shared host), any caller can read the cost report and POST /api/adapt/cache/apply, which switches the keep-alive campaign and starts builds. The PR text says "Single-tenant: the local DB on loopback", but the code does not enforce it. Gate the single-tenant branch with h.statsTrusted(r) (loopback and no forwarded headers), the rule /stats and #523's local apply use, and add a test with a non-loopback peer.
  2. "Apply anyway" turns on the fleet plan, not the chosen one. On a non-ship build, autoSpec sets policy to e.final.FleetPlan, the rule from #7. adaptAfterBuild with force then makes that spec ACTIVE, and the answer says "Applied anyway, as asked … campaign X is live". The user picked, say, by_hour, but what runs is the single fleet plan. Either build a forced apply with the option's own plan (and mark the spec as forced, so the refresh keeps it), or say plainly in the note and the docs that "apply anyway" runs the fleet plan.
  3. The public PR text has experiment numbers. The Evidence section carries real-data dollar figures and intervals, request and session counts, engine ratios and model spend, plus "production snapshot". docs/adapt-cache/DESIGN.md:42 also has "about 2x on one real tenant's month … about 1.7x". Move those to the private research repo and keep only the mechanism and the test list here.

Non-blocking:
4. The report's gate equals the builder's only by duplicated code. It is the same rows, the same seeds (sessionCI(…, 1)) and the same units, but the formula is written out again in adaptReport. TestAdaptReportGateMatchesTheBuilder checks one case with wide margins: if the report's "vs the default" leg compares against K3 instead, the test still passes. Factor the gate into one function that autoSpec and the report both call, so "equals the builder's verdict" holds by construction.
5. A non-manager's ?tenant= is ignored, which is correct, but nothing tests it. Dropping the IsManager() check passes every test.
6. turn counts per session, not per thread. rowFacts.turn indexes the session's requests across all threads and models, so the replayed default pings a sub-agent thread's first request, which the live default skips. That overstates the default's ping spend and biases the comparison against it.
7. SessionEnd is assumed to arrive the moment the last response ends. A real exit comes later and is not always delivered, so label every SessionEnd figure as an upper bound in the report's method note.
8. A forced active campaign never refreshes (an active campaign changes only on ship). That is fine, but say so in the apply note.

@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: REQUEST CHANGES at 5c60900. (Posted as a comment: GitHub does not let the author account request changes.)

Status of the three earlier blockers:

  1. Single-tenant access check: fixed. adaptPrincipal uses directLoopback (the statsTrusted rule, so relayed requests are refused). With it disabled, TestAdaptApplyLocalHotReloadsAndPersists fails.
  2. "Apply anyway": not fixed. When the build's verdict is not ship, autoSpec sets the policy to policy(e.final.FleetPlan) (campaignauto.go, case rec != "ship"). adaptAfterBuild(force=true) then activates that spec. So a forced by_hour (or auto) apply switches on the fleet plan, yet the answer says "applied": "<option>" and "Applied anyway, as asked … campaign … is live". Either have a forced build ship the chosen plan (when force, put the tenant's or segment plan in the policy and mark it forced), or say in the answer that the fleet plan runs.
  3. Real-data numbers in public text: not fixed.
    • PR body: the "Real data" and calibration paragraphs still have dollar nets and intervals, request and session counts, model spend, the 2x / 1.7x / 40-80% engine ratios, the measured ping-rewrite rates and "production snapshot". The SessionEnd paragraph has real ping counts.
    • docs/adapt-cache/DESIGN.md:42: "about 2x on one real tenant's month … about 1.7x".
    • proxy/adaptcache.go:443: the comment "within 10% on a reference account where both run 40-80% above".
    • proxy/adaptcache.go:484: the note the API returns to every caller says "on a reference account by 40-80%".
    • Code constants the replay uses (rewrite rates, the cliff) are product parameters and can stay. Remove the measured comparisons and the real-data paragraphs.

Your focus points:

  • (a) Token scope on POST /api/adapt/cache/apply. A proxy token resolves only to its own tenant, and ?tenant= widens scope only for a manager's cookie. The basis is per account, with a 1 h TTL, and the rate limit is keyed cache:<tenant>. Three issues:
    • The manager ?tenant= check is still untested. With && t.IsManager() removed, every Adapt|CacheCampaign|Auto test passes.
    • The basis TTL is untested too. Removing time.Since(b.at) > adaptBasisTTL passes every test.
    • An empty basis is accepted ("the last report"), while #523 and #528 now require it. A report a manager generated for the account under ?tenant= sets the same per-account basis, so a basis-less apply can act on numbers the user never saw. Require the basis, as the other two do.
  • Policy question, not a code bug. Through this route a plain user, or the account token, can switch off a manager-created live campaign (default), start builds, and force-activate a plan that failed the gate. The manager campaign routes needed a manager for all of this. If users owning their keep-alive is the intended design, say so in the docs.
  • (b) ByThread. Only the window partition changes, to (tenant, session, model, thread_id), so nothing can link across sessions or tenants. Legacy rows with thread_id = '' form one partition per (session, model), exactly as before. In a session that mixes '' and real ids (only at the upgrade boundary), a '' row loses its successor on a real-thread row, so it reads as no-return. That is conservative (pings counted as wasted) and negligible in volume. With the partition change reverted, TestKVCacheDatasetByThreadLinksWithinTheThread fails.
  • (c) Builder.
    • The ship gate now includes the default, and the refresh gate still holds (active changes plan only on ship, swapSpec under the lock): with that check removed, TestAutoRefreshSwapRechecksTheModeUnderTheLock fails.
    • Report gate vs builder verdict: autoEval is shared, but the gate itself is still written twice: the builder_gate block in adaptcache.go, and the cands loop in autoSpec. With the report's K3 leg changed to K2, every Adapt test still passes, so equality is still unpinned. Factor the gate into one function both call, or add a test asserting builder_gate.pass == (autoSpec rec == "ship") on the same rows.
  • Checks. gofmt and go vet are clean. go test ./proxy passes in full, and so do ./predictive and the dash KVCache|Adapt|Thread tests. All commits are by Osher-Elhadad and signed off, with no AI lines. Two commit titles start with wip:, so 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: REQUEST CHANGES at b16093c. (Posted as a comment: GitHub does not let the author account request changes.)

Fixed since 5c60900:

  • Single-tenant gate. Both routes go through the shared adaptPrincipal: direct loopback only, no forwarding headers.
  • Apply anyway. A forced non-ship build installs own_policy, and the live policy equals it. With the swap in forcePolicy removed, TestAdaptApplyShipsActiveAndShadowsTheRest fails. If the swap cannot be written, the campaign is left off. The daily rebuild still changes a live campaign only on a passing gate, so a forced plan is not swapped back.
  • Other items. shipGate is one function. A non-manager's ?tenant= is ignored, and that is tested. Turns are counted per thread, and SessionEnd is labelled an upper bound.
  • Checks. gofmt and go vet are clean. go test ./predictive and ./proxy pass in full, as do the dash KVCache|Adapt|Thread tests.

Blocking:

  1. Production figures are still in public text. The PR body is much better, but production measurements and their provenance remain:

    • proxy/adaptreplay.go:15-24: the fid* constants carry production counts in their comments (pings rewritten out of pings sent), and fidMiss is labelled "production short-gap misses".
    • proxy/adaptcache.go:471: the calibration.note that the API returns to every caller lists the measured rewrite rates and the cliff.
    • docs/adapt-cache/DESIGN.md:36 (the calibration multipliers) and :40 ("on a reference account it ran above that engine").
    • The PR body: "measured in production" and the cliff value with its spread.

    Remove the provenance counts, the "production" and "reference account" wording, and the figures in the API note and the docs. Whether the constants the code needs can stay in a public file (the method is cleared) is an owners' call, so I have raised it.

  2. The replay's ping span does not match the keeper. rowFacts.span (campaignauto.go:77) stops pings at the session's next request in any model or thread, on the grounds that "the keeper holds one body per session". It doesn't: entries are keyed per thread (kaThreadKey). A request on thread B does not stop thread A's pings. Its only effect is a pause while it is in flight, and that pause is on the #527 stack, not this base. In sessions with sub-agents the replay therefore counts fewer wasted pings than the keeper sends, which flatters every strategy that pings. Use the thread's own next request (the ByThread partition already has it), or state the bias next to the upper-bound label.

Non-blocking:

  • revert switches off whatever campaign is live for the account, including one a manager built. There is no actor or kind check like #528's adaptRevert. Together with apply, this lets a plain user or the account token turn off a manager's campaign or force a plan that failed the gate. That is a policy question, and I have raised it.
  • basis is still optional. Without one, the apply uses the account's latest report, and a manager running ?tenant= for the account sets that same per-tenant basis. #523 and #528 require basis; consider doing the same here.
  • Gate equality is still unpinned. The report builds its own gate legs (adaptcache.go:358-360). Changing its K3 leg to K2 still passes every test, TestAdaptReportGateMatchesTheBuilder included.
  • Commits. The branch contains #528's commits (merged in), so merge #528 first. Its two merge commits have no sign-off; a squash merge with an explicit subject and body covers that.
  • History. A squash merge leaves main's tree clean. The earlier branch commits and the PR body's edit history keep the figures, and stay reachable through the PR on GitHub. I have raised that with the owners.

@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: REQUEST CHANGES at 856bee7. Two one-line follow-ups to the manager-guard ruling are needed; everything else from the earlier reviews is fixed. (Posted as a comment: GitHub does not let the author account request changes.)

Fixed and verified:

  • Provenance. The PR body, DESIGN.md, the API's calibration note and the fid* comments carry no production counts, sources or reference-account wording. What remains are the shipped default's parameters and runtime-formatted strings, which is acceptable under the ruling that neutral defaults may stay.
  • Ping span per keeper thread. With the span made session-level again, TestPingSpanIsPerThread fails. Legacy rows with an empty thread id group by session as before.
  • Manager guard. It runs before the rate limit and before every option (adapted, force, default, revert), for the cookie and the proxy token alike. With the guard disabled, TestAdaptCacheNeverOverridesAManagersCampaign fails.
  • Revert. It undoes only the caller's own adapt campaign (via == "adapt" and mode_by == actor). That matches the ruling's actor-and-kind intent, so not routing through adaptRevert (which edits config_yaml) is right. With the guard disabled, TestAdaptCacheForceOnTheAccountsOwnCampaignIsAudited fails.
  • A forced apply writes the audit row active: forced, gate failed.
  • gofmt and go vet are clean. go test passes in full for proxy, dash, predictive and kvcache. The new commit is signed off with no AI attribution.

Blocking:

  1. Check and activate are separated in time. managedCampaign is checked once, before the build (adaptcache.go:582). The activation (setCampaignMode at :709) runs after a build that can take up to adaptApplyWait. If a manager sets a campaign in that window, the adapt campaign's load switches the manager's campaign off. Re-check managedCampaign(h.predRT().forTenant(tn.ID), who) immediately before activating, and return 409 with nothing changed.
  2. An empty mode_by counts as "not managed". A campaign whose meta predates this field, including a manager-built one, can then be overridden by a non-manager. Fall back to meta.Actor, which every build has always recorded, when ModeBy is empty, and add a test with a meta that lacks mode_by.

Non-blocking:

  • campaignauto.go:77: the span field comment still says "session's next request (any model or thread): the keeper holds one body per session". Update it to say per thread.
  • byConv and byThr are now built with the same key and the same values, so one map would do.

@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 3a53875. (Posted as a comment: GitHub does not let the author account request changes or approve.)

  • Both remaining blockers are fixed.
    • The manager re-check now runs inside setCampaignModeIf, under the package campaignModeMu that every mode change goes through, immediately before the write. A manager who sets a campaign during an adapt build is not overridden, and the apply returns 409. TestAdaptCacheApplyRefusesWhenAManagerActsMidBuild covers it over HTTP.
    • An empty mode_by falls back to meta.Actor, and if both are empty a non-manager is refused (fail closed). With the fail-closed line weakened, the mid-build test fails.
  • The per-thread span comment and the merged map are fixed, and the revert comment explains why it does not use adaptRevert.
  • gofmt and go vet are clean, and go test -race ./proxy -run 'Adapt|Campaign|Manager' passes. Both commits are signed off with no AI attribution.

Non-blocking: managedCampaign treats a writer whose account no longer exists (reg.Get error) as unmanaged. That is probably fine, but say so in a comment.

Approved. Merge after #528 and #521, squash with an explicit subject and body.

@OsherElhadad
OsherElhadad force-pushed the port/predictive-campaigns branch 3 times, most recently from 46c6a30 to 196aade Compare October 14, 2026 15:06

@amiddavid amiddavid 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.

Verdict

Blocked. CI is red for two reasons. Both come from this PR. I also found one defect and a stacking problem. The code that I could test passes (182 s of adapt tests, race on). Do not merge until findings 1 to 3 are fixed.

Findings

  1. CI build fails: mkdocs build --strict. The log says docs/adapt-cache/DESIGN.md exists in the docs directory, but is not included in the "nav". This PR adds that file. Fix: add it to the nav, or list it with the excluded design pages in mkdocs.yml (as docs/proposals/ is).
  2. CI build-test fails: go test timeout (10 m) in ./proxy. It is not a flake. It is a time budget this PR spends.
    • Package time in CI: 313 s (#521), 425 s (#527), more than 600 s here. The run died while TestOversizedAgentCompactionRequestSucceeds was at 1 m 37 s.
    • This PR adds three slow tests. I measured them on box 1 with -race: TestAdaptReportGateMatchesTheBuilder 62.8 s, TestAdaptCacheForceOnTheAccountsOwnCampaignIsAudited 51.8 s, TestAdaptCacheApplyRefusesWhenAManagerActsMidBuild 51.8 s. Total 166 s more. All other adapt tests take under 2 s. They do pass.
    • Fix: make those three use a small fixture (the others finish in 1 to 2 s), or give them t.Parallel(), or set -timeout 20m in the make cover target. Shrinking is better. #527 already used 425 s of the 600 s.
  3. Defect: the adapt report reads the whole fleet and silently loses the caller's rows. adaptReport (proxy/adaptcache.go:211) calls KVCacheDataset(Filter{TenantAll: true, ...}) and drops the second return value, which is the matched row count. The dashboard keeps only the newest kvCacheMaxRows (200,000) rows of the whole fleet and says so on its own pages (TestATruncatedAnalysisSaysSo: "a silent top-N ... the failure this dashboard has already shipped once").
    • Failing case (test I wrote, not pushed): account A has 4 requests in the window. Account B has 6 newer ones. Cap set to 6. Without the cap, A gets window.requests = 4. With the cap, A gets 404 "no traffic for this account in that window". With a cap that cuts only part of A's rows, A gets a shorter window and no warning.
    • Same read is in the auto builder (runAutoBuild, refreshAutoCampaigns in proxy/campaignauto.go, from #521). So a campaign can be built on a truncated window too.
    • Proposed fix: read the caller's rows with Tenant: tn.ID (no cap problem), and take only the fleet part from a bounded read. Or compare total with len(reqs) and return truncated: true plus a warning, and refuse an apply from a truncated report.
  4. The branch cannot merge on its base. #530 was built on the old port/predictive-campaigns (commits 21fb7a2b, 9f102994). #521 was rewritten since (bf20445f, 8780aa83, 9ac6baf8, 196aade4). A merge of #530 into the current #521 tip gives add/add conflicts in proxy/campaignbuild.go, campaignbuild_test.go, predictive.go and a content conflict in clientsignal.go. A rebase stops at the first commit (control.go). That is why the GitHub diff is +11k lines: it contains #521 twice. Against current main there are 2 conflicts (cmd/context-guru-proxy/main.go, proxy/keepalive.go, from #524).
    • Needed: git rebase --onto <new #521 tip> 9f102994 feat/adapt-cache, then fix the conflicts commit by commit. Squash the wip: commits.
    • #530 also carries #528 (adapt compaction: dash/adaptcompaction.go, 1,658 lines, and proxy/adaptapply.go) through two merge commits. #528 is still open. Merge #528 first and rebase, or the code lands twice.
  5. Default behavior change on every request: ownOutputs (components/pipeline.go). A tool result is now exempt from all compaction when its command matches one of 3 patterns. The third and second patterns are wider than "our plugin": I ran the regex. python3 "${CLAUDE_PLUGIN_ROOT}/scripts/other_plugin_tool.py" matches (any plugin). cat /home/u/work/context-guru-notes/scripts/gen.py matches (any path with "context-guru" in it, such as this repo's own checkout). The result is lost savings for those outputs, not wrong output. Narrow the second and third pattern to cg.py and tv.py. Also, ownOutputs(req) runs in Pipeline.Run outside the per-component recover. Please confirm that the caller's recover covers it.

What I verified

  • Default state: the two routes GET /api/adapt/cache and POST /api/adapt/cache/apply run work only when called. Nothing starts at boot. AdaptOverride is a file next to the dashboard DB and exists only after an apply. No Python is called by the adapt path (autoRowsX and the auto build run in process).
  • Auth: both routes go through adaptPrincipal. Hosted: the dashboard cookie, or the account's own proxy token. The token is accepted only on /api/adapt/* (DashAuth), never as manager. ?tenant= works only for a manager. Single-tenant: direct loopback only, forwarding headers refused. POST bodies go through readJSON, which checks origin. Tests: no identity gives 401. Another account gets 404 for the report. Another account's basis gives 409. A non-manager's ?tenant= is ignored. An apply is rate-limited (6 in 10 min) and audited.
  • Manager guard: tests pass for "adapt never overrides a manager's campaign" and "revert undoes only the caller's own apply".
  • Fail open: report and apply are off the request path. Active campaigns follow #521's rules (the keep-alive is never turned on for an account that has it off, the ceiling is not widened).
  • Money: adapt dollars are labelled upper_bound with a warning and calibration. I found no path that adds them to a real saved counter.
  • Data: the report reads counts, tokens, timing and stop reasons. No stored content. The fleet read is the same cross-tenant metadata use as in #521.
  • Tests on box 1 (-race): go test ./proxy -run 'Adapt|SessionEnd|KVCache' pass, 182 s. ./kvcache and ./predictive pass. I did not run the full ./proxy, ./dash and ./components suites, and I did not run go vet.
  • Interplay: #519/#520/#525 are on main and not touched by the new files. The sessionEnded hooks in clientsignal.go match #521's. The #527 in-flight count does not conflict.

Questions

  1. Notice: #521 shows as MERGED, but its merge commit 216d551a is on port/lifecycle-signals, the branch of #520, which was already merged. git merge-base --is-ancestor 216d551a origin/main says no, and main has no proxy/predictive.go. The campaign code is not on main. Was a retarget missed?
  2. Any account with a token can start the fleet-wide read. adaptCacheMu.TryLock makes every other account get 429 while it runs (minutes on a big fleet). The GET has no per-account rate limit (only apply has one). Is that acceptable for hosted use? I did not test it.
  3. Same question as in #521: building one account's plan from other accounts' rows. Please state it in the release notes.

Reviewed by an AI reviewer (Claude)

@OsherElhadad
OsherElhadad changed the base branch from port/predictive-campaigns to port/predictive-campaigns-main October 14, 2026 21:10
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

@amiddavid thank you for the review. #530 is rebuilt as 46bcd677, based on the re-landed #521 (port/predictive-campaigns-main). Point by point:

  1. mkdocs. The design page moved to docs/proposals/adapt-cache.md. docs/proposals/ is already in exclude_docs, and mkdocs build --strict passes locally.
  2. CI time. The three slow tests now share one small fixture (16 sessions of 10 requests) and run the build with its evidence floors lowered to match (autoMinTst/autoMinSes are now variables). They still check the same things: the report's gate equals the builder's verdict and a per-stop-reason plan ships; apply anyway installs the chosen plan and writes the audit row; a manager acting mid-build gets 409. Under -race on our box: 62.8 s, 51.8 s and 51.8 s before, 5.4 s, 3.7 s and 4.1 s after. Whole ./proxy with -race: 714 s for the old branch on the old base, 546 s after the test fix; on the rebuilt branch, 527 s with this PR against 500 s without it (same base).
  3. Truncated read. The report now makes the same read as the auto builder: port-public's autoDataset in the re-landed feat(cache): predictive keep-alive campaigns: shadow mode, build endpoint, automatic per-tenant builder #521, which I extended with ByThread. The fleet's rows are read for the prior and the account's own rows on their own, so other accounts' newer rows can no longer push the caller's out. If the account's own window is over the cap, the report answers 422 ("choose a shorter window") instead of a silently short report. If the fleet prior was cut, a warning says so, and the builder records the same in evidence.data and caveats. Test: TestAdaptReportReadsTheCallersRowsPastTheFleetCap (4 requests among 6 newer ones from another account, cap 6, returns a full report with the warning; cap 3 returns 422).
  4. Branch. It is rebuilt on port/predictive-campaigns-main as three signed commits (dash ByThread, the builder, the adapt report and apply), with no wip: commits and no copy of feat(cache): predictive keep-alive campaigns: shadow mode, build endpoint, automatic per-tenant builder #521. feat: adapt compaction report and apply (hosted and local) #528 is in it through one signed merge commit, not a copy, because the report uses its shared helper. That part leaves the diff once feat: adapt compaction report and apply (hosted and local) #528 is on main and the base is rebased. The PR base is retargeted.
  5. ownOutputs. This is feat: adapt compaction report and apply (hosted and local) #528's code. adapt-compaction narrowed it there (63dfba90, 9496607d): it now matches only scripts/cg.py read subcommands and scripts/tv.py, and it is pinned fail-open.

Your questions:

@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: REQUEST CHANGES at 46bcd67. One blocker: the PR needs a rebase onto its base's current tip. (Posted as a comment: GitHub does not let the author account request changes.)

Blocker: the branch conflicts with its base. port/predictive-campaigns-main is now at c542fcd (#536). That commit replaced autoDataset with autoFleet plus autoRowsFor, so a refresh holds one tenant's read at a time and dedupes by scope. This branch is based on 4587c2d and still builds on autoDataset. A local merge of c542fcd into 46bcd67 conflicts in proxy/campaignauto.go and does not compile. Rebase onto c542fcd and move the report's data read (adaptReport → autoDataset([]string{tn.ID}, …)) and the builder onto autoFleet plus autoRowsFor, keeping ByThread. Re-adding autoDataset would undo #536's memory bound.

Verified at 46bcd67, which should carry over to the rebase:

  • The 3a53875 guards survived. Each of these makes a test fail:
    • fail-closed mode_by weakened → TestAdaptCacheApplyRefusesWhenAManagerActsMidBuild;
    • the mid-build re-check under campaignModeMu removed → that test and TestAdaptCacheManagerGuardHoldsAcrossTheBuildAndForOldCampaigns.
  • Basis. It is still required for adapted options, with a one-hour TTL keyed per (actor, account).
  • One gate. shipGate and gateLegs are shared by the builder (campaignauto.go:444) and the report (adaptcache.go:378).
  • Busy and quota ordering. The process-wide adaptCacheMu.TryLock answers 503 with Retry-After: 30 before Limiter.AllowAction, so a busy answer doesn't spend the hourly allowance. This is the same ordering as #528.
  • Test-only variables. autoMinTst and autoMinSes are package variables changed only in a test, which uses t.Cleanup and is not parallel. Production never writes them.
  • No real-data numbers in the PR body, docs/proposals/adapt-cache.md or code strings. Only product parameters and runtime-formatted fields remain.
  • dash/zz_adapt_live_test.go is env-gated and skips without a DB copy, so no data is committed.
  • gofmt and go vet are clean, and the -race adapt, campaign and auto subset of ./proxy passes. All commits, including merge 7162565, are signed off with no AI lines.

Non-blocking: nothing tests the busy 503 path. Disabling the TryLock is not a valid mutation (the deferred Unlock panics), and no test holds the slot. A test that holds adaptCacheMu and checks for a 503 with no quota spent would pin the ordering.

@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 0612ae3. (Posted as a comment: GitHub does not let the author account approve.)

The rebase blocker from 46bcd67 is fixed.

  • The branch contains #536's c542fcd and #528's 9496607, through a signed merge. No autoDataset remains.
  • The builder and the refresh use autoFleet plus autoRowsFor. The report uses the same autoFleet, autoOwn and rowsWith, all with ByThread.
  • One tenant's read is held at a time. The fleet rows are cached once per session_end per pass.
  • #536's behaviour is kept: the scope dedupe (r.Scope != tenant in rowsWith), the per-job window filter (r.EndMs >= j.since), and the active-only-on-ship gate with swapSpec.

The guards are still pinned. Turning the fail-closed mode_by check into an allow makes TestAdaptCacheApplyRefusesWhenAManagerActsMidBuild fail.

New since 46bcd67:

  • to_date is labelled observed. The gain is counterfactual, held_out: true, upper_bound: true. Its grid is pinned to sum to the gain against the default.
  • strategyTZFor only considers strategies whose Target.Covers(tenantID). Dropping that check makes TestAdaptHeatmapIsInTheStrategyTimezone fail, so another account's strategy cannot set this account's zone.
  • Execution stays on hour_utc and dow_utc; local hours are display-only.
  • The busy 503 is taken before the hourly limit (TryLock before AllowAction), and TestAdaptCacheBusyAnswers503WithoutSpendingTheBudget pins it.

Checks:

  • gofmt and go vet are clean. -race ./proxy -run 'Adapt|Campaign|Auto|Heatmap|Busy' passes, and dash, kvcache, predictive and tenant pass.
  • CI is green; build-test, including ./proxy, took about 9 min.
  • All commits, the merge included, are signed off with no AI attribution.
  • The PR body and docs/proposals/adapt-cache.md carry product parameters only, no real-data figures.

Nit, non-blocking: segLabel takes the UTC offset from the report window's end, so in a window that spans a DST change the hours before the change are labelled one hour off. Execution is unaffected; a "(offset as of )" note next to display_tz would make that explicit.

This approval covers 0612ae3.

@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-confirm: APPROVE at ebf5d38. The full review was at 0612ae3 (comment above): the rebase onto #536's autoFleet/autoRowsFor/autoOwn with ByThread, the save-more fields, the local-time labels and the busy-503 test. ebf5d38 only adds a display_tz_note field (and gofmt alignment) that states the daylight-saving labelling limit, which addresses that review's nit. No logic changed. CI is green (build-test 8m54s). Signed off. This approval covers ebf5d38.

@amiddavid
amiddavid force-pushed the port/predictive-campaigns-main branch from c542fcd to 41c4f63 Compare October 15, 2026 10:12
Osher-Elhadad added 7 commits October 15, 2026 13:41
…e on its own thread

KVCacheOptions.ByThread partitions the successor window by thread_id as well as by
conversation, so a sub-agent's request is not taken for the main thread's successor.
Rows written before threads existed have thread_id '' and link as before. The thread
id is read into kvcache.Request (not on the JSON wire).

Signed-off-by: Osher-Elhadad <[email protected]>
…fault and keep the account's own plan

- segment_by (dow, hour, prefix, model, client, stop_reason): one tuner scope per segment
  value, the policy one rules segment per value; the daily refresh keeps it. Runtime facts
  hour_utc and dow_utc let per-time segments run live.
- The ship gate is one function (shipGate over gateLegs) and also requires beating the
  shipped default (K2, >= 80K prefix, <= $0.50 a ping, SessionEnd).
- Every evaluated spec keeps the account's own tuned plan as own_policy, so an explicit
  apply anyway can run it instead of the fleet plan.
- SessionEnd cancels the pings after the end of the session's last response in any
  model's conversation; successors and turns are per thread.
- Build start and mode change are factored out of the manager handlers
  (startCacheBuild, setCampaignModeIf under one mode-change lock); a campaign records
  who last set its mode.

Signed-off-by: Osher-Elhadad <[email protected]>
…the account's history and enforces the chosen one

GET /api/adapt/cache replays never, the default, the current setting, blanket K1-K3 and
adapted plans (one per account, or one per segment) on the account's own history, and
leads with the relative comparison: best vs the default vs the current setting, on the
last 30% of decisions with plans tuned only on what came before, paired by session. Each
adapted option carries the builder's own gate verdict; only one that passes is
recommended. Money is in gateway dollars from the closed form in expectation over the
model parameters in adaptreplay.go, always labelled an upper bound.

POST /api/adapt/cache/apply: default switches the account's campaign off; revert undoes
only the caller's own adapt campaign; an adapted option runs the auto build and its gate
decides active or shadow, unless force (apply anyway) installs the account's own plan.
An apply needs the caller's own unexpired report basis, is rate-limited and audited, and
never overrides a campaign a manager set. Reports are bounded per account per hour.

Scope comes from the shared adapt principal (adaptapply.go). Design:
docs/proposals/adapt-cache.md.

Signed-off-by: Osher-Elhadad <[email protected]>
…in, a day-of-week x hour grid

The report now also returns to_date (what the current keep-alive saved so far, observed
from the ledger), gain (the change on offer against the default and the current setting,
held-out and paired by session, per held-out week too), a Monday..Sunday x 00..23 UTC
heatmap of that gain plus one per option, and ci95 / per_week_usd on the recommendation.
The design page states the shared prior for the release notes.

Signed-off-by: Osher-Elhadad <[email protected]>
A day x hour cell is now the span of a keep-alive window the user would write: the grid
uses the zone of the account's highest-priority strategy windows, or
tenant.DefaultStrategyTZ when it has none, and says which (heatmap.tz, heatmap_tz).

Signed-off-by: Osher-Elhadad <[email protected]>
The by_dow / by_hour options keep running on UTC days and hours, but what the user reads
is converted for display: each option's plan per segment, its label, the change line and
an apply's note read in the account's strategy timezone (display_tz).

Signed-off-by: Osher-Elhadad <[email protected]>
@amiddavid
amiddavid changed the base branch from port/predictive-campaigns-main to main October 15, 2026 10:43
@amiddavid amiddavid closed this Oct 15, 2026
@amiddavid amiddavid reopened this Oct 15, 2026
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 15, 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.

Re-review: APPROVE at eb838f4, retargeted to main after #536 and #528 merged. (Posted as a comment: GitHub does not let the author account approve.)

  • Same patches. git range-diff c542fcd4..0612ae3e c82ae31c..eb838f40 shows all 7 of this PR's own commits as =, identical patches. #528's three commits drop out because they are now on main, so there is no conflict resolution to review.
  • Current main. The branch merges cleanly with current origin/main, which adds #544, #523 and #529. On that local merge:
    • gofmt and go vet are clean.
    • go test -race ./proxy -run 'Adapt|Campaign|Auto|Busy', ./dash, ./predictive, ./kvcache and ./tenant pass.
  • Guards still pinned.
    • Weakening the fail-closed mode_by check fails TestAdaptCacheApplyRefusesWhenAManagerActsMidBuild.
    • Disabling managedCampaign fails TestAdaptCacheNeverOverridesAManagersCampaign.
    • The busy-503 test passes.
  • CI is green (build-test 9m54s). All commits are signed off with no AI attribution. The PR body and docs carry only product parameters, no real-data figures.

Note: the DST note ("offset as of " / display_tz_note) that was promised for this rebase is not on this head. That is non-blocking: labels are display-only and execution stays on UTC. Land it as a follow-up.

This approval covers eb838f4.

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