Skip to content

feat(cache): predictive keep-alive campaigns (re-land of #521 onto main) - #536

Merged
amiddavid merged 5 commits into
mainfrom
port/predictive-campaigns-main
Oct 15, 2026
Merged

amiddavid merged 5 commits into
mainfrom
port/predictive-campaigns-main

Conversation

@OsherElhadad

Copy link
Copy Markdown
Collaborator

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 into main. main has no predictive/ package. This PR carries the same commits, rebased onto current main (after #520, #524 and #527), plus two fixes. cc @amiddavid

Changes against #521's approved head (196aade):

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

Lifecycle signals from #520: SessionEnd and SessionStart compact also resolve the campaign's open decisions for that session; a late compact event leaves decisions made after compaction open.

Lifecycle signals and threads

  • SessionEnd resolves the campaign's open decisions on every thread of the session. SessionStart compact resolves 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).
  • Codex hooks name a session by an id the proxy does not key it by (feat(keepalive): client lifecycle signals on by default whenever the keep-alive runs #524 handles that for the keeper). That gap does not reach campaigns, and no fix is added for it: campaign decisions are made in one place, 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 only predictiveDecide call is inside that gate), not in a live Codex run. A comment at the SessionEnd call records why.

Routes (manager only, audited)

POST /api/cache/campaigns/build start a build (one at a time; 429 otherwise)
GET /api/cache/campaigns, GET /api/cache/campaigns/{id} list, view (result, recommendation, shadow score)
POST /api/cache/campaigns/{id}/mode off / shadow / active; active needs ship unless force

How to turn it on

Nothing runs until a campaign is built and switched on. Settings: CG_CAMPAIGN_DIR (default campaigns/ beside the dashboard DB), CG_CAMPAIGN_PYTHON (model builder; needs numpy, pandas, lightgbm, scikit-learn), CG_CAMPAIGN_SCRIPT, CG_CAMPAIGN_AUTO_REFRESH (default 24h, off disables). Full description: predictive/README.md; pointer in docs/how-to/cache-keepalive.md.

How it fails safe

  • Shadow changes nothing; the campaign runs after the kill switch and the audit-sink check, so a switched-off or unaudited keep-alive tracks nothing for it.
  • Active never turns the keep-alive on for a tenant that has it off, never overrides a manager strategy or a per-session override, never widens the per-ping ceiling.
  • A panic inside a campaign is recovered and means "no campaign" for that response.
  • A model file whose SHA-256 does not match its spec is refused.
  • An auto refresh keeps the previous plan when history is too thin, changes an active plan only on a ship rebuild, and checks the mode and swaps the plan under one lock.
  • The build subprocess gets a minimal environment (no upstream or gateway credentials), niced, 45 min limit.
  • Tenant purge and delete erase the tenant's campaigns.

Tests

  • This branch: go test -race ./predictive ./proxy pass. ./proxy took 455 s with -race on a shared, loaded host; CI times are in the checks.

  • gofmt -l clean; go vet ./proxy ./predictive clean.

  • go test -race ./predictive ./proxy pass.

  • python scripts/campaign/test_pipeline.py pass (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.py regenerates every file under predictive/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.

@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: 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*.go is empty. range-diff shows commits 2-4 identical, and commit 1 differs only by the record() conflict. That conflict keeps #524's clientSessionAlias condition, 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's retireSessionStartedBefore, 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 in evidence.data and caveats. Without the per-tenant read, TestAutoDatasetReadsTheTenantsOwnRowsPastTheFleetCap fails.
  • Checks. gofmt and go vet are clean. go test passes for ./predictive, ./dash and ./proxy, and -race on 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:

  1. The dedupe is untested. Removing the seen check, 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.
  2. 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.go comment). That is bounded by the distinct rows in the window and fine under the service's memory limit. A one-line note next to autoDataset would record the ceiling.
  3. Test hooks. dash.SetKVCacheMaxRows writes 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.InsertEvents skips the recorder's queue but uses the same insertBatch the 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 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 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 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 c542fcd (on top of 5900839). (Posted as a comment: GitHub does not let the author account approve.)

  • One tenant at a time. autoDataset is split into autoFleet (one capped fleet read, whose rows are cached per session_end for the pass) and autoRowsFor (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 != tenant filter removed, TestAutoRowsForReadsTheTenantsOwnRowsPastTheFleetCap fails.
  • gofmt and go vet are clean, and the proxy Auto tests pass. CI is green (build-test about 8.5 min). Signed off with no AI attribution.

This approval covers c542fcd.

Osher-Elhadad added 5 commits October 15, 2026 13:10
…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]>
@amiddavid
amiddavid force-pushed the port/predictive-campaigns-main branch from c542fcd to 41c4f63 Compare October 15, 2026 10:12
@amiddavid
amiddavid merged commit 3aed93f into main Oct 15, 2026
4 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 15, 2026
OsherElhadad pushed a commit that referenced this pull request Oct 15, 2026
… 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]>
amiddavid pushed a commit that referenced this pull request Oct 15, 2026
… 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]>
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