Repository navigation
fix(read): don't count --max-lines truncation as token savings (#1045) - #1076
ousamabenyounes wants to merge 3 commits into
Conversation
pszymkowiak
left a comment
There was a problem hiding this comment.
Thanks for tackling this — issue #1045 has been a real pain point in our telemetry data, and the diagnosis is spot-on. The core fix (capturing post-filter / pre-truncation content for tracking) is the right approach, well-bounded, and symmetrically applied to both run() and run_stdin(). The numerical proof test (test_savings_inflation_is_zero_with_fix) is a particularly nice touch.
A few things to address before merge — happy to discuss any of them.
🔴 Blocking — please split the PR
This PR currently contains 3 commits, only one of which relates to #1045:
a6dee12feat(hooks): add dangerous-actions-blocker PreToolUse hookdb556a3test(hooks): add test suite for dangerous-actions-blocker65de749fix(read): don't count --max-lines truncation as token savings
The dangerous-actions-blocker hook (102 lines + 115 lines of tests) is a meaningful security feature that deserves its own PR, its own review, and its own discussion. Could you git rebase -i develop to keep only 65de749 here, and open a separate PR for the hook? Happy to review that one too.
🟠 Tests — three of the four don't actually test the production code
simulate_tracking() re-implements the exact branching logic from run() (the Some(filtered.clone()) if-condition, the as_deref().unwrap_or(...) fallback). The first three tests then assert against simulate_tracking, which means a regression in run() itself wouldn't fail them — they validate their own helper.
Two ways to fix this:
-
Extract the selection into a tiny pure function that both
run()and the tests call:fn pick_tracking_output<'a>(pre_truncation: Option<&'a str>, rtk_output: &'a str) -> &'a str { pre_truncation.unwrap_or(rtk_output) }
Then the tests exercise the real function instead of a copy.
-
Or drive
run()end-to-end with atempfile::NamedTempFile, then read back from the tracking DB and assert onsaved_tokens. This is heavier but catches more.
The 4th test (test_savings_inflation_is_zero_with_fix) does call estimate_tokens from the production module, so it's already in good shape — just needs the same shift to exercising real code paths instead of simulate_tracking.
🟡 Minor — print! → println! change
- print!(\"{}\", rtk_output);
+ println!(\"{}\", rtk_output);This isn't mentioned in the description and silently adds a trailing newline to all rtk read output. It may break downstream pipes or scripts that count on the original behavior. Could you either revert it (orthogonal to #1045) or note the rationale in the commit message?
🟡 Minor — avoidable allocation
Some(filtered.clone()) duplicates the entire filtered content in memory whenever truncation is active. For a power user running rtk read --max-lines 1 on a 100 MB log file, that's 100 MB held twice for no reason. A std::mem::take (or restructuring to keep filtered immutable) would avoid the copy:
let pre_truncation = if max_lines.is_some() || tail_lines.is_some() {
Some(std::mem::take(&mut filtered))
} else {
None
};
let windowed = apply_line_window(
pre_truncation.as_deref().unwrap_or(&filtered),
max_lines, tail_lines, &lang,
);
// …
let tracking_output = pre_truncation.as_deref().unwrap_or(&windowed);Not a blocker, but the bug-affected workload (large files + truncation) is exactly where this matters.
🟡 Note — same pattern likely exists in git diff / git show
src/cmds/git/git.rs:200,314 track against the compacted output. There, compact_diff is real RTK compression so it's legitimate — but when the user passes --max-lines N to rtk git diff, the same inflation pattern applies. Worth opening a follow-up issue rather than expanding the scope here.
📋 Out of scope but worth flagging
- Already-polluted historical data. Devices that have been over-reporting for weeks (we have several reporting 4-72 G tokens/day in the API DB) will keep skewing lifetime totals until they re-ping with the fixed binary. Probably needs a server-side cap or a one-off migration in a follow-up.
- CHANGELOG.md isn't updated. Since this fix will visibly lower
rtk gainnumbers for affected users, it's worth a user-facing line.
Again, the diagnosis and the core fix are good — just need the scope split and the tests pointed at the real code path. Let me know if you'd like me to push the test refactor as a suggestion commit instead.
|
@pszymkowiak Thanks for the review — all points addressed. Summary of the final state: 🔴 PR scopeRebased onto 🟠 Tests exercise real production code
🟡
|
When --max-lines or --tail-lines is active, timer.track() was comparing the full raw file against the truncated output, inflating savings by the entire skipped portion (250M+ tokens reported for large files). Fix: capture post-filter, pre-truncation content and use it as the tracking baseline when a line window is active. Savings now reflect only RTK's actual compression, not user-requested truncation. Same fix applied to run_stdin(). Adds 4 regression tests covering max-lines, tail-lines, no-truncation (unchanged behaviour), and a numerical proof that the bug inflated savings >1k tokens while the fix reports 0 for uncompressed content. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…drop clone - Pull selection logic into a pure `pick_tracking_output()` helper called by both `run()` / `run_stdin()` and the regression tests, so a regression in production code now fails the tests (previously they exercised a copy). - Replace `Some(filtered.clone())` with `std::mem::take(&mut filtered)` to avoid duplicating the entire filtered buffer when truncation is active — matters precisely on the bug-affected workload (large files + --max-lines). - Revert `print!` → `println!` in `run()`: orthogonal to #1045 and silently added a trailing newline. - CHANGELOG.md: user-facing note that `rtk gain` numbers will lower for affected users. cargo test: 1691 passed. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The 4 unit tests around `pick_tracking_output()` exercise the helper directly, so they pass for any wiring where the first argument is `Some(&filtered)`. A regression that swaps the call site to `pick_tracking_output(Some(&windowed), &rtk_output)` in `run()` would silently restore the #1045 inflated-savings bug without failing any existing test. Add a true end-to-end test that: - Points RTK_DB_PATH at a temp SQLite file (serialized via static Mutex like tracking.rs::test_db_path_env_and_default). - Writes a 1000-line plain text file (Language::Unknown filter is identity, so any reported savings are tracking bugs, not filtering). - Calls the real `run(..., max_lines=Some(5), ...)`. - Reads back the persisted row and asserts input_tokens ≈ output_tokens and saved_tokens ≈ 0. With the bug present, output_tokens would collapse to ~5 lines and saved_tokens would explode — the assert fails and the regression is caught at the call-site level, not just the helper level. Use `Mutex::lock().unwrap()` (not `unwrap_or_else(into_inner)`) so a poisoned guard from a previous panicked test propagates the original panic instead of leaking a stale RTK_DB_PATH into this test. cargo test --all: 1692 passed, 0 failed. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> Signed-off-by: Ousama Ben Younes <[email protected]>
Summary
rtk read file --max-lines Nwas comparing the full raw file against the truncated output intimer.track(), inflating reported savings by the entire skipped portion — 250M+ tokens reported for a single command on large files--max-linesor--tail-linesis activerun_stdin()Root cause
Test plan
4 new regression tests in
src/cmds/system/read.rs:test_max_lines_tracking_uses_pretruncation_content— tracking baseline equals full filtered content, not truncated slicetest_tail_lines_tracking_uses_pretruncation_content— same invariant for--tail-linestest_no_truncation_tracking_unchanged— without truncation flags, behaviour is identical to beforetest_savings_inflation_is_zero_with_fix— numerical proof: buggy code reports >1k fake tokens, fix reports 0Fixes #1045
🤖 Generated with Claude Code
Vibe Coded by Ousama Ben Younes
Developed With Ora Studio (Claude Code)