Repository navigation
feat(cache): /context-guru:adapt cache: replay keep-alive strategies on your history and enforce through the auto builder - #530
Conversation
OsherElhadad
left a comment
There was a problem hiding this comment.
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.
gofmtandgo vetare clean. go test ./predictiveand./dashpass../proxypasses except TestDashboardAddsNoRequestLatencyWithContentCapture, which failed once under host load and passes when rerun alone.- The refresh gate from before is intact.
refreshAutoCampaignskeepssegment_by(it is inrequest.json), still skips a non-ship rebuild of an ACTIVE campaign, and still swaps throughswapSpecunder the campaign lock. - The SessionEnd change matches the keeper.
toEndis measured to the end of the session's last response on any model (ConversationIDis the session), and the live SessionEndretireSessionretires every entry under the session prefix, whatever its model. Withstop = f.toEndreverted to the oldstop = 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:
- Single-tenant routes have no access check.
adaptCallerreturnsh.staticfor anyone whenregistry() == nil.mountAdaptputs 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 andPOST /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 withh.statsTrusted(r)(loopback and no forwarded headers), the rule/statsand #523's local apply use, and add a test with a non-loopback peer. - "Apply anyway" turns on the fleet plan, not the chosen one. On a non-ship build,
autoSpecsetspolicytoe.final.FleetPlan, the rule from #7.adaptAfterBuildwithforcethen 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. - 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:42also 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
left a comment
There was a problem hiding this comment.
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:
- Single-tenant access check: fixed.
adaptPrincipalusesdirectLoopback(thestatsTrustedrule, so relayed requests are refused). With it disabled, TestAdaptApplyLocalHotReloadsAndPersists fails. - "Apply anyway": not fixed. When the build's verdict is not
ship,autoSpecsets the policy topolicy(e.final.FleetPlan)(campaignauto.go,case rec != "ship").adaptAfterBuild(force=true)then activates that spec. So a forcedby_hour(orauto) 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 (whenforce, put the tenant's or segment plan in the policy and mark it forced), or say in the answer that the fleet plan runs. - 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: thenotethe 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 keyedcache:<tenant>. Three issues:- The manager
?tenant=check is still untested. With&& t.IsManager()removed, everyAdapt|CacheCampaign|Autotest passes. - The basis TTL is untested too. Removing
time.Since(b.at) > adaptBasisTTLpasses every test. - An empty
basisis 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.
- The manager
- 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 withthread_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,
swapSpecunder the lock): with that check removed, TestAutoRefreshSwapRechecksTheModeUnderTheLock fails. - Report gate vs builder verdict:
autoEvalis shared, but the gate itself is still written twice: thebuilder_gateblock in adaptcache.go, and thecandsloop in autoSpec. With the report's K3 leg changed to K2, everyAdapttest still passes, so equality is still unpinned. Factor the gate into one function both call, or add a test assertingbuilder_gate.pass == (autoSpec rec == "ship")on the same rows.
- The ship gate now includes the default, and the refresh gate still holds (active changes plan only on ship,
- Checks.
gofmtandgo vetare clean.go test ./proxypasses in full, and so do./predictiveand the dashKVCache|Adapt|Threadtests. All commits are by Osher-Elhadad and signed off, with no AI lines. Two commit titles start withwip:, so squash-merge with an explicit subject and body.
OsherElhadad
left a comment
There was a problem hiding this comment.
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 inforcePolicyremoved, 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.
shipGateis 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.
gofmtandgo vetare clean.go test ./predictiveand./proxypass in full, as do the dashKVCache|Adapt|Threadtests.
Blocking:
-
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: thefid*constants carry production counts in their comments (pings rewritten out of pings sent), andfidMissis labelled "production short-gap misses".proxy/adaptcache.go:471: thecalibration.notethat 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.
-
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:
revertswitches off whatever campaign is live for the account, including one a manager built. There is no actor or kind check like #528'sadaptRevert. 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.basisis 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 requirebasis; 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
left a comment
There was a problem hiding this comment.
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 thefid*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"andmode_by == actor). That matches the ruling's actor-and-kind intent, so not routing throughadaptRevert(which edits config_yaml) is right. With the guard disabled, TestAdaptCacheForceOnTheAccountsOwnCampaignIsAudited fails. - A forced apply writes the audit row
active: forced, gate failed. gofmtandgo vetare clean.go testpasses in full forproxy,dash,predictiveandkvcache. The new commit is signed off with no AI attribution.
Blocking:
- Check and activate are separated in time.
managedCampaignis checked once, before the build (adaptcache.go:582). The activation (setCampaignModeat:709) runs after a build that can take up toadaptApplyWait. If a manager sets a campaign in that window, the adapt campaign'sloadswitches the manager's campaign off. Re-checkmanagedCampaign(h.predRT().forTenant(tn.ID), who)immediately before activating, and return 409 with nothing changed. - An empty
mode_bycounts 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 tometa.Actor, which every build has always recorded, whenModeByis empty, and add a test with a meta that lacksmode_by.
Non-blocking:
campaignauto.go:77: thespanfield comment still says "session's next request (any model or thread): the keeper holds one body per session". Update it to say per thread.byConvandbyThrare now built with the same key and the same values, so one map would do.
OsherElhadad
left a comment
There was a problem hiding this comment.
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 packagecampaignModeMuthat 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_byfalls back tometa.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 manager re-check now runs inside
- The per-thread span comment and the merged map are fixed, and the revert comment explains why it does not use
adaptRevert. gofmtandgo vetare clean, andgo 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.
46c6a30 to
196aade
Compare
amiddavid
left a comment
There was a problem hiding this comment.
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
- CI
buildfails:mkdocs build --strict. The log saysdocs/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 inmkdocs.yml(asdocs/proposals/is). - CI
build-testfails:go testtimeout (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
TestOversizedAgentCompactionRequestSucceedswas at 1 m 37 s. - This PR adds three slow tests. I measured them on box 1 with
-race:TestAdaptReportGateMatchesTheBuilder62.8 s,TestAdaptCacheForceOnTheAccountsOwnCampaignIsAudited51.8 s,TestAdaptCacheApplyRefusesWhenAManagerActsMidBuild51.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 20min themake covertarget. Shrinking is better. #527 already used 425 s of the 600 s.
- Package time in CI: 313 s (#521), 425 s (#527), more than 600 s here. The run died while
- Defect: the adapt report reads the whole fleet and silently loses the caller's rows.
adaptReport(proxy/adaptcache.go:211) callsKVCacheDataset(Filter{TenantAll: true, ...})and drops the second return value, which is the matched row count. The dashboard keeps only the newestkvCacheMaxRows(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,refreshAutoCampaignsinproxy/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 comparetotalwithlen(reqs)and returntruncated: trueplus a warning, and refuse an apply from a truncated report.
- 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
- The branch cannot merge on its base. #530 was built on the old
port/predictive-campaigns(commits21fb7a2b,9f102994). #521 was rewritten since (bf20445f,8780aa83,9ac6baf8,196aade4). A merge of #530 into the current #521 tip gives add/add conflicts inproxy/campaignbuild.go,campaignbuild_test.go,predictive.goand a content conflict inclientsignal.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 thewip:commits. - #530 also carries #528 (adapt compaction:
dash/adaptcompaction.go, 1,658 lines, andproxy/adaptapply.go) through two merge commits. #528 is still open. Merge #528 first and rebase, or the code lands twice.
- Needed:
- 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.pymatches (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 tocg.pyandtv.py. Also,ownOutputs(req)runs inPipeline.Runoutside the per-componentrecover. Please confirm that the caller's recover covers it.
What I verified
- Default state: the two routes
GET /api/adapt/cacheandPOST /api/adapt/cache/applyrun work only when called. Nothing starts at boot.AdaptOverrideis a file next to the dashboard DB and exists only after an apply. No Python is called by the adapt path (autoRowsXand 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 throughreadJSON, 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_boundwith a warning andcalibration. 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../kvcacheand./predictivepass. I did not run the full./proxy,./dashand./componentssuites, and I did not rungo vet. - Interplay: #519/#520/#525 are on main and not touched by the new files. The
sessionEndedhooks inclientsignal.gomatch #521's. The #527 in-flight count does not conflict.
Questions
- Notice: #521 shows as MERGED, but its merge commit
216d551ais onport/lifecycle-signals, the branch of #520, which was already merged.git merge-base --is-ancestor 216d551a origin/mainsays no, and main has noproxy/predictive.go. The campaign code is not on main. Was a retarget missed? - Any account with a token can start the fleet-wide read.
adaptCacheMu.TryLockmakes 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. - 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)
cf70db0 to
46bcd67
Compare
|
@amiddavid thank you for the review. #530 is rebuilt as
Your questions:
|
46bcd67 to
f0036cd
Compare
OsherElhadad
left a comment
There was a problem hiding this comment.
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_byweakened → TestAdaptCacheApplyRefusesWhenAManagerActsMidBuild; - the mid-build re-check under
campaignModeMuremoved → that test and TestAdaptCacheManagerGuardHoldsAcrossTheBuildAndForOldCampaigns.
- fail-closed
- Basis. It is still required for adapted options, with a one-hour TTL keyed per (actor, account).
- One gate.
shipGateandgateLegsare shared by the builder (campaignauto.go:444) and the report (adaptcache.go:378). - Busy and quota ordering. The process-wide
adaptCacheMu.TryLockanswers 503 withRetry-After: 30beforeLimiter.AllowAction, so a busy answer doesn't spend the hourly allowance. This is the same ordering as #528. - Test-only variables.
autoMinTstandautoMinSesare package variables changed only in a test, which usest.Cleanupand is not parallel. Production never writes them. - No real-data numbers in the PR body,
docs/proposals/adapt-cache.mdor code strings. Only product parameters and runtime-formatted fields remain. dash/zz_adapt_live_test.gois env-gated and skips without a DB copy, so no data is committed.gofmtandgo vetare clean, and the-raceadapt, campaign and auto subset of./proxypasses. 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
left a comment
There was a problem hiding this comment.
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
autoDatasetremains. - The builder and the refresh use
autoFleetplusautoRowsFor. The report uses the sameautoFleet,autoOwnandrowsWith, all withByThread. - 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 != tenantinrowsWith), the per-job window filter (r.EndMs >= j.since), and the active-only-on-ship gate withswapSpec.
The guards are still pinned. Turning the fail-closed mode_by check into an allow makes TestAdaptCacheApplyRefusesWhenAManagerActsMidBuild fail.
New since 46bcd67:
to_dateis labelledobserved. The gain iscounterfactual,held_out: true,upper_bound: true. Its grid is pinned to sum to the gain against the default.strategyTZForonly considers strategies whoseTarget.Covers(tenantID). Dropping that check makes TestAdaptHeatmapIsInTheStrategyTimezone fail, so another account's strategy cannot set this account's zone.- Execution stays on
hour_utcanddow_utc; local hours are display-only. - The busy 503 is taken before the hourly limit (
TryLockbeforeAllowAction), and TestAdaptCacheBusyAnswers503WithoutSpendingTheBudget pins it.
Checks:
gofmtandgo vetare clean.-race ./proxy -run 'Adapt|Campaign|Auto|Heatmap|Busy'passes, anddash,kvcache,predictiveandtenantpass.- 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.
ebf5d38 to
0612ae3
Compare
OsherElhadad
left a comment
There was a problem hiding this comment.
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.
c542fcd to
41c4f63
Compare
…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]>
Signed-off-by: Osher-Elhadad <[email protected]>
0612ae3 to
eb838f4
Compare
OsherElhadad
left a comment
There was a problem hiding this comment.
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..eb838f40shows 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:
gofmtandgo vetare clean.go test -race ./proxy -run 'Adapt|Campaign|Auto|Busy',./dash,./predictive,./kvcacheand./tenantpass.
- Guards still pinned.
- Weakening the fail-closed
mode_bycheck fails TestAdaptCacheApplyRefusesWhenAManagerActsMidBuild. - Disabling
managedCampaignfails TestAdaptCacheNeverOverridesAManagersCampaign. - The busy-503 test passes.
- Weakening the fail-closed
- 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.
This is the backend of
/context-guru:adapt cache. It follows the plugin's/context-guru:adaptcontract (#526) and uses the shared adapt principal, rate limit and audit inproxy/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: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).in_sample.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).shipGatefunction on the same rows and units. It must beat the default, blanket K3 and the fleet plan.disagreementgives one line when money and the gate disagree.For
/context-guru:save-more cachethe 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 underoption_heatmaps;ci95andper_week_usdon the recommendation.POST /api/adapt/cache/apply {"option","basis","force"}:defaultswitches the caller's campaign off.revertundoes only the caller's own adapt campaign (one an adapt apply by the same actor started and last set); anything else is 409.ok: falseandforce_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.?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".Data: the report makes the same reads as the auto builder (
autoFleetfor the prior,autoOwnfor the account's own rows,rowsWithto 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:
?tenant=, or the account's own proxy token./statsrule).Changes outside the new files (reviewers: please check)
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.KVCacheOptions.ByThreadlinks each request to the next one on its ownthread_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.ThreadIDis not on the JSON wire.segment_by, kept on refresh;own_policystored in every evaluated spec;shipGate;hour_utcanddow_utc.startCacheBuildandsetCampaignModeare factored out of the manager handlers; the handlers behave the same.Evidence
proxy/adaptcache_test.gocovers:force_available, insufficient history stays off, and revert works;TestPingSpanIsPerThread);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);TestAdaptReportReadsTheCallersRowsPastTheFleetCap); reports are bounded per account per hour (TestAdaptCacheReportsAreRateLimitedPerAccount);?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;TestShipGateNeedsToBeatK3TheFleetAndTheDefault).dash:TestKVCacheDatasetByThreadLinksWithinTheThread.go test ./proxy ./dash ./kvcache ./predictive ./components/... ./cmd/...pass, andmkdocs build --strictpasses. With-race,./proxytakes 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 olderproxyanddashtests 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.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.