Skip to content

fix(tracking): weighted savings rate in low_savings_commands and avg_savings_per_command - #1298

Merged
KuSh merged 3 commits into
developfrom
fix/tracking-weighted-aggregations
Sep 13, 2026
Merged

KuSh merged 3 commits into
developfrom
fix/tracking-weighted-aggregations

Conversation

@FlorianBruniaux

Copy link
Copy Markdown
Contributor

Summary

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

Two SQL queries affected:

  • low_savings_commands (tracking.rs:989): AVG(savings_pct) → SUM(saved_tokens)*100/SUM(input_tokens). A command with 1 big call (95%) + 4 small calls (0%) showed 19% and got incorrectly flagged as "needs improvement". Weighted rate is 94.6%. This is shipped via telemetry.
  • avg_savings_per_command (tracking.rs:1007): inner AVG(savings_pct) → SUM(saved)/SUM(input) per command. Outer average across distinct command names stays unweighted (intentional — each filter counts once). Documented in TELEMETRY.md.

Two regression tests added using direct conn.execute() inserts (5 rows each, isolated by unique rtk_cmd name) to avoid polluting the shared test DB window.

Test plan

  • cargo test --all passes
  • cargo test tracking::tests::test_low_savings_commands_excludes_high_volume_command passes
  • cargo test tracking::tests::test_avg_savings_per_command_inner_weighted passes
  • rtk gain — no command with Rate >= 90% appears in the "filters to improve" list

🤖 Generated with Claude Code

…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]>
Copilot AI review requested due to automatic review settings April 14, 2026 09:52

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

Fix telemetry tracking metrics to use weighted savings rates per command (by token volume) so a few low-savings invocations don’t dilute high-volume filter performance.

Changes:

  • Update low_savings_commands to compute per-command savings as SUM(saved_tokens) * 100 / SUM(input_tokens) instead of AVG(savings_pct).
  • Update avg_savings_per_command to use a weighted inner per-command rate while keeping the outer average unweighted across command names.
  • Add regression tests and update telemetry documentation to reflect the weighted behavior.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
src/core/tracking.rs Switch SQL aggregations from unweighted AVG(savings_pct) to weighted SUM(saved)/SUM(input) and add regression tests.
docs/TELEMETRY.md Document the new weighted calculation for low_savings_commands and the inner weighted/outer unweighted behavior for avg_savings_per_command.

Comment thread src/core/tracking.rs Resolved
Comment thread src/core/tracking.rs Resolved
Comment thread src/core/tracking.rs Resolved
@rtk-release-bot

Copy link
Copy Markdown
Contributor

This pull request has been automatically marked as stale due to 90 days of inactivity. If this pull request is still relevant, please leave any comment (for example, "bump"), and we'll keep it open. Your contribution is very much appreciated — we're sorry we haven't been able to review it yet.

KuSh and others added 2 commits September 13, 2026 20:35
…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]>

@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 1 of 3 — APPROVED, fixup pushed

Claim: low_savings_commands and avg_savings_per_command compute each command's rate as SUM(saved_tokens)/SUM(input_tokens) instead of AVG(savings_pct), so the telemetry payload agrees with the weighted rate get_by_command already uses for rtk gain.
Scope: accept (round 1, frozen)
Ran: rtk ls -R × 5 real calls into one DB (one 5.9K-token listing at 97%, four empty listings at 0%) with a develop build and this head merged on develop; rtk gain on both; a real telemetry ping from both binaries (endpoint compiled in, local listener); the queries verbatim through sqlite3, also on a negative / zero-input fixture; the two tests under four mutations (each query reverted to AVG, the row filter put back, the positive bound put back). Savings floor not applicable: no filter output changes.
CI @cb5e5994 (fixup head): all 20 checks green — fmt, clippy, doc review, test presence, test on ubuntu/macos/windows, benchmark, Security Scan, semgrep, CodeQL (5 languages), CLA. The reviewed head 0f45992 was also green but five months behind develop and conflicting; the fixup merges develop.

Blocks merge (1, frozen at round 1 — closed by the fixup)

  1. src/core/tracking.rs (tests 14/15 as pushed) — tests write into the developer's real tracking DB (2 sites; both changed). Both open Tracker::new() and insert five rows each, one at 100k input tokens; develop's tracking tests moved to Tracker::new_in_memory() precisely so cargo test stops feeding history.db and rtk gain. Evidence: with RTK_DB_PATH on an empty file, one run left rtk_lowsav_test_<pid>|5 and rtk_avgtest_<pid>|5 behind; with the fixup the file is never created. Test: the same two, in memory.

Optional — will not hold merge; folded into the fixup

  • The reference moved under the PR. #891 landed after this branch was opened and made get_by_command sum every call with a group-level guard. Two clauses carried over here still disagreed with it, verified with sqlite3 on the queries as pushed: WHERE input_tokens > 0 dropped a call that had no input but still printed something, so a command reads 50% here and 10% in the gain table; and sav > 0.0, applied to the now-signed weighted rate, dropped net-regressing commands, so a command develop listed at 15% vanished at −25.9% while rtk gain prints −25.9%. The fixup removes the row filter in both queries (the HAVING SUM(input_tokens) > 0 the PR already had keeps never-input commands out, as before) and lists negatives via sav <> 0.0, keeping exact 0% with passthrough_top. Test 18 checks every listed rate against get_summary().
  • test_avg_savings_per_command_inner_weighted asserted only 0..=100; reverting the query to AVG(savings_pct) left it green (Copilot's second comment, confirmed by mutation), and the floor contradicts the signed contract test_avg_savings_per_command_reflects_negative pins. It now asserts the exact figure on an in-memory tracker.
  • test_low_savings_commands_excludes_high_volume_command only asserted absence, so an empty result set passed. It now asserts the exact listed set: a 24% command, a −50% command, and nothing for the ~94.6% one.
  • Test numbering: the PR's // 14 / // 15 collided with develop's 14–17 from #891 and sat above // 13 (Copilot's third comment); the "avoid polluting get_recent window" note was also wrong, get_recent reads every row. Renumbered 18/19, placed after 17, comments rewritten; rows go through record() instead of hand-written 9-column inserts.
  • low_savings_commands doc: "Same fix as get_by_command (PR #891)" is true again now that #891 is merged; reworded without the PR pointer (Copilot's first comment) and extended for the two points above.
  • docs/guide/resources/telemetry.md rows 70–71 still described the row average; both field tables now describe the new semantics.

Filed as follow-ups

  • none. Adjacent, not absorbed: #1785 (three-word command prefix in the same field, untouched), #3506 (the rtk gain half of this defect, fixed on develop by #891).

Checked and correct — no need to re-verify

  • Reference vs head on the same DB: rtk gain shows rtk ls -R … 5 5.7K 96.2% on both; the telemetry payload is low_savings_commands=['rtk ls -R:19%'], avg_savings_per_command=19.4 on develop and [], 96.2 on this head, unchanged by the fixup. That is the wrong answer the PR removes.
  • Signed rates survive: test_avg_savings_per_command_reflects_negative (develop) passes on the merged head; a −50% command yields −50 under both queries.
  • No NULL can reach row.get::<_, f64>: the group-level HAVING guarantees a positive divisor.
  • Readers: only telemetry.rs consumes both values (format!("{}:{:.0}%"), <= 100.0 assertion); a negative entry formats as rtk read:-50%, nothing to change.
  • #891's tests 14–17 pass on the merged head.
  • Full gate on the merged head + fixup: cargo fmt --check, cargo clippy --all-targets (0 warnings), cargo test --all (0 failures), run with XDG_* pointed away from the developer's data.

Hypotheses built and dropped

  • "Division by zero when a group has only zero-input rows" — the group-level HAVING excludes it; such a command is 0.0% in the gain table and absent here, both "no signal".
  • "Style/convention findings on the surrounding lines" — pre-existing, file-wide; not this PR's.

Your questions

  • none asked.

Next

fixup cb5e599 pushed (after merge commit 4b6c0f0), CI green on it: merges develop with the doc-comment and TELEMETRY.md conflicts resolved keeping both sides, aligns both queries with the post-#891 get_by_command (every call summed, net-negative commands listed), moves the two tests to Tracker::new_in_memory() with exact assertions cross-checked against get_summary(), renumbers them 18/19, drops the PR pointer from the doc comment, updates both telemetry field tables — approving.
Rounds: 1/3. Threads: 0 open, 3 resolved this round (all Copilot threads, fixup-closed).

@KuSh
KuSh merged commit 2ff2f71 into develop Sep 13, 2026
17 checks passed
@KuSh
KuSh deleted the fix/tracking-weighted-aggregations branch September 13, 2026 22:37
@rtk-release-bot rtk-release-bot Bot mentioned this pull request Sep 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants