Skip to content

fix(read): bound memory for --tail-lines instead of loading the whole file - #3132

Open
albatrossflyon-coder wants to merge 2 commits into
rtk-ai:developfrom
albatrossflyon-coder:fix/read-stream-memory-bound
Open

albatrossflyon-coder wants to merge 2 commits into
rtk-ai:developfrom
albatrossflyon-coder:fix/read-stream-memory-bound

Conversation

@albatrossflyon-coder

Copy link
Copy Markdown
Contributor

Fixes #3107.

The bug

rtk read always called fs::read_to_string on the entire file before applying --tail-lines/--max-lines, so a bounded tail -n 3000 on a 161GB log materialized the whole file (plus later .clone()s in the line-numbers/raw-comparison path) in memory before the tail window was ever applied — the reported 49GB RSS OOM, with no config escape hatch.

The fix

Added read_tail_lines_bounded: seeks backward from the end of the file in 64KB chunks, stopping once enough newlines have been seen to satisfy the requested tail. Memory use is bounded by the tail content itself, not file size. Used only for the --tail-lines path.

--max-lines (smart_truncate) is intentionally left unbounded in this PR: it scans the entire file for structurally important lines (function signatures, imports) anywhere in the document, so a prefix-only read would silently change its output — that's a separate, harder problem, flagged here as a follow-up rather than claimed as fixed.

Testing

  • 6 new unit tests covering the boundary cases that actually matter for a hand-rolled backward reader: normal tail, tail exceeding file length, no trailing newline, empty file, tail_lines == 0, and a tail that spans multiple 64KB chunk reads.
  • Manual verification against a real 136MB / 2,000,000-line file: 41ms runtime, byte-for-byte identical output to coreutils tail -n 3000 on the same file (previously this unconditionally read the full 136MB).
  • cargo test --bin rtk: 2463 passed, 8 ignored (pre-existing, require a built binary).
  • cargo fmt --check and cargo clippy --bin rtk -- -D warnings: both clean.

Not addressed here

  • --max-lines unbounded read (see above) — separate follow-up.
  • exclude_commands not suppressing the tail -n hook-rewrite — didn't touch hook/rewrite.rs/config.rs in this PR since the underlying crash this issue reports is now fixed regardless of whether that rewrite fires; happy to take that on separately if useful.

… file

Fixes rtk-ai#3107.

`rtk read` always called fs::read_to_string on the entire file before
applying --tail-lines/--max-lines, so a bounded `tail -n 3000` on a
161GB log materialized the whole file (plus later .clone()s) in memory
before the tail window was ever applied — a 49GB RSS OOM with no way
around it.

Added read_tail_lines_bounded: seeks backward from the end of the file
in 64KB chunks, stopping once enough newlines have been seen to satisfy
the requested tail, so memory use is bounded by the tail content itself
rather than file size. Used only for the --tail-lines path.

--max-lines (smart_truncate) is intentionally left unbounded here: it
scans the *entire* file for structurally important lines (function
signatures, imports) anywhere in the document, so a prefix-only read
would silently change its output. That's a separate, harder problem —
noted as a follow-up, not silently claimed as fixed.

Testing:
- 6 new unit tests covering the boundary cases that matter for a
  hand-rolled backward reader: normal tail, tail exceeding file length,
  no trailing newline, empty file, zero tail_lines, and a tail spanning
  multiple 64KB chunk reads.
- Manual verification against a real 136MB/2M-line file: 41ms runtime,
  byte-for-byte identical output to coreutils `tail -n 3000` on the same
  file (previously this would have read the full 136MB unconditionally).
- Full suite: 2463 passed, 8 ignored. cargo fmt --check and clippy
  (-D warnings) both clean.

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

The memory fix itself is solid — verified on a compiled build that a tiny --tail-lines on 200–300 MB files stays at ~16.6 MB RSS (OOM #3107 genuinely fixed), the backward-chunk reassembly is correct, and it's byte-exact with tail -n N across LF fuzzing (3141/3141), UTF-8/emoji straddling 64 KB chunk boundaries (6/6), and all the count edge cases (N=0/1/=lines/>lines, empty, no-trailing-newline). Nice work on the off-by-one margin and byte-level UTF-8 handling.

Two correctness regressions on the --tail-lines path, though — both should be fixed before merge:

1. CRLF line endings get normalized to LF (tail-lines only).
read_tail_lines_bounded does text.lines().join("\n"), which drops the \r:

file:  a\r\nb\r\nc\r\n
tail -n 1                → c\r\n   (63 0d 0a)   ✓
rtk read --tail-lines 1  → c\n      (63 0a)      ✗  \r lost
rtk read --max-lines 1   → CRLF preserved
rtk read (whole file)    → CRLF preserved

Only the new path corrupts CRLF; the whole-file and --max-lines paths preserve it, so this is a regression, not pre-existing.

2. Stateful filters lose context when combined with --level minimal|aggressive.
The bounded reader now feeds the filter only the tail slice instead of the whole file, and MinimalFilter/AggressiveFilter track block-comment state line-by-line:

fn main() {}
/* long comment
spanning several
lines
*/
fn foo() {}

rtk read file.rs --level minimal → strips the comment ✓
rtk read file.rs --level minimal --tail-lines 3 → lines\n*/\nfn foo() {} ✗ (comment fragment leaks; the filter never saw the opening /*)
Latent because the default level is none, but it's silent output corruption when both flags are used. The PR comment flags this context-loss risk for max_lines/smart_truncate but the same class now applies to tail_lines + stateful filtering.

Suggested fix: operate on raw bytes — locate the byte offset of the N-th-from-last \n and emit that slice verbatim (no .lines().join()), which fixes CRLF for free; and either skip stateful filtering on the tail-bounded slice or document that --tail-lines disables it. A CRLF test and a block-comment-straddling-the-tail-boundary test would lock both down.

Minor: from_utf8_lossy on the tail path silently succeeds on invalid UTF-8 while the whole-file read_to_string path errors — worth a deliberate call on which behavior wins.

Two correctness regressions flagged in review on rtk-ai#3132:

1. read_tail_lines_bounded and apply_line_window both used .lines()
   (which strips \r) then .join("\n") to extract the tail window,
   silently converting CRLF files to LF on the --tail-lines path only.
   Replaced with split_lines_preserve_cr, which splits on \n alone so
   any trailing \r survives the round trip.

2. MinimalFilter/AggressiveFilter track state (open block comments,
   docstrings) line-by-line from the top of the file. --tail-lines only
   reads the tail slice, so combining it with --level minimal|aggressive
   let the filter start mid-context and leak comment/docstring fragments
   as code. Now --tail-lines forces the effective level to none with a
   stderr warning, since there's no way to see prior context without
   reading the whole file (defeating the point of the memory bound).

Added regression tests for both cases.
@albatrossflyon-coder

Copy link
Copy Markdown
Contributor Author

Both issues fixed in f8a9a81:

  1. CRLF preservation — replaced the .lines().join("\n") round trip (which strips \r) with a split_lines_preserve_cr helper that splits on \n only, so any trailing \r survives. Applied in both read_tail_lines_bounded and apply_line_window. Added a regression test for each.
  2. Stateful filter context loss — --tail-lines now forces the effective filter level to none when combined with --level minimal|aggressive, with a stderr warning explaining why (the tail slice can't carry the file's prior block-comment/docstring state). Added tests for the override logic.

Live-verified against your exact repro cases — CRLF now round-trips byte-for-byte, and the block-comment-straddling-the-tail-boundary case now warns and shows raw content instead of leaking the comment fragment as code. Thanks for the thorough review.

@albatrossflyon-coder

Copy link
Copy Markdown
Contributor Author

Both issues from the review are addressed in f8a9a81: split_lines_preserve_cr now keeps \r intact on the --tail-lines path (matches whole-file/--max-lines behavior), and stateful filters are skipped on the tail-bounded slice to avoid the dangling-comment-fragment case. Added test_read_tail_lines_bounded_preserves_crlf to lock in the CRLF fix. Ready for another look whenever you get a chance.

@KuSh

KuSh commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator

#3941 (merged 2026-09-13) moved --head-lines and --tail-lines onto byte windows in src/cmds/system/read.rs, which keeps CRLF intact, so the split_lines_preserve_cr and apply_line_window changes here are no longer needed. What develop still lacks is the bounded backward read for --tail-lines: run() still loads the whole file with fs::read before taking the tail, which is the memory problem in #3107. Could you rebase onto current develop and narrow the PR to read_tail_lines_bounded and its chunk-boundary, empty-file, zero-tail and no-trailing-newline tests, returning bytes and wiring it in next to read_head_lines, the way develop already streams --head-lines when no filter level or line numbers are set? With that shape the forced --level none for filtered tails is no longer needed, so please drop it rather than change what --level does. Thanks for the careful work here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants