Skip to content

fix(read): window the tracking baseline like the output, so a partial read is not booked as a saving - #3943

Merged
KuSh merged 9 commits into
developfrom
fix/gain-savings-inflation
Oct 28, 2026
Merged

KuSh merged 9 commits into
developfrom
fix/gain-savings-inflation

Conversation

@pszymkowiak

@pszymkowiak pszymkowiak commented Sep 8, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

rtk read with --max-lines, --head-lines or --tail-lines recorded the whole file as the raw side and the window as the output, so one partial read of a large file booked the entire unshown remainder as a saving (real case: one rtk read --max-lines 5 on an 11.6 MB file recorded 3,037,038 → 32 tokens, "99.999 % saved"). The user asked for those lines; rtk did not compress anything.

This PR windows the raw side the same way the output is, on every rtk read tracking path:

  • tracking_baseline cuts the raw content to the requested window (and numbers it when -n is set). With no window it borrows the formatted raw string the caller already built, so a whole-file read costs no extra copy.
  • The three no-filter fast paths (head on an endless source, byte windows on a file and on stdin) record the window as both sides.

What the user sees is unchanged: stdout is still never_worse(raw, filtered), and --head-lines N stays byte-identical to head -n N.

Measured on a 3.7 MB file, isolated DB:

command before after
rtk read f --max-lines 5 922,224 → 12 (100 %) 12 → 12 (0 %)
rtk read f --tail-lines 3 922,224 → 15 (100 %) 15 → 15 (0 %)
rtk read f --head-lines 4 --level none 922,224 → 14 (100 %) 14 → 14 (0 %)
rtk read f (no window) 922,224 → 922,224 unchanged

Scope note

This PR originally also carried a write-time token cap (tracking.estimate_cap_chars / RTK_TRACK_CAP_CHARS), a retroactive migration capping history, and weighted per-command rates. develop has since taken a different route for those: per-command and low_savings_commands rates are weighted (SUM(saved) / SUM(input)), and rows above HEADLINE_INPUT_CAP_TOKENS (7,500) are excluded from the headline totals at read time while staying visible for diagnosis. That makes the write-time cap and the one-time rewrite of history unnecessary, so they are dropped here. Only src/cmds/system/read.rs changes.

Tests

  • 7 unit tests on tracking_baseline / apply_line_window, plus the ignored regression test that checks --max-lines never leaks unfiltered raw into stdout (spawned through test_isolation).
  • cargo fmt, cargo clippy --all-targets clean, cargo test --lib 4391 passed.

pszymkowiak and others added 6 commits September 8, 2026 22:36
`rtk gain`'s "tokens saved" headline can be inflated by orders of
magnitude by a single oversized command. Root cause: nothing bounds a
per-call token estimate, and RTK's counterfactual is "the agent would
have consumed the full raw output" -- it wouldn't have, since agent
shells (Claude Code, etc.) truncate captured tool-result output well
below what RTK's estimator counts.

Confirmed against a real local history.db: a single `rtk read` call
recorded 135,722,224 input tokens against a 21-token real output --
one row alone accounting for ~92% of the entire lifetime "saved"
total (135.7M of 148.2M), invisible in the unweighted by-command
average (5.3%) since 4,627 of 5,180 `rtk read` calls genuinely saved
0%, and 158 outlier rows (3% of calls) supplied 99.86% of the sum.

This combines and adapts two stale/unmerged community PRs (#3635,
#1978) that independently targeted the same bug from different
angles -- neither was mergeable as-is (both conflicting with develop,
zero maintainer review, two different unreconciled magic-number
ceilings):

- New `tracking.estimate_cap_chars` config (default 30,000 chars,
  0 = uncapped), overridable via `RTK_TRACK_CAP_CHARS` (from #3635).
  `TimedExecution::track` clamps input_tokens/output_tokens to this
  ceiling before they ever reach the DB.
- A version-gated retroactive migration (schema v1 -> v2) caps
  already-inflated historical rows to the same ceiling and
  recomputes saved_tokens/savings_pct from the capped values --
  adapted from #1978's migration idea, but keyed to the same
  configurable cap instead of a second, hardcoded 25,000-token
  ceiling, so historical and new rows converge on one number. Floors
  at 0 rather than manufacturing a fake positive saving when capping
  turns two oversized values into an equal pair (or when the original
  row was already a regression pre-cap).

Deliberately out of scope (separate, real issues, not band-aided
here): #3702 (saturating_sub silently floors regressions to 0 instead
of surfacing a negative delta -- needs a signed-delta schema change,
not a quick fix) and the `rtk read`-specific measurement issues in
#2805/Cybercommanders' OOM-stub-return finding (hardcoded "rtk read"
rtk_cmd label blocks auditing which flag combinations are affected;
worth its own PR).

9 new tests, including a direct regression test replaying the exact
135.7M-token row found in the wild and asserting it lands at the cap
afterward, plus a test proving the migration can't turn a genuine
regression into a fake positive saving.
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.
Adapted from stale community PR #2699 (fixes the same defect as the
closed-as-duplicate #1045: "truncation via --max-lines incorrectly
counted as token savings, producing 250M+ saved tokens in one
command" -- a real bioinformatics-file repro).

rtk read's --max-lines/--tail-lines window was applied only to the
filtered output before comparing it against the raw content for
tracking. The raw baseline stayed the FULL file. Content the user
explicitly asked NOT to see (outside the window) was then counted as
"token savings" -- but that's the user choosing to see less, not RTK
compressing anything.

Extracted prepare_outputs() to window both raw and filtered content
identically before the timer.track() comparison. 3 new tests,
including one proving real filter savings INSIDE the window (e.g. a
stripped comment) still get counted correctly -- only content outside
the window stops counting.

Verified live: `rtk read --max-lines 5` on a 50,000-line file with no
real filtering (level=none) now correctly records 0 saved tokens
(previously, even after this branch's earlier cap fix alone, it
recorded ~7,458 saved tokens / 99% -- a bounded but still fake
"compression" that was actually just the window).
Independent codex review of this branch caught a real regression in
the previous commit: prepare_outputs() computed a single windowed
"raw" value and returned it as both the tracking baseline AND the
value fed into never_worse()/print!() -- so windowing the raw side for
tracking purposes could also change what actually gets PRINTED to the
user. Concrete failure: comparing two already-windowed strings can
flip never_worse's fallback, printing an unfiltered raw excerpt
instead of the real filtered content.

This bug was already present in the stale community PR (#2699) this
commit's parent was adapted from -- caught by independent review, not
by that PR's own tests, which never exercised the display path.

Fix: split the concern. run()/run_stdin() go back to computing
raw/shown exactly as before this branch touched them (full,
unwindowed content feeds the display safety net, unchanged). A new
tracking_baseline() helper -- returning a single String, not a pair,
so this bug class can't be silently reintroduced -- computes ONLY the
windowed value passed to timer.track().

Replaced the 3 prepare_outputs tests with tracking_baseline
equivalents, and added a new #[ignore]-gated integration test running
the real binary end-to-end (rtk read --level minimal --max-lines 2 on
a file with a comment RTK should strip) asserting the printed output
never contains the raw comment -- directly reproducing and guarding
against the exact scenario the review caught.
…commands

Independent review of this branch (5 parallel adversarial agents +
codex + this repo's own tests) converged on two real HIGH-severity
bugs in the schema-v2 retroactive cap migration itself, plus two
MEDIUM ones:

1. The migration UPDATE's Result was discarded via `let _ =`, then
   `user_version` got stamped unconditionally right after. A
   transient failure (SQLITE_BUSY past the busy_timeout under a
   concurrent rtk/hook process, disk pressure, a read-only mount)
   would silently mark the DB as migrated forever while the exact
   oversized rows this migration exists to fix stayed uncapped, with
   no error surfaced anywhere. Now propagated with `?`, matching the
   file's existing pattern for non-idempotent statements: on failure,
   run_schema_migrations returns Err, user_version stays stale, and
   the retry happens naturally on the next Tracker::new() call.

2. `rtk init` -> ensure_schema_fresh() -> MigrationMode::Always
   deliberately re-invokes run_schema_migrations unconditionally (to
   self-heal a table dropped out-of-band) -- which also unconditionally
   re-ran the retroactive cap UPDATE every time, with whatever cap was
   CURRENTLY configured. A user lowering RTK_TRACK_CAP_CHARS and then
   running `rtk init` again (an ordinary repair action) would silently
   and irreversibly re-cap -- and lose, with no backup -- legitimate
   historical data already correctly under the OLD cap. Now guarded by
   reading the on-disk user_version directly against a new
   TOKEN_CAP_MIGRATION_VERSION constant, independent of which caller
   invoked run_schema_migrations or why.

3. low_savings_commands (feeds telemetry's low-savings flagging) had
   the identical unweighted AVG(savings_pct) flaw this branch already
   fixed in get_by_command, left unconverted in this sibling query.
   Same fix: SUM(saved_tokens)*100.0/SUM(input_tokens).

4. estimate_cap_chars() (called on effectively every rtk invocation
   via TimedExecution::track) opened and TOML-parsed config.toml a
   second time through its own private OnceLock instead of reusing
   the crate's existing cached_config(), doubling config I/O on a
   path the file's own comments document as latency-sensitive. Now
   reuses cached_config().

4 new regression tests, including one that forces a REAL SQLITE_BUSY
via a second connection holding an exclusive lock to verify the
migration genuinely fails closed (Err, no version bump, successful
retry once unblocked) rather than just asserting the code shape. The
4 existing migration tests needed their setup adjusted: calling
run_schema_migrations() twice in a row now correctly no-ops the
second time (that's the fix), so tests seed their pre-fix row against
a DB whose version is explicitly rolled back to simulate a real
pre-upgrade state, rather than an already-migrated one -- the old
setup happened to still "work" only because the old code re-ran the
migration unconditionally, i.e. it was inadvertently exercising bug 2
above instead of the intended one-time-migration path.

36 tracking tests green (including 4 new + 1 rewritten), full suite
green, clippy clean, 3x repeated default-parallel test runs clean (no
flakiness).
The SQLITE_BUSY variant could not reach the statement under test. An
EXCLUSIVE lock on a second connection blocks readers too, so
`run_schema_migrations` died on its first statement and the retroactive
cap UPDATE never ran; `is_err()` and the unchanged `user_version` were
both satisfied by that earlier failure. Discarding the UPDATE's Result
kept the test green.

An ABORT trigger on `UPDATE OF input_tokens` fails exactly that one
statement, and asserting the propagated error is the UPDATE's own
context pins which statement failed.

Also drop the stale `CommandStats` doc line the weighted-rate change
left behind, and a stray blank line in the read tests.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/core/tracking.rs Resolved
Comment thread src/core/tracking.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.

Round 1 of 3 — CHANGES REQUESTED

Claim: rtk gain's savings figures are inflated by unbounded per-call token estimates and by counting user-requested rtk read truncation as compression; cap the estimate, retroactively cap history, weight the per-command rate, and window the rtk read tracking baseline.

Scope: accept. This is the survivor for #3635, #1978, #891, #2699 and the second half of #1298 — all five are stale against develop and none is separately mergeable. Nothing else open touches these hunks; no maintainer branch competes. (round 1, frozen)

Ran: rtk read × 12 option forms (file + stdin) × base/head, byte-compared stdout; 7 real producers (git log/status/diff, ls -R, grep, tree, cargo check) × base/head; 4 migration scenarios × 2 binaries on seeded v1 DBs; 3 mutation checks against the PR's own tests. fmt clean, clippy 0 warnings, cargo test --all 3345+108 green, --ignored 8/9 (the 1 failure, test_git_status_not_a_repo_exits_nonzero, fails identically on develop). hyperfine rtk git status: 8.0 ms ±0.3 vs 8.2 ms ±0.4 on develop — the cached_config() reuse holds, no startup regression.

The core claim checks out. On an 11.6 MB file, rtk read --max-lines 5 went from a recorded 3,037,038 → 32 tokens (99.999 % "saved") to 32 → 32 (0 %), and stdout is byte-identical to develop in all 12 forms — the display-path regression codex caught stays fixed, including on the stdin path.

Blocks merge (1, frozen at round 1)

1. src/core/tracking.rs:471 — the one-time migration's permanent effect is decided by one arbitrary reading of a mutable runtime knob. Two arms, same class; the guard added in eb2f5b30 closes neither, because it only protects re-runs and the damage is done on the first run.

Arm A — a transient low cap destroys real history. Seeded v1 DB with legit = 6789→2081 (69.3 %) and the 135.7M phantom row:

RTK_TRACK_CAP_CHARS=400 rtk gain     # one invocation, any rtk command
  legit: 6789 -> 100    huge: 135722224 -> 100
rtk gain                             # cap back to default, forever after
  legit: 100            huge: 100

RTK_TRACK_CAP_CHARS is advertised in this PR's own docs hunk, so this is a documented knob, not a hostile input. One reading of it rewrites input_tokens, output_tokens, saved_tokens and savings_pct in place, with no backup and no recovery.

Arm B — 0 = uncapped at that moment forfeits the repair permanently. Same seeded DB:

RTK_TRACK_CAP_CHARS=0 rtk gain   # UPDATE skipped...
  user_version = 2               # ...but line 491 stamps v2 anyway
rtk gain                         # cap re-enabled, default
  huge: 135722224                # still there. "Tokens saved: 135.7M (100.0%)"

current_version < TOKEN_CAP_MIGRATION_VERSION is false from then on, so the exact row this PR exists to delete survives for the whole retention window while the write-time clamp quietly works on new rows. This is the failure mode the ?-propagation fix (case 2 in your comment block) was written to prevent, reached through the skip path instead of the error path.

I prototyped a fix, built it and ran all four scenarios against both binaries; your 36 tracking tests still pass unchanged:

// ceiling for the one-time repair is the constant, never a lower runtime override
let cap = match max_tracked_tokens() {
    usize::MAX => usize::MAX,
    n => n.max(DEFAULT_ESTIMATE_CAP_CHARS.div_ceil(4)),
};
...
// and don't stamp past the migration when it did not actually run
let version = if token_cap_migration_applied {
    SCHEMA_VERSION
} else {
    TOKEN_CAP_MIGRATION_VERSION - 1
};
conn.pragma_update(None, "user_version", version)?;
head prototype
plain upgrade legit 6789, huge 7500 legit 6789, huge 7500
first open cap=400 legit 100, huge 100 legit 6789, huge 7500
first open cap=0, then default legit 6789, huge 135722224 legit 6789, huge 7500
cap=0 always uv=2, untouched uv=1, untouched

I'm sending this back rather than pushing it: whether a user-configured cap should govern a one-time historical rewrite is your call, and it destroys data either way it's decided. Take the prototype, or a marker column, or a pre-migration backup — but the first run needs the same protection you already gave the second.

My two threads on eb2f5b3 — resolutions

Answering my own review notes here so they aren't scattered across threads.

Duplicated doc line (tracking.rs:299) → fixed in a7560d5a, pushed; thread resolved. The old avg_savings_pct line was left above the new weighted_savings_rate one, so the type alias documented itself twice and contradicted itself once.

SchemaVersions enum (tracking.rs:324) → worth doing — fold it into the blocker push, with the first discriminant pinned. The snippet in that thread uses default discriminants, which start at 0: Next as i64 - 1 then yields SCHEMA_VERSION = 1, not 2, and TOKEN_CAP_MIGRATION_VERSION becomes 1. Every install on develop already reads user_version = 1, so 1 < 1 is false and the retroactive migration never runs for a single existing user. Built both against a seeded v1 DB holding the 135.7M phantom row:

GatedMigration = 1:              uv 1 -> 2,  input 135722224 -> 7500   (36/36 tracking tests pass)
default discriminants (from 0):  uv 1 -> 1,  input 135722224 -> unchanged — migration never runs

So GatedMigration = 1 explicitly, with a comment saying the discriminants are the on-disk user_version values — the failure mode is silent on every existing install rather than loud at compile time.

That leaves GatedMigration itself unreferenced, and this repo builds clippy with -D warnings, so it is a hard error rather than a lint:

error: variant `GatedMigration` is never constructed
error: could not compile `rtk` (bin "rtk") due to 1 previous error

Three ways out, all built and gated here:

clippy tracking tests v1 DB upgrade
keep GatedMigration = 1, use it as the "migration did not run" stamp clean, no allow 36/36 uv 1→2, 135722224→7500
keep it + #[allow(dead_code)] clean via the allow 36/36 same
omit it, start at TokenCapMigration = 2 clean, no allow 36/36 uv 1→2, 135722224→7500

The first if the blocker below is closed by conditional stamping, which is the shape I prototyped: that fix needs exactly "the version to stamp when the token-cap migration did not run", and SchemaVersions::GatedMigration as i64 names it better than TOKEN_CAP_MIGRATION_VERSION - 1. The two then close each other's loose end. All five migration scenarios with both in place:

A plain upgrade                    uv=2   legit 6789 kept, huge -> 7500
B first open cap=400               uv=2   legit 6789 kept, huge -> 7500
C first open cap=0, then default   uv=1   untouched -> uv=2, huge -> 7500
D cap=0 always                     uv=1   untouched (repair still pending)
E three runs at default            uv=2   idempotent

If the blocker is instead closed with a marker column, nothing needs the value 1 and the third option is cleaner — omit the variant rather than keep it alive with an allow, which would mute the same signal for every future variant.

Optional — will not hold merge

  • src/core/tracking.rs:1419, avg_savings_per_command is the third sibling and is unconverted. Its inner AVG(savings_pct) is exactly what the new CommandStats warning at line 301 says never to write, and telemetry.rs:282-289 ships it in the same payload as the now-weighted low_savings_commands — two contradictory figures for one command. This is the other half of #1298, which you're already superseding; converting the inner aggregate (the outer AVG over command names is deliberately unweighted) finishes it. Sites: 5 total — summary.avg_savings_pct and overall_savings_pct were already SUM/SUM, get_by_command and low_savings_commands you fixed, this one is left.
  • Comment volume and review narration. 227 comment lines added, 29 % of the PR's non-blank additions. tracking.rs already runs verbose (24 blocks ≥8 lines on develop, longest 30), so most of that is house style — but the block at :421 is now the file's longest at 44 lines guarding 13 lines of SQL, and read.rs had zero blocks ≥8 lines before this PR and now has an 18-line one. Separately, seven comments narrate this PR's own review history rather than the code: "caught in review", "an earlier version computed…", "The old version discarded the UPDATE's Result via let _ =", "Two correctness requirements caught in review", "6i-b. Regression test for a real HIGH-severity bug caught in review". CONTRIBUTING.md:198 — comments explain why, not what; a reader six months out needs the invariant, not the diff of a version that never landed. Please rewrite those blocks whole rather than trimming around them.
  • read.rs:79 allocates a second full copy of the file. tracking_baseline calls apply_line_window, which returns content.to_string() when neither flag is set, on top of the content.clone() already made for raw. On a 300 MB read that's an extra 300 MB for a value that equals raw. Returning Cow or short-circuiting when both flags are None costs nothing.
  • Body says "40 new/rewritten unit tests"; the diff adds 17 (tracking 12, config 2, read 3) and rewrites none. Worth correcting before this is quoted anywhere.
  • docs/guide/resources/savings-explained.md doesn't mention the consequence users will actually notice: when raw and filtered both exceed the cap, the recorded saving is 0 %. rtk read --level minimal on that 11.6 MB file goes 32.1 % → 0.0 %, and rtk git diff HEAD~5 goes 63.7 % → 26.4 %. That's correct under the truncation model, but it will read as a regression to anyone watching their own numbers.

Fixup pushed: a7560d5a

test(tracking): make the migration-failure test fail on the bug it names — 2 files, +23/−24, gate green. Pushed as a fast-forward on top of eb2f5b3.

test_migration_failure_does_not_silently_mark_the_db_as_migrated does not test what it names. BEGIN EXCLUSIVE on a second connection blocks readers too, so run_schema_migrations dies on its first statement and the retroactive cap UPDATE never executes; is_err() and the unchanged user_version are both satisfied by that earlier failure. Asserting the error text proves it — it reads database is locked, never retroactive token-cap migration (schema v2) failed.

mutation: `?` -> `let _ =` on the cap UPDATE   =>  test still passes

The fixup swaps the lock for a BEFORE UPDATE OF input_tokens ABORT trigger, which fails exactly that statement, and asserts the propagated error is the UPDATE's own context. It passes clean and fails under the same mutation. Also drops the stale duplicate CommandStats doc line the weighted-rate change left behind, and a stray blank line in the read tests.

For contrast, the guard test is real: mutating current_version < TOKEN_CAP_MIGRATION_VERSION to always-true makes test_repeated_always_mode_migration_does_not_recap_with_a_new_lower_cap fail with the right message.

Checked and correct — no need to re-verify

  • Migration SQL. SQLite evaluates every SET right-hand side against pre-update values, so saved_tokens = MAX(MIN(input,cap) - MIN(output,cap), 0) uses originals; two-arg MIN/MAX are the scalar forms; the formula matches record's write-time saturating_sub + pct. Seeded regression row 20000/25000 → 7500/7500, saved 0 — no fake positive, as claimed.
  • usize::MAX as i64 guarded before the cast; cap = 0 skips the UPDATE.
  • read.rs: tracking_baseline is genuinely separate from raw, so never_worse still compares against full content and cannot print an unfiltered excerpt. Verified by stdout comparison, not by reading: 12 forms byte-identical. The mut→shadowing change in run_stdin is behaviour-neutral; the empty-filter fallback yields 0 %, not a fake saving.
  • Sibling call sites closed: --max-lines/--tail-lines exist only on Commands::Read in main.rs, and both run and run_stdin are converted. run_stdin verified separately (100000→31 becomes 31→31).
  • Independent clamping collapsing large genuine savings to 0 % is correct under the stated model — the agent truncates both sides at the same ceiling, so the token cost really is equal. Not a bug.
  • serde(default) parses pre-v2 configs; cached_config() avoids the second TOML parse, confirmed by hyperfine.

Hypotheses built and dropped

  • rtk git diff --max-lines has the same phantom-baseline bug as read. Could not reproduce — rtk git diff HEAD~30 --max-lines 20 records 0/0, the flag isn't reaching that path. git.rs is untouched here regardless, so it would be an issue, not a finding. Not filed without a repro.
  • Capping could turn a pre-cap regression into a fake positive. Constructed a mutation for it; the MAX(…, 0) floor holds for every row shape I could build. Dropped.
  • rtk find --max is a sibling of the same class. Not a flag this PR touches, and my repro was eaten by shell globbing. Not pursued.
  • The --max-lines baseline windows raw content while the output windows filtered content, so the two cover different spans of the file (N=50/200/1000 all record baseline slightly below output, floored to 0). Honest under the counterfactual "the user asked for N lines either way". Noted, not filed.

Next

Close both arms of finding 1 in one push, and fold the enum into it with GatedMigration = 1. Everything else is optional or mine to push. Once that lands I'll take the fixup with it and approve.

Rounds: 1/3. Threads: 2 open (finding 1; the SchemaVersions thread, resolved above but left open for the author to act on), 1 resolved this round by the fixup.

Comment thread src/core/tracking.rs Resolved
@KuSh

KuSh commented Sep 8, 2026 •

Copy link
Copy Markdown
Collaborator

Fixup pushed as a7560d5 — the review body's "prepared (not pushed)" line has been updated.

It contains only test/doc changes, no production behaviour change:

  1. Removes the duplicated CommandStats doc line (thread resolved).
  2. Replaces test_migration_failure_does_not_silently_mark_the_db_as_migrated. The BEGIN EXCLUSIVE lock blocks readers too, so run_schema_migrations died on its first statement and the retroactive cap UPDATE never executed — the propagated error read database is locked, never the migration'''s own context, so reverting ? to let _ = left the test green. It now uses a BEFORE UPDATE OF input_tokens ABORT trigger, which fails exactly that statement, and asserts which statement failed. It passes clean and fails under that mutation.
  3. One stray blank line in the read tests.

cargo fmt --all -- --check clean, cargo clippy --all-targets 0 warnings, cargo test --all green (3345 + 108).

The blocking item and the SchemaVersions decision are unchanged and still open for the author.

@yeahjack

yeahjack commented Oct 4, 2026

Copy link
Copy Markdown
Contributor

Hi @pszymkowiak, I'd like to coordinate a focused follow-up for rtk read tracking so we don't duplicate the baseline-windowing work in this PR.

The proposed scope is to apply the user-requested line window consistently across all five tracking paths, including early-return/fallback paths, and account for raw bytes on non-UTF-8 input so lossy decoding cannot manufacture a negative saving. This concerns the per-invocation baseline; it does not attempt to resolve the historical-cap migration decision highlighted in the review above.

Would you prefer to receive this as a patch for your PR, or would you be comfortable with a separate, narrowly scoped PR against develop for the read-window/raw-byte accounting changes? I'll coordinate the boundary before opening an overlapping PR.

Narrows this PR to the `rtk read` tracking baseline. develop now covers
the rest of what it set out to do, so those parts are taken from develop:

- per-command and low_savings_commands rates are already weighted
  (SUM(saved) / SUM(input)) on develop;
- oversized rows are excluded from the headline totals at read time
  (HEADLINE_INPUT_CAP_TOKENS) while staying visible for diagnosis, which
  makes the write-time cap, the RTK_TRACK_CAP_CHARS knob and the
  retroactive migration this PR carried unnecessary. Dropping the
  migration also closes the review blocker on it: there is no one-time
  rewrite of history any more.

What remains, rebased on develop's read paths:

- `tracking_baseline` windows the raw side with --max-lines, --head-lines
  and --tail-lines the same way the output is, and borrows the formatted
  raw string when no window is set, so a whole-file read costs no extra
  copy;
- the no-filter fast paths (head on an endless source, byte windows on a
  file and on stdin) record the window as both sides, for the same reason:
  the user asked for those lines, rtk did not compress anything;
- review-history narration is gone from the comments; the ignored
  regression test spawns rtk through test_isolation.
@pszymkowiak pszymkowiak changed the title fix(tracking): cap token estimates to stop savings-figure inflation fix(read): window the tracking baseline like the output, so a partial read is not booked as a saving Oct 22, 2026
@pszymkowiak

Copy link
Copy Markdown
Collaborator Author

@KuSh thanks for the round. Merged develop and narrowed the PR; details in the updated description.

Finding 1 (the migration's permanent effect decided by a runtime knob) is closed by removal rather than by the prototype: develop now excludes rows above HEADLINE_INPUT_CAP_TOKENS from the headline at read time and keeps them diagnosable, and already weights get_by_command / low_savings_commands. A write-time cap plus a one-time rewrite of history would fight that design (a capped row at exactly 7,500 is no longer "oversized" and would land in the headline at 0 %), so the cap, RTK_TRACK_CAP_CHARS, the migration and the SchemaVersions question all go away with it. Your fixup commit's test went with the migration it covered.

What is left is the rtk read baseline windowing, extended to the head/tail fast paths develop added since (they tracked the whole file against the window, same bug), with tracking_baseline returning Cow so the no-window path makes no second copy, and the review narration rewritten out of the comments. The "40 tests" claim is gone from the body too.

@pszymkowiak

Copy link
Copy Markdown
Collaborator Author

@yeahjack thanks for checking before overlapping. The push I just made covers the read-side baseline on all the rtk read tracking paths, including the no-filter fast paths and stdin, so no separate PR is needed for the line-window part. The raw-byte accounting on non-UTF-8 input (so lossy decoding cannot manufacture a negative saving) is not addressed here; a narrowly scoped PR against develop for that one is welcome once this lands.

@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 — CHANGES REQUESTED

Claim: rtk read with --max-lines, --head-lines or --tail-lines books the window it shows against the same window of raw input, on every tracking path (main path, stdin, and the three no-filter fast paths), instead of against the whole file.
Scope: accept (round 1, frozen). The narrowing to read.rs is yours and fits it: round 1's blocker on the history migration is closed by its removal, and both its threads are resolved below. This is the rtk read half of #2805. It lands before #4153 and #2790, which change the same read.rs tracking lines; they rebase onto it.
Ran: rtk read × 42 forms × develop 5ab629136 / head eed26a42e, each with its own history DB: 9 through rtk rewrite and then the command it returned (head -n 5, head -20, tail -n 5, tail -3, cat), 33 direct (file and stdin, -n, --level none/minimal/aggressive, CRLF, unterminated last line, non-UTF-8, empty, a window larger than the file, --max-lines 0, /dev/urandom). Stdout and exit code are byte-identical in 41/42; the 42nd is /dev/urandom. Six more --max-lines rows for finding 1. Invariants: under the hook, every decision, accounting (saved = input − output on every row). Savings: windowed reads with no filter now book 0% by design, filtered windows keep 24–43%, and whole-file reads are unchanged. The 20% floor (CONTRIBUTING.md) does not apply to an accounting change.
Pins: 8 decisions, 12 mutations, 6 survived: the two tracking_baseline call sites, the three fast paths and the unfiltered-baseline choice (M3–M8). The ignored test's own guard (M9) also survives; see Optional.
Matrix: executed round 1 @eb2f5b30, rerun this round on the new head; pin check: never before, executed this round
CI @eed26a42e: all green (21 pass, check-target skipped)

The core claim holds, and it is the latest repro on #2805: head -n 5 / tail -n 5 on an 8.8 KB file go from rtk gain 4.4K → 56 (98.7%) on develop to 56 → 56 (0%) here, with stdout unchanged. On a 100k-line log, head -20 goes from 2,072,224 → 398 to 398 → 398.

Blocks merge (2)

  1. src/cmds/system/read.rs:270 — the --max-lines baseline covers a different span from what is shown. The baseline is smart_truncate(raw, N). What is shown is never_worse(raw, smart_truncate(filtered, N)). When never_worse prints the raw file, or when the filtered file fits in N lines, the user sees more than the baseline counts:

    file, flags shown develop head
    3-line short.txt, --max-lines 2 the whole file, as cat 2 → 2, 0% 4 → 2, +50%
    same, -n --max-lines 2 the whole file 6 → 6, 0% 8 → 6, +25%
    3-line t.rs, --level minimal --max-lines 2 the whole filtered file 28 → 15, 46% 5 → 15, −200%
    120-line c.rs, --level minimal --max-lines 60 the whole filtered file 1238 → 370, 70% 489 → 370, 24%

    The first two book a saving on output identical to cat. The third records a negative row: at round 1 the write-time clamp floored this to 0, and develop's record keeps the sign, so it now lowers the totals. --head-lines and --tail-lines are correct in every case, because both sides there are byte windows of the same input. A correct fix keeps big.log --max-lines 5 at 44 → 44, books 0 when what is shown is the raw file, books the develop row (whole raw against the shown output) when the window cut nothing from the filtered content, and never records saved < 0 for any --max-lines × --level × -n combination.

  2. src/cmds/system/read.rs:129 — unpinned behaviour: no test sees what any call site books. The new unit tests call tracking_baseline directly, and they pin it: all six mutations of its guard and its -n branch turn them red. Nothing reads a tracking row, though, so each of these passes all 4391 lib tests, the 35 read tests (--include-ignored) and read_window_bytes_test:

    • M3 run: &tracking_baseline(…) → &raw (the 2,072,224-token row is back)
    • M4 run_stdin: the same
    • M5 head fast path: develop's track_bytes(cat_label, …, regular_file_len(file).unwrap_or(window.len()), …) restored
    • M6 file byte window: input &String::from_utf8_lossy(&bytes)
    • M7 stdin byte window: the same
    • M8 run: tracking_baseline(&filtered, …) in place of &content (books 0 on a filtered window)

    The test must run each path with RTK_DB_PATH set on the command and read the row back. Files: --head-lines 3, --tail-lines 3, --max-lines 3, -n --tail-lines 3. Stdin: --tail-lines 3, --max-lines 3, -n --tail-lines 3. Input: a source file of a few thousand lines. Each row must show input == output and input far below the whole file. A filtered window (--level minimal --tail-lines 4 on a commented .rs file) must also show input > output. Each mutation above must turn it red.

Optional — will not hold merge

  • read.rs:494: /// A device node reports a size of 0, which would book the window as pure cost. belonged to the removed regular_file_len test and now documents test_read_rust_file.
  • read.rs:779: the comment still narrates review history ("a bug caught in review … an earlier version computed …"), and :526 cites "250M+ phantom saved tokens in the wild". Both would read better stating the invariant they pin.
  • read.rs:808: test_max_lines_does_not_leak_unfiltered_raw_into_printed_output passes against the bug it names. Feeding the windowed raw into never_worse (M9) prints short\n[2 more lines], which contains no // a comment either. A positive assertion that a_very_long_real_code_line_that_should_still_print(); is printed would make it bite. It is also #[ignore], so CI never runs it.

Follow-up — outside this PR's claim

  • #3339 (evidence added: #3339 (comment)): windowed rtk reads of non-UTF-8 input book U+FFFD-expanded token counts on both sides (ratio stays 0%, absolute totals inflate up to 3× per invalid byte); the raw-byte accounting yeahjack offered to send once this lands would close it.

Checked and correct — no need to re-verify

  • Stdout and exit codes are unchanged against develop in all 41 deterministic forms, including the hook's head/tail rewrites, stdin, -n, CRLF, an unterminated last line and non-UTF-8.
  • --head-lines and --tail-lines book window → window on every path, with and without -n. With a filter level, the saving made inside the window is kept: 24–43% on commented code.
  • With no window, tracking_baseline borrows raw (Cow::Borrowed, pinned by test_tracking_baseline_without_a_window_borrows_raw), so a whole-file read makes no second copy.
  • Sibling entry points: Commands::Read is the only caller of read::run and read::run_stdin, both are converted, and toml_filter's head_lines/tail_lines don't track a read.
  • /dev/urandom --head-lines 2 used to book a negative row (159 → 286, the lossy output against the raw size). It now books 198 → 198.

Your questions

  • Closing round 1's finding 1 by removing the write-time cap and the migration, since develop excludes rows above HEADLINE_INPUT_CAP_TOKENS at read time → agreed. Both tracking.rs threads are resolved as no longer relevant at eed26a42e.

Next

Fix 1 so the four --max-lines rows above match develop (none negative) while big.log --max-lines 5 stays 44 → 44, and add a test that reads the booked row for each path in 2. Then this merges.
Rounds: 2. Threads: 2 open on this round's findings, 2 resolved this round (round 1's tracking.rs threads, code removed).

Comment thread src/cmds/system/read.rs Resolved
Comment thread src/cmds/system/read.rs Resolved
pszymkowiak and others added 2 commits October 26, 2026 17:09
With --max-lines the tracking baseline was smart_truncate(raw, N) while
the printed output was never_worse(raw, smart_truncate(filtered, N)): the
two sides truncated different text. A small file printed as cat would
booked a saving, a filter whose result fit the window lost its saving,
and a row could go negative.

The baseline now follows what was printed: when never_worse fell back to
the raw content, or when the window removed nothing from the filtered
content, the baseline is the whole raw content; otherwise it is the raw
content cut to the same window, never smaller than what was shown.

tests/read_tracking_baseline_test.rs runs the binary with an isolated
RTK_DB_PATH and reads the row it booked, for the file and stdin paths,
--head-lines, --tail-lines, --max-lines, -n and a filtered window. Three
of its cases fail on the previous code, one of them with a negative row.
The ignored unit test that spawned the binary moves there with a
positive assertion on the printed code line.
run_stdin computes window_cut on its own; only the file path had a test
for a filtered window that removed nothing.

Co-Authored-By: Claude Opus 5.5 <[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 3 — APPROVED

Claim: rtk read with --max-lines, --head-lines or --tail-lines books the span it shows against the same span of raw input, on every tracking path (main path, stdin, and the three no-filter fast paths), instead of against the whole file.
Scope: accept (round 1, frozen). Lands before #4153 and #2790, which change the same read.rs tracking lines.
Ran: rtk read × 55 forms × develop 7a73af1b3 / this head merged into it, each with its own history DB: 10 through rtk rewrite and then the command it returned, 45 direct (file and stdin, -n, --level none/minimal/aggressive, CRLF, unterminated last line, non-UTF-8, empty, a window larger than the file, --max-lines 0, /dev/urandom, the four round-2 --max-lines rows, and filtered windows that cut and that cut nothing). Stdout and exit code are byte-identical in 54/55; the 55th is /dev/urandom. Invariants: under the hook, every decision, accounting (saved = input − output, no row negative in any of the 55). Savings: windowed reads with no filter book 0% by design, filtered windows that cut keep 24–43%, filtered reads whose window cut nothing keep the whole-file saving (70.1% on c.rs, as on develop), whole-file reads are unchanged. The 20% floor (CONTRIBUTING.md) does not apply to an accounting change.
Pins: 13 decisions, 17 mutations, 1 survived your tests: run_stdin's let window_cut = windowed != filtered; → true. The fixup below adds the test that kills it.
Matrix: executed this round on the new head; pin check: executed this round
CI @12078a078: all green (21 pass); @bbaafe04a (with the fixup): all green (20 pass)

Blocks merge (0) — round 2's two are closed

  1. read.rs:270, the --max-lines span: fixed. The four rows now book what develop books: short.txt --max-lines 2 2 → 2, -n 6 → 6, t.rs --level minimal --max-lines 2 28 → 15, c.rs --level minimal --max-lines 60 1238 → 370; big.log --max-lines 5 stays 44 → 44.
  2. read.rs:129, unpinned call sites: fixed. tests/read_tracking_baseline_test.rs reads the booked row back and kills all six round-2 mutations (both call sites, the three fast paths, the unfiltered-baseline choice), plus the printed-window mutation through its positive assertion on the code line.

Checked and correct — no need to re-verify

  • The new rule holds on every row: a never_worse fallback books the file against itself, a window that cut nothing from the filtered text books the whole raw content against the output, and a cut window books the raw window, never below what was shown.
  • --head-lines and --tail-lines under the hook (head -n, head -20, tail -n, tail -3) still book window → window, with stdout unchanged.
  • Stdin with a filter that strips every line books the same row as develop.
  • Merged with the fixup into develop 5f4a4dcb9: fmt and clippy clean, 5263 tests pass. One Go help test fails on this machine on develop too, from a local toolchain shim unrelated to this PR.
  • A whole-file read of an 8 MB log takes 10.9 ± 0.9 ms on develop and 11.5 ± 0.5 ms here, within noise.

Your questions

  • None since round 2.

Next

Fixup bbaafe04a pushed and code-reviewed. It adds stdin_max_lines_that_cuts_nothing_books_the_filter_saving, the stdin twin of your file test, which kills run_stdin's let window_cut = true; (that mutation passed every test before). Its saving comes from minimal trimming blank lines rather than from // comments, so it does not depend on stdin's Unknown-language comment rules, which #4258 changes. It also replaces the test-module comment at read.rs:544, which said "books the develop row" and left out --head-lines, with a pointer to the cases documented on tracking_baseline. Approving.
Rounds: 3. Threads: 0 open, 2 resolved this round (round 2's, fixed by 12078a078).

@KuSh
KuSh merged commit 544ab1a into develop Oct 28, 2026
20 checks passed
@KuSh
KuSh deleted the fix/gain-savings-inflation branch October 28, 2026 23:53
@rtk-release-bot rtk-release-bot Bot mentioned this pull request Oct 28, 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.

3 participants