Repository navigation
feat: bulk-create keep-alive strategies from KV-cache suggestions (strategy campaigns) - #126
Conversation
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]>
…gies # Conflicts: # docs/results/kv-ttl-predictor-comparison.md # docs/results/kv-ttl-predictor-features.md # docs/results/kv-ttl-predictor-summary.md # kvcache/registry.go # kvcache/sticky_test.go # proxy/keepalivestrategy_test.go
tenant.Strategy gains HeadTTL1h/HeadTTLMinTokens, the same knob a tenant's own account config already exposes (config.CacheConfig.HeadTTL1h). A strategy can only turn it ON, never off, mirroring how it already forces KeepAlive on. The write-tier decision is read on the REQUEST path (applyMode), not inside keeper.record where a strategy's ping schedule resolves — so applyStrategy's existing resolution alone can't reach it. Factor the matching walk out into bestStrategyFor and add resolveHeadTTL beside it, consulted from applyMode before falling back to the account's own setting; a tenant with no matching strategy behaves exactly as before. The 5-minute idle/ping bounds (minOverrideIdle..maxOverrideIdle, minOverridePings..maxOverridePings) are too tight for a 1-hour hold, so validStrategyBounds picks a second band (maxOverrideIdle1h, maxOverridePings1h) when HeadTTL1h is set: the same 10-second-under-the-lifetime margin the 5-minute band already uses, and a much lower ping ceiling than the 5-minute tier's, since a longer-lived strategy holds a caller's credential in memory for (MaxPings+1) x Idle and the 1-hour tier needs far fewer refreshes to hold the same span in the first place. Migration v10 adds the two columns, additive with defaults, so an existing strategy behaves identically after it. Signed-off-by: Osher Elhadad <[email protected]> Signed-off-by: Osher-Elhadad <[email protected]>
StrategyLedger's two-query pattern — ping cost and credited saving never share a row, since only the ping carries a strategy id — is the right shape for a time-bounded, per-hour-of-day breakdown too, not just one strategy's lifetime total. CampaignRealSavings runs the same two queries grouped by tenant AND hour instead of tenant alone, adds the time floor StrategyLedger's own saving-side query is missing (needed so a comparison against a frozen prediction never folds in traffic from before the thing being measured existed), and folds in real request volume and distinct active days for a normalized read, since a fixed backtest window and an open-ended live one are not comparable as raw totals. New index on (keepalive_strategy_id, ts): today's equivalent query is an unindexed full scan. Additive — CREATE INDEX IF NOT EXISTS needs no schemaVersion bump. Signed-off-by: Osher Elhadad <[email protected]> Signed-off-by: Osher-Elhadad <[email protected]>
A strategy campaign turns a batch of GET /api/kvcache/suggest cells into real keepalive_strategies rows in one manager action, and freezes what each cell predicted so it can be checked against reality later — see tenant/campaign.go's persistence (migration v11, in the previous commit's tenant.go change: strategy_campaigns + campaign_cells, alongside that commit's head-TTL columns) and proxy/campaign.go's engine. Enforcement is restricted to arms with a real live path. Most suggest arms (historical-probability, sticky-session-1h, observed-policy, ...) are simulation-only and are recorded with a reason, never activated. The 1h-tier arms are additionally gated per tenant by which model that tenant's own traffic runs on: this deployment's own measurement (apply/headttl.go) shows Bedrock granting the 1h cache tier only to aws/claude-haiku-4-5 and silently downgrading everything else, including the model carrying most of this service's traffic — activating it blindly would pay the tier's write premium for zero benefit on exactly the traffic that dominates. Cells are coalesced by (arm, exact hour set) into the fewest strategies that stay correct: a strategy's Target and Windows both apply to the WHOLE strategy, so merging two tenants recommended for different hours would activate an hour for one of them it was never recommended for. Windows are tiled in UTC, matching exactly the hour suggest computed each cell's saving from. A cell with no tenant id (single-tenant traffic, or a pre-tenancy row) is excluded outright — an ambiguous, unsafe target in a hosted deployment. Routes: create (from a live fetch or an uploaded suggest payload), list, get (with the per-tenant predicted/real aggregate), a per-tenant per-hour drill-down, and archive. Signed-off-by: Osher Elhadad <[email protected]> Signed-off-by: Osher-Elhadad <[email protected]>
Self-mounted, the same way kvcache.js and tools.js are: one <script> tag in index.html is the only change there, campaigns.js does the rest (tab, section, loader registration). The create flow always submits source:"upload" with the exact payload the preview grid showed — even when that payload came from "Fetch live suggestions" — rather than asking the server to re-fetch live data at commit time. Re-fetching would let traffic between preview and commit change the numbers a manager just reviewed; submitting exactly what was shown means "create this" always means what it says. The per-tenant drill-down shows both the UTC hour a window actually fires at (matching exactly the hour suggest computed each cell's saving from) and today's real Asia/Jerusalem equivalent, so the two never drift apart across a DST boundary the way storing windows in local time would. Signed-off-by: Osher Elhadad <[email protected]> Signed-off-by: Osher-Elhadad <[email protected]>
The early return on `len(strategyIDs) == 0 || len(tenantIDs) == 0` meant a campaign whose every cell resolved to a non-activatable arm (so strategyIDs is empty) silently skipped the saving-half query too, even though that half only needs tenantIDs — the two halves answer unrelated questions (a strategy's ping cost; a tenant's credited saving) and neither needs the other's list to be non-empty. Gate each half on its own list instead, and only skip the whole call when both are empty. Found and verified by the multi-agent review of PR rossoctl#126, along with every other fix in this batch of commits — see the PR's own comment thread for the full review. Signed-off-by: Osher Elhadad <[email protected]> Signed-off-by: Osher-Elhadad <[email protected]>
…nset skip reason CreateCampaign now rejects two cells sharing (TenantID, HourUTC) before the transaction starts, naming the duplicate — campaign_cells' own primary key would otherwise catch this anyway, but only after keepalive_strategies rows had already been created for the batch, surfacing a raw SQLite constraint message to the caller instead of a clear error. cell.SkipReason is now routed through nullableString(), the same helper StrategyID already used: both columns are declared as bare nullable TEXT in the same migration, so an unset skip reason should be indistinguishable from a pre-feature row at the SQL level, not stored as a literal empty string while its sibling column correctly used NULL. Also drops the redundant idx_campaign_cells_campaign index from the (still unmerged, so safe to edit directly) v11 migration: campaign_cells' own PRIMARY KEY (campaign_id, tenant_id, hour_utc) already creates SQLite's automatic index over exactly those columns, leading on campaign_id — measured via EXPLAIN QUERY PLAN, the planner never chooses the now-removed explicit index over the PK's own. Found and verified by the multi-agent review of PR rossoctl#126 — see the PR's own comment thread for the full review. Signed-off-by: Osher Elhadad <[email protected]> Signed-off-by: Osher-Elhadad <[email protected]>
…s, and bad input "Create campaign" had no re-entrancy guard, so a double-click sent two independent POSTs, each creating its own full set of live keep-alive strategies — not just a UI glitch, a real duplicated recurring cost. createBtn is now disabled synchronously before the first await and re-enabled only in a finally, the same pattern fetchLiveSuggestions already used. The campaign drawer's async renders (the aggregate overview, and the per-tenant drill-down that replaces it in the same singleton #drawer-body node) had no cancellation/generation guard: closing a drawer, or navigating to a different campaign or tenant, does not cancel an in-flight fetch, so a slow earlier response could resolve later and silently overwrite whatever the manager is now actually looking at. Both renders now check a drawer generation token, bumped on every openCampaignDrawer call, before mutating the shared body. Uploading a file containing valid-but-wrong-shaped JSON (a bare `null`, a number, an array) threw an uncaught TypeError with no visible error, since JSON.parse succeeds on all of those without throwing. Guarded with an explicit object check right after parsing. Also updates the two normalized-rate columns ($/1k requests, $/active day) to check `!= null` instead of truthiness, matching proxy/campaign.go's change (same commit series) from a plain omitempty float64 to a *float64: the rate can legitimately be exactly 0 for real traffic with $0 credited that hour, which a truthy check rendered as "—" (no data) instead of "$0" — the same "zero looks like absence" mistake already fixed once on the aggregate totals, recurring here. Found and verified by the multi-agent review of PR rossoctl#126, then re-verified live in a real browser (signed in through the actual sign-in form, exercised the null-payload guard, a rapid double-click on Create, and the $0 rendering) — see the PR's own comment thread for the full review. Signed-off-by: Osher Elhadad <[email protected]> Signed-off-by: Osher-Elhadad <[email protected]>
…a real-data leak This is the biggest cluster from the multi-agent review of PR rossoctl#126, all in the campaign create/read path: - HeadTTL1h=true campaign strategies (keepalive-1h, keepalive-1h-once) were created with HeadTTLMinTokens left at the zero value. apply.Opts' own gate is `HeadTTL1h && HeadTTLMinTokens > 0` — 0 means "never upgrade" — so every 1h-tier campaign strategy silently never promoted the head to the 1-hour tier while still pinging on the 1-hour cadence: full cost, zero benefit, on exactly the arms this feature exists to activate. campaignArm now carries its own headTTLMinTokens (50000, mirroring config.DefaultHeadTTLMinTokens), and validStrategyBounds refuses HeadTTL1h=true paired with a zero-or-negative token floor outright, closing this for any future caller too, not just this one. - ctlCreateCampaign never ran validWindows/Target.Validate/validStrategyBounds before persisting a coalesced strategy — unlike its sibling ctlCreateKeepAliveStrategy, which always does. Combined with tileHours having no bounds check on hour_utc, an uploaded suggest payload with an out-of-range hour (a plausible hand-edit artifact) produced a strategy that was created successfully (HTTP 201, activatable:true) but could never match anything, ever — pinging and saving nothing forever with no error anywhere. HourUTC is now bounds-checked in resolveCampaignCell before the arm is even resolved (marking the cell non-activatable with a clear reason instead), and validateGroupStrategy runs the same four checks the manual route does as defense in depth before every CreateStrategy call. - The per-tenant drill-down leaked real ping/saving data across tenants: two tenants sharing a coalesced strategy (same arm, same hour — an ordinary, expected outcome of this feature's own coalescing) both appear in CampaignRealSavings' un-tenant-scoped cost-half rows, and the caller collapsed them into a map keyed on hour alone, discarding which tenant each row belonged to. Whichever tenant's row landed last silently overwrote the other's in the map — a manager viewing tenant A's drill-down could see tenant B's ping cost and credited saving. Now filtered to the requested tenant before insertion. - The predicted-saving total summed every cell's frozen PredictedUSD regardless of whether it was ever actually activated, while the paired real-saving total only ever covers cells that got a real strategy — so a campaign dominated by simulation-only arms (the common case per this feature's own design) showed an inflated "Predicted" figure beside a "Real" figure computed over a different, smaller population, with no caveat distinguishing the two. Now only sums PredictedUSD for cells that received a StrategyID, matching exactly the population Real can ever be checked against. - The post-create audit-write loop returned on the FIRST failure, so any strategy later in the batch than the failing one never even got an attempted audit write, despite being fully live and already referenced by committed campaign_cells rows. Now continues attempting every strategy's audit write and reports the aggregate failure only after the whole batch has been tried. - resolveHeadTTL's call site in applyMode used time.Now() directly, while applyStrategy (the ping-scheduling half resolved in keeper.record) uses the keeper's own injectable clock — both halves' doc comments assert they resolve the same matching strategy "so the two can never disagree," an invariant that only holds if they see the same instant. They happen to agree today only because the keeper's clock defaults to time.Now in production; a new nil-safe keeper.clockNow() helper makes this provably true instead of coincidentally true. - The two normalized real-saving fields (per 1k requests, per active day) were plain omitempty float64s, so a genuinely zero rate (real traffic, $0 credited that hour) was indistinguishable on the wire from "never computed" and rendered as if absent. Both are now *float64, non-nil exactly when their denominator was actually nonzero. New tests cover each of the above directly, including one exercising the REAL, DB-backed 1h-tier model-honoring gate (tenantHonorsHeadTTL1h) end to end with actual recorded traffic under both an honored and a downgraded model — every prior test of that gate injected a fake closure instead. All fixes additionally re-verified live in a real browser where applicable — see the PR's own comment thread for the full review and what was and wasn't addressed. Signed-off-by: Osher Elhadad <[email protected]> Signed-off-by: Osher-Elhadad <[email protected]>
Multi-agent review + fixesRan a comprehensive review of this PR: 8 independent dimensions (engine logic, Fixed everything that was a real bug or a meaningful gap, re-verified with new FixedThe 1h-tier arms didn't actually work ( An out-of-range hour created a live-but-permanently-dead strategy ( Cross-tenant data leak in the per-tenant drill-down ( Predicted vs. real compared two different populations ( Audit-write loop stopped on the first failure ( Two clocks that were supposed to be one (
Duplicate
A redundant index ( Frontend: double-submit, stale drawer renders, a bad-upload crash ( Not fixed (flagged, not acted on)The audit surfaced ~14 test-coverage-only suggestions with no actual bug behind them — Verification
|
…hold validPredictorRef accepted PredictorID != "" with PredictorThreshold <= 0 as a perfectly valid strategy shape — but predictorFor's probability functions only ever return values in [0,1], so pingable()'s `p(stopReason) >= threshold` is satisfied by EVERY possible prediction once threshold hits 0. A predictor-gated strategy created that way pings unconditionally, on its own idle/max-ping schedule, identically to an ungated arm, while still being labeled and billed as predictor-gated — the same class of "a field silently left at its zero value disables the mechanism it gates, while the strategy still runs as if the gate were active" mistake validStrategyBounds already refuses for HeadTTL1h/HeadTTLMinTokens. Refused outright now, mirroring that refusal, so this cannot recur silently for a future predictor either. Found by the second, independent round of multi-agent review of PR rossoctl#126 — see the PR's own comment thread for the full review. Signed-off-by: Osher Elhadad <[email protected]> Signed-off-by: Osher-Elhadad <[email protected]>
…campaign gaps A second, independent multi-agent review round of PR rossoctl#126 (28 agents, fresh eyes on top of the already-fixed round-1 batch) found these still-real issues, all in the campaign create/read path: - stop-reason-gated shipped with no PredictorThreshold at all: campaignArm had no field for it, so strategyForGroup left tenant.Strategy.PredictorThreshold at its zero value. Combined with the fix in this branch's previous commit, this would have been REFUSED at create time (a strategy this deployment could not actually enforce as predictor-gated, marked non-activatable with a reason, same as any other unenforceable arm) — but the arm itself now also carries its own live threshold (0.5, matching the value this codebase's own tests already use for this exact predictor) so the arm is enforceable as designed, not merely refused safely. - The predicted/real "population consistency" fix from round 1 (fc09a8a) only scoped the PREDICTED side to activated cells; the REAL side did not match. A tenant with zero activated cells in a campaign (every one of its cells resolved to a simulation-only arm, or a model-gated-out 1h arm) could still show a nonzero real saving figure — both in the aggregate overview and the per-tenant drill-down — if it happened to have unrelated real keep-alive credit from anywhere else (another campaign, a manually-created strategy). campaignTenantSummaries now tracks which tenants actually received a strategy and reads real savings only for that narrower set; campaignRealSavings' per-tenant gate now checks whether the SPECIFIC requested tenant was activated, not merely whether the campaign as a whole activated anyone. - resolveCampaignCell never checked a cell's own InsufficientData flag before activating a real, live strategy for it — contradicting the suggest API's own documented guarantee that a thin cell's winner (as few as 1-4 requests can still "win" an arm by chance) must not be acted on as a pattern. Now skipped for any non-baseline arm; a baseline ("change nothing") cell stays exempt, since doing nothing carries no risk regardless of sample size. - weekdaysFromNames could silently return an empty []time.Weekday (Weekdays omitted entirely by a hand-edited upload, or every name in it misspelled), and tenant.Window.contains treats an empty Days as "every day matches," not "no day restricted" — so a strategy built from it would fire on Friday/Saturday too, traffic the frozen PredictedUSD was never backtested against (both this suggester and its own callers only ever read Sunday-Thursday history). Now falls back to that same canonical work week instead of silently expanding to every day. - The (tenant, hour) duplicate-cell guard added in round 1 (2e3d9d3) runs inside tenant.CreateCampaign, which this package only calls AFTER already creating a real, live keepalive_strategies row for every coalesced group — so a duplicate-cell upload still caused live strategies to be created and then rolled back, rather than never created at all. Checked here now, before the create-strategy loop runs. - rollbackCampaignStrategies deleted a failed create's strategies from the registry but never reloaded the keeper's in-memory list — and strategyForGroup marks a created strategy Active immediately, so it is matchable to live traffic the instant it exists, before the campaign or its cells are ever persisted. A concurrent, unrelated strategy/campaign mutation reloading the keeper in that window could pick up the about-to-be-rolled-back strategy and keep it matching (pinging real spend, toggling KeepAlive/HeadTTL1h) until some later, unrelated reload evicted it. Now reloads the keeper once after every delete attempt; delete failures are logged instead of silently swallowed, so an orphaned row is at least discoverable. Also stops leaking internal/DB-layer error text to the HTTP client on the three DB-backed failure branches in this route (the live suggest call, strategy create, campaign create) — logged server-side instead, matching the hand-authored validation errors that stay in the response. New tests cover each of the above, including an end-to-end test driving keepalive-5m-once, stop-reason-gated, and keepalive-1h-once through the real create route with an assertion on every field of the resulting strategy (previously only keepalive-5m and keepalive-1h got that depth — precisely the gap that let the PredictorThreshold omission ship unnoticed), a multi-tenant test with one activated and one non-activated tenant asserting zero real saving for the latter, and a fix for an existing test (TestCtlGetCampaignTenantDoesNotLeakAnotherTenantsRealSavings) whose pass/fail outcome depended on which UTC hour it happened to run in. Re-verified: full go build/vet/gofmt/test sweep across the whole repo, plus a live pass in a real browser (signed in through the actual sign-in form) exercising upload, create, the aggregate view, and rapid back-and-forth drill-down navigation. Signed-off-by: Osher Elhadad <[email protected]> Signed-off-by: Osher-Elhadad <[email protected]>
…en; guard the preview and list against overlapping fetches Round 1's (3c8881d) drawer generation-token guard bumped camp.drawerGen only inside openCampaignDrawer — once per drawer OPEN, never on an in-drawer navigation. Every render (the overview, and the per-tenant drill-down that replaces it in the same singleton #drawer-body node) took `gen` as a parameter from whichever call opened the drawer, so two navigations inside the SAME open drawer — two rapid tenant-row clicks, or an overview/drill-down bounce via "Back to overview" — shared the identical token and remained exactly as vulnerable to a slow-response-overwrites-a-newer-one race as before that fix, despite the fix's own commit message claiming to have closed it. renderCampaignOverview and renderCampaignTenantDrilldown now each bump camp.drawerGen themselves, at the start of every call, so every render — including a second one inside the same drawer session — gets its own token. Two more of the same shape, neither previously guarded at all: - fetchLiveSuggestions, onUploadSuggestFile, and createCampaignFromPending all write into the shared #camp-preview node and camp.pending with no token — whichever of a live-fetch and a file-upload resolves last wins, even if the manager has since moved on to reviewing the other one's preview. Added camp.previewGen, bumped by the two fetch/upload entry points and checked by every one of the three before it writes. - refreshCampaignsList writes #campaigns-list/#campaigns-count with no token either; two overlapping refreshes (a list load and an archive-triggered refresh, say) let whichever resolves last win regardless of which started last. Added camp.listGen, same shape. Found by the second, independent round of multi-agent review of PR rossoctl#126, then re-verified live in a real browser: signed in through the actual sign-in form, uploaded a suggest file, created a campaign, opened its drawer, and rapidly bounced between the overview and a tenant drill-down (back, into a tenant, back, into a tenant again) — correct final state, zero console errors. Signed-off-by: Osher Elhadad <[email protected]> Signed-off-by: Osher-Elhadad <[email protected]>
Second review round: fresh-eyes multi-agent pass + fixesRan a second, independent multi-agent review of this PR — 28 agents across 8 Two of the confirmed findings were incomplete fixes from round 1 — closing them Fixed
Predicted vs. real still compared two different populations, on the REAL side this A thin cell could still become a real, live strategy ( A rolled-back strategy could keep matching live traffic ( A duplicate-cell upload created strategies before being rejected ( An omitted or fully-misspelled weekday list silently meant "every day" ( Internal errors leaked to the client ( Frontend: three more unguarded overlapping-fetch races ( A test whose outcome depended on the wall-clock hour it happened to run at Not fixed (flagged, not acted on)Two test-coverage-only findings with no bug behind them: the round-1 audit-write- A Verification
|
|
Reviewed on current head ( Verified: all 6 originally-reported fixes hold, not superficiallyConfirmed by reading current code and exercising it live against a hosted instance:
Adversarial JSON-upload pass (beyond the existing review) — no new vulnerability foundTested directly against a live instance: negative/out-of-range Campaigns tab: audited against the dashboard's own tab-mounting convention and "the four rules" — zero deviationsChecked Checked against Real browser pass (Playwright) — cleanFull walk against a live instance (register → verify → sign in via the real cookie flow): Campaigns tab lists existing campaigns correctly; "fetch live suggestions" on zero traffic shows a correct empty state, not a crash; a hand-crafted 4-cell/2-tenant upload (mixing a normal cell, a thin-data cell, and an out-of-range hour) previewed correctly with a thin-data pill, and Create surfaced "2 activated, 2 recorded but not activated" grouped by skip reason — exactly the visible, grouped surfacing the design should have; a rapid double-click on Create produced exactly one campaign (the round-1 guard holds live); the Stats drawer and per-tenant drill-down both rendered correctly, including the zero-vs-absence distinction above; a 3x rapid tenant-drilldown/back-to-overview bounce left the UI in a stable, correct final state with zero console/page errors; malformed/null/bare-int uploads all produced a clean visible error, zero uncaught exceptions. The UX goal the user asked for (easy to fetch-or-upload, preview, create, and see why something didn't activate) is met. Oracle-gap measurement — blocked at the permission layer; here's what's honestly available insteadDirect and copy-based access to the live production DB (the only path to a real oracle-gap number on production traffic) was correctly denied by the tool-permission layer as insufficiently authorized for production tenant data — on two independent review agents, in two different framings, neither routed around. So there is no honest production oracle-gap number for campaign-eligible arms in this review, and — separately confirmed — no repo doc has ever published one: What's genuinely available:
The historical-probability-tenant-tuned result is worth the author's direct attention regardless of the oracle question: a campaign-eligible arm that's net negative on real pooled traffic shouldn't ship into Suggested fixes, by importance
|
…edicted tile dash/kvcachesim.go already computes every registered arm through Simulate, including optimal — the exact ceiling — but only the top-level simulator ever built it; the per-cell suggester (kvcache/suggest) never did, so a strategy campaign's own "Predicted" figure had no headroom number beside it without an offline script. kvSuggestCell now also builds and simulates `optimal` on exactly the same rows every other candidate is scored on, and freezes the saving over Baseline as OptimalUSD/OptimalSavingUSD — never added to Candidates, since kvSuggestCandidates() already excludes `optimal` for the whole suggester on purpose (it reads the true next-request time; see that function's own doc comment). Threaded through resolveCampaignCell into a new CampaignCell.OptimalSavingUSD column (migration v11, still unmerged so safe to edit directly, the same way round 1 did for skip_reason/the redundant index), and summed in campaignTenantSummaries/ctlGetCampaign over exactly the same population PredictedUSD already is (StrategyID != ""), so the two figures are always compared apples-to-apples. The Campaign drawer's aggregate overview gets one new tile, "Oracle ceiling (predicted)", right beside Predicted. Also adds a line to the Campaigns UI copy noting that a fetched or uploaded payload can name, and create strategies for, any tenant it lists, regardless of who is uploading — not a new privilege (a manager already has this scope through the existing manual-strategy form), but worth being explicit about given there is no separate per-tenant confirmation step before Create. Both from the suggested-fixes list in the PR's own second review-reply comment (items 1 and 4) — see the PR's own comment thread. New tests: kvcachesuggest_test.go asserts the ceiling is frozen, is never below the cell's own winner's saving, and never appears as a candidate or a winner; campaign_test.go and tenant/campaign_test.go cover the population-scoping and the column's round trip through a real migration. go build/vet/gofmt clean; go test ./dash/... ./proxy/... ./tenant/... green. (One unrelated, pre-existing flake observed in TestCtlGetCampaignAggregatesPredictedAndRealPerTenant under `go test ./...` full-repo load only, reproduced identically on the unmodified e79c72c base — a timing-sensitive real-savings read unrelated to this change; not touched here.) Signed-off-by: Osher Elhadad <[email protected]> Signed-off-by: Osher-Elhadad <[email protected]>
Acted on the suggested-fixes list (items 1 and 4) — commit
|
…by regime, and add rtk Addresses the three blocking items from review, plus the cheap ones. 1. Two candidates, and only one is a new transport. The document analysed plugin-as-interceptor (PostToolUse -> updatedToolOutput) without ever weighing plugin-as-installer-for-the-proxy (a skill writing env.ANTHROPIC_BASE_URL into the user's own settings.json), which is what #130 proposes and which gives up none of the component set. New section states the distinction, the component tables are scoped explicitly to (A), and a header note stops this page being read as the justification for #130. The headline blocker is rescoped: a plugin *manifest's* settings.json accepts only agent/subagentStatusLine -- that is not the same as "a plugin cannot set ANTHROPIC_BASE_URL", and the difference is the option that won. Title said "third transport" against the body's "fourth"; now fourth throughout. 2. cachesplit is priced by regime. -34.1%/0%->96.7% is a warm-regime figure -- one Terminal-Bench task x 3 trials (cacheinject.md:203, and :209 says treat it as one task, not a fleet average) with the A/B run back-to-back inside the TTL (dashboard.md:219). Cold interactive traffic is $0.0298 across 1,127 sessions / 11,361 requests (dashboard.md:204). Both are right; the document transferred the warm number onto a definitionally cold-regime user, called cachesplit "the best-evidenced component we have" where cacheinject.md:209 says otherwise, and claimed the figures were "not re-verified against current traffic" -- which for cachesplit is false. Corrected, the Anthropic row reads close to the vLLM row. The DAM recommendation stands but is now justified on spendgate/tenancy/limits and harness-plurality rather than on that figure. 3. Gate 0 is closed consistently. The ranked go/no-go section still called the case conditional and told the reader to run the experiment that already ran. Also: rtk is this architecture and we benchmarked it as a full arm -- -9.0% billed cost, reward-neutral, zero request-path latency (results/rtk.md:11) -- so expected value has a floor instead of resting on one session's -6,285 tokens, and the doc now claims the edge it was missing: rtk is a shell hook, so Read/Grep/Glob bypass it, while matcher ".*" does not. mask quoted as ~27.5-29.5%, single-task replay, never enforced in a benchmark arm. extract_llm 8x -> 82x underwater. Hook events ~34 -> 33. Dropped the guessed 32,768 threshold, keeping the measured (30,000, 40,000] bracket. Noted that inspect_transcript.py reports key names, not record types, so its `system` record type is a transcript event and not a request system array. Keepalive branch reference replaced with #126; extract_llm_sweep (#118) added to the offload table. inspect_transcript.py moved to deploy/harbor/, this repo's convention for analysis Python. Rebased onto main (3ebc65d). Docs-only; no code and no behaviour change. mkdocs is unaffected because docs/superpowers/ is excluded from the site build (mkdocs.yml:88-90); the three in-page anchors were validated against the file's own heading slugs and all other links are external. Assisted-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…129) * docs(analysis): evaluate a Claude Code plugin as a fourth transport Asks whether the `components` core can ship as a Claude Code plugin — a thin transport beside `proxy/`, the AuthBridge plugin and `adapters/bifrost`, reusing components via configuration. Not a replacement for the proxy. One fact decides the whole evaluation. No plugin surface can read or write the outbound request: across all ~34 hook events there is no field that rewrites `messages[]`, `system[]`, `tools[]` or `cache_control`, and plugin `settings.json` accepts only `agent` and `subagentStatusLine`, so a plugin cannot even point a session at the proxy. What IS interceptable is one tool result at the moment it is produced, via `PostToolUse` → `updatedToolOutput`. That draws the line between content-scoped and envelope-scoped work, and it is the line between the two component families. Offloaders distribute. `cmdfilter`, `format`, `toon`, `extract`, `collapse`, `smartcrush`, `skeleton` and `dedup` are pure functions from one tool output to a shorter one, which is exactly what the hook hands over and accepts back. Two get better than they are in the proxy: the hook supplies `tool_input.command` and `tool_input.file_path` instead of making `cmdfilter` and `skeleton` infer both from transcript text. Cache management does not distribute, and this is the finding worth arguing with. `cachesplit` restructures the top-level `system` array; `cacheinject` reasons over `messages[]` positionally and emits request metadata; the keepalive on `feat/keepalive-strategies` must originate a request that byte-exactly reproduces a prefix and price it from `CachedTokens`, which only the provider's response carries. None of that is a tool output — it is the envelope, assembled after the last hook runs and never persisted. Verified rather than assumed: a session transcript carries `messages` and `toolUseResult` and no system prompt or tool schemas (`scripts/inspect_transcript.py`). The failure modes are asymmetric too, which is the deeper reason. A wrong offload wastes one expand round-trip, bounded and type-enforced reversible. Wrong cache work inverts: a mistimed keepalive creates at 1.25x instead of refreshing at 0.1x, a breakpoint over budget is a 400, a representation flip inside a cached prefix re-writes the suffix at 11.5x. Envelope work has no merely-no-saving fail direction. The compensating result is that the defensive half of our KV-cache layer stops being necessary rather than being ported. `state.go` names its own premise — an offloader must re-emit identical bytes "otherwise the agent (which re-sends the ORIGINAL each turn)" flips the representation. A hook rewrites the output before it enters the transcript, so the agent never holds the original. Freeze/replay, `MaxCachedIdx`, `Tracker`, `frozen_flips` and sticky ids have nothing left to defend, and `extract_llm`'s sampling nondeterminism stops disqualifying it from repair. Also `PreCompact`/`SessionEnd` replace `proxy/agentcompaction.go`'s string match against Claude Code 2.1.215 internals, which has a documented reachable false positive. What is given up: `cachesplit` (-34.1% cost, 0% -> 96.7% hit, and in every preset), plus `mask` (27.5% Terminal-Bench, 12.5% SWE-bench) and `failed_run`, both of which rewrite EARLIER messages and so cannot work at a hook that fires once at birth. On implicit prefix-cache backends (vLLM/llm-d) the cache loss is zero, because `prefixsplit` is already a no-op there. Also documented: permanence cuts both ways (an expand's restored original joins the transcript for good, so the plugin wants a more conservative pipeline than the proxy), `/stats` cost tiers are unobtainable so plugin mode cannot be benchmarked the way the proxy is, and the whole thing is gated on one unverified fact — whether `updatedToolOutput` persists into the transcript. If it does not, the proposition collapses to an expand-only MCP server. That experiment is named as gate 0 and should run before any adapter code. On DAM: land the proxy in the gateway. DAM is harness-plural and its egress already matches our gateway credential model, so a Claude-Code-only plugin covers one harness of four and none of the bring-your-own-ACP case. Ship the plugin as the Claude-Code-session layer on top, never as the DAM integration. Docs only — no code, no behavior change. Signed-off-by: DAVID AMID <[email protected]> Assisted-By: Claude Opus 5 (1M context) <[email protected]> * docs(analysis): address review — fix CI, close Gate 0, correct the cap figure Review found one broken thing, settled the doc's central open question, and caught a wrong number. All four points addressed. CI was red: mkdocs build --strict rejected docs/analysis/claude-code-plugin.md because it was in no nav entry, and there is no docs/analysis convention to copy. Moved it to docs/superpowers/specs/2026-08-30-claude-code-plugin-transport-design.md, which exclude_docs already covers and whose stated purpose — "working plans/specs ... not published site content" — is what this doc is. That also matches the dated-spec naming of the keepalive design doc and of the local-distribution proposal in #130. The reviewer offered the alternative of a nav entry under Results:; exclusion is the better fit, because publishing a page that evaluates a plugin we have not built would read on the docs site as a product that exists. Verified with a real strict build (1.45s, no warnings) and a negative control: the same file under docs/analysis/ still aborts strict mode, so the move is the fix rather than something incidental. Gate 0 is closed, in the doc's favour. Review ran the experiment the doc asked for — a PostToolUse hook replacing a Bash output with a sentinel, captured through a raw-logging reverse proxy so the evidence is the literal outbound body rather than the transcript file — and the replacement persists and is resent verbatim on later turns. A working collapse plugin then measured -6,285 tokens on a real session, appearing as the same reduction on turn 1's cache-write and turn 2's cache-read, which is what separates a permanent reduction of resent context from a one-turn display trick. The "three things to verify" section becomes a resolved-gate section plus the risks that actually remain, and the recommendation stops being conditional. The predicted failure mode arrived on the first attempt, which is worth recording rather than smoothing over: updatedToolOutput must be the object tool_response shape ({stdout, stderr, interrupted, isImage, noOutputExpected} for Bash), and a bare string is silently ignored. That is now a hard requirement on adapters/cchook — emit the object shape, count your own rejections — instead of a general warning. The 10,000-character cap figure was wrong, and "cap" was the wrong frame. That number came from the additionalContext / systemMessage / plain-stdout cap, which does not govern this field. Measured: verbatim and uncapped to ~30,000 chars, real threshold in (30,000, 40,000] and most likely 32,768, and above it neither truncation nor rejection — the CLI's ordinary large-output handler produces a ~2,260-char <persisted-output> wrapper with a 2KB preview and a disk pointer while the local record stays intact. For an oversized hook emission that is a token-cost improvement, not a hazard. Two precision fixes. The envelope claim now records that it was verified by a stronger method than the docs (11 events exercised live, plus the installed CLI's own hookSpecificOutput validation schema: 33 events, 22 with output fields, none touching the envelope) and carries the nuance that promptCacheTtl / CLAUDE_CODE_PROMPT_CACHE_TTL is a reachable cache-TTL lever via settings or env — not via any hook or manifest field, and session-wide rather than per-breakpoint — so a flat "zero cache control" reading would overstate the gap. And the component figures quoted throughout (cachesplit's -34.1%, mask's 27.5%/12.5%, the ~7,017-token system block) are now labelled as this repo's frozen historical measurements, quoted accurately but not re-verified against current traffic by this evaluation. Finally, the recommendation leads with the scope the reviewer articulated better than the doc did: a plugin can replicate the offloader half of this repo, persistently and measurably, and categorically cannot replicate the cache-management half — not "a plugin can do what the proxy does." Docs only — no code, no behavior change. Signed-off-by: DAVID AMID <[email protected]> Assisted-By: Claude Opus 5 (1M context) <[email protected]> * docs(analysis): separate the two plugin candidates, price cachesplit by regime, and add rtk Addresses the three blocking items from review, plus the cheap ones. 1. Two candidates, and only one is a new transport. The document analysed plugin-as-interceptor (PostToolUse -> updatedToolOutput) without ever weighing plugin-as-installer-for-the-proxy (a skill writing env.ANTHROPIC_BASE_URL into the user's own settings.json), which is what #130 proposes and which gives up none of the component set. New section states the distinction, the component tables are scoped explicitly to (A), and a header note stops this page being read as the justification for #130. The headline blocker is rescoped: a plugin *manifest's* settings.json accepts only agent/subagentStatusLine -- that is not the same as "a plugin cannot set ANTHROPIC_BASE_URL", and the difference is the option that won. Title said "third transport" against the body's "fourth"; now fourth throughout. 2. cachesplit is priced by regime. -34.1%/0%->96.7% is a warm-regime figure -- one Terminal-Bench task x 3 trials (cacheinject.md:203, and :209 says treat it as one task, not a fleet average) with the A/B run back-to-back inside the TTL (dashboard.md:219). Cold interactive traffic is $0.0298 across 1,127 sessions / 11,361 requests (dashboard.md:204). Both are right; the document transferred the warm number onto a definitionally cold-regime user, called cachesplit "the best-evidenced component we have" where cacheinject.md:209 says otherwise, and claimed the figures were "not re-verified against current traffic" -- which for cachesplit is false. Corrected, the Anthropic row reads close to the vLLM row. The DAM recommendation stands but is now justified on spendgate/tenancy/limits and harness-plurality rather than on that figure. 3. Gate 0 is closed consistently. The ranked go/no-go section still called the case conditional and told the reader to run the experiment that already ran. Also: rtk is this architecture and we benchmarked it as a full arm -- -9.0% billed cost, reward-neutral, zero request-path latency (results/rtk.md:11) -- so expected value has a floor instead of resting on one session's -6,285 tokens, and the doc now claims the edge it was missing: rtk is a shell hook, so Read/Grep/Glob bypass it, while matcher ".*" does not. mask quoted as ~27.5-29.5%, single-task replay, never enforced in a benchmark arm. extract_llm 8x -> 82x underwater. Hook events ~34 -> 33. Dropped the guessed 32,768 threshold, keeping the measured (30,000, 40,000] bracket. Noted that inspect_transcript.py reports key names, not record types, so its `system` record type is a transcript event and not a request system array. Keepalive branch reference replaced with #126; extract_llm_sweep (#118) added to the offload table. inspect_transcript.py moved to deploy/harbor/, this repo's convention for analysis Python. Rebased onto main (3ebc65d). Docs-only; no code and no behaviour change. mkdocs is unaffected because docs/superpowers/ is excluded from the site build (mkdocs.yml:88-90); the three in-page anchors were validated against the file's own heading slugs and all other links are external. Assisted-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> --------- Signed-off-by: DAVID AMID <[email protected]>
Summary
GET /api/kvcache/suggestcells in one manager action, restricted to arms with a real enforcement path today.
later without ever storing it — the same convention
dash/cachehistory.goalreadyfollows for "computed on read, never written."
Campaigns): fetch live suggestions or upload a JSON file,preview, create, and drill from an aggregate per-tenant overview into any tenant's
hour-by-hour historical/predicted-vs-real breakdown.
How it works
(
historical-probability,sticky-session-1h,observed-policy, ...) aresimulation-only and are recorded with a reason, never activated — see
campaignArmForinproxy/campaign.go.tenant.StrategygainsHeadTTL1h/HeadTTLMinTokensso the 1h-tier arms(
keepalive-1h,keepalive-1h-once) can be enforced too. The write-tier decision isread on the request path (
applyMode), not insidekeeper.recordwhere a strategy'sping schedule resolves, so
resolveHeadTTLis a second resolution besideapplyStrategy's existing one. Additionally gated per tenant by which model thattenant's traffic runs on: this deployment's own measurement (
apply/headttl.go) showsBedrock granting the 1h tier only to
aws/claude-haiku-4-5and silently downgradingeverything else — activating it blindly would pay the tier's write premium for zero
benefit on the traffic that dominates.
TargetandWindowsboth apply to the whole strategy, so merging two tenantsrecommended for different hours would activate an hour for one of them it was never
recommended for. Windows are tiled in UTC, matching exactly the hour suggest computed
each cell's saving from.
pre-tenancy row, never a safe campaign target in a hosted deployment.
StrategyLedger's two-disjoint-query shape(
dash/campaignsavings.go): a ping's cost carries its strategy id, the real request itlater rescues does not, so cost and saving can never come from one query. Generalized
to a per-(tenant, hour) grid, time-bounded to each campaign's own activation, with a
new covering index.
source: "upload"), even when that payload came from "Fetch live suggestions" — re-fetching atcommit time would let traffic between preview and commit change the numbers a manager
just reviewed.
Test plan
go build ./...go vet ./...gofmt -lclean on all touched filesgo test ./...— full suite greenvia detached-HEAD checkout), so the history bisects cleanly
validStrategyBounds,empty-tenant-id exclusion, non-activatable arms recorded with a reason, the 1h-tier
per-tenant model gate, window tiling has no gap/overlap and never wraps hour 23
into hour 0, coalescing only merges tenants sharing the exact same hour set, an
end-to-end campaign create through the real HTTP route (fixture suggest payload →
correct strategies → correct cells), and the per-tenant real/predicted aggregate
wiring
uploaded a suggest fixture, created a campaign, opened the aggregate drawer,
drilled into a tenant, navigated back — caught and fixed one real bug along the
way (
omitemptyon the aggregate totals made a genuine$0render as—)