Skip to content

feat: predictor-driven keep-alive strategies - #114

Merged
OsherElhadad merged 23 commits into
rossoctl:mainfrom
OsherElhadad:feat/keepalive-strategies
Aug 26, 2026
Merged

OsherElhadad merged 23 commits into
rossoctl:mainfrom
OsherElhadad:feat/keepalive-strategies

Conversation

@OsherElhadad

Copy link
Copy Markdown
Collaborator

Summary

Builds a full predictor pipeline for the keep-alive/TTL ping mechanism, end to end:

  • A feature catalog over the live deployment's own traffic (66,779 requests, 17 tenants):
    stop_reason splits into three behavioural clusters, not two -- only "actually done"
    (end_turn/max_tokens/refusal) clears the ping break-even with real margin. Per-tenant
    band rate ranges 0.76%-41.4%, and the requested-vs-honoured 1h TTL gap (17.7% requested, 0%
    billed at the 1h tier on aws/claude-sonnet-5) is measured directly.
  • Rule-based and learned predictor arms, scored with rolling-origin time splits and a
    conversation-level bootstrap. Headline: a one-line stop_reason gate buys +1.54% vs
    fixed-5m (95% CI [+0.60%, +2.79%]) and is statistically indistinguishable from a trained
    logistic regression on the same window -- the free rule ships, not the model.
  • kvcache.StopReasonGated: registered in the arm registry, in the KV-cache page's default
    comparison set, and wired as an opt-in live production hook
    (CachePolicy.PredictorID/PredictorThreshold, proxy/keepalive.go's pingable()).
    Nothing changes for any account until a manager names it on a strategy.
  • kvcache.StickySession1h: a whole-session (not per-turn) 1h-vs-5m commitment arm, plus a
    real claude-haiku-4-5 measurement (14.6% cheaper on one real 3-turn trajectory --
    aws/claude-sonnet-5, which carries this deployment's actual spend, never honours a
    requested 1h TTL, confirmed on all 11,822 live requests that asked for one).
  • A feature-importance panel on the KV-cache dashboard page, served as static data from the
    offline model fit.
  • A Strategies-tab predictor-gate dropdown (manager-only), and a fix for the Strategies-tab
    vs Overview savings-figure discrepancy a manager reported (two real, unlabeled gaps --
    cross-strategy double counting and an all-time-only ledger -- not an arithmetic bug).

Everything shipped is one query away on the dashboard itself: KV-cache tab -> arm comparison

  • feature-importance panel; Strategies tab -> predictor gate. Full methodology, per-fold
    tables, and an honest "what's not solved yet" section are in
    docs/results/kv-ttl-predictor-summary.md, with five linked docs for anyone who wants the
    complete derivation.

Test plan

  • go build ./... && go vet ./... && go test ./... clean.
  • New tests: kvcache/kvcache_test.go (ClusterOf), kvcache/registry_test.go
    (StopReasonGated gating + registry invariants), kvcache/sticky_test.go
    (StickySession1h), proxy/keepaliveoverride_test.go /
    proxy/keepalivestrategy_test.go (the predictor-gate hook, the predictor-id/threshold
    validators, the applyStrategy field carry-through).
  • TestOptimalIsALowerBoundOnEveryOtherArm and TestStrategiesCannotSeeTheFuture still pass
    with the two new arms in the registry.
  • Manual check: KV-cache tab shows stop-reason-gated in the default arm comparison and the
    feature-importance panel below it; Strategies tab's create/edit form shows the predictor
    dropdown + threshold field, disabled until a predictor is selected.

Osher-Elhadad added 20 commits August 25, 2026 09:56
Scheduled, cross-account keep-alive policies (time windows, targets,
per-strategy cost-vs-savings) layered above the existing per-account
config and per-session override mechanisms.

Signed-off-by: Osher-Elhadad <[email protected]>
The idle keep-alive ping mechanism was reachable only two ways: a manager
flipping one account-wide boolean, or arming a single session for up to 12h.
There was no way to run a schedule ("only during Israel business hours"), no
way to apply one policy across every account at once, and no way to see cost
vs. savings broken out per policy per account.

This adds a manager-authored, durable Strategy: Idle/MaxPings/MinPrefixTokens/
MaxUSDPerPing plus one or more time-of-day Windows (day-of-week, HH:MM, IANA
timezone) and a Target (every account, or a named list). It slots into the
keep-alive's existing resolution chain between account config and the
per-session override: account CachePolicy -> highest-priority matching ACTIVE
strategy -> session override (unchanged, still wins on top, still cannot widen
MaxUSDPerPing). Precedence among matching strategies is fixed, not
configurable: a list-target strategy beats an all-target one, and ties go to
the most recently updated.

Persistence lives in the tenant registry (new keepalive_strategies table),
because a strategy is a standing rule a manager expects to survive a deploy,
unlike a per-session override which is deliberately memory-only. It is loaded
into the keeper's memory at boot and reloaded on every write through the new
control routes, so a strategy created through the API matches on the very
next request with no restart.

New control routes (all manager-only, audited): GET/POST
/api/keepalive/strategies, PATCH/DELETE /api/keepalive/strategies/{id}.
Validation reuses the existing per-session override's numeric bounds for
Idle/MaxPings/MinPrefixTokens, plus its own checks for windows, timezone and
target shape.

A ping fired under a matching strategy is tagged with the strategy's id on its
own dash.Event (a new nullable, never-backfilled keepalive_strategy_id column
on `requests`), which a new dashboard route
(GET /api/keepalive/strategies/{id}/ledger) reads to show pings, ping cost and
each tenant's own keep-alive credit, grouped by tenant.

The dashboard gains a manager-only "Strategies" tab (create/edit form, a
table with active/pause/edit/delete and a per-tenant ledger), and every user's
Overview tab gets a small keep-alive savings callout reusing the existing
account ledger response.

One stdlib-only addition beyond the letter of the design: a blank import of
time/tzdata, so IANA zone data is compiled into the binary rather than
depending on the deployed image's OS packages (the shipped Dockerfile does
not install tzdata), which would otherwise make every window silently fail to
resolve its timezone.

Signed-off-by: Osher-Elhadad <[email protected]>
…lers

The four new keep-alive strategy control routes relied only on the route
table's ctlManager gate. Every other handler in this file's neighbourhood
(ctlKeepAliveArm) re-checks the role inside the handler itself as
defense in depth, and the list handler did not call webPrincipal at all.
Add the same check to list/create/patch/delete.

Also revert a strategy's PATCH when its audit write fails, the same way
create already deletes what it cannot account for, so a strategy update
never stands without an audit row.

Signed-off-by: Osher-Elhadad <[email protected]>
docs/superpowers/ holds working design docs for the skill that authored
them, not published site content. mkdocs build --strict was failing
because the new keep-alive strategies spec had no nav entry.

Signed-off-by: Osher-Elhadad <[email protected]>
Define KeepAlive5mOnce/KeepAlive1hOnce (KeepAlive.Once + PingCap()),
completing the WIP the tree already carried in registry.go/simulate.go/
strategy.go/dash/kvcachesim.go. Each holds its tier and refreshes with
exactly one keep-alive per idle span via the PingCapper seam, then lets
the entry lapse, instead of pinging for as long as the window's MaxPings
allows.

Signed-off-by: Osher-Elhadad <[email protected]>
Add tenant.Strategy.PredictorID/PredictorThreshold (v9 migration,
additive, default ''/0 so every existing strategy behaves identically)
so a strategy can later gate its pings on a registered kvcache.Predictor
in addition to its time windows. Threaded through the create/patch ctl
handlers and the strategy view, validated (threshold in [0,1], and the
id must be in proxy's knownPredictorIDs — empty for now on purpose,
since the runtime gating hook does not exist yet: this is groundwork,
not a behavior change).

docs: feature catalog for the TTL predictor work (stop_reason's 3-way
split, extreme per-tenant heterogeneity, UTC hour structure, and the
17.7%-requested/0%-honoured 1h TTL finding), and the Strategies-tab vs
Overview savings reconciliation (two real UX gaps — cross-strategy
double counting and an unlabeled all-time ledger — not an arithmetic
bug). Two matching one-line UI notes added to dash/ui/app.js.

Signed-off-by: Osher-Elhadad <[email protected]>
TestValidatePredictor (tenant) and TestValidPredictorRef (proxy) for
the threshold-bounds and known-predictor-id checks added in 97cff48.

Signed-off-by: Osher-Elhadad <[email protected]>
immutable=1 skips SQLite's own change-detection and threw intermittent
"database disk image is malformed" errors against the live, actively-
checkpointing WAL database (found while reproducing the savings
reconciliation). mode=ro alone is safe and was already sufficient.

Signed-off-by: Osher-Elhadad <[email protected]>
Extends kv-cache-ttl.md and kv-ttl-predictor-features.md. Builds four
arms (stop-reason-gated, stop-reason-x-hour, historical-probability
ported and per-tenant tuned, a logistic regression) and scores each
against fixed-5m on rolling-origin time splits with a conversation-
level bootstrap CI, on the live deployment's own 66,779-request/
17-tenant capture.

Headline: a one-line stop_reason gate buys +1.54% pooled (CI95 [0.60%,
2.79%], does not cross zero) with no training step, and is not
statistically distinguishable from the fancier arms (logreg +1.69%,
CI95 [0.79%, 2.94%], CIs overlap almost entirely). The per-tenant-tuned
historical-probability port is indistinguishable from doing nothing
(-0.03%, CI straddles zero) because its Stats cells are keyed on
tenant/model/hour, not on stop_reason cluster -- the same blind spot
kv-cache-ttl.md's original two ML arms had. Per-tenant breakdown shows
the pooled gain is carried almost entirely by three tenants (t01/t06/
t12), while two others (t04/t11) lose a little under the naive global
gate -- directly matching the heterogeneity already found in
kv-ttl-predictor-features.md.

The stop_reason gate is framed explicitly as extending, not
correcting, the deliberate decision already recorded in proxy/
keepalive.go's pingable() and commit 50e3966 -- that decision correctly
keeps pinging on end_turn; this adds the other half, excluding the low-
value clusters that decision never addressed.

Signed-off-by: Osher-Elhadad <[email protected]>
StickySession1h decides once, at a conversation's first request, whether
to commit that whole session to the 1-hour or the 5-minute tier, and
never revisits the choice. Every other decision-making arm (bar the
fixed tiers) is free to re-decide per turn, which is not a realistic
model of a deployment that cannot renegotiate an already-created cache
entry: once a tier is committed, every later request in that
conversation can only ever be served against it. The decision reuses the
write-versus-recreate break-even cacheinject's own TTL doc and
dash/kvcachesim.go's Raise5mTo1h/SavedPerMiss already derive
((Write1h-Write5m)/(Write5m-CacheRead)) against the account's own
P(return within 1h), falling back to 5m through Stats's usual ladder.

Registered as sticky-session-1h in the kvcache registry and dash's
mirror constants, and covered by the same "never beats optimal" and
"never sees the future" invariants every arm is held to, plus dedicated
tests for the sticky-per-conversation, per-conversation-independence,
fallback and break-even properties.

Its simulated performance against production traffic is not reported:
scoring it needs the aggregate-only DB access pattern another
workstream is using, and improvising a second path to that data was
avoided. In its place, a real session was run through a local
single-tenant proxy against claude-haiku-4-5 with cacheinject
requesting ttl:1h: unlike aws/claude-sonnet-5 (cache_write_1h is 0 on
100% of live 1h requests), the hourly tier was genuinely granted, and a
392-second gap that a 5-minute TTL cannot survive still hit the cache.
The real, measured 3-turn trajectory cost $0.019594; the same real
tokens under a 5-minute TTL would have cost $0.022951 by hand
computation -- 14.6% more, on this one small real trajectory.

Documented in docs/how-to/kv-cache-ttl.md.

Signed-off-by: Osher-Elhadad <[email protected]>
Pulls together the feature catalog, the current-mechanism baseline
(net +\$6.48 but 8 of 12 touched tenants are net-negative -- the
"helps some, not others" finding quantified), the rule-based/learned
arm scoring (stop-reason-gated wins on Occam's razor: statistically
indistinguishable from the logistic regression, needs no training),
the diagnosed historical-probability blind spot (Stats cells keyed on
tenant/model/hour, not stop_reason cluster), and the sticky 1h/5m
arm's real haiku-4-5 measurement (14.6% cheaper on one real
trajectory, sonnet-5 numbers remain simulated-only).

Recommendation: ship the stop_reason gate as the pooled default;
combine it with a per-tenant historical-probability threshold as the
next iteration, before the naive global gate goes out unconditionally.

Signed-off-by: Osher-Elhadad <[email protected]>
Threads stop_reason through: Request.StopReason (new field, plus
StopReasonCluster/ClusterOf's three-way split -- still_working,
looks_done_isnt, actually_done -- matching what
docs/results/kv-ttl-predictor-features.md and kv-ttl-predictor-arms.md
measured), Observation.StopReason (present-tense, the request just
served's own reason, no future leakage), dash's row projection/scan
(the column already existed on the requests table and in the CTE, but
was never read into kvcache.Request), and the wire-contract lock.

Registers StopReasonGated: write the five-minute tier on every
request, ping while idle only when the cluster is actually_done.
Extends, rather than revisits, proxy/keepalive.go's pingable() and its
own recorded decision (commit 50e3966) to keep pinging on end_turn --
this adds the other half, excluding the two low-value clusters that
decision never addressed. Measured +1.54% vs fixed-5m pooled (CI95
[0.60%, 2.79%]), statistically indistinguishable from a trained
logistic regression on the same window -- the free rule, not a model,
is what earns the spot in dash's default arm set.

Covered by the same "never beats optimal" / "never sees the future"
invariants every arm here is held to, plus dedicated tests for the
cluster split and the gate's own per-reason and full-replay behavior.

Signed-off-by: Osher-Elhadad <[email protected]>
Adds KVCacheFeatureImportance to /api/kvcache/simulate's payload: each
model's own top-5 (logistic regression, gradient-boosted trees) from
docs/results/kv-ttl-predictor-arms.md's offline fit. Two separate
ranked lists, not one table with a column per model -- the two models
only agree on ranks 1-2 and diverge from rank 3, so a shared-row shape
would have had to fabricate a score for a feature one model never
ranked at all.

Deliberately STATIC data, unlike every other figure this page
computes: a feature importance comes from a model fit offline, not
from replaying a window's rows through a formula, and the
production-safe arm it justifies (StopReasonGated) is a rule for
exactly that reason. Re-running the offline study is how this table
gets refreshed.

Signed-off-by: Osher-Elhadad <[email protected]>
Two side-by-side tables (logistic regression, gradient-boosted trees),
reusing the existing grid-2 layout rather than adding new CSS. Wired
into the same load path as the strategy comparison (kvLoadSim), right
below it, since the panel exists to explain the arm the comparison
just showed. States plainly that this is static offline-fit data, not
something recomputed from the window on screen.

Signed-off-by: Osher-Elhadad <[email protected]>
CachePolicy gains PredictorID/PredictorThreshold, carried through
applyStrategy from the matched tenant.Strategy (the data model for
this landed earlier, deliberately ahead of this hook). kaEntry now
carries the request that established it own stop_reason
(Usage.StopReason, already computed, just never stored). pingable()
adds one more condition when a strategy names a predictor: the named
predictor's probability at that stop_reason must clear the strategy's
tuned threshold, on top of every existing check. No PredictorID (every
account today, every pre-existing strategy) means this whole block is
skipped and behaviour is byte-for-byte unchanged -- opt-in per
strategy, not a fleet-wide default.

predictorFor is the whole production-safe predictor class: a switch
over ids, each a plain function over stop_reason -- no embedded model,
no call out of the hot path. Only "stop-reason-gated" exists today
(kvcache.ClusterOf, the arm measured in
docs/results/kv-ttl-predictor-arms.md at +1.54% vs fixed-5m, CI95
[0.60%, 2.79%]). An unregistered predictor id refuses to ping rather
than letting the entry through unconditionally -- fail toward not
spending, since money rather than the request path is what a drifted
reference could waste. knownPredictorIDs and predictorFor are pinned
against each other by TestKnownPredictorIDsMatchPredictorFor so a
strategy can never be validated against a gate pingable() cannot
actually evaluate.

Strategies-tab form gains a predictor dropdown + threshold field
(disabled while no predictor is selected), pre-filled on edit, and the
list table shows which strategies carry a gate. STRATEGY_PREDICTORS
mirrors knownPredictorIDs; the server remains the actual source of
truth and refuses anything not registered there.

Signed-off-by: Osher-Elhadad <[email protected]>
Explains the distinction from the existing "deliberately not gated on
stop_reason" decision (that one keeps end_turn in; this one excludes
the two clusters it never addressed), the measured effect, and that
it's opt-in per strategy rather than a fleet-wide default -- carrying
forward the per-tenant heterogeneity caveat from the arms study.

Signed-off-by: Osher-Elhadad <[email protected]>
Pulls the headline recommendation, every feature, every arm (pooled
and per-tenant, properly caveated), and what's now live on the
dashboard into docs/results/kv-ttl-predictor-summary.md -- a single
entry point over kv-ttl-predictor-features.md, kv-ttl-predictor-arms.md,
kv-cache-ttl.md, kv-ttl-predictor-comparison.md and
kv-ttl-savings-reconciliation.md, none of which are duplicated, only
cited and pulled forward.

Assessed building the stop_reason-AND-per-tenant-history combined arm
the arms doc flags as the next iteration, and did not build it: it
requires changing kvcache.History's cell keying (Observe's signature,
every fallback level, everything that reads Stats), which ripples
across HistoricalProbability, StickySession1h and Custom and would
need a fresh live-data scoring pass to back any claimed result -- a
structural change to a shared accumulator, not a new arm wired onto
existing pieces. Flagged as the recommended next step instead, with
the concrete shape it should take.

Signed-off-by: Osher-Elhadad <[email protected]>
The reconciliation UI fix (additive-savings note, all-time ledger
label) was already applied earlier in the same session, before this
summary doc was drafted -- correcting the "not applied" claim.

Signed-off-by: Osher-Elhadad <[email protected]>
Osher-Elhadad added 3 commits August 26, 2026 17:21
Resolves overlap with rossoctl#107 (manager-controlled keep-alive strategies,
already on main) and rossoctl#108 (dash/api.go, dash/schema.go caching/index
fixes). The predictor pipeline in this branch was built as a superset
of rossoctl#107's base feature, so every conflict resolves by keeping this
branch's version (already contains rossoctl#107's content plus the predictor
gate on top); rossoctl#108's caching and index additions land untouched
alongside it.

Signed-off-by: Osher-Elhadad <[email protected]>
StickySession1h commits once per conversation and never revisits, keyed
on the first request it sees for a given (user, conversation, model) in
whatever Simulate call it is handed -- there is no way for it to tell
"the first row of this call" apart from the conversation's true first
turn, since Simulate itself makes no completeness promise about the
slice it is given.

A caller that replays one real conversation's requests across several
disjoint Simulate calls -- a per-account, per-hour-of-day sweep, for
one -- will see the arm silently re-decide in every call it appears in,
each time believing it is at turn one. That is a real, not
hypothetical, scenario: a conversation whose idle gaps run close to an
hour crosses a UTC hour-of-day boundary routinely.

Add StrategySpec.PartialReplayUnsafe so any such caller can exclude the
arm from an unattended, per-slice sweep the same way it already excludes
optimal/replay/custom, without a second, driftable list of arm names.

Signed-off-by: Osher-Elhadad <[email protected]>
gofmt -w on kvcache/sticky_test.go and proxy/keepalivestrategy_test.go
(a trailing blank line and a struct-literal alignment `make lint`
flagged).

mkdocs build --strict was failing on two independent things:
- five docs/results/*.md files added by this branch were never added
  to mkdocs.yml's nav.
- seven links inside those files pointed at kv-cache-ttl.md and
  cache-keepalive.md as bare filenames, which mkdocs resolves relative
  to the LINKING file's own directory (docs/results/) -- but both
  targets live in docs/how-to/. Fixed every one to ../how-to/....

Verified locally: gofmt -l . is empty, and mkdocs build --strict
(installed into a throwaway venv per requirements-docs.txt, matching
this repo's own convention) builds clean.

Signed-off-by: Osher-Elhadad <[email protected]>
@OsherElhadad
OsherElhadad merged commit 2c4d54b into rossoctl:main Aug 26, 2026
5 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Aug 26, 2026
OsherElhadad pushed a commit that referenced this pull request Aug 31, 2026
…he fix

Reported as "every strategy shows $0 Saved, including last week's" — and
that part was real: a real row credited before dashcapture.go learned to
tag it (2026-08-30) has a permanently NULL keepalive_strategy_id, and
StrategyLedger's SavedUSD filters on that column, so historical activity
under a strategy read $0 forever, not just until the next ping.

The information was not actually lost: the ping(s) that rescued each such
row were already tagged (that half of the feature is older, PR #114), and
the real row's own keepalive_pings > 0 says a ping preceded it. For each
untagged real row, the ping(s) that immediately preceded it in the SAME
session — after that session's own previous real row, so this never
reaches into an earlier, already-consumed idle span — carry exactly the
strategy id the code would have recorded on the real row directly, had it
existed at the time. On a copy of the production database, 109 of 130
such rows recover a tag this way; the other 21 have no matching tagged
ping at all, meaning the rescue came from plain account config or a
session override with no strategy involved — correctly left NULL rather
than guessed at.

One-time, additive-only backfill (nothing already tagged is touched, and
nothing is ever deleted), following the exact shape dedupetext.go already
established: a predicate over the data, resumable and idempotent, marked
done in the existing meta table once nothing is left to recover.

Sequenced onto dedupeLoop's existing goroutine rather than given its own:
running the two migrations as separate concurrent goroutines measurably
doubled SQLite write-lock contention on every startup, enough that
TestRecorderMigratesLegacyPromptTextOnStart missed its own busy_timeout
under -race on a database with no real content at all. One shared
goroutine, one writer at a time, fixes that with no real cost — neither
migration takes more than a fraction of a second on any deployment
measured so far.

Signed-off-by: Osher-Elhadad <[email protected]>
OsherElhadad added a commit that referenced this pull request Aug 31, 2026
* fix(dash): bound the connection pool and move gzip out of the write lock

The pool had no cap at all, and a burst of concurrent dashboard/metrics
reads climbed past 600 connections and OOM-killed the process within
minutes. Bounded it at 20/10 first; that turned out too low for this
deployment's real concurrent demand (queued for a pool slot long enough
to blow the dashboard handlers' own 10s timeout, on a box with zero
SQLITE_BUSY errors logged — i.e. never even reaching SQLite to contend
on a lock). Raised to 100/50, costing at most ~285MB more against an 8GB
cgroup cap.

Also moved every gzip compression insertBatch needs out of the open
transaction and into a precomputed pass before Begin(): compression is
real CPU work, and this driver blocks a concurrent reader for the
writer's whole open transaction, so doing it inside the transaction was
making every dashboard reader on the box wait on CPU work the write lock
never needed to cover.

Signed-off-by: Osher-Elhadad <[email protected]>

* fix(dash): stop the dedupe migration's full-table rescan on every restart

The one-time prompt-text backfill re-proved "nothing is pending" on every
single process start by scanning the whole tool_declarations table (now
1.65M+ rows and growing) from rowid 0 — a cost that was measured at ~3s
when this file was written, at 488k rows. It has grown to ~18-20s of real
CPU/lock contention per restart, which was the dominant cause behind
/metrics timing out for the first tens of seconds after every deploy.

Added a one-row marker in the existing `meta` table (already used for
schema_version) that records the scan has reached the end of the table
with nothing left pending. Once set, every later restart skips the scan
entirely instead of re-proving an answer that cannot change: the current
write path never produces a text_gz-carrying row, so once the historical
backlog is gone, it stays gone.

Also fixes a data race caught by -race: TestWaterfallTotalMatchesThe-
HeadlineAfterAllPricedAdditions built a Recorder via NewRecorder (which
starts dedupeLoop against whatever DB it opens) and then swapped rec.db
to a different, pre-seeded DB out from under the still-running goroutine.
The test now builds the Recorder directly around the seeded DB instead,
starting no background goroutines it doesn't need.

Signed-off-by: Osher-Elhadad <[email protected]>

* perf(dash): run Overview's independent queries concurrently

Overview() ran ~12 independent SQL queries one after another — the
replay-ceiling estimate, its ping-side correction, CompactionResets,
four countBy breakdowns, two percentile lookups, the breakpoint mode,
and the keep-alive ping-cost query. None of them reads another's
result (the two exceptions are noted inline and stay sequential within
their own goroutine). Measured summing to ~9-10s on a production-sized
copy of the table with zero write contention — which is why /api/stats
was timing out its 10s caller-facing deadline on every single call, not
just under load.

Run concurrently via a small errgroup.Group against the same pooled
*sql.DB (store.go's SetMaxOpenConns already sizes the pool for this),
wall time drops to roughly the slowest single query instead of their
sum: measured ~10.0-10.2s -> ~5.0-5.2s on the same corpus, verified with
go test -race showing no new races and every existing Overview test,
including the waterfall-vs-headline reconciliation test, still passing
with byte-identical output.

Signed-off-by: Osher-Elhadad <[email protected]>

* perf(dash): run stats()'s four independent DB calls concurrently

Overview(), CachesplitHistoricalUSD, TierCosts, and DeclCreditFor are
independent of each other — none reads another's result, only this
handler's own fields afterward do — but ran sequentially. Combined with
Overview's own ~5-10s and DeclCreditFor's ~4-16s (see the SelfRemovals
fix in the same round), the sum reliably exceeded this handler's 10s
caller-facing timeout. Run via errgroup.Group instead: Overview's error
is reported on its own so a pricing failure in one of the other three
cannot mask it and vice versa, matching each call's existing best-effort
contract. Measured: the four calls together dropped from ~10.4s
sequential to ~7.1-7.3s concurrent on the same production-sized copy.

Signed-off-by: Osher-Elhadad <[email protected]>

* fix(dash): stop SelfRemovals pooling declaration history across tenants

SelfRemovals grouped tool_declarations candidates by (kind, name,
server) with no tenant_id under TenantAll (the manager's service-wide
view — also the default for any single-tenant deployment, which is why
no fixture ever caught it), and two subordinate queries had the same
flaw keyed on bare session_id instead of (tenant_id, session_id).

On the live corpus this pooled every tenant's declaration timeline into
one: an MCP tool declared in exactly one session of one tenant was
reported "self-removed" on the strength of 555 sessions belonging to
OTHER tenants that never had that server at all — $154.53 of a $537.32
total SelfUSD was fabricated this way. Every candidate, cohort flag, and
"sessions after" comparison now keys on tenant throughout; the honest
total on the same corpus is $33.51.

Locked in with a new regression test, TestSelfRemovalDoesNotPoolAcross-
Tenants (two tenants sharing colliding session-id strings, mirroring
TestInventoryKeysAreTenantScoped's write-side technique) — confirmed to
fail on the pre-fix code and pass after.

Also fixes the query's real performance cost, the same shape the
CompactionResets bug had (see dash/CLAUDE.local.md): two separate joins
each drove a nested loop from the small side (a few thousand sessions)
and did a non-covering index probe into the 1.65M+ row tool_declarations
table per session — EXPLAIN QUERY PLAN confirmed a per-row CO-ROUTINE
probe, not a scan. Replaced both joins with one sequential scan of
tool_declarations plus a Go-side map join against the already-cheap
requests aggregate. Measured on a production-sized copy: SelfRemovals
65.2s cold / 19.1s warm -> a stable ~5.9-6.0s regardless of cache state;
DeclCreditFor 19.1s -> ~6.0s. Token-level output (AvoidedReads,
SessionsAfter) verified identical before and after the rewrite.

Signed-off-by: Osher-Elhadad <[email protected]>

* fix(proxy): collapse concurrent /metrics renders into one

metricsHandler rendered outside any lock on a cache miss, on the stated
assumption that a race between concurrent misses costs "at most one
redundant render." That held only while a render finished faster than
requests arrived. Once real write contention pushed a render's own time
past that interval, every request arriving during a slow render saw the
same stale cache and started ANOTHER render — more concurrent renders
competing for the same bounded connection pool made each one slower
still, a spiral that measured live as /metrics reliably timing out.

Collapse every concurrent cache-miss into the one render already in
flight via singleflight.Group, scoped per-Handler (not a package-level
var) to avoid cross-test/cross-instance leakage. However long a render
takes, it now happens once, and every waiter shares its result.

Signed-off-by: Osher-Elhadad <[email protected]>

* perf(proxy): run the tenant-metrics adapter's four queries concurrently

tenantMetricsAdapter.TenantMetrics made four independent, grouped-by-
tenant DB calls one after another for every /metrics scrape. Measured
individually against a production-sized copy: TenantMetrics ~0.5-0.75s,
CachesplitHistoricalUSDByTenant ~2s, KeepAliveNetUSDByTenant ~0.4s,
DeclFilterSavingsByTenant ~0.16s — not the dominant cause of tonight's
outage (that was the dedupe migration's rescan and Overview's/
SelfRemovals' own query costs), but a real, easy, additional safety
margin under real contention.

Run via a plain sync.WaitGroup rather than errgroup: three of the four
calls have an existing best-effort contract (a failed query zeroes that
one metric for every tenant rather than failing the whole scrape), and
errgroup.Wait's first-error-wins behavior would have turned one optional
query's failure into the whole scrape's. Each goroutine writes only its
own disjoint variable and nothing is read until after Wait, so this is
race-free by construction — confirmed with go test -race.

Signed-off-by: Osher-Elhadad <[email protected]>

* fix(grafana): promote the total-savings panel and collapse ops rows

Verified the dashboard's own Overview.TotalSavedUSD and the "Total
avoided this month" panel's PromQL against a copy of the production DB
with the real price file: they now reconcile exactly (both read
62.718268 on the same month-to-date window) now that dash/api.go folds
CachesplitHistoricalUSD into the headline total. The per-tenant
keepalive-net and decl-filter series the panel's formula needs were
already being emitted; the gap was in the dashboard's own total, not
missing metrics.

Reorganized the dashboard itself: promoted "Am I saving tokens and
money?" to the top row and the per-component bargauge row to third
(right after basic health), and collapsed the two host/ops rows ("Is
storage and cold storage healthy?", "Is anything failing?") into native
Grafana collapsed rows. All 41 panels and their ids are unchanged —
nothing was deleted, panels were only reordered and nested.

Signed-off-by: Osher-Elhadad <[email protected]>

* fix(dash): explain a strategy's $0 Saved instead of leaving it unexplained

The Strategies tab's per-strategy Stats drawer shows real Pings and
Ping cost the moment a strategy fires, but Saved only turns nonzero once
a REAL request the strategy protected actually resumes after its idle
gap — pinging and crediting are two different moments, and every ping a
strategy has sent so far can predate the per-strategy attribution itself
(2026-08-30) or simply not have been followed by a resumption yet. Both
looked identical to a stuck $0 with no explanation. Added a note, shown
only when pings > 0 and saved_usd == 0, that says plainly why the number
is $0 right now and that it is not a broken calculation.

Also collapsed the Keep-alive tab's four behavioral-breakdown histograms
(idle-gap timing, cached-prompt size, time-of-day, per-account spread)
into a details block, reusing the existing setup-others pattern: the two
daily trend charts above them answer "is this trending", the four below
answer "why" and do not need the same visual weight. Element ids are
unchanged, so app.js's existing render calls are unaffected.

Signed-off-by: Osher-Elhadad <[email protected]>

* test(proxy): cover arrive() reporting the strategy that sent the ping

TestArriveCancelsAndReports only covered the no-strategy case. Added
TestArriveReportsTheStrategyThatSentThePing, which configures a matching
strategy, lets a ping fire against it, and asserts arrive() reports that
strategy's id back to the real request it rescues — the exact property
dash/keepalivestrategy.go's per-strategy ledger depends on.

Signed-off-by: Osher-Elhadad <[email protected]>

* fix(dash): recover keepalive_strategy_id on real rows tagged before the fix

Reported as "every strategy shows $0 Saved, including last week's" — and
that part was real: a real row credited before dashcapture.go learned to
tag it (2026-08-30) has a permanently NULL keepalive_strategy_id, and
StrategyLedger's SavedUSD filters on that column, so historical activity
under a strategy read $0 forever, not just until the next ping.

The information was not actually lost: the ping(s) that rescued each such
row were already tagged (that half of the feature is older, PR #114), and
the real row's own keepalive_pings > 0 says a ping preceded it. For each
untagged real row, the ping(s) that immediately preceded it in the SAME
session — after that session's own previous real row, so this never
reaches into an earlier, already-consumed idle span — carry exactly the
strategy id the code would have recorded on the real row directly, had it
existed at the time. On a copy of the production database, 109 of 130
such rows recover a tag this way; the other 21 have no matching tagged
ping at all, meaning the rescue came from plain account config or a
session override with no strategy involved — correctly left NULL rather
than guessed at.

One-time, additive-only backfill (nothing already tagged is touched, and
nothing is ever deleted), following the exact shape dedupetext.go already
established: a predicate over the data, resumable and idempotent, marked
done in the existing meta table once nothing is left to recover.

Sequenced onto dedupeLoop's existing goroutine rather than given its own:
running the two migrations as separate concurrent goroutines measurably
doubled SQLite write-lock contention on every startup, enough that
TestRecorderMigratesLegacyPromptTextOnStart missed its own busy_timeout
under -race on a database with no real content at all. One shared
goroutine, one writer at a time, fixes that with no real cost — neither
migration takes more than a fraction of a second on any deployment
measured so far.

Signed-off-by: Osher-Elhadad <[email protected]>

---------

Signed-off-by: Osher-Elhadad <[email protected]>
Co-authored-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.

1 participant