Repository navigation
fix(tracking): weighted savings rate in low_savings_commands and avg_savings_per_command - #1298
Conversation
…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]>
There was a problem hiding this comment.
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_commandsto compute per-command savings asSUM(saved_tokens) * 100 / SUM(input_tokens)instead ofAVG(savings_pct). - Update
avg_savings_per_commandto 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. |
|
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. |
…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
left a comment
There was a problem hiding this comment.
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)
src/core/tracking.rs(tests 14/15 as pushed) — tests write into the developer's real tracking DB (2 sites; both changed). Both openTracker::new()and insert five rows each, one at 100k input tokens; develop's tracking tests moved toTracker::new_in_memory()precisely socargo teststops feedinghistory.dbandrtk gain. Evidence: withRTK_DB_PATHon an empty file, one run leftrtk_lowsav_test_<pid>|5andrtk_avgtest_<pid>|5behind; 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_commandsum every call with a group-level guard. Two clauses carried over here still disagreed with it, verified withsqlite3on the queries as pushed:WHERE input_tokens > 0dropped a call that had no input but still printed something, so a command reads 50% here and 10% in the gain table; andsav > 0.0, applied to the now-signed weighted rate, dropped net-regressing commands, so a command develop listed at 15% vanished at −25.9% whilertk gainprints −25.9%. The fixup removes the row filter in both queries (theHAVING SUM(input_tokens) > 0the PR already had keeps never-input commands out, as before) and lists negatives viasav <> 0.0, keeping exact 0% withpassthrough_top. Test 18 checks every listed rate againstget_summary(). test_avg_savings_per_command_inner_weightedasserted only0..=100; reverting the query toAVG(savings_pct)left it green (Copilot's second comment, confirmed by mutation), and the floor contradicts the signed contracttest_avg_savings_per_command_reflects_negativepins. It now asserts the exact figure on an in-memory tracker.test_low_savings_commands_excludes_high_volume_commandonly 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/// 15collided 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_recentreads every row. Renumbered 18/19, placed after 17, comments rewritten; rows go throughrecord()instead of hand-written 9-column inserts. low_savings_commandsdoc: "Same fix asget_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.mdrows 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 gainhalf of this defect, fixed on develop by #891).
Checked and correct — no need to re-verify
- Reference vs head on the same DB:
rtk gainshowsrtk ls -R … 5 5.7K 96.2%on both; the telemetry payload islow_savings_commands=['rtk ls -R:19%'], avg_savings_per_command=19.4on develop and[],96.2on 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-levelHAVINGguarantees a positive divisor. - Readers: only
telemetry.rsconsumes both values (format!("{}:{:.0}%"),<= 100.0assertion); a negative entry formats asrtk 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 withXDG_*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
HAVINGexcludes 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).
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): innerAVG(savings_pct)→SUM(saved)/SUM(input)per command. Outer average across distinct command names stays unweighted (intentional — each filter counts once). Documented inTELEMETRY.md.Two regression tests added using direct
conn.execute()inserts (5 rows each, isolated by uniquertk_cmdname) to avoid polluting the shared test DB window.Test plan
cargo test --allpassescargo test tracking::tests::test_low_savings_commands_excludes_high_volume_commandpassescargo test tracking::tests::test_avg_savings_per_command_inner_weightedpassesrtk gain— no command withRate >= 90%appears in the "filters to improve" list🤖 Generated with Claude Code