Skip to content

fix(gain): use weighted savings rate in per-command stats - #891

Merged
KuSh merged 4 commits into
developfrom
fix/gain-weighted-avg
Sep 13, 2026
Merged

KuSh merged 4 commits into
developfrom
fix/gain-weighted-avg

Conversation

@FlorianBruniaux

Copy link
Copy Markdown
Contributor

Summary

  • Replace AVG(savings_pct) with SUM(saved_tokens)*100.0/SUM(input_tokens) in the per-command SQL query — the old unweighted mean diluted high-volume commands (grep showed 14.8% instead of the real 98.6%)
  • Rename Avg% column header to Rate (more accurate)
  • Add doc warning on CommandStats type alias against using AVG() on savings_pct
  • Add regression test with intentionally skewed data proving weighted != unweighted

Root cause

Each invocation stores its own savings_pct. AVG() treated a 10-token call identically to a 10M-token call. Small calls at 0% savings (passthroughs, short greps) massively diluted the average — grep had 184M tokens saved out of 193M input, yet showed 14.8% instead of 95%.

Credit

Hat tip to Mathieu Grenier who spotted the inconsistency on LinkedIn: grep at 184M saved on 193M input showing 14.8% while global efficiency was 98%. Good instinct, real bug.

Test plan

  • cargo test --all passes (1135 tests)
  • rtk gain shows Rate >= 90% for grep/read (was 14-43%)
  • Global efficiency % unchanged (already correct, uses a different calculation)
  • Regression test fix: improve command robustness and flag support #14 asserts rate > 90% on skewed data (10% small call + 95% large call)

Copilot AI review requested due to automatic review settings March 28, 2026 00:36

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR corrects rtk gain per-command savings to use a weighted savings rate (based on total tokens) rather than an unweighted average of per-invocation percentages, improving accuracy for high-volume commands.

Changes:

  • Update the per-command SQL aggregation to compute SUM(saved_tokens) * 100 / SUM(input_tokens) and rename the UI column header from Avg% to Rate.
  • Add documentation warning on the CommandStats tuple semantics and add a regression test proving weighted vs unweighted behavior.
  • Expand discover command classification coverage for additional git/cargo/pnpm subcommands (passthrough routing) and document supported ecosystems.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
src/core/tracking.rs Switch per-command savings from AVG(savings_pct) to a weighted rate; document semantics; add regression test.
src/analytics/gain.rs Update per-command table header from Avg% to Rate to reflect weighted rate semantics.
src/discover/rules.rs Extend discover patterns/rules to recognize more git/cargo/pnpm subcommands and mark them passthrough.
src/discover/registry.rs Update/extend tests ensuring registry covers the expanded subcommand set and passthrough classification/rewrites.
CLAUDE.md Add a one-line list of supported ecosystems.

Comment thread src/core/tracking.rs Resolved
Comment thread src/core/tracking.rs Resolved
Comment thread CLAUDE.md Resolved
Comment thread src/discover/rules.rs Resolved

@KuSh KuSh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM!

Comment thread src/core/tracking.rs Resolved
Comment thread src/core/tracking.rs Resolved
Comment thread src/discover/rules.rs Resolved
@aeppling

Copy link
Copy Markdown
Contributor

LGTM, please rebase / resolve conflicts and will merge

@FlorianBruniaux

@aeppling aeppling added DONE_REVIEW enhancement New feature or request labels Apr 10, 2026
FlorianBruniaux and others added 2 commits April 13, 2026 14:54
AVG(savings_pct) produced a simple unweighted mean that diluted the
reported rate for high-volume commands — grep showed 14.8% while the
true weighted rate was 98.6%, a 84-point gap.

Replace AVG(savings_pct) with SUM(saved_tokens)*100.0/SUM(input_tokens)
in the per-command SQL query so the rate reflects actual byte savings
rather than an average of per-invocation percentages.

Also:
- Rename "Avg%" column header to "Rate" (more accurate label)
- Add doc warning on CommandStats type alias against using AVG()
- Add regression test proving weighted != unweighted on skewed data

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: Florian BRUNIAUX <[email protected]>
FlorianBruniaux added a commit that referenced this pull request Apr 14, 2026
…avg_savings_per_command

AVG(savings_pct) over rows produces an unweighted mean: a handful of 0%-savings
passthrough calls dilute a filter that genuinely performs well on high-volume
invocations. Same root cause as PR #891 (get_by_command).

Changes:
- low_savings_commands: AVG(savings_pct) → SUM(saved)*100/SUM(input). A command
  with 1 big call (95%) + 4 small calls (0%) now shows 94.6%, not 19%. Filters
  correctly excluded from the "needs improvement" list shipped in telemetry.
- avg_savings_per_command: inner per-command rate is now weighted (SUM/SUM);
  outer average across command names stays unweighted (intentional, each filter
  counts once). Documented in TELEMETRY.md.
- Two regression tests added (conn.execute direct inserts for DB isolation).
- docs/TELEMETRY.md updated to reflect the weighted formula.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: Florian BRUNIAUX <[email protected]>
pszymkowiak added a commit that referenced this pull request Sep 8, 2026
Adapted from stale community PR #891. get_by_command's SQL used
AVG(savings_pct) -- an unweighted mean across all calls of a command,
which buries the real signal when many small, near-0%-savings calls
sit alongside a handful of high-volume outliers.

Confirmed against the same real history.db from the savings-inflation
investigation this branch already fixes: rtk read showed a 5.3%
average while SUM(saved_tokens) for that command was 138.9M, entirely
because 4,627 of 5,180 calls genuinely saved 0% and only 158 outlier
rows supplied 99.86% of the sum -- the unweighted AVG made that skew
invisible instead of surfacing it.

Replaced with SUM(saved_tokens) * 100.0 / SUM(input_tokens), the same
weighting the overall summary already uses. Column renamed Avg% ->
Rate to reflect the change. New regression test proves the gap: an
unweighted average of a 10%-savings call and a 95%-savings call reads
~52.5%; the weighted rate correctly reads ~95% (dominated by the
high-volume call, as it should be). Verified live: rtk gain's By
Command table now shows the weighted figure.
@anujsingh-cse

Copy link
Copy Markdown
Contributor

I had opened #3977 for this same change before seeing this PR — figured I'd offer my regression test here since it uses an isolated in-memory DB and a long-tailed pair that pins the weighted-vs-mean distinction explicitly, in case it's useful:

#[test]
fn test_get_by_command_uses_total_savings_pct() {
    let tracker = Tracker::new_in_memory().expect("Failed to create tracker");

    // A long-tailed pair: one huge command (90% savings) and one tiny
    // command (10% savings) under the same rtk_cmd. The mean of percentages
    // is 50%, but the total-based percentage is dominated by the huge
    // command (~89.99%), matching the SUM(saved_tokens) in the same row.
    tracker
        .record("grep huge", "rtk grep", 1_000_000, 100_000, 50)
        .expect("record huge");
    tracker
        .record("grep tiny", "rtk grep", 100, 90, 5)
        .expect("record tiny");

    let by_command = tracker.get_by_command(None).expect("get_by_command");

    let (_cmd, count, saved, pct, _avg_time) = by_command
        .iter()
        .find(|(cmd, ..)| cmd == "rtk grep")
        .expect("rtk grep row not found");

    assert_eq!(*count, 2);
    assert_eq!(*saved, 900_010);
    // Total-based: 100 * (900_000 + 10) / (1_000_000 + 100). The old
    // AVG(savings_pct) would report 50.0 here.
    let expected = 100.0 * 900_010.0 / 1_000_100.0;
    assert!(
        (pct - expected).abs() < 0.01,
        "expected total savings pct ~{expected:.2}, got {pct:.2}"
    );
    assert!(
        (pct - 50.0).abs() > 1.0,
        "mean-of-percentages regression: got {pct:.2}"
    );
}

Happy to adapt it to whatever shape you prefer here, or just leave it as a reference.

KuSh and others added 2 commits September 13, 2026 17:25
Move the weighted-rate regression test off the real tracking database, which
it wrote two rows into on every run, and onto an in-memory tracker. Add the
long-tailed pair that pins the weighted rate against the mean of percentages,
the same assertion through get_summary(), and a zero-input group: without the
CASE guard that last one fails on a NULL rate, and no other test covers it.

Name the 4th field of GainSummary::by_command for what it now holds, and state
the rate formula on the CommandStats warning in percentage order, with the zero
guard, so that following it verbatim cannot reintroduce the NULL.

Head the column Total% rather than Rate, keeping the shape of the Avg% it
replaces and naming the total the figure is now taken over.

Drop the hand-written CHANGELOG entry: release-please generates it from the
commit subject, and CONTRIBUTING.md asks for that file to be left alone.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

@KuSh KuSh left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Round 2 of 3 — APPROVED, fixup pushed (95734889)

Claim: rtk gain's per-command percentage should be a volume-weighted rate consistent with the Saved column in the same row, not a mean of per-invocation percentages.
Scope: accept (round 1, frozen). Two other PRs made the same change and were closed in favour of this one, #3510 and #3977, so their tests are folded in here rather than lost.
Ran: rtk gain from both binaries against a copy of a real 254k-command tracking DB. rtk read reads 17.3% before and 96.8% after, next to 111.2M saved — the distortion #3506 reported. This PR's CASE WHEN and the COALESCE/NULLIF form the other two PRs used are bit-identical on every command group, so nothing was lost by keeping this one. Merged onto develop (d0c29851): clean; cargo fmt clean, 0 clippy warnings, 3742 tests pass.
CI @95734889: all green (10/10), on the pushed head.

Blocks merge (0)

Nothing. The blocking set has been empty since round 1.

Fixup — on a merge of current develop

The branch was 6 months behind and Tracker::new_in_memory(), which every in-memory test below needs, exists only on develop. So the fixup sits on a merge of upstream/develop rather than a rebase — no history rewritten, and it answers the rebase request from April.

  • The regression test wrote to the real tracking database. Tracker::new() opens the developer's own history.db, so every cargo test run inserted two rows into it. Now Tracker::new_in_memory(), still carrying a project path so the project-filtered form of the query stays the one under test.
  • GainSummary::by_command still documented its 4th field as avg_pct, the aggregation this PR removes. That is the doc a caller of the public struct reads.
  • The CommandStats warning now states the formula in percentage order with the column names, and includes the zero guard. Without that clause it told a maintainer to write the unguarded division, which is exactly the failure the new zero-input test catches.
  • The expected value in the test comment was ≈ 94.99%; the exact value is 94.915…, so it reads ≈ 94.9%.
  • The column header is Total%, not Rate. It keeps the shape of the Avg% it replaces, so the change reads as one word swapped, and it names the total the figure is now taken over — which is the fix. It is also what #3506 asked for and what both other PRs chose independently.
  • The CHANGELOG entry is dropped. CONTRIBUTING.md says twice not to edit that file by hand — release-please generates it from the commit subject, and this PR's subject already produces the entry. As it stood, the merge left it under a stale [Unreleased] heading ~750 lines down, where nobody reading for the next release would see it, and its commit link b3ab873 no longer resolves.
  • Three in-memory cases added, each mutation-checked rather than assumed: reverting the SQL to AVG(savings_pct) fails three of them; deleting the CASE … ELSE 0.0 guard fails only test_by_command_zero_input_has_zero_savings_percentage. That last one is the case nothing else covered — without the guard the rate comes back NULL, get_by_command fails on the conversion, and rtk gain prints no table at all.

Filed as follow-ups

  • low_savings_commands() still computes AVG(savings_pct) and still feeds telemetry, so after this merges the same binary can print a command at 98.6% in the By Command table while reporting it as a sub-30% "filter that needs improvement". It is untouched by this PR and pre-dates the branch, so it does not hold this up. #1298 already fixes it together with avg_savings_per_command but currently conflicts; it wants a rebase rather than a new patch here. Note avg_savings_per_command is deliberately unweighted and documented as such — low_savings_commands has no such rationale.

Checked and correct — no need to re-verify

  • The CASE WHEN SUM(input_tokens) > 0 guard is right: SUM(input_tokens) is 0 only when every row in the group has zero input, and then SUM(saved_tokens) <= 0.
  • The develop merge dropped and resurrected nothing: the whole delta against develop is the header rename, the SQL, two doc comments and the tests. The rename landed at develop's new location for that header, which moved during the 6 months.
  • Column alignment is unaffected: Total% is exactly the {:>6} field, and so is every non-negative value it sits above. Rendered against the 254k-row DB to confirm.

Your questions

  • aeppling, "please rebase / resolve conflicts and will merge" → done, as a merge of current develop inside the fixup. The conflicts were already gone; the branch was simply behind.
  • @anujsingh-cse, "Happy to adapt it to whatever shape you prefer here, or just leave it as a reference" → folded in as test_weighted_rate_via_get_by_command, near-verbatim. Thank you.
  • @cakeni's two in-memory cases from #3510 are folded in as well, the zero-input one being the case with no other coverage.

Threads resolved by me

  • The percentage-order thread on the CommandStats warning, and the 94.99 → 94.9 correction: both fixed by the fixup.
  • The CLAUDE.md and src/discover/rules.rs threads, including the alphabetical-sort one, no longer anchor to anything — neither file is part of this PR any more.

Next

Nothing — approving once CI is green on the pushed head.
Rounds: 2/3. Threads: 0 open, 6 resolved this round (3 fixup-closed, 3 no longer relevant).

@KuSh
KuSh merged commit b6a1712 into develop Sep 13, 2026
18 checks passed
@KuSh
KuSh deleted the fix/gain-weighted-avg branch September 13, 2026 18:30
@rtk-release-bot rtk-release-bot Bot mentioned this pull request Sep 13, 2026
KuSh added a commit that referenced this pull request Sep 13, 2026
…n memory

`get_by_command` moved to the volume-weighted rate while this branch was
open (#891), summing every call and guarding the division at group level.
The two telemetry queries now use the same shape: the row-level
`WHERE input_tokens > 0` is gone, so a call with no input that still
printed something counts against its command exactly as it does in the
By Command table, and `HAVING SUM(input_tokens) > 0` keeps commands that
never had any input out of both, as before.

`low_savings_commands` lists net-regressing commands: `sav > 0.0` became
`sav <> 0.0`, so only exact 0% stays with `passthrough_top`. A command
that emits more than it saves is the filter to fix first, and with the
weighted rate the old bound also dropped commands the unweighted query
used to list.

The two regression tests opened the on-disk tracker, so every `cargo test`
wrote ten synthetic rows (one at 100k input tokens) into whichever history
database `Tracker::new()` resolves to, on a developer machine the real one.
They now use `Tracker::new_in_memory()` like the rest of the module, and
`test_avg_savings_per_command_inner_weighted` only asserted a `0..=100`
range that the unweighted query also satisfied. Both tests now assert the
exact weighted figures, check each listed rate against `get_summary()`,
and fail when either query goes back to `AVG`, to the row filter, or to
the positive bound.

Tests are numbered 18 and 19 after the ones develop already carries as
14-17. The `low_savings_commands` doc no longer points at a PR, and both
telemetry field tables describe the new semantics.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

DONE_REVIEW enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants