Skip to content

feat(dash): learn the 5-hour limit's token weights (#1047) - #1068

Merged
amiddavid merged 8 commits into
mainfrom
feat/fivehour-weights
Nov 11, 2026
Merged

amiddavid merged 8 commits into
mainfrom
feat/fivehour-weights

Conversation

@amiddavid

Copy link
Copy Markdown
Collaborator

Behavior change (needs a human yes before merge). On a Claude subscription with enough history, two figures use learned 5-hour weights in place of API prices:

Who it affects: members and local proxies on a Claude subscription, and only after the fit passes its gate. Managers, API-key, Bedrock and Vertex users, and hosted mode: no change.
Old: estimate at API-price weights, Forecast at API-price weights. New: estimate at learned 5-hour weights (from N requests), Forecast at learned 5-hour weights (from N requests), in API dollars.
Fallback: below the gate, or on any error in the read or the fit, both figures and labels stay exactly as today. There is no switch; a fit that fails the gate is the off state.

Fixes #1047

Summary

What changed

  • dash/fivehourfit.go (new, pure): FitFiveHourWeights(rows, price).
    1. Rows with the same limit_5h_reset form one window, in time order.
    2. A row where the whole-percent share changes is a change point: the true usage crossed that percent within one request. This removes most of the whole-percent rounding error.
    3. A span runs from one change point to the next one at least 2 percents higher. Its change comes from the tokens billed between them.
    4. Lawson-Hanson non-negative least squares fits weights for input, cache read, 5-minute write, 1-hour write and output.
    5. Traffic outside the proxy (claude.ai, another machine) adds share with no tokens on our rows, so it can only push a span up. The fit drops spans with a residual above 3.5 robust standard deviations (MAD), at most 20% of spans, and fits again.
    6. It is not known whether a row's header counts the row itself. The fit runs both ways and keeps the one with the smaller error. The answer says which (header_after_row).
    7. A tier it cannot learn (too few spans, or a relative standard error above 0.5) takes its API price, scaled to the account's own spend. Example: input tokens are too few in agent traffic to learn.
  • The gate: at least 200 requests, 3 windows and 30 spans; fit error at most 0.25 (RMS span error over the mean span change); a learned cache-read weight and one learned cache-write weight. Below it: ok: false and a reason.
  • dash/fivehourweights.go (new): the row read (numeric columns and the model only, last 14 days, at most 100,000 rows, on the limit_seen partial index), the per-account cache, the endpoint, and window_ping (the pings' tokens in the open window, so the estimate can net them as the dollar one does).
  • dash/keepalive.go: the recommendation replay takes a scale for the saving and the ping cost. On the caller's own subscription with a passing fit, /api/keepalive/recommend adds learned (yes/no, range, requests, windows). The API-price fields do not change. The refusal text moved into recRefusal, unchanged.
  • dash/ui/savings.js: fiveHourLearnedPct (100 × Σ (saved − caused − pings) × weight, same floors and cap), weightsLabel, forecastView.
  • dash/ui/app.js: 3 small edits. The Overview fetches the weights with the window stats. renderKADecision uses forecastView for the range and the label line. The other "at API-price weights" lines (ledger tiles, tables) are not touched, to stay clear of dash: Cache strategy tab tables still show dollars on a subscription #1048.
  • Docs: a "Learned 5-hour weights" section in docs/dashboard.md, and a row in docs/data-dependence.md.

How it was tested

Synthetic traffic with known weights that are not the API mix (cache reads weigh one third of the API ratio). Whole-percent shares, 1-8% of requests as cold writes.

Case Requests / windows / spans Fit error Cache read 5m write Output 1h write
Clean 1,079 / 8 / 286 0.124 8.7% off 5.7% off 3.5% off price fallback, 19% off
Header before its row 1,087 / 8 / 288 0.115 14.1% off 6.2% off 4.8% off price fallback
Outside traffic (3% of requests add a burst up to 3%) 1,316 / 10 / 346 (28 dropped) 0.134 18.5% off 3.8% off 3.8% off price fallback
Coarse steps (about 40 requests per percent) 8,955 / 6 / 275 0.069 within 15% within 15% - -
Half on the 1-hour cache 1,390 / 12 / 400 0.113 3.2% off 5.3% off 7.2% off learned, 4.4% off
  • The fit found the header alignment in both directions.
  • Clean case forecast scale: save_5m 1.23, save_1h 1.03, ping 0.45 (pings cost less than API prices say, as the true weights do).
  • Gate cases, all refused with the expected reason: no rows; 1 window (715 requests); 138 requests; pure noise (fit error 0.44); no cache writes ("no cache-write weight could be learned"); no prices and an unlearnable tier.
  • Endpoint test: own account, manager's ?tenant=* reads their own, {} for an API key, cache holds within 15 minutes, window_ping with since, thin history gives no weights.
  • Recommendation test: scale 1 equals the API-price range; costly pings give a learned COST refusal and leave the API-price fields as they were; a failed fit adds nothing.
  • node --test dash/*.test.mjs: 37 pass (3 new: the learned estimate and label, 6 fallback cases, the forecast view).
  • Box: gofmt -l clean, go vet ./dash/... clean, ./dash/... with -race in two halves: ^Test[A-H] ok (371 s). ^Test[^A-H] found 1 failure, TestOverviewSubscriptionHeadlineIsWired (a wiring test that pins the old headline call); the test is updated and passes with -race. No other failure.

Data dependence

Metadata only. The fit reads numbers already stored on each request row: the 5-hour share and reset time, the billed tokens by tier, the time and the model name. It reads no text and stores nothing new; the fit lives in memory for 15 minutes. New row in docs/data-dependence.md; "Decided by" needs the owner's confirmation before merge.

Open questions

  1. No real-data check yet. The local proxies run a version from before feat(proxy): record the subscription limit headers and serve GET /api/me/limits #991. The first real fit should be checked against a few known windows before we trust the label.
  2. Models. The fit uses one weight per tier for all models. If the limit weighs Opus and Sonnet tokens differently, a mixed account fits worse; the fit error gate should catch a large mismatch. A per-model fit needs more data.
  3. Input weight. Agent traffic has too few fresh input tokens to learn its weight. It falls back to the API price, scaled. Its effect on both figures is small.
  4. Forecast unit. The learned forecast stays in "API dollars" (dollars at API input prices, with tiers weighed as the limit weighs them). A range in "% of the 5-hour limit" is possible later.
  5. Manual pings are not netted in the learned estimate; only the cache strategy's automatic pings are.

🤖 Generated with Claude Code

On a Claude subscription, the dashboard now learns how much of the
5-hour limit one token of each kind uses. It fits non-negative weights
per tier by least squares over spans between changes of the stored
5-hour share. A gate (rows, windows, spans, fit error, learned read and
write weights) decides if the fit is good enough.

- GET /api/me/fivehour-weights serves the fit, cached 15 minutes.
- The Overview's 5-hour estimate and the Cache strategy forecast use
  the learned weights when the fit passes the gate. Otherwise they keep
  the API-price figures and labels.

Fixes #1047

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
The Overview headline now passes the fit, and the Cache strategy
decision row reads the forecast through forecastView.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.322 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 e235b79d3e4b blocking

Verdict: blocking

Findings

  1. dash/ui/app.js:9902 — the "Which setting should I use?" panel still renders the API-price forecast, so the Keep-alive tab can show two opposite verdicts
    • What fails: on a subscription whose fit passed the gate, renderKADecision (app.js:9125) shows the learned forecast through forecastView. loadKARecommend (app.js:9889–9960) renders the same recommendation from the raw payload, with no forecastView and no weight label. When the two forecasts disagree, the tab answers one question two ways. Example: the API-price interval spans zero (rec.refused = "cannot tell this apart from zero") while the learned one is positive. The top panel then says "Yes, it should pay for itself, $1.50 to $4.00, at learned 5-hour weights". The panel below says "Not enough history to recommend: your own history cannot tell this apart from zero", plus an "Use these values in Settings" button. The reverse also happens: a learned COST refusal under an API-price yes.
    • Proof: renderKADecision merges rec.learned via forecastView (savings.js:140–160); loadKARecommend reads rec.refused, rec.lo_usd, rec.hi_usd, rec.idle_seconds, rec.max_pings straight off the raw payload (app.js:9902–9960). Both panels sit on the same tab (#ka-decision at index.html:640, #ka-recommend at index.html:773). The tab's own comment (app.js:9183–9185) names this exact failure: "Rendering it only here is how the refusal came to sit 2,900 px under a green 'Winner' tile that contradicted it." The tests cover forecastView itself (savings.test.mjs) and its use in renderKADecision (savingsparts_test.go), but nothing covers loadKARecommend. docs/dashboard.md says "the yes or no and the range come from learned" without limiting it to one panel, and does not list this panel under "What stays in dollars".
    • Fix: run the raw payload through forecastView(rec, kaState.sub) in loadKARecommend too, and label the detail panel's figures with the weight basis (learned or API-price). Or state in docs that this panel stays at API prices, and label it "at API-price weights".

Non-blocking

  • dash/fivehourfit.go:139–141 — rows with the same millisecond stay in reverse order. FiveHourRows returns ORDER BY r.ts DESC, r.id DESC; the per-window sort.SliceStable on TsMs only sorts ascending, so equal timestamps keep the newest row first. Two requests in one millisecond with different shares then read as a fall-then-rise, and the "share fell" reset discards those spans. Conservative (it drops data, never bends the fit), but an id on FiveHourRow and a second sort key would fix it.
  • dash/fivehourweights.go:96–126 — no single-flight on the fit. The API has jsonInflight for its other caches. N concurrent first loads after the 15-minute TTL each read up to 100,000 rows and run the fit. Wasteful, not wrong: each computes the same answer.
  • dash/fivehourfit.go:243–252 — the outlier drop takes spans in list order, not by size. When more than fhMaxDropShare qualify, the first 20% encountered are dropped and larger residuals later in the list stay. The second fit round sees them; the effect is a slightly worse fit error, which the gate catches.
  • dash/fivehourweights.go:165–171 — a failed ping read discards the whole fit. On a PingTokensSince error the endpoint replaces body.FiveHourFit with a bare reason, dropping requests, windows and fit_error too. The UI cannot tell "pings failed" from "not enough data" except by the reason string. The comment says this is deliberate; noting it for the record.
  • docs/data-dependence.md:244 — the row says "Decided by: David Amid, #1047 (to confirm before merge)". Per CLAUDE.md the human must confirm the data dependence before merge. The row is metadata-only and states its dependence in plain words, so the row itself is right; the confirmation must actually happen before merge.

What I checked

  • Read both commits in full: the fit (dash/fivehourfit.go), its wiring (dash/fivehourweights.go, dash/api.go, dash/keepaliveapi.go), the forecast path (dash/keepalive.go), the UI (dash/ui/savings.js, dash/ui/app.js), the docs (docs/dashboard.md, docs/data-dependence.md) and every test file.
  • Verified the fit's math by hand: change-point detection, the two header alignments (a+1..b vs a..b-1 are the correct token windows for each), span accumulation, the outlier drop (upward-only residuals match outside traffic), NNLS column scaling, and the relative standard error via (XᵀX)⁻¹. Checked fhFit's loop: the final weights always match the final kept set; kept can never empty (max 20% dropped); fitErr cannot be NaN or Inf when spans exist.
  • Verified the gate's order and its fallbacks: unlearned tiers take k·pbar[j] only with a price list; without one the gate fails rather than guess, except an absent output tier. Checked the forecast ratios' algebra (weights over k over API price).
  • Verified the SQL against dash/schema.go: every column exists; MAX(a, b) is SQLite's scalar max; the partial indexes on limit_seen fit both queries. Verified autoPing excludes manual pings, so the Overview estimate nets only the strategy's own pings, and that the lean tokens.saved/caused cover agent rows only (ping rows store zeros), so the ping subtraction is not a double count.
  • Verified tenant scoping: meFiveHourWeights forces the caller's own tenant before ownSubscription; a manager's ?tenant=* or ?tenant=<other> gets no fit in the recommend; the no-auth local proxy reads its single tenant under the "\x00all" key. Both new routes are scopeTenant.
  • Verified fail-open on every path I could find: read errors, fit panics (recovered and cached as a failed fit), a missing pricer, a fit below the gate — each leaves the API-price figures in place, and the JS tests cover those fallbacks.
  • Verified the JS arithmetic in savings.test.mjs by hand (3.15% checks out) and the forecastView merge; traced renderKADecision, loadKARecommend, loadOverviewLimits and loadKeepAlive for races between the ledger, the subscription flag and the recommendation (the Promise.all ordering holds).
  • Did not run tests: live tests are not approved for this review.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.322 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 e235b79d3e4b approve

Verdict: approve

Findings

None. I could not prove a wrong behavior, a data loss, a broken fail-open path or a security problem.

Non-blocking

  • dash/fivehourfit.go:546 (fhRelSE) — the standard errors run on the unscaled matrix. fhNNLS scales its columns to unit RMS because token counts are large; fhRelSE builds XᵀX from raw token counts (entries up to ~1e16) and solves with gaussSolve's absolute 1e-12 pivot test. On real data, where input and cache-read counts correlate, the 5×5 solve can lose precision, so rel_se and the learned flag behind the 0.5 gate may be arbitrary. It fails safe either way (an unlearned tier takes the scaled API price). Reuse the NNLS column scaling here too.
  • dash/fivehourfit.go:196 (fhSpans) — a fall inside a window biases the next span down. A fall resets the span start, but the rise that follows must also climb back over the fall. Its dy then under-states the tokens' effect, and the outlier test drops only UP residuals, so the span stays. Rare by the code's own comment. A downward residual also moves the MAD, so the fit degrades gracefully.
  • dash/fivehourweights.go:91 — sql.ErrNoRows cannot happen. PingTokensSince is a SUM over a filtered scan; it always returns one row. The branch is dead. Any real error replaces a passing fit with ok: false, which is the documented fail-open, so only the dead branch is worth removing.
  • dash/fivehourweights_test.go:71 — the ping read's tenant isolation is not tested. The test has one ping, on tenant "a". A ping on tenant "c" since the same start would prove PingTokensSince keeps tenants apart. The SQL does filter by tenant, so this is a test gap only.
  • dash/fivehourweights.go — the first fit after each 15-minute TTL runs under the default route timeout. /api/me/fivehour-weights is in neither cachedRoutes nor routeBounds. The read is bounded (100,000 rows, limit_seen partial index) and cached, so this is probably fine; note it if the first load times out on a large account.
  • dash/ui/savings.js:125 — a learned estimate at or below zero falls back to the API-price estimate. The label stays honest ("estimate at API-price weights"), and the test pins this on purpose. A reader may still wonder why the figure is positive when the learned weights said it was not. A future line "the learned weights say no saving in this window" would remove the doubt.

What I checked

  • The fit, line by line (dash/fivehourfit.go): window grouping and sorting; change-point detection against whole-percent shares; the two header alignments and their token ranges (rows a+1..b vs a..b-1 — both correct for their semantics); the fhMinSpanStep accumulation and the fall reset; fhFit's three-round outlier drop (the final weights always match the final kept spans; the 20% drop cap holds across rounds); fhNNLS column scaling; lawsonHanson (the passive-set inner loop keeps x >= 0; gaussSolve copies G, so iterations do not corrupt it); fhRelSE's (XᵀX)⁻¹ read; the gate order and every refusal reason; the price fallback (k, pbar) and the ForecastScale ratios, including the pt <= 0 and negative-numerator edges.
  • The read and the endpoint (dash/fivehourweights.go): the SQL against dash/schema.go — all token columns are NOT NULL, so MAX(cache_write - cache_write_1h, 0) cannot go NULL; the partial indexes on limit_seen cover the query; MAX(a, b) is SQLite's scalar max. Scope: the handler forces the caller's own tenant before ownSubscription, the same pattern as meLimits, so a manager's ?tenant=* and ?tenant=<other> cannot read another account's weights. The route is declared scopeTenant in the table both scoping tests walk. Fail-open: a read error, a panic in the fit, or a failed ping read all give ok: false / {}, and the UI keeps API prices (fiveHourLearnedPct checks fit.ok === true). The cache: keyed by tenant (or \x00all for a single-tenant proxy), 15-minute TTL, mutex-guarded, failure-tolerant.
  • The recommendation (dash/keepalive.go, dash/keepaliveapi.go): with fit == nil the net closure multiplies by all-1 scales, so the API-price interval is byte-identical to before (also x * 1.0 == x in IEEE-754, and bootstrapCI reseeds per call) — the golden endpoint is safe. out.Learned is set before the API-price refusal check, so a dollar refusal still carries the learned view, and a learned refusal does not leak into out.Refused. recRefusal is the old text unchanged. The handler passes a zero fit when the account is not the caller's own subscription.
  • The UI (dash/ui/savings.js, dash/ui/app.js): fiveHourLearnedPct's arithmetic against the .mjs test numbers (3.15%); the floors and cap match fiveHourSavedPct; forecastView's merge and label; state.sub.fit lifecycle in loadOverviewLimits (sequence-guarded, failure keeps API prices); w.tokens really is in the lean=1 payload (dash/overview_lean.go's leanAgg), so the wiring is not dead; the wiring greps in savingsparts_test.go match the app.js source.
  • Repo rules: fail-open holds on every new error path; the data-dependence row is added with a "Decided by … to confirm" note and the PR states the dependence and the behavior change at the top; /stats fields untouched; the keep-alive's own behavior (what is sent, when) unchanged — only the forecast's display weights.
  • Tests: read fivehourfit_test.go, fivehourweights_test.go and savings.test.mjs in full. The sim is honest (whole-percent quantization, header lag, outside bursts, 1-hour mix, coarse steps), and the gate cases cover each refusal reason. I did not run them (live tests not approved).

…d errors

Review round 1 on #1068:
- "Which setting should I use?" now reads the recommendation through
  forecastView, as the decision row does, with the same weight line.
  The fixed-count comparison and the 3-ping offer are API-price
  figures, so they do not show beside a learned range.
- fhRelSE solves on the same scaled columns as the fit, and the
  elimination pivot test is relative.
- FiveHourRow carries the row id; rows in one millisecond sort by it.
- The fit runs under single-flight. A read error is not cached.
- PingTokensSince: no dead ErrNoRows branch; a test pins tenants apart.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
…ytes

The panel grew with the learned forecast, and the fixed cut no longer
reached the "Nothing is saved" line. The check now reads to the
function's closing brace.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 1 answers. All fixes are in commit 08435ec.

Reviewer 2 (blocking)

  1. Two panels, two verdicts: fixed (08435ec). loadKARecommend ("Which setting should I use?") now reads the recommendation through forecastView, the same function the decision row uses. It also shows the same weight line (data-testid: ka-rec-weights).
    • The panel now waits for the subscription flag. A recommendation that arrives first cannot render at API prices.
    • With a learned forecast, the fixed-count comparison (fixed_k) and the 3-ping offer (alt_max_pings) do not show. They are API-price figures. forecastView leaves them out, and savings.test.mjs pins this.
    • New wiring pins are in savingsparts_test.go. docs/dashboard.md now says both panels use the learned forecast.

Reviewer 2 (non-blocking)

  • Rows in one millisecond: fixed (08435ec). FiveHourRow has the row id. Each window sorts by (ts, id) ascending. TestFiveHourFitOrdersOneMillisecondByID gives the rows newest first and oldest first, and checks the same fit both ways.
  • No single-flight: fixed (08435ec). The fit runs under a.jsonInflight with its own key. A read error is no longer cached for 15 minutes, because it can be the leading caller's own cancelled request.
  • Outlier drop in list order: kept as a note. The second fit round sees the spans that stay, and the fit-error gate catches a worse fit. Sorting by residual is a later refinement.
  • A failed ping read drops the whole fit: kept, on purpose. The page cannot subtract the pings without them. ok:false keeps the API-price estimate, which is the documented fail-open. The reason string says what failed.
  • Data-dependence row needs the owner's yes: agreed. It stays marked "to confirm before merge".

Reviewer 1 (non-blocking)

  • fhRelSE on unscaled XᵀX: fixed (08435ec). The standard errors use the same column scaling as the fit (fhColScale): Var(w_j) = σ²[(X̃ᵀX̃)⁻¹]_kk / d_k². The pivot test in gaussSolve is now relative: 1e-12 of the largest entry. In TestFiveHourRelSEIsScaleFreeOnCorrelatedColumns, input follows cache read within 5%. The test checks that rel_se is the same at token units 1, 1e-9 and 1e4 (input 0.779, cache read 0.080, write 0.003). The synthetic fit results in the PR body do not change.
  • Dead sql.ErrNoRows branch: fixed (08435ec). It is removed. The endpoint test now has a ping on another tenant in the same window. Tenant a still reads only its own 90,000 rd.
  • A fall inside a window biases the next span down: kept as a note. A fall inside one window is rare, and a downward error widens the MAD, so the fit degrades gracefully.
  • First fit runs under the default route timeout: kept as a note. The read is bounded (14 days, 100,000 rows, partial index). The result is cached and now single-flight. We revisit if a large account times out.
  • A learned estimate at or below zero falls back to the API-price one: kept as a note. The label stays honest. A "the learned weights show no saving in this window" line can come later.

Tests on c9ab515

  • node --test dash/*.test.mjs: 37 pass.
  • On the box: gofmt -l is clean and go vet ./dash/... is clean.
  • ./dash/... with -race, first half (^Test[A-H]): ok, 367 s.
  • Second half (^Test[^A-H]): ok, 494 s.
  • One failure came up in the second half and is fixed in c9ab515. TestTheRecommendationRendersARangeAndRefusesThinHistory read only the first 4,000 bytes of loadKARecommend, and the longer panel pushed its "Nothing is saved" line past that cut. The test now reads to the function's closing brace.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.322 offload-review skill, @amiddavid's session resumed 1 of 2 2 of 2 c9ab5150c3fb approve

Verdict: approve

Findings

None in the new commits. I checked every fix below and could not prove a wrong behavior.

Earlier findings, and their state

  • Reviewer 2, finding 1 (two panels, two verdicts) — fixed, and I verified it myself. loadKARecommend now awaits the subscription flag with the recommendation (Promise.all), runs the payload through the same forecastView, and shows the same weight line (ka-rec-weights). With a learned forecast, fixed_k and alt_max_pings are stripped so no panel mixes the two bases; savings.test.mjs pins that. I traced the render order: the detail panel can no longer paint at API prices first, and the decision row only renders when kaState.ledger is set, which happens in the same block that sets kaState.sub — so the two panels cannot disagree. Docs updated.
  • Reviewer 2, non-blocking (ms ordering) — fixed. FiveHourRow carries the row id; each window sorts by (ts, id); FiveHourRows selects r.id. The new test fits the same rows newest-first and oldest-first and wants the same answer.
  • Reviewer 2, non-blocking (no single-flight) — fixed, with one new note below (the leader's request context).
  • Reviewer 2, non-blocking (outlier drop in list order) — rejected with a reason I accept. The spans that stay feed the next round and the fit-error gate catches the damage. A size-ordered drop is a refinement, not a fix.
  • Reviewer 2, non-blocking (a failed ping read drops the fit) — rejected with a reason I accept. Without the pings the page cannot net them, so the estimate would be wrong rather than absent. ok: false is the documented fail-open.
  • My round-1 note (fhRelSE unscaled) — fixed, and the algebra is right. The standard errors now solve on the columns scaled by fhColScale, with Var(w_j) = σ²[(X̃ᵀX̃)⁻¹]_kk / d_k² — the code computes sqrt(σ²·v_k)/d_k/w_j, which matches. The gaussSolve pivot test is relative (1e-12 of the largest entry, over the coefficient columns only). The new scale-free test checks rel_se at token units 1, 1e-9 and 1e4 on correlated columns.
  • My round-1 note (dead ErrNoRows branch) — fixed. Removed.
  • My round-1 note (tenant isolation of the ping read untested) — fixed. A 7,000,000-token ping on tenant "c" now sits in the same window; tenant "a" still reads only its own 90,000.
  • My round-1 notes (fall bias, route timeout, learned ≤ 0 fallback) — kept as notes, with reasons I accept. All three fail toward the API-price figures.
  • Data-dependence confirmation — still open, on purpose. The row stays "Decided by: David Amid, #1047 (to confirm before merge)". The owner must say yes before merge; that is a person's step, not a code defect.

Non-blocking

  • dash/fivehourweights.go:107 — the single-flight runs on the leader's request context. computeFiveHourFit reads through a.db(r), which binds FiveHourRows to the leader's r.Context(). If the leader's client disconnects mid-read, the query fails with a cancelled context and singleflight hands "the rows could not be read" to every concurrent waiter. That is the exact shape dash/api.go:404-414 documents and removed for jsonCache ("one reader closing a tab failed the tab for everyone else"). The blast radius here is small and fails open: the waiters get ok: false and keep API prices for one load, the failure is not cached, and the next reader retries. The commit message names the caching half of this but not the waiter half. A detached context with its own timeout, as line 419 does, would close it.

What I checked

  • Last review: round 1, e235b79, 2026-11-11T07:05:15Z
  • New commits read: 2 — 08435ecc fix(dash): one forecast on both Cache strategy panels, scaled standard errors; c9ab5150 test(dash): read the whole recommendation panel, not its first 4000 bytes
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt)
  • New items since my last review:
    • Reviewer 2's round-1 review (blocking, 1 finding, 5 non-blocking) — checked each against the fix commit; the finding is fixed, three non-blocking items fixed, two rejected with reasons I verified as right.
    • The author's round-1 answers (07:37:34Z) — every "fixed" claim re-verified in the code, every "kept" reason checked.
    • Commit 08435ecc — full diff of all 9 files plus the code around each change: forecastView in loadKARecommend (both panels read the same view; fixed_k/alt_max_pings stripped and the panel's own guards handle their absence); fhColScale extraction; the scaled fhRelSE (algebra verified above); the relative pivot in gaussSolve (tolerance built from the coefficient columns only, 1e-300 floor for an all-zero matrix); the (ts, id) sort and the r.id column; the single-flight and the read-error no-cache path; the ErrNoRows removal; the tenant-isolation ping test; the new wiring pins in savingsparts_test.go (each string matched against the app.js source).
    • Commit c9ab5150 — test-only; the brace cut (\n}\n) finds the function's end because no nested brace sits at column 0; the panel's own tests then cover the lines the old 4,000-byte cut lost.
    • The fit's math from round 1 was re-verified where the commit touched it: fhNNLS and fhRelSE now share the same scaling, and solvePassive/lawsonHanson behavior is unchanged.
    • The single-flight key "fivehour\x00"+key cannot collide with a jsonCache flight key: those are prefixed with a %p pointer, which never formats as fivehour.
  • Did not run tests: live tests are not approved for this review. The author reports node --test 37 pass and -race clean on both halves at c9ab5150.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.322 offload-review skill, @amiddavid's session resumed 2 of 2 2 of 2 c9ab5150c3fb approve

Verdict: approve

Findings

None. My round-1 finding is fixed correctly, and the two new commits introduce no defect I can prove.

Round-1 findings

  1. Two panels, two verdicts — fixed (08435ec). loadKARecommend now runs the payload through forecastView(raw, sub) (app.js:9897), the same function the decision row uses, and shows the same weight line (ka-rec-weights, app.js:9905). The panel waits for the subscription flag: loadKeepAlive passes subP (app.js:9048) and the panel reads it in its own Promise.all (app.js:9889), so a recommendation that lands first can no longer render at API prices. The API-price comparisons (fixed_k, alt_max_pings) are stripped from the merged payload (savings.js:148–150) so no panel mixes the two bases, and savings.test.mjs pins that. savingsparts_test.go pins the wiring, and docs/dashboard.md now names both panels. Checked the merged payload field by field: the refusal banner, the range tile and the suggested setting all read the learned values; the service-wide "For scale" line stays service-wide; the "measured tie" sentence that still shows when alt_max_pings is stripped states its own basis ("rather than for a dollar reason"), so it does not mix figures.

Non-blocking

  • dash/fivehourweights.go:105–115 — the single-flight leader's request context also carries the price lookups. readFailed excludes a failed row read from the cache, but not a price lookup degraded by the leader's cancelled context (a.priceFn(r) closes over r.Context(); the litellm pricer's refresh can fetch). Such a fit can be cached for 15 minutes as below-gate. It fails open (API prices), the exposure needs a stale-price fetch cancelled mid-fit, and the pre-single-flight code had the same cache-a-degraded-fit exposure. Noting it for the record, with the read-error handling as the pattern if it ever bites.
  • docs/data-dependence.md:244 — the row still says "to confirm before merge". The human's confirmation of the data dependence must happen before merge, per CLAUDE.md. Unchanged from round 1; nothing in the PR breaks it.

What I checked

  • Last review: round 1, e235b79, 2026-11-11T07:04:09Z.
  • New commits read: 2 — 08435ecc fix(dash): one forecast on both Cache strategy panels, scaled standard errors; c9ab5150 test(dash): read the whole recommendation panel, not its first 4000 bytes.
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three saved files).
  • New items since my last review: the author's round-1 answer comment (07:37:34Z) and the two commits above. Both commits read line by line; every claim in the answer comment checked against the code.

On the fixes:

  • Both-panels fix (08435ec): read the whole new loadKARecommend (app.js:9884–9975) and renderKADecision's use of it; traced the ledger/subscription/recommendation races — the panel and loadKeepAlive share one subP promise, and renderKADecision(kaState.ledger, raw) is only reached with kaState.ledger set, which loadKeepAlive sets after its own Promise.all of the same flag. Verified forecastView's undefined assignments really hide fixed_k and alt_max_pings in both display branches.
  • Scaled standard errors (08435ec): checked the algebra — with X = X̃·D, (XᵀX)⁻¹ = D⁻¹(X̃ᵀX̃)⁻¹D⁻¹, so Var(w_j) = σ²[(X̃ᵀX̃)⁻¹]_kk / d_k² and the new sqrt(σ²·v_k)/scale[k]/w[j] is right; σ² comes from raw residuals and is scale-invariant, and the whole expression is invariant under a unit change of the token counts, which is what TestFiveHourRelSEIsScaleFreeOnCorrelatedColumns pins at units 1, 1e-9 and 1e4. Checked gaussSolve's relative pivot (1e-12 of the largest coefficient entry, row[:m] excludes the augmented column) and that each per-k solve copies G, so elimination cannot corrupt the shared matrix.
  • Row-id ordering (08435ec): FiveHourRows selects r.id; the per-window sort.Slice on (TsMs, ID) is a total order, so the fit no longer depends on the read's DESC order. TestFiveHourFitOrdersOneMillisecondByID feeds the same rows newest-first and oldest-first and requires the same spans, requests and weights.
  • Single-flight (08435ec): jsonInflight.Do("fivehour\x00"+key, …) — no key collision with the other caches' %p\x00%s format; the panic recover sits inside the flight function, so a panicking fit never escapes singleflight; readFailed keeps read errors out of the 15-minute cache; no lock is held across the flight.
  • Ping read (08435ec): the dead sql.ErrNoRows branch is gone and the database/sql import with it; the new other-tenant ping (7M rd on tenant "c") pins PingTokensSince to the caller's tenant.
  • Test cut (c9ab515): the whole-function read stops at the first \n}\n after loadKARecommend's start; every nested brace in that function is indented, so the cut is the function's own closing brace, and the "Nothing is saved" pin now sits inside the checked body.

On the kept items: the author kept the outlier-drop order, the whole-fit discard on a failed ping read, and the fall-inside-a-window bias, each with a reason I checked and accept — all three degrade toward a worse fit error or the documented fail-open, never toward a wrong confident figure. Reviewer 1's round-1 items are addressed by the same commits (scaled fhRelSE, dead branch, tenant test) or kept with reasons I accept; I verified each fix myself above rather than taking the reply on trust.

Did not run tests: live tests are not approved for this review. The author reports green ./dash/... with -race and the node tests on c9ab5150.

David Amid confirmed the behavior change and the data-dependence row
on 2026-11-11.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
Clean merge.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Owner decision (David Amid, 2026-11-11): approved.

  • The behavior change: on a subscription with a fit that passes the gate, the Overview 5-hour estimate and the Cache strategy forecast use learned weights. Below the gate, nothing changes.
  • The data-dependence row: metadata only, nothing new stored.

Commit 1b28582 sets the row's "Decided by" to "David Amid, #1047 (2026-11-11)". Then a clean merge of origin/main. Round 3 re-checks this delta.

Round 2 notes kept, with reasons:

  • Single-flight on the leader's context (reviewer 1). Fails open: the waiters keep API prices for one load, and the failure is not cached. Kept as a note.
  • A price lookup cancelled mid-fit can be cached as below gate (reviewer 2). Fails open, needs a cancelled stale-price fetch, and the code before single-flight had the same exposure. Kept as a note.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.322 offload-review skill, @amiddavid's session resumed 2 of 2 3 of 3 b6617e3e62ad approve

Verdict: approve

Findings

None. The round-3 delta is one docs line and a clean merge of origin/main. Both check out.

Earlier findings, and their state

  • My round-1 finding (two panels, two verdicts) — fixed in round 2, unchanged since. The fix (08435ecc) is in the merged head word for word; I re-read the merged loadKARecommend and forecastView.
  • My round-2 non-blocking (data-dependence confirmation pending) — resolved. Commit 1b28582b sets the row's "Decided by" to "David Amid, #1047 (2026-11-11)", and the owner's decision is on the PR (comment at 08:14:01Z: behavior change and metadata-only row both approved). This was the last open condition from my rounds.
  • My round-2 non-blocking (a cancelled price lookup can cache a below-gate fit) — kept by the author, reason accepted. It fails open to the API-price figures, needs a cancelled stale-price fetch, and the code before single-flight had the same cache exposure. Reviewer 1's round-2 note (the waiter half of the leader's context) is the same shape; the author's reason there is right too: one uncached failed load, waiters keep API prices, the next reader retries.

The round-3 delta

  1. 1b28582b (docs). One line in docs/data-dependence.md: "(to confirm before merge)" becomes "(2026-11-11)". Nothing else changes.
  2. b6617e3e (merge of origin/main). Verified clean, not just claimed clean: git merge-tree --write-tree 1b28582b d865b250 produces tree 5d673f22…, byte-identical to the merge commit's own tree. No hand resolution.
    • Main's only change inside this PR's files is a comment fix in dash/ui/savings.js (the strategyName source note, from #1055). It touches no code, and the merged file carries both it and this PR's fiveHourLearnedPct / forecastView unchanged.
    • git diff c9ab5150..HEAD -- dash/ docs/dashboard.md docs/data-dependence.md shows exactly those two changes and nothing else, so the merge did not alter any line of the code I approved in round 2.
    • The rest of what the merge brings (the agent/ package from #1029, plugin version bumps, tests) sits outside this PR's files and was reviewed in its own PRs; nothing in it touches the dashboard, the fit's SQL, or the UI panels this PR changes.

What I checked

  • Last review: round 2, c9ab515, 2026-11-11T07:42:04Z.
  • New commits read: 2 — 1b28582b docs: record the owner's yes on the learned 5-hour weights row; b6617e3e Merge origin/main into feat/fivehour-weights. (The other commits in git log c9ab5150..HEAD are main's, arrived through the merge.)
  • Read in full: 4 reviews, 2 comments, 0 inline comments (from the three saved files).
  • New items since my last review:
    • Reviewer 1's round-2 review (07:41:54Z, approve) — read in full; its one non-blocking note checked and covered above.
    • The author's round-2 answers and test report (07:37:34Z) — already covered in round 2; re-checked nothing new was added.
    • The owner's decision comment (08:14:01Z) — the approval this PR's data-dependence row needed.
    • Commits 1b28582b and b6617e3e — verified as described above: the docs line, the byte-identical clean-merge tree, the only-in-PR-files diff from main, and the full git diff d865b250..HEAD stat matching the files reviewed in rounds 1–2 plus that one docs line.
  • Did not run tests: live tests are not approved for this review. The author's round-2 report (./dash/... with -race both halves, node --test 37 pass, gofmt and go vet clean) stands at c9ab5150, and the merge changed no dash code.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.322 offload-review skill, @amiddavid's session resumed 1 of 2 3 of 3 b6617e3e62ad approve

Verdict: approve

Findings

None. The delta since round 2 is one docs line and a clean merge, and I could not prove a wrong behavior in either.

What changed since round 2, and its state

  • 1b28582b — the owner's decision is recorded. The data-dependence row now reads "Decided by: David Amid, #1047 (2026-11-11)" instead of "to confirm before merge". The PR comment (08:14:01Z) states the owner approved both the behavior change and the metadata-only row. This closes the process item reviewer 2 and I both flagged. The row's text is otherwise unchanged.
  • b6617e3e — merge of origin/main, verified clean. Main moved from 9d34f00f to d865b250 (the agent/ package, #1029, and the plugin bumps). I checked the merge three ways:
    • The PR's diff against the NEW base is identical, file by file and line count by line count, to its diff against the old base before the merge (sorted --stat outputs match exactly).
    • Main's only change inside the PR's 14 files is a one-line comment fix in dash/ui/savings.js (line 45), in a hunk disjoint from the PR's additions. The merge result carries both.
    • The PR's own files changed by nothing else between c9ab5150 and the merge, apart from the data-dependence line above.
  • My round-2 note (single-flight on the leader's request context) — kept by the author, and I keep accepting the reason. The waiters get ok: false for one load, the failure is not cached, and the next reader retries. Fails open.
  • Reviewer 2's round-2 note (a price lookup cancelled mid-fit can be cached as below gate) — I checked it myself and agree it is real but minor. computeFiveHourFit calls tierPriceFn(a.priceFn(r)) inside the flight, and a.priceFn(r) closes over the leader's r.Context(). A context cancelled between the row read and the price lookups gives priced = false, the gate can fail with "no API price", and readFailed does not cover that path — so the below-gate answer is cached for 15 minutes. It fails open (the screens keep API prices), the code before single-flight had the same exposure, and it needs a stale-price fetch cancelled at exactly that moment. A note, not a defect.

Non-blocking

  • Nothing new. The two open notes (leader-context single-flight, cancellable price lookup) are recorded above and in round 2; both fail toward the API-price figures, and the author has answered them with reasons that hold.

What I checked

  • Last review: round 2, c9ab515, 2026-11-11T07:41:54Z
  • New commits read: 2 — 1b28582b docs: record the owner's yes on the learned 5-hour weights row; b6617e3e Merge origin/main into feat/fivehour-weights
  • Read in full: 3 reviews, 2 comments, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt)
  • New items since my last review:
    • Reviewer 2's round-2 review (07:42:04Z, approve) — its one new note (a.priceFn(r) in the flight) re-derived from the code above; its round-1 fix re-verification needed nothing from me.
    • The author's owner-decision comment (08:14:01Z) — the decision is the human's; the recording commit matches it.
    • Commit 1b28582b — read in full; one line changes, nothing else in the file moves.
    • Commit b6617e3e — merge verified clean by the three checks listed above; the PR's own delta is untouched by it.
  • Did not run tests: live tests are not approved for this review. The author reported the dash tests and node tests green at c9ab5150; the merge commit changes none of the PR's dash files beyond main's one-line comment, which the dash wiring greps do not pin.

Two conflicts, both additions side by side; keep both:
- dash/ui/savings.js: the export list names this branch's
  fiveHourLearnedPct, weightsLabel, forecastView and #1065's
  kaSessionTokenCells, bandTokens, tierSeries.
- dash/savings.test.mjs: this branch's three tests, then #1065's two.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Nov 11, 2026
The go test time limit goes from 20m to 40m on the test and cover
targets. On main's CI, the dash package took 1140 s of the 1200 s
limit, so PRs that add dash tests (#1001, #1064, #1068) failed
build-test with "test timed out after 20m0s".

Behavior change: none (CI and local test limits only). Data
dependence: none. Follow-up: speed up or split the dash tests.

Reviews: 2 offload reviews (GLM), round 1, both approve at 0612436,
which is the PR head.

Signed-off-by: DAVID AMID <[email protected]>
Assisted-By: Claude Opus 5.5 <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Integrator note: #1082 is on main (3c876dc). It raises the go test time limit to 40m. The build-test failure here ("test timed out after 20m0s" in the dash package) came from the old limit. Please merge origin/main into this PR, so CI runs with the new limit.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.322 offload-review skill, @amiddavid's session fresh 1 of 2 4 of 4 18f449499b46 blocking

Verdict: blocking

The code is approved. One team request is open, and CI on this head is red. Merge the current
origin/main, and this PR is done from my side.

Findings

  1. Makefile (via the missing merge) — the head does not carry #1082, so build-test still runs at the 20-minute limit and fails
    • What fails: CI on this head runs go test -race -timeout 20m and fails: panic: test timed out after 20m0s, FAIL github.com/rossoctl/context-guru/dash 1205.872s (run 42993229567,
      job build-test). The integrator asked for this at 09:39:01Z: "#1082 is on main (3c876dc) …
      Please merge origin/main into this PR, so CI runs with the new limit." The head does not
      answer it.
    • Proof: git merge-base --is-ancestor 3c876dcb 18f44949 fails. The head's merge (18f4494,
      09:12:06Z) merged main at 27c0c40 (09:08:56Z). #1082 landed on main at 09:38:36Z, after the
      merge and 25 seconds before the integrator's comment. The head's Makefile still reads
      -timeout 20m; #1082 changes it to 40m and names this PR (#1068) as one that fails at 20m.
      The PR's mergeable_state is blocked; build-test on the head is failure.
    • Fix: merge the current origin/main (through 3c876dc or newer) into feat/fivehour-weights
      and push. No code change is needed. Everything this PR itself changes is approved below and
      in rounds 1–3.

Earlier findings, and their state

  • Reviewer 2's round-1 finding (two panels, two verdicts) — fixed in 08435ec, and I re-verified
    it in the merged head.
    Both renderKADecision (app.js:9137) and loadKARecommend
    (app.js:9974) read the payload through forecastView, and both show the same weight line. The
    merge changed none of it.
  • All non-blocking notes from rounds 1–3 — kept by the author, reasons still accepted. The
    single-flight leader context, the cancellable price lookup, the fall-in-window bias, the route
    timeout, the learned ≤ 0 fallback. All fail toward the API-price figures.
  • The data-dependence confirmation — closed in round 3 (owner's yes at 08:14:01Z, recorded in
    1b28582). Nothing in the round-4 delta touches it.

The round-4 delta: the merge of origin/main, checked

The four new commits are main's #1066, #1065, #1067 and the merge 18f4494. The branch's own
files (the fit, the weights endpoint, its tests) are byte-identical to what I approved at
b6617e3e; the merge delta touches none of them.

  1. The two hand-resolved conflicts are correct, and nothing else was hand-edited.
    git merge-tree --write-tree b6617e3e 27c0c406 gives tree aa7a22be…; git diff aa7a22be HEAD
    shows only the conflict-marker lines removed. So every other file is exactly git's own
    auto-merge.
    • dash/ui/savings.js: the export list now names both sides — this branch's
      fiveHourLearnedPct, weightsLabel, forecastView and #1065's kaSessionTokenCells,
      bandTokens, tierSeries. No export lost.
    • dash/savings.test.mjs: this branch's three tests, then #1065's two, with the closing brace
      restored. I read the seam in the merged file; the syntax is valid and both sides' assertions
      are intact.
  2. The auto-merged files that both sides touched are sound. dash/keepalive.go: this branch's
    changes sit at the recommend function (line 1996+), #1065's at the behaviour and sessions
    queries (lines 62–1080) — disjoint regions, no shared symbol. dash/ui/app.js and
    docs/dashboard.md: the hunks do not overlap, and I read the merged regions (the forecast
    panel, loadKARecommend, the "What stays in dollars" section) in full.
  3. Both sides' wiring pins hold in the merged app.js. I grepped every pinned string from the
    merged savingsparts_test.go — this branch's six (the state.sub.fit headline call, the
    fivehour-weights fetch, the two forecastView calls, ka-rec-weights, loadKARecommend(subP))
    and #1065's — against the merged app.js. Each matches exactly once.
  4. No symbol clash. #1065's TierTokens/TokenFlow live in dash/acctokens.go (pre-existing);
    this branch's ForecastScale is its own type. No duplicate definition in the dash package.
  5. #1066 and #1067 do not reach this branch's code. #1066 changes the keeper's refresh clock
    and the dash restart-grace seed; the branch's fit reads stored usage and limit columns, which
    those changes do not touch. #1067 adds the restored_tokens column and accountant operations;
    it is additive to the schema and to the Overview payload, and the lean w.tokens aggregate the
    branch's headline reads is unchanged.
  6. The merged docs stay coherent. The branch's "With learned 5-hour weights, the forecast uses
    them" follows #1065's "the forecast keeps dollars" text in one section, and the learned-weights
    section follows #1065's tables section. I read both.

Non-blocking

  • None new.

What I checked

  • Last review: round 3, b6617e3, 2026-11-11T08:16:46Z
  • New commits read: 4 — 62289d9a fix(keepalive): a ping that re-wrote the cache restarts the
    refresh clock (#1066); 8b311f10 feat(dash): on a subscription the Cache strategy tables show
    tokens (#1065); 27c0c406 fix(dash): count the fixed_restore copy in the saved figure (#1067);
    18f44949 Merge origin/main into feat/fivehour-weights
  • Read in full: 6 reviews, 3 comments, 0 inline comments (from .review-in-reviews.txt,
    .review-in-comments.txt, .review-in-inline.txt)
  • New items since my last review:
    • The integrator's comment (09:39:01Z) — checked, and it is finding 1: the head predates it and
      does not carry #1082; CI on the head is red at the old 20-minute limit.
    • Reviewer 2's round-3 review (08:16:45Z, approve) — read in full; it landed one second before
      mine, so I had not seen it. Its checks (clean merge, the docs line) match what I re-derived
      independently above. Nothing to add.
    • The four commits — read as described in "The round-4 delta": the merge verified against git's
      own auto-merge tree, both conflict resolutions compared hunk by hunk with both parents, the
      merged keepalive.go/app.js/savings.js/savings.test.mjs/savingsparts_test.go read in
      full around every seam, all wiring pins from both sides grepped against the merged app.js,
      #1066's and #1067's diffs read for interaction with this branch's fit, headline and forecast.
  • The PR's own delta against the new base (git diff 27c0c406..HEAD, 14 files) read in full; it
    is the code I approved in rounds 1–3, unchanged.
  • Did not run tests: live tests are not approved for this review. CI ran them on the head and
    failed only at the 20-minute limit, which is finding 1, not a test failure.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.322 offload-review skill, @amiddavid's session resumed 2 of 2 4 of 4 18f449499b46 blocking

Verdict: blocking

Findings

  1. Makefile:46,50 — the head still runs the tests at the 20-minute limit, so build-test fails on it; the integrator's requested merge of origin/main is not in the head
    • What fails: CI on head 18f44949 → build-test fails (conclusion failure, 09:40:16Z). The log says panic: test timed out after 20m0s and FAIL github.com/rossoctl/context-guru/dash 1205.872s. No single test fails; the suite runs out of time. The integrator asked for this at 09:39:01Z: merge origin/main, so CI runs #1082's 40-minute limit. The merge 18f44949 (pushed 09:12 UTC) merged main only up to 27c0c406, and #1082 (3c876dcb) landed on main at 09:38 UTC — after it. git merge-base --is-ancestor 3c876dcb HEAD fails, and the Makefile at HEAD still reads go test -race -timeout 20m on both the test and cover targets, which is what build-test runs (make cover).
    • Proof: check-runs on 18f44949 (build-test failure); the run's log (42993229567) with the panic and the dash package's 1205.872s; git log 27c0c406..origin/main lists 3c876dcb ci: raise the go test timeout to 40m (#1082); grep timeout Makefile at HEAD shows 20m on lines 46 and 50. #1082's own commit message names #1068 as one of the PRs that fail build-test this way.
    • Fix: merge origin/main again (its tip is now b125d4b3), so 3c876dcb lands, and push. No code change. The dash suite took 1205s, so it fits the 40-minute limit; the next CI run should turn green with no other change.

Earlier findings, and their state

  • My round-1 finding (two panels, two verdicts) — fixed in round 2, and the merge keeps the fix intact. I re-verified at this head: loadKARecommend still awaits the subscription flag with the recommendation and runs the payload through forecastView (app.js:9060, 9961); all 16 of the branch's wiring pins in TestKeepAliveTabSubscriptionTokensAreWired still match the merged app.js (I re-ran the pin checks mechanically against the comment-stripped source, as the test does).
  • Data-dependence confirmation — resolved in round 3 (1b28582b plus the owner's comment at 08:14:01Z). Unchanged since.
  • My round-2 non-blocking notes (the leader's request context in the single-flight; a cancelled price lookup cached as below-gate) — kept by the author, reasons accepted. Both fail toward the API-price figures; the merge changes nothing about them.

The round-4 delta, and what I checked on it

  1. 62289d9a (#1066, from main). Read the full diff: the refresh clock moves on a 2xx ping that read OR wrote the cache, in record1, the manual ping, both substitute paths, dash/capture.go and SeedGraceSessions. All changes sit in keepalive/, dash/capture.go and dash/grace_test.go; this branch's code does not call into any of them. No interaction with the fit, the forecast or the UI panels.
  2. 8b311f10 (#1065, from main). Read the full diff: token columns on the Cache strategy tables (dash/keepalive.go), kaSessionTokenCells / bandTokens / tierSeries (dash/ui/savings.js), the renders in app.js, the headers in index.html, the docs. Interaction with this branch is the real merge risk, so I checked it beyond the diff:
    • loadKeepAlive (app.js:9047–9079) sets kaState.sub before rest() starts every #1065 render, on both the success and the failure path (the flag promise never rejects; it catches to false), so no #1065 panel can paint in the wrong units.
    • The branch's 16 wiring pins and the four index.html label counts (5, 4, 2, and the Sessions table's 3) all still hold on the merged files — I re-ran the exact counting the merged test does, panel segment by panel segment.
    • The merged savings.js and app.js parse clean, and the merged savings.test.mjs parses with fit defined once and both sides' five tests present.
  3. 27c0c406 (#1067, from main). Read the full diff: the restore copy counted in the saved figure, the restored_tokens column, SafetyCost.RestoredTokens. It changes what tokens_after means on fixed-restore sessions, which is data this branch's fit reads — that makes the fit's input more correct, and nothing in the branch's named-column SQL breaks on an additive column. No code-path conflict.
  4. 18f44949 (the merge). Verified, not just read:
    • git merge-tree --write-tree b6617e3e 27c0c406 reproduces exactly two conflicts, as the message says; the actual merge tree differs from the auto-merge tree by conflict-marker lines only — the hand resolution is precisely "keep both sides", nothing more.
    • dash/ui/savings.js: one export list carrying both sides' names (fiveHourLearnedPct, weightsLabel, forecastView and kaSessionTokenCells, bandTokens, tierSeries); both function blocks present.
    • dash/savings.test.mjs: the branch's three tests close cleanly, then #1065's two; no shared identifier.
    • git diff b6617e3e..HEAD over each file the branch owns shows only main's additions; every line I approved in rounds 1–3 is unchanged.

Non-blocking

  • The merged dash suite has no green run anywhere yet. CI on this head is red (the timeout above), and no test report on the PR covers 18f44949. The dash package's 1205s fits the new 40-minute limit, but that is an inference from main's 1140s plus this branch's additions, not a measurement. The next CI run after the merge of #1082 is the proof.
  • The golden files for #1065 (ka_sessions.json, ka_behaviour.json) carry the new token fields for every row — regenerated fixtures, consistent with the queries' new columns. Nothing to act on.

What I checked

  • Last review: round 3, b6617e3, 2026-11-11T08:16:45Z
  • New commits read: 4 — 62289d9a fix(keepalive): a ping that re-wrote the cache restarts the refresh clock (#1066); 8b311f10 feat(dash): on a subscription the Cache strategy tables show tokens (#1065); 27c0c406 fix(dash): count the fixed_restore copy in the saved figure (#1067); 18f44949 Merge origin/main into feat/fivehour-weights
  • Read in full: 6 reviews, 3 comments, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt)
  • New items since my last review:
    • The integrator note (09:39:01Z), the only new comment — checked: the merge it asks for is not effective on this head, because #1082 landed on main after the merged tip. That is finding 1.
    • The three main commits — read in full, each interaction surface with this branch traced (see the delta section above).
    • The merge commit — verified three ways: the auto-merge tree comparison (marker-only resolution), both directions of the two conflicted files, and the branch's wiring pins and label counts re-run against the merged sources.
    • CI on the head — the check-runs and the failed run's log: one timeout, zero failing test cases.
  • Did not run tests: live tests are not approved for this review. The parse checks and string-pin checks I ran are static reads of the merged sources, not test runs.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.322 offload-review skill, @amiddavid's session resumed 1 of 2 5 of 5 57d38f7bb434 approve

Verdict: approve

The round-4 finding is fixed. The head now carries #1082, so CI runs the 40-minute test limit.
The code this PR changes is byte-for-byte what I approved in rounds 1–4.

Earlier findings, and their state

  • My round-4 finding (the head does not carry #1082; build-test fails at the 20-minute limit) —
    fixed.
    git merge-base --is-ancestor 3c876dcb 57d38f7b succeeds. The head's Makefile reads
    go test -race -timeout 40m on both the test and cover targets (lines 47 and 51). The
    integrator's request (09:39:01Z) is answered by the merge 57d38f7b, which brings main up to
    d501cdb5.
  • Reviewer 2's round-4 finding — the same one, and I verified the fix myself rather than
    taking it on trust: the ancestor check and the Makefile grep above.
  • All non-blocking notes from rounds 1–4 — kept by the author, reasons still accepted. The
    single-flight leader context, the cancellable price lookup, the fall-in-window bias, the route
    timeout, the learned ≤ 0 fallback. All fail toward the API-price figures.
  • Reviewer 2's round-1 finding (two panels, two verdicts) — fixed in 08435ec, unchanged since.
    Both panels still read the payload through forecastView in the merged head.

The round-5 delta: one clean merge of six main commits

The new commits are main's #1054, #1082, #1073, #1087, #334 and #1064, plus the merge 57d38f7b.
None of them is this branch's own work.

  1. The merge is clean, with no hand resolution. git merge-tree --write-tree 18f44949 d501cdb5
    exits 0 with no conflicted file, and the merge commit's tree is af12a30e… — byte-identical to
    git's own auto-merge tree (git rev-parse 57d38f7b^{tree} returns the same hash).
  2. The branch's own delta is unchanged. git diff d501cdb5..57d38f7b is byte-identical to the
    round-4 patch git diff 27c0c406..18f44949 — I compared the two patch files; the only
    differences are blob hashes and 7 lines of offset in dash/keepalive.go, where #1064 added
    lines above the recommend function. Every line I approved is still there, unchanged.
  3. #1064 (tenant-session isolation) — the one commit that touches this branch's files, checked at
    every shared surface.
    Its dash/keepalive.go changes sit at lines 291–1325 (the ledger, the
    sessions and live queries), disjoint from the recommend region this branch changes (line 2003+).
    Its dash/api.go changes sit in the transcript and archive handlers; the branch adds only the
    fiveHour field and fiveHourRoutes(). dash/overview_lean.go — the source of the w.tokens
    the branch's headline reads — is untouched. The schema changes are additive to requests and a
    PK rebuild of archived_sessions, a table the fit never reads. The branch's fit queries were
    tenant-scoped through the Filter before #1064 (verified in round 1), and #1064 does not change
    the Filter mechanism.
  4. #1073 and #1054 — proxy files only. The accountant moves off the request goroutine and the
    latency guard is added; neither reaches the dash library this branch changes.
  5. #1087 — RELEASING.md only. No code.
  6. #334 (price lookup by bare tail) — feeds the fit's pricer. The fit's tierPriceFn resolves
    through the price table; a bare id now takes its qualified entry's price. That is an
    owner-approved behavior change in #334's own PR, and it makes the fit's price fallback more
    correct, not less. No code-path conflict with this branch.

Non-blocking

  • build-test on this head was still running when I posted (started 11:46:11Z; the dash suite
    needs about 20 minutes). It is not red. On the previous head the dash package took 1205.872s,
    which fits the new 40-minute limit with room. The green run is the last proof, and it is CI's
    to give, not the code's.

What I checked

  • Last review: round 4, 18f4494, 2026-11-11T11:26:28Z
  • New commits read: 7 — 43802c5a test(proxy): time the dashboard's own work on the request
    goroutine (#1054); 3c876dcb ci: raise the go test timeout to 40m (#1082); e86d897e
    perf(proxy): move the savings accountant off the request path (#1073); df5110d6 docs(releasing):
    the integrator merges main when that is all a PR waits for (#1087); b125d4b3 fix(modelinfo):
    index a qualified price entry by its own bare tail (#334); d501cdb5 fix(dash): keep one
    tenant's rows out of another's per-session figures (#1064); 57d38f7b Merge origin/main into
    feat/fivehour-weights
  • Read in full: 8 reviews, 3 comments, 0 inline comments (from .review-in-reviews.txt,
    .review-in-comments.txt, .review-in-inline.txt)
  • New items since my last review:
    • Reviewer 2's round-4 review (11:27:38Z, blocking) — read in full. Its finding is mine; I
      verified the fix myself (the ancestor check and the Makefile grep above).
    • The seven commits — read as described above: the merge verified against git's own auto-merge
      tree (byte-identical), the branch's delta compared patch against patch with round 4's
      (identical), #1064's diffs read at every file it shares with this branch, #1073/#1054/#1087
      read for reach into the dash library, #334 read for its effect on the fit's price fallback.
    • CI on the new head — checked: build-test in progress, no failure; the 40-minute limit is in
      the head's Makefile.
  • Did not run tests: live tests are not approved for this review. CI is running them on this head
    at the new 40-minute limit.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.322 offload-review skill, @amiddavid's session resumed 2 of 2 5 of 5 57d38f7bb434 approve

Verdict: approve

The round-4 finding is fixed, and the head's own CI proves it: build-test on 57d38f7b
concluded success at 12:13:08Z (run 43014665544). No new finding. The code this PR
changes is byte-for-byte what I approved in rounds 1–4.

Findings

None.

Earlier findings, and their state

  • My round-4 finding (the head lacked #1082, so build-test failed at the 20-minute limit) — fixed, and I verified it three ways.
    1. git merge-base --is-ancestor 3c876dcb 57d38f7b succeeds.
    2. The head's Makefile reads go test -race -timeout 40m on both the test and cover targets (lines 47 and 51), which is what build-test runs.
    3. build-test on this head is green — not an inference this time. The previous head's dash suite took 1205.872s; this run finished inside the 40-minute limit with no failure.
  • My round-1 finding (two panels, two verdicts) — fixed in 08435ec, unchanged since. git diff 18f44949..57d38f7b over every file this branch owns (dash/ui/, dash/savings.test.mjs, dash/savingsparts_test.go, dash/fivehourfit.go, dash/fivehourweights.go) is empty, so the round-4 pin and parse checks still hold at this head word for word.
  • My round-2 non-blocking notes (the single-flight leader's request context; a cancelled price lookup cached as below-gate) — kept by the author, reasons still accepted. Both fail toward the API-price figures.

The round-5 delta: one clean merge of six main commits

  1. The merge 57d38f7b is clean, with no hand resolution at all. git merge-tree --write-tree 18f44949 d501cdb5 exits 0 with no conflicted file, and its tree af12a30e… is byte-identical to the merge commit's tree (git rev-parse 57d38f7b^{tree} returns the same hash). Unlike the round-4 merge, there was nothing to resolve by hand.
  2. d501cdb5 (#1064, per-session figures keyed by tenant and session) — read both diffs in full (dash/keepalive.go and the rest), and traced every shared surface.
    • Its dash/keepalive.go changes sit at lines 291–1325: the ledger, sumBySession/countBySession, the sessions and live queries, now keyed by sessKey{tenant, session}. The recommend region this branch changes starts at line 2003 and is untouched.
    • The recommend path's bySession (from d.expiries) is still keyed by bare session id. Both forecasts this branch adds — the learned one and the API-price one — read that same map, so they stay consistent with each other. The tenant-collision question in expiries is #1064's scope on main, not this branch's.
    • The fit's queries were tenant-scoped through the Filter before #1064 (verified in round 1); #1064 does not change the Filter mechanism. The archived_sessions PK rebuild touches a table the fit never reads.
  3. e86d897e (#1073, the accountant off the request path) — read the full diff. accBegin now only notes the body; accEnd runs the record on its own goroutine; accWait joins it in finish before the request is priced. Proxy files only. The dash library this branch changes reads the same stored rows through the same schema. The one behavioral note — two requests of one thread may now book in either order — does not touch the fit, which buckets requests by their own timestamps.
  4. 43802c5a (#1054, the request-goroutine timing guard) — read in the same diff. The spendHook/timedSpan hook is test-only: nil in production, one atomic load per call. No reach into the dash library.
  5. 3c876dcb (#1082) — Makefile only, the 40-minute limit above.
  6. df5110d6 (#1087) — RELEASING.md only. No code.
  7. b125d4b3 (#334, a qualified price entry indexed by its bare tail) — read the full diff, and verified its one reach into this branch myself. The fit's per-tier prices resolve through tierPriceFn(a.priceFn(r)) (dash/fivehourweights.go:136) → API.priceFn (dash/toolapi.go:1362) → a.pricer.Price → the modelinfo table that #334 changes. A bare model id now takes its qualified entry's rate instead of a wildcard family's. That is #334's own owner-approved change on main; it makes the fit's prices more correct, not less. No code-path conflict.

Non-blocking

None.

What I checked

  • Last review: round 4, 18f449499b46bbca5dce2602dfcb98a911d24ed9, 2026-11-11T11:27:38Z
  • New commits read: 7 — 43802c5a test(proxy): time the dashboard's own work on the request goroutine (#1054); 3c876dcb ci: raise the go test timeout to 40m (#1082); e86d897e perf(proxy): move the savings accountant off the request path (#1073); df5110d6 docs(releasing): the integrator merges main when that is all a PR waits for (#1087); b125d4b3 fix(modelinfo): index a qualified price entry by its own bare tail (#334); d501cdb5 fix(dash): keep one tenant's rows out of another's per-session figures (#1064); 57d38f7b Merge origin/main into feat/fivehour-weights
  • Read in full: 9 reviews, 3 comments, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt, plus reviewer 1's round-5 review saved as .review-in-r1r5.txt)
  • New items since my last review:
    • Reviewer 1's round-4 review (11:26:28Z, blocking) — in my round-5 snapshot; same CI finding as mine; the fix is verified above.
    • Reviewer 1's round-5 review (11:50:55Z, approve) — read in full. It matches my own reading of the delta. Its one claim I did not take on trust — that #334 feeds the fit's tierPriceFn — I traced myself (dash/fivehourweights.go:136 → dash/toolapi.go:1362 → the pricer).
    • The seven commits — read as described above: the merge verified against git's own auto-merge tree (byte-identical), #1064 read in full at every file it shares with this branch, #1073/#1054 read for reach into the dash library, #334 read and its reach into the fit traced, #1082/#1087 read.
    • CI on the head — checked to the end: build-test concluded success at 12:13:08Z; CodeQL, build, DCO, trivy and analyze are green too. The merge base d501cdb5 and 3c876dcb carry green build-test runs of their own.
    • No new issue comments (still 3, newest the integrator note at 09:39:01Z, which this merge answers) and no inline comments.
  • Did not run tests: live tests are not approved for this review. CI ran them on this head at the new 40-minute limit, and they are green.

@amiddavid
amiddavid merged commit 9dda47d into main Nov 11, 2026
9 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 11, 2026
amiddavid added a commit that referenced this pull request Nov 11, 2026
#1074 and #1068 added rows to docs/data-dependence.md after this branch.
They are now files under docs/data-dependence/features/, and the page is
rebuilt by the generator. Both tables equal main's tables.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Nov 11, 2026
…ce.md (#1090)

docs/data-dependence.md is now built from one file per row, so two
PRs that change different rows never edit the same source file.

- Row files: docs/data-dependence/components/<name>.md (24, the file
  name is the component name) and docs/data-dependence/features/
  <slug>.md (28 + 2 new from #1068 and #1074). key: value lines between
  two --- lines, then the reason as the body. An optional order number
  keeps the page order.
- The page text lives in docs/data-dependence/page.md.tmpl.
- cmd/gen-datadep (parser in internal/datadep) writes the page; make
  datadep runs it. The page stays checked in (owner's choice).
- A drift test fails when the page is out of date, and names the
  command. components/all/datadep_test.go keeps every guard on the row
  files: a registered component without a file, a file for an unknown
  or misspelt component, a missing reason.
- On a conflict in the generated page: take either side and re-run the
  generator. RELEASING.md says this is not a hand resolution.
- CLAUDE.md, RELEASING.md, the PR template and the offload-review
  reviewer prompt describe the new process.

Behavior change: none (docs, tests, a generator). Data dependence:
none; the rows' content is unchanged.

Closes #1088.

Reviews: 2 offload reviews (GLM), round 2, both approve at 98d6383,
which is the PR head.

Signed-off-by: DAVID AMID <[email protected]>
Assisted-By: Claude Opus 5.5 <[email protected]>
amiddavid added a commit that referenced this pull request Nov 12, 2026
…5-hour limit (#1135)

On a Claude subscription, the band and the pane show the next message
as a share of the 5-hour limit, warm and cold, when the learned 5-hour
weights (#1068) pass their checks.

Behavior change: subscription users of the band and the pane. Old: one
token figure for the cache state ("next message 90.0k rd", or "○ cache
cold · next message 90.0k wr"). New: "next message ≈0.1% of 5h ·
≈1.5% if cold", or "○ cache cold · next message ≈1.5% of 5h". Without
weights that pass their checks, the old token figure stays.
Owner's yes, 2026-11-12, in the integrator session: "1135 approved
behavior change".

Data dependence: metadata only, no change of level. The band reads the
cached prefix's token count and the fitted weights; the plugin keeps
the endpoint's answer in its local cache directory. It reads no
request text.

Reviews: 2 offload review rounds (GLM). Round 2: both approve at
14d1ef0, which is the PR head.

Signed-off-by: DAVID AMID <[email protected]>
Assisted-By: Claude Opus 5.5 <[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.

dash: learn the 5-hour limit's token weights from the stored limit headers

1 participant