Skip to content

fix(read): don't count --max-lines truncation as token savings (#1045) - #1076

Closed
ousamabenyounes wants to merge 3 commits into
rtk-ai:developfrom
ousamabenyounes:fix/issue-1045-max-lines-false-savings
Closed

ousamabenyounes wants to merge 3 commits into
rtk-ai:developfrom
ousamabenyounes:fix/issue-1045-max-lines-false-savings

Conversation

@ousamabenyounes

@ousamabenyounes ousamabenyounes commented Apr 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • rtk read file --max-lines N was comparing the full raw file against the truncated output in timer.track(), inflating reported savings by the entire skipped portion — 250M+ tokens reported for a single command on large files
  • Fix: capture the post-filter, pre-truncation content and use it as the tracking baseline when --max-lines or --tail-lines is active
  • Same fix applied to run_stdin()

Root cause

// BEFORE — bug
timer.track("cat file", "rtk read", &content, &rtk_output);
//                                   ^^^^^^^^   ^^^^^^^^^^
//                                   11MB file  5 lines → fake 2.8M token "savings"

// AFTER — fix
let tracking_output = filtered_for_tracking.as_deref().unwrap_or(&rtk_output);
timer.track("cat file", "rtk read", &content, tracking_output);
//                                             ^^^^^^^^^^^^^^
//                                             pre-truncation filtered content → real savings only

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 slice
  • test_tail_lines_tracking_uses_pretruncation_content — same invariant for --tail-lines
  • test_no_truncation_tracking_unchanged — without truncation flags, behaviour is identical to before
  • test_savings_inflation_is_zero_with_fix — numerical proof: buggy code reports >1k fake tokens, fix reports 0
cargo test: 1347 passed, 0 failed

Fixes #1045

🤖 Generated with Claude Code


Vibe Coded by Ousama Ben Younes
Developed With Ora Studio (Claude Code)

@pszymkowiak pszymkowiak 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.

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:

  • a6dee12 feat(hooks): add dangerous-actions-blocker PreToolUse hook
  • db556a3 test(hooks): add test suite for dangerous-actions-blocker
  • 65de749 fix(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:

  1. 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.

  2. Or drive run() end-to-end with a tempfile::NamedTempFile, then read back from the tracking DB and assert on saved_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 gain numbers 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.

@ousamabenyounes

Copy link
Copy Markdown
Contributor Author

@pszymkowiak Thanks for the review — all points addressed. Summary of the final state:

🔴 PR scope

Rebased onto develop, dropped the dangerous-actions-blocker hook commits. Only the #1045 fix remains here. That hook has its own PR (#1008).

🟠 Tests exercise real production code

  • Extracted pick_tracking_output() helper, called from both run() / run_stdin() and the regression tests — simulate_tracking() removed.
  • Added test_run_does_not_inflate_savings_with_max_lines_e2e: points RTK_DB_PATH at a temp SQLite (serialized via static Mutex like tracking.rs::test_db_path_env_and_default), drives real run(..., max_lines=Some(5), ...) against a 1000-line file (Language::Unknown filter = identity, so any reported savings can only come from a tracking-baseline bug), reads back the persisted row and asserts input_tokens ≈ output_tokens and saved_tokens ≈ 0. Catches call-site regressions, not just helper-level ones.

🟡 print! → println!

Reverted in run() — unintentional drift in the original commit, orthogonal to #1045.

🟡 Avoidable allocation

Replaced Some(filtered.clone()) with std::mem::take(&mut filtered) and plumbed through pre_truncation.as_deref().unwrap_or(&filtered). No double-allocation on the bug-affected path.

🟡 Same pattern in git diff / git show

Tracked as follow-up: #1561.

📋 CHANGELOG

Added under ## [Unreleased]:

cargo fmt ✅ · cargo clippy --all-targets ✅ · cargo test --all: 1692 passed, 0 failed.

Ready for re-review when you have a moment.

ousamabenyounes and others added 3 commits May 24, 2026 22:28
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]>
@ousamabenyounes ousamabenyounes closed this by deleting the head repository May 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

rtk read: truncation via --max-lines incorrectly counted as token savings, producing 250M+ saved tokens in one command

2 participants