Repository navigation
feat(cache): predictive keep-alive campaigns (re-land of #521 onto main) - #536
Conversation
OsherElhadad
left a comment
There was a problem hiding this comment.
Review: APPROVE at 4587c2d. (Posted as a comment: GitHub does not let the author account approve.)
- Re-land fidelity.
git diff 196aade4 0161a2ba -- predictive scripts proxy/campaign*.go proxy/predictive*.gois empty.range-diffshows commits 2-4 identical, and commit 1 differs only by therecord()conflict. That conflict keeps #524'sclientSessionAliascondition, and removing it makes TestCodexSessionEndMatchesTheSessionIDHeader fail. - Nothing from main is reverted. The diff against main only adds code. The compact path's
sessionEnded(..., now-margin)sits next to main'sretireSessionStartedBefore, and both are scoped to the main thread. The per-thread in-flight code from #527 is untouched. autoDataset(e9474ff). The fleet read stays capped. Each campaign tenant's own rows are read separately and deduplicated by request id. Truncation is reported inevidence.dataandcaveats. Without the per-tenant read, TestAutoDatasetReadsTheTenantsOwnRowsPastTheFleetCap fails.- Checks.
gofmtandgo vetare clean.go testpasses for./predictive,./dashand./proxy, and-raceon the auto, refresh, signal, compact and campaign subset passes. CI is green, all 7 commits are signed off with no AI attribution, and the PR text has no figures.
Non-blocking:
- The dedupe is untested. Removing the
seencheck, so a tenant's rows already in the fleet read are counted twice (which doubles its evidence and narrows its intervals), still passes every test. The current test only covers rows outside the cap. Add a case with a cap large enough to include the tenant's rows, and assert their row count does not change. - Memory. A refresh now holds the fleet read plus each live campaign tenant's own read, up to one capped read per tenant at about 135 MB each (the figure from the
kvcache.gocomment). That is bounded by the distinct rows in the window and fine under the service's memory limit. A one-line note next toautoDatasetwould record the ceiling. - Test hooks.
dash.SetKVCacheMaxRowswrites an unsynchronised package global. It is fine while no test that calls it runs in parallel with a dataset read, so say "not for parallel tests" in its comment.DB.InsertEventsskips the recorder's queue but uses the sameinsertBatchthe writer uses, so it is acceptable as an exported fixture helper. Its name doesn't say "test", so the comment is the only guard. That is fine.
OsherElhadad
left a comment
There was a problem hiding this comment.
Re-review: APPROVE at 5900839. On top of the approved 4587c2d, this adds the dedupe test (under the default cap the fleet read already holds the tenant's rows, and the tenant read must not add them twice), a ponytail note on the per-refresh memory ceiling, and a not-for-parallel-tests note on dash.SetKVCacheMaxRows. All three non-blocking notes are addressed. CI is green; the build-test job, which runs ./proxy, took about 10 min. Signed off. This approval covers 5900839.
OsherElhadad
left a comment
There was a problem hiding this comment.
Re-review: APPROVE at c542fcd (on top of 5900839). (Posted as a comment: GitHub does not let the author account approve.)
- One tenant at a time.
autoDatasetis split intoautoFleet(one capped fleet read, whose rows are cached per session_end for the pass) andautoRowsFor(one tenant's own read, built into rows and then dropped). A refresh therefore holds the fleet read plus a single tenant's read at a time, and the bound is in the doc comment. The refresh still filters each job's rows to its own window (r.EndMs >= j.since). - Dedupe. It now works by scope: the tenant's rows from the fleet read are replaced by its own full read. With the
r.Scope != tenantfilter removed, TestAutoRowsForReadsTheTenantsOwnRowsPastTheFleetCap fails. gofmtandgo vetare clean, and the proxyAutotests pass. CI is green (build-test about 8.5 min). Signed off with no AI attribution.
This approval covers c542fcd.
…eet cap
The auto builder fitted a tenant's plan from one fleet-wide dataset read, which
keeps only the dashboard's newest-rows limit and dropped the matched count. On a
busy fleet a tenant's own history could fall out of its build without notice.
autoDataset now reads the fleet (capped, for the prior) and each campaign
tenant's own rows separately, and the spec's evidence.data and caveats say when
a read was truncated. Also reword the client-signal comment ("never on the
OpenAI route").
Signed-off-by: Osher-Elhadad <[email protected]>
… less per test under -race) Signed-off-by: Osher-Elhadad <[email protected]>
Signed-off-by: Osher-Elhadad <[email protected]>
Signed-off-by: Osher-Elhadad <[email protected]>
…ow in both reads once Signed-off-by: Osher-Elhadad <[email protected]>
c542fcd to
41c4f63
Compare
… keep-alive campaigns A manager command over the proxy's campaign routes (#536): - build [--builder auto] [--session-end]: start a build for a tenant and wait up to 80 s. - show [ID] [details]: the verdict against the best fixed rule; details lists every strategy. - mode ID off|shadow|active [--force]: shadow spends nothing; active needs a ship recommendation unless forced. The routes are manager only: Api.send now sends CG_DASH_COOKIE when set. The command uses the shared Api.send (a timeout reads "did not answer in time") and the shared --force flag. The skill pre-approves only its reads (no argument, details, show), quoted the way the skill runs them; build and mode get the permission prompt. A proxy without the routes gets a sample screen labelled as an example. Same script in the Codex plugin. Users pick their own keep-alive strategy with save-more cache; docs/plugin/cache-campaign.md says so. Signed-off-by: Osher-Elhadad <[email protected]>
… keep-alive campaigns (#522) feat(plugin): /context-guru:cache-campaign builds, shows and switches keep-alive campaigns A manager command over the proxy's campaign routes (#536): - build [--builder auto] [--session-end]: start a build for a tenant and wait up to 80 s. - show [ID] [details]: the verdict against the best fixed rule; details lists every strategy. - mode ID off|shadow|active [--force]: shadow spends nothing; active needs a ship recommendation unless forced. The routes are manager only: Api.send now sends CG_DASH_COOKIE when set. The command uses the shared Api.send (a timeout reads "did not answer in time") and the shared --force flag. The skill pre-approves only its reads (no argument, details, show), quoted the way the skill runs them; build and mode get the permission prompt. A proxy without the routes gets a sample screen labelled as an example. Same script in the Codex plugin. Users pick their own keep-alive strategy with save-more cache; docs/plugin/cache-campaign.md says so. Signed-off-by: Osher-Elhadad <[email protected]>
Why a re-land
#521 was approved and merged, but into its stale base branch
port/lifecycle-signals(the branch of #520, which had already merged), not intomain.mainhas nopredictive/package. This PR carries the same commits, rebased onto currentmain(after #520, #524 and #527), plus two fixes. cc @amiddavidChanges against #521's approved head (196aade):
proxy/keepalive.gorecord()with feat(keepalive): client lifecycle signals on by default whenever the keep-alive runs #524: feat(keepalive): client lifecycle signals on by default whenever the keep-alive runs #524'sclientSessionAliascondition is kept, with feat(cache): predictive keep-alive campaigns: shadow mode, build endpoint, automatic per-tenant builder #521's comment above it.autoDataset(proxy/campaignauto.go) now reads the fleet (capped, for the prior) and each campaign tenant's own rows separately, used by both the build and the daily refresh. The spec'sevidence.dataandcaveatssay when a read was truncated. Test:TestAutoDatasetReadsTheTenantsOwnRowsPastTheFleetCap: an account with 4 requests, older than another tenant's 6 that fill a cap of 6, still gets all 4 of its rows, and the build reports the fleet read as truncated. The test fails without the per-tenant read.dash.SetKVCacheMaxRowswas added so the test can lower the cap.-race). They now write it in one transaction (dash.DB.InsertEvents): about 11 s each.What
A manager can build a keep-alive campaign for one tenant from that tenant's own history and run it in shadow (decides on live traffic, changes nothing, keeps a running estimate) or active (sets how many pings the tenant's keep-alive sends after each response).
Two builders:
builder: "model"(default): a learned policy. A LightGBM discrete-time hazard model estimates when the conversation will come back; a fixed economic rule buys as many pings as pay for themselves. Training runs in Python at build time (scripts/campaign/); inference runs in Go (predictive/), after the response is complete.builder: "auto": no Python. Picks the tenant's best fixed plan (k pings, 270 s apart, k = 0..6), shrunk toward the fleet's plan, with a held-out ship gate. Live auto campaigns are rebuilt daily.Every build reports a held-out comparison against simple fixed rules and a recommendation:
ship,baseline(keep the current setup, the default) orinsufficient_data.Lifecycle signals from #520:
SessionEndandSessionStart compactalso resolve the campaign's open decisions for that session; a late compact event leaves decisions made after compaction open.Lifecycle signals and threads
SessionEndresolves the campaign's open decisions on every thread of the session.SessionStart compactresolves only the main thread's (thread""), matching the keeper (feat(keepalive): client lifecycle signals retire a session's cache on exit and compaction #520): a subagent's open decision stays open (TestCompactSignalLeavesASubagentThreadsDecisionOpen).keeper.record, only when the provider is not OpenAI, and Codex always uses the OpenAI route, so a Codex session never has a campaign decision. Confirmed in the code (the onlypredictiveDecidecall is inside that gate), not in a live Codex run. A comment at theSessionEndcall records why.Routes (manager only, audited)
POST /api/cache/campaigns/buildGET /api/cache/campaigns,GET /api/cache/campaigns/{id}POST /api/cache/campaigns/{id}/modeoff/shadow/active;activeneedsshipunlessforceHow to turn it on
Nothing runs until a campaign is built and switched on. Settings:
CG_CAMPAIGN_DIR(defaultcampaigns/beside the dashboard DB),CG_CAMPAIGN_PYTHON(model builder; needs numpy, pandas, lightgbm, scikit-learn),CG_CAMPAIGN_SCRIPT,CG_CAMPAIGN_AUTO_REFRESH(default24h,offdisables). Full description:predictive/README.md; pointer indocs/how-to/cache-keepalive.md.How it fails safe
shiprebuild, and checks the mode and swaps the plan under one lock.Tests
This branch:
go test -race ./predictive ./proxypass../proxytook 455 s with-raceon a shared, loaded host; CI times are in the checks.gofmt -lclean;go vet ./proxy ./predictiveclean.go test -race ./predictive ./proxypass.python scripts/campaign/test_pipeline.pypass (LightGBM build end to end on a synthetic table; the MLP path is skipped without torch).Parity: the Go tree evaluator, both feature trackers and the auto tuner against the Python reference, on synthetic fixtures.
scripts/campaign/synth_fixtures.pyregenerates every file underpredictive/testdata/(fixed seeds, deterministic content): synthetic multi-tenant traffic with tool loops, subagent threads, overlapping requests and compactions, and a reference Python auto tuner.Mutation checks: breaking the tree evaluator's missing-value direction or its float32 input rounding, a tracker feature (tool streak, request duration), the MLP output layer, or the tuner's inner split or tie rule each fails a parity test. (Known gap, as before: a value exactly on a threshold,
<=vs<, is not exercised.)Fix found by the synthetic fixture: the Go evaluator now rounds inputs to float32 before comparing with a threshold. Training and the Python reference see float32 inputs, so a float64 value just above a float32 threshold went the other way.