Skip to content

fix(dash): correct four money figures computed over the wrong row population, and stop activating ping schedules off partially-priced cells - #167

Merged
OsherElhadad merged 5 commits into
mainfrom
fix/dash-money-formulas-0901
Sep 1, 2026
Merged

OsherElhadad merged 5 commits into
mainfrom
fix/dash-money-formulas-0901

Conversation

@OsherElhadad

@OsherElhadad OsherElhadad commented Sep 1, 2026 •

Copy link
Copy Markdown
Collaborator

One commit here changes behaviour, not just a displayed number. 853b360 makes proxy/campaign.go refuse to activate a live keep-alive ping schedule for a cell whose winning arm was chosen on partially-priced traffic. It fails toward not acting, and it reverts cleanly on its own — see fix 5. Everything else in this PR only changes what a figure reads.

Four money figures on the dashboard were each computed over a population that was not the population they claimed to describe, plus one gate on the live ping-activation path that never checked whether the cell it was activating could be priced. Each is measured against a real corpus where one exists, and each ships with a test that fails without it.

What a reader of the dashboard sees change

1. Frozen tokens are no longer priced at a rate they were not billed at — MEDIUM

dash/readvalue.go documents FrozenReadUSD as the frozen prefix priced "at the cache-READ rate they were actually billed at". The frozen count is what compaction declined to touch; cache_read is what the provider served from cache. Neither bounds the other.

Real corpus, 133,064 requests: 3,004 of the 75,185 rows with frozen_tokens > 0 — 4.0% — have frozen_tokens exceeding that same request's cache_read, by 73,162,809 tokens. Those were billed fresh or written.

before after
frozen tokens priced (token_accounting = 'complete') 2,535,303,824 2,462,141,015

−2.886% on FrozenReadUSD and on FrozenWriteRiskUSD, per model at that model's own rates. Clamped per row to min(frozen_tokens, cache_read) rather than dropping the rows, which is the conservative direction this file already errs in.

2. The "gross, of what we tried to compact" ratio is summed over one row population — MEDIUM

The numerator summed over every row, the denominator over the rows that recorded one. attempted_tokens is additive, so a row written before it shipped reads 0 while still carrying a saving.

Real corpus: 7,032 rows have a saving with attempted_tokens = 0 — they raise the numerator and cannot raise the denominator.

numerator denominator ratio
served 82,608,519 3,932,190,169 2.101%
same-basis (118,823 of 133,064 rows) 71,706,297 3,932,190,169 1.824%

This is the residual of a repair already made once. dash/overview.go's own comment above the ratio records it being fixed from 13× too small and names the intended figure as "1.838% on production traffic" — which independently corroborates 1.824%. That repair fixed the numerator's definition and never its row population.

Residual, deliberately not fixed here: 21,321 rows (16.0%) still have gross > attempted, so the ratio is unbounded in principle. That is not an arithmetic problem — gross counts content saved per turn including what is re-sent, attempted is what compaction was allowed to touch on that turn, and clamping one to the other would discard real savings to make a ratio look tidy. The display case is already handled on main: dash/ui/app.js:1753,1757 (from #155) renders a ratio over 100% as a multiplier rather than a percentage.

That guard was camouflaging this defect. On the fixture below, the old arithmetic renders "2.75×", not "275%" — an honesty feature reformatted an impossible value into a plausible-looking one, and made the arithmetic bug harder to notice than if it had rendered raw. A guard that reformats an impossible value should also record that it fired. Named as a follow-up below rather than fixed here: it is a dash/ui/ change and this PR deliberately touches no front-end file.

3. The historical cachesplit credit refuses models whose stable half is not constant — LOW (honesty)

dash/cachehistory.go retro-applies one model's recorded stable half to rows that predate the instrumentation. Its header asserted the premise that makes that legitimate: "per model on this deployment the recorded minimum and maximum are the same number". The file also ships CachesplitSizeSpread, the query written so an operator would not have to take that on trust.

Run it and the premise is false. 7 of 9 models with a recorded stable half have min ≠ max, the widest spread 5.5× (1,301..7,190 tokens); 3 of 3 on the synthetic corpus. The code then took MAX while the doc said the ends coincide.

The direction is safe, not inflationary. stable gates as well as prices (read >= stable > write), so the larger end admits far fewer rows. Over the same 6,667 candidate requests on the real corpus:

stable half qualifying requests tokens credited
MAX (shipped) 11 49,626
MIN 280 1,565,566

MAX under-credits ~31×. This is an honesty defect, not an over-credit.

Refused rather than repicking an end: the doc's factual premise is disproved, so choosing either end swings a money figure 31× on an assumption just falsified; Uncovered already exists to report "we cannot value this model's history"; and stable serves two roles that want opposite ends, so no single constant is defensible while the spread is real. Before/after: 11 valued requests → 2, with 6,664 candidates moving into Uncovered. Applied at both sites, which are deliberate copies of the same arithmetic; the test pins that they agree. The header's false claim is corrected too — a doc comment asserting something measurably untrue is half the defect, and this one was cited as the estimate's justification.

4. The kv-cache headline total is gated on full pricing coverage — MEDIUM

KVCacheSuggest summed each cell's SavingUSD into a service-wide total gated on cell.Valued, which is Requests > 0 && Unpriced < Requests — any one request priced, not all. A cell with 99 of 100 requests unpriced is Valued.

Not an inflation. An unpriced request contributes $0 to the baseline and $0 to every arm, so a partially-priced cell understates its saving. What is damaged is the choice of arm: BestStrategy is an argmax over the priced subset, and that ranking moves. Pricing one missing model flips keepalive-5m-once from −0.07% to +1.07% and stop-reason-gated from −0.35% to +0.75%, reordering ranks 5–8. stop-reason-gated buys 249 pings. So the defect is a total claiming coverage it does not have, over cells whose winner was picked on a fraction of their own traffic. The gate makes the total a floor over fully-covered cells rather than a blend of two populations.

cell.SavingKnown was computed and gated nothing, so it is now in the gate — but on its own it does not close this, and a test says so. Savings.Known is baseline.TotalUSD != 0, i.e. "the percentage has a divisor", which one priced request is enough to give. A reviewed cell with 20 of its 36 requests unpriced reads Valued: true AND SavingKnown: true. The gate that closes it is UnpricedRequests == 0.

Coverage was absent from the payload, not merely unrendered — before this PR grep -n Unpriced dash/kvcachesuggest.go returned zero hits, so no UI could disclose it however much it wanted to, while the sibling table on the same tab already carries that column (dash/ui/kvcache.js:1136). Added KVCacheSuggestion.UnpricedRequests, and TotalSavingKnown / TotalSavingCells / TotalUnpricedRequests on the payload.

No real-corpus figure for this fix, and that is unknown rather than zero. How many requests are unpriced depends on the operator-supplied rate table, which lives with the live service and is not reachable from a development checkout. The before/after quoted in its commit — $0.038000 over one cell → n/a over zero cells — is on a synthetic 1-in-6-priced fixture. Reviewed-corpus exposure, measured separately: 5 of 19 cells contain unpriced rows carrying 16.1% of that headline.

5. A campaign cell whose arm won on priced rows only no longer activates a live schedule — HIGH

proxy/campaign.go:resolveCampaignCell is the path that activates live ping schedules, and it never consulted whether the cell's dollars could be priced: grep -n 'Valued\|SavingKnown' proxy/campaign.go returned zero hits. It gated on hour range, arm activatability, per-tenant 1h-tier honoring and InsufficientData — strictly weaker than the dash/kvcachesuggest.go total fixed above. The measured 20-of-36 cell passes every one of those gates and gets a real strategy created off it, and :167 copies predictedUSD from the same cell with no coverage test at all.

This is the only commit here with behavioural rather than display consequences, and it reverts cleanly on its own as 853b360 (2 files, ~20 lines) if a reviewer prefers it split out.

The objection is InsufficientData's, on the other axis: too few priced requests rather than too few requests. One guard in resolveCampaignCell, which is the single funnel — it decides activation and fills predictedUSD, so both the activation path and the :867/:908 sums are covered by one predicate. Baseline arms exempt, for exactly the reason InsufficientData exempts them: enforcing "change nothing" needs no evidence about which arm won.

Every fix verified to fail without itself

Each fix reverted in turn on the final tree, the rest left in place:

--- FAIL: TestFrozenTokensArePricedOnlyUpToWhatTheRequestActuallyRead
    moneybasis_test.go:41: FrozenReadUSD = $0.001672000, want $0.000456000 (3000 clamped
        tokens, not 11000): tokens beyond a request's own cache_read were not read, so the
        cache-read rate is not the rate they were billed at
    moneybasis_test.go:47: FrozenWriteRiskUSD = $0.019228000, want $0.005244000 — it
        multiplies the same count and must not re-import the unclamped one
--- FAIL: TestAttemptedRatioCountsSavingsOnlyWhereItCountsTheDenominator
    moneybasis_test.go:81: attempted ratio = 11000/4000 (275.000%), want 2000/4000
        (50.000%): the pre-instrumentation row's 9000-token saving has no denominator and
        may not inflate a ratio it cannot divide into
--- FAIL: TestHistoricalSplitRefusesAModelWhoseStableHalfIsNotConstant
    moneybasis_test.go:130: valued 2 request(s) over 2 model(s), want 1 and 1: the model
        whose recorded min (1000) and max (6000) disagree has no constant stable half
    moneybasis_test.go:135: credit $0.013984000, want $0.003496000 (the flat model only)
    moneybasis_test.go:138: Uncovered = 0, want 1 — a refused model must be REPORTED as
        unvaluable, not silently dropped; that is what this counter is for
    moneybasis_test.go:151: per-tenant pass valued 2 and refused 0, want 1 and 1 — it must
        agree with CachesplitHistoricalUSD, not drift from it
--- FAIL: TestKVCacheSuggestTotalRefusesAPartiallyPricedCell
    moneybasis_test.go:190: total = $0.038000 over 1 cell(s); a cell with 5 of 6 requests
        unpriced describes only a sixth of itself
    moneybasis_test.go:195: TotalSavingKnown is true with no qualifying cell — the figure
        must read n/a, never $0.00
--- FAIL: TestResolveCampaignCellRefusesACellWhoseArmWasPickedOnPricedRowsOnly
    campaign_test.go:115: got {... arm:stop-reason-gated activatable:true skipReason: ...},
        want not activatable with a reason: 20 of 36 requests unpriced means
        stop-reason-gated (which buys pings) won on 16 of them

TestResultValuedIsAFloorNotCoverage additionally pins why the coverage gate is not redundant, so a future reader does not simplify it back to Valued alone.

Verification

$ CGO_ENABLED=1 go build ./... && go vet ./...      # both silent
$ CGO_ENABLED=1 go test -count=1 ./dash/ ./proxy/ ./components/... ./internal/...
ok  github.com/rossoctl/context-guru/dash                85.538s
ok  github.com/rossoctl/context-guru/proxy               48.459s
ok  github.com/rossoctl/context-guru/components           0.175s
ok  github.com/rossoctl/context-guru/components/all       0.348s
ok  github.com/rossoctl/context-guru/components/dsl       0.028s
ok  github.com/rossoctl/context-guru/components/offload   12.127s
ok  github.com/rossoctl/context-guru/components/reformat  13.447s
ok  github.com/rossoctl/context-guru/internal/cheapmodel   0.274s
ok  github.com/rossoctl/context-guru/internal/extract      0.344s
ok  github.com/rossoctl/context-guru/internal/logging      0.046s
ok  github.com/rossoctl/context-guru/internal/modelinfo    0.318s
ok  github.com/rossoctl/context-guru/internal/redact       0.027s
ok  github.com/rossoctl/context-guru/internal/skills       0.045s
ok  github.com/rossoctl/context-guru/internal/tokens       0.158s

Follow-up work this PR does NOT do

  • total_saving_known is not read by any UI. The payload now carries the coverage fields; nothing renders them, so the kv-cache total still displays as a number rather than n/a. The honesty fix is complete server-side and unfinished end to end — a front-end change is needed to close it.
  • The percent > 100 render guard does not record that it fired (dash/ui/app.js:1753). It silently reformats an impossible ratio into a multiplier, which is how this PR's fix 2 stayed unnoticed. It should surface that it triggered — a reformatted impossible value is a defect signal, not a display preference.
  • Nothing under dash/ui/ is touched at all in this PR.

Note for branches landing beside this one

This PR inserts two aggregate expressions into DB.Overview's main SELECT (dash/overview.go:484-485) and two matching targets into its Scan(...). Two consequences for anyone rebasing onto it:

  • The existing keepalive_saved_usd aggregates moved from :539-540 to :555-556. No textual conflict — apply by content, not by line number.
  • That SELECT list and its Scan(...) are coupled by position. Reshaping one without the other shifts every column silently, with no compile error and no test failure that names the cause.

A re-pricing decision, not in this PR

baselineDeltaUSD prices the unique term at p.CacheWrite unconditionally while the replay term one line below correctly tests what the turn actually paid. On a turn that read cache and wrote none, the removed tail would have been billed fresh.

Branch: propose/unique-term-repricing-0901 (one commit on top of this one). It asks for one decision: re-pricing published savings figures downward by 0.710% on the real corpus — the unique term moves −2.71%, and 86.4% of unique tokens sit on turns whose write did cover the prompt and do not move at all. The complete blast radius is on that branch so it can be seen at once: four copies of the formula, a fifth GROUP BY key on both read-path queries, and five test expectations updated. That call belongs to the repo owner, not to this PR.

Osher-Elhadad added 5 commits September 1, 2026 12:47
TierCosts documents FrozenReadUSD as the frozen prefix priced "at the cache-READ
rate they were actually billed at". For 4.0% of the rows behind it that claim is
false: the frozen count is what compaction DECLINED to touch, cache_read is what
the provider served from cache, and neither bounds the other.

On the real 133k-request corpus, 3,004 of the 75,185 rows with frozen_tokens > 0
have frozen_tokens greater than that same request's cache_read, by 73,162,809
tokens in total. Those tokens were billed fresh or written, so pricing them at
the read rate prices a tier they were never charged at. FrozenWriteRiskUSD
multiplies the same count by the write/read spread and inherited the error.

Clamped per row to min(frozen_tokens, cache_read), which is the conservative
direction this file already errs in, rather than dropping the offending rows.

Before/after on the real corpus (SUM over token_accounting = 'complete'):
  frozen tokens priced   2,535,303,824 -> 2,462,141,015   (-2.886%)
Both FrozenReadUSD and FrozenWriteRiskUSD move by exactly that factor, per model
at that model's own rates.

The test fails on the unclamped form with FrozenReadUSD reading 11,000 tokens
where the two rows read 3,000.

Signed-off-by: Osher-Elhadad <[email protected]>
The "gross, of what we tried to compact" denominator summed attempted_tokens
over the rows that recorded one and its numerator over every row. Read
overview.go's own comment above the ratio: this figure was already repaired once,
from 13x too small, and that repair fixed the numerator's DEFINITION (gross, not
unique) without touching the rows it was summed over. This is the residual, and
it runs the other way.

attempted_tokens is an additive column, so a row written before it shipped reads
0 while still carrying a saving. On the real 133k-request corpus 7,032 rows have
a saving with attempted_tokens = 0, and 21,321 rows (16.0%) have a gross saving
exceeding their own attempted_tokens. The numerator was therefore raised by rows
that could not raise the denominator.

Before/after on the real corpus:
  served      82,608,519 / 3,932,190,169 = 2.101%
  same-basis  71,706,297 / 3,932,190,169 = 1.824%   (118,823 of 133,064 rows)

1.824% independently corroborates the intended figure the earlier repair's own
comment names, "1.838% on production traffic", which is what makes this the
residual of that repair rather than a second opinion about it.

Adds Overview.SavedGrossAttempted and .AttemptedRequests so the restricted
population is a stated field rather than an inline SQL condition, and matches the
guard idiom the sibling new_input ratio already uses. SavedGross keeps its
all-rows meaning; only the ratio's basis changed.

Signed-off-by: Osher-Elhadad <[email protected]>
…s not constant

cachehistory.go retro-applies one model's recorded stable half to the rows that
predate the instrumentation for it. Its header states the premise that makes that
legitimate rather than a guess: "per model on this deployment the recorded minimum
and maximum are the same number". The file also ships CachesplitSizeSpread, the
query written so an operator would not have to take that on trust.

Run it and the premise is false. On the real corpus 7 of 9 models with a recorded
stable half have min != max, the widest spread 5.5x (1,301..7,190 tokens); 3 of 3
on the synthetic corpus. The code then took MAX while the doc said the ends
coincide.

The direction is SAFE, not inflationary, and that matters for how this reads:
`stable` gates as well as prices (read >= stable > write), so the larger end
admits far fewer rows. Measured on the real corpus over the same 6,667 candidate
requests:
  MAX (shipped)  11 qualifying requests,     49,626 tokens credited
  MIN             280 qualifying requests, 1,565,566 tokens credited
MAX under-credits by ~31x. This is an honesty defect, not an over-credit.

Refusing rather than picking an end, because:
  - the doc's factual premise is disproved, and picking either end would swing a
    money figure 31x on an assumption we just falsified;
  - Uncovered already exists to report exactly "we cannot value this model's
    history", so the refusal is visible instead of silent;
  - `stable` serves two roles that want opposite ends, so no single constant is
    defensible while the spread is real.

Before/after on the real corpus: 11 valued requests -> 2, with 6,664 candidate
requests moving into Uncovered (only 2 of the 9 models are flat, and 3 of the
6,667 candidates are on one of them). Applied at both sites, CachesplitHistoricalUSD
and CachesplitHistoricalUSDByTenant, which are deliberate copies of the same
arithmetic; the test pins that they agree.

Corrects the header's claim too. A doc comment asserting something measurably
untrue is half the defect, and this one was cited as the estimate's justification.

Signed-off-by: Osher-Elhadad <[email protected]>
KVCacheSuggest sums each cell's SavingUSD into a service-wide TotalSavingUSD,
gated on cell.Valued && !cell.InsufficientData. Valued comes from
kvcache.Result.Valued, which is `Requests > 0 && Unpriced < Requests` — ANY one
request priced, not all. A cell with 99 of 100 requests unpriced is Valued, and
its saving is measured on that one request while being labelled with the cell.

NOT an inflation. An unpriced request contributes $0 to the baseline AND $0 to the
winning arm, so a partially-priced cell UNDERSTATES its own saving; that is the
safe direction. What is damaged is the CHOICE of arm. BestStrategy is an argmax
over the priced subset and the ranking moves: pricing one missing model flips
keepalive-5m-once from -0.07% to +1.07% and stop-reason-gated from -0.35% to
+0.75%, reordering ranks 5 through 8, and stop-reason-gated buys 249 pings. So the
defect is a total that claims coverage it does not have, over cells whose winner
was picked on a fraction of their own traffic.

cell.SavingKnown was computed and gated nothing, so it is now in the gate; on its
own it does NOT close this, and the test says so. Savings.Known is
`baseline.TotalUSD != 0` — "the percentage has a divisor" — and one priced request
is enough to give it. Measured: a cell with 20 of its 36 requests unpriced reads
Valued: true AND SavingKnown: true. The gate that closes it is full coverage,
which makes the total a floor over fully-covered cells rather than a blend of two
populations.

Coverage was ABSENT from the payload, not merely unsurfaced: before this commit
`grep -n Unpriced dash/kvcachesuggest.go` returned zero hits, so no UI could
disclose it however much it wanted to, while the sibling table on the same tab
carries that column already (kvcache.js:1136). Added:

  KVCacheSuggestion.UnpricedRequests  - how many of this cell's own requests
                                        contributed nothing to its SavingUSD
  KVCacheSuggestions.TotalSavingKnown - false when no cell qualified, so the UI
                                        renders n/a and never $0.00; a zero here
                                        would claim that switching every cell to
                                        its own winner saves nothing
  .TotalSavingCells                   - how many cells are behind the figure
  .TotalUnpricedRequests              - how many requests were left out of it

Measured exposure on the reviewed corpus: 5 of 19 cells contain unpriced rows
carrying 16.1% of the headline. On the synthetic 1-in-6-priced fixture the total
reads $0.038000 over one cell before and n/a over zero cells after.

The dashboard still renders total_saving_usd as a number; total_saving_known needs
a front-end read to become an n/a, which is out of scope for this branch.

Signed-off-by: Osher-Elhadad <[email protected]>
…d rows only

resolveCampaignCell is the path that activates LIVE ping schedules, and it never
consulted whether the cell's dollars could be priced: `grep -n 'Valued\|SavingKnown'
proxy/campaign.go` returned zero hits. It gates on hour range, arm activatability,
per-tenant 1h-tier honoring and InsufficientData — strictly weaker than the
dash/kvcachesuggest.go total gated in the previous commit. A measured cell with 20
of its 36 requests unpriced passes every one of those gates and gets a real
strategy created off it, and :167 copies predictedUSD from the same cell with no
coverage test at all.

The objection is InsufficientData's, on the other axis: too few PRICED requests
rather than too few requests. BestStrategy is an argmax over whichever of the
cell's requests had rates, so unpriced traffic means the arm we are about to
enforce won a comparison the rest of that cell never entered. Not a dollar
overstatement — an unpriced request contributes $0 to the baseline and $0 to every
arm, so SavingUSD is understated — but the RANKING does move: pricing one missing
model reordered ranks 5 through 8 and flipped stop-reason-gated from -0.35% to
+0.75%, and stop-reason-gated buys 249 pings.

One guard in resolveCampaignCell rather than at the several call sites, because
that function is the single funnel: it decides activation AND fills predictedUSD,
so both of the lead's cited sites (:167 and the :867/:908 sums) are covered by it.
Baseline arms are exempt for exactly the reason InsufficientData exempts them:
enforcing "change nothing" needs no evidence about which arm won.

Folded into this PR rather than routed separately because it depends on
dash.KVCacheSuggestion.UnpricedRequests, which the previous commit adds — before
that field this path could not see the condition at all. It is one guard plus one
test and reverts cleanly on its own if that call goes the other way.

Signed-off-by: Osher-Elhadad <[email protected]>
@OsherElhadad OsherElhadad changed the title fix(dash): correct four money figures computed over the wrong row population fix(dash): correct four money figures computed over the wrong row population, and stop activating ping schedules off partially-priced cells Sep 1, 2026
@OsherElhadad
OsherElhadad merged commit b193ff8 into main Sep 1, 2026
4 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Sep 1, 2026
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