Repository navigation
fix(read): bound memory for --tail-lines instead of loading the whole file - #3132
albatrossflyon-coder wants to merge 2 commits into
Conversation
… 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
left a comment
There was a problem hiding this comment.
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.
|
Both issues fixed in
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. |
|
Both issues from the review are addressed in |
|
#3941 (merged 2026-09-13) moved |
Fixes #3107.
The bug
rtk readalways calledfs::read_to_stringon the entire file before applying--tail-lines/--max-lines, so a boundedtail -n 3000on 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-linespath.--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
tail_lines == 0, and a tail that spans multiple 64KB chunk reads.tail -n 3000on 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 --checkandcargo clippy --bin rtk -- -D warnings: both clean.Not addressed here
--max-linesunbounded read (see above) — separate follow-up.exclude_commandsnot suppressing thetail -nhook-rewrite — didn't touchhook/rewrite.rs/config.rsin 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.