Skip to content

fix(read): fall back to raw bytes when a plain read is not valid UTF-8 - #4066

Merged
KuSh merged 3 commits into
rtk-ai:developfrom
sypsyp97:fix/read-non-utf8-raw-fallback
Nov 1, 2026
Merged

KuSh merged 3 commits into
rtk-ai:developfrom
sypsyp97:fix/read-non-utf8-raw-fallback

Conversation

@sypsyp97

@sypsyp97 sypsyp97 commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Motivation

run() reaches the raw-byte path only when byte_line_window() returns Some, which needs head_lines or tail_lines. A plain read has neither and falls through to String::from_utf8. The Claude Code hook splits cat f (rewritten to rtk read f, fails) from head -2 f (rewritten to rtk read f --head-lines 2, works) on the same file.

Same gate as #1019, which the stale bot closed on 2026-09-14 after it sat unreviewed. This one is written against current develop.

Test plan

  • cargo fmt --all && cargo clippy --all-targets && cargo test
  • Manual testing: rtk <command> output inspected

3 unit tests on the new raw_byte_window() gate, 2 integration tests (--ignored) that run the built binary against a Latin-1 file. With the one-line fallback dropped and the tests kept, cargo test read::tests:: -- --include-ignored is red:

test cmds::system::read::tests::test_raw_byte_window_passes_a_plain_read_through ... FAILED
test cmds::system::read::tests::test_read_non_utf8_file_is_byte_exact ... FAILED
test result: FAILED. 29 passed; 2 failed; 0 ignored; 0 measured; 3595 filtered out; finished in 0.78s

and green with it:

test result: ok. 31 passed; 0 failed; 0 ignored; 0 measured; 3595 filtered out; finished in 0.59s

cargo test --all on a clean HOME:

test result: ok. 3616 passed; 0 failed; 10 ignored; 0 measured; 0 filtered out; finished in 1.46s

On my own machine one test fails both before and after this change: test_claude_pipeline_rewrites_only_safe_final_stage reads ~/Library/Application Support/rtk/config.toml, I have grep in exclude_commands, so the rewrite it unwraps is None. Same failure on unmodified develop — same family as #2640.

Manual:

$ rtk read /tmp/nonutf8.log | cmp - /tmp/nonutf8.log && echo identical
identical
$ rtk read -l minimal /tmp/nonutf8.log; echo $?
cat: /tmp/nonutf8.log: invalid utf-8 sequence of 1 bytes from index 38
1

Copilot AI lite review requested due to automatic review settings September 14, 2026 18:18

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@CLAassistant

CLAassistant commented Sep 14, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@sypsyp97

Copy link
Copy Markdown
Contributor Author

@pszymkowiak — you confirmed this one on #1019 in May, so you already have the context. Same narrow gate, written against current develop, with tests. CLA is signed.

@rtk-wshm-sync-bot rtk-wshm-sync-bot Bot added bug Something isn't working read labels Sep 14, 2026
@rtk-wshm-sync-bot

Copy link
Copy Markdown

wshm · Automated triage by AI

📊 Automated PR Analysis

🐛 Type bug-fix
🟢 Risk low

Summary

Fixes rtk read <file> to write raw bytes verbatim when a plain read encounters a file that isn't valid UTF-8, instead of failing with a UTF-8 decode error. Adds a raw_byte_window() gate that returns the raw byte slice for plain reads and head/tail windows, while still decoding (and erroring) when filtering, line numbers, or --max-lines require text.

Review Checklist

  • Tests present
  • Breaking change
  • Docs updated

Linked issues: #4065


Analyzed automatically by wshm · This is an automated analysis, not a human review.

@sypsyp97
sypsyp97 force-pushed the fix/read-non-utf8-raw-fallback branch from 7785ab0 to 412d34e Compare September 14, 2026 18:28
@sypsyp97

Copy link
Copy Markdown
Contributor Author

Rebased onto develop (5e0f92c). The let-chains refactor and the 2024 style-edition reformat both touched the lines this changes, so the conflict was in read.rs; resolved by keeping the new let bytes = fs::read(file)... formatting and routing it through raw_byte_window(). Numbers in the description were re-run on the new base.

@dopaemon dopaemon left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked this out locally, built it, and exercised the gate against a Latin-1 file (\xe9). The change is correct and behavior-preserving for every path that still needs text.

case result
rtk read nonutf8.log byte-exact (cmp clean), exit 0
rtk read -l minimal / -n still errors, exit 1 — correct, filtering needs &str
valid UTF-8 plain read identical output, no regression
no trailing newline / empty file verbatim, exit 0
--max-lines unchanged

cargo clippy --all-targets clean, cargo test --bin rtk read::tests:: -- --include-ignored → 31 passed. byte_line_window() is still tried first inside raw_byte_window(), so head/tail windows keep winning over the new pass-through exactly as before.

One gap: run_stdin() still fails on non-UTF-8

run_stdin() carries a copy of the same gate and wasn't touched, so the sibling path is still broken on this branch:

$ cat nonutf8.log | rtk read -
cat: -: invalid utf-8 sequence of 1 bytes from index 18   # exit 1

Same root cause, and raw_byte_window() is already the shared helper — it looks like a one-line swap in run_stdin plus one test. Since the framing here is "rtk read should behave like cat", leaving rtk read - failing means pipelines (curl … | rtk read -) still hit the original bug. Happy either way on doing it here or as a follow-up, but it's worth not losing.

Nits (non-blocking)

  • raw_byte_window takes 6 positional params; (level, line_numbers) are really one "needs decoded text" question.
  • test_raw_byte_window_keeps_line_windows passes max_lines + tail_lines together, which clap's conflicts_with_all makes unreachable from the CLI. Harmless as a unit test, just noting it isn't a reachable state.
  • Tracking on the raw path counts both sides via from_utf8_lossy, so stats for non-UTF-8 files are approximate. Pre-existing, cosmetic.

@sypsyp97

Copy link
Copy Markdown
Contributor Author

Thanks — you were right, and it was worth not losing. Fixed here in 7cb3a04 rather than as a follow-up, since rtk read - failing is the same bug and splitting it would leave the pipeline case broken between merges.

run_stdin() now calls raw_byte_window() with the same arguments the file path passes, so byte_line_window() has a single caller again.

case before after
cat nonutf8.log | rtk read - exit 1, no output byte-exact (cmp clean), exit 0
… | rtk read - -l minimal exit 1 exit 1 — filtering still needs &str
… | rtk read - -n exit 1 exit 1 — same
… | rtk read - --head-lines 2 worked unchanged, window still wins
valid UTF-8 stdin fine identical output
empty stdin fine 0 bytes, exit 0

New #[ignore] integration test test_read_stdin_non_utf8_is_byte_exact writes the Latin-1 bytes into a piped child and asserts stdout is verbatim. cargo test --bin rtk read::tests:: -- --include-ignored → 32 passed (was 31). Full suite on a clean HOME: 3616 passed / 0 failed. cargo fmt --all --check and cargo clippy --all-targets clean; semgrep against the PR base is 0 findings.

On the nits:

  • test_raw_byte_window_keeps_line_windows — agreed, --max-lines + --tail-lines is unreachable past conflicts_with_all, so the assertion was covering a state that cannot occur. Dropped the max_lines argument; the tail window itself is still asserted.
  • 6 positional params — left as-is deliberately. Folding (level, line_numbers) into a "needs decoded text" type reads better in isolation, but the argument list here is the same shape run() and run_stdin() already take from the CLI layer, so the wrapper would have to be built and destructured at both call sites to save one bool. Happy to do it if you'd rather see it.
  • from_utf8_lossy in tracking on the raw path — agreed it's approximate for non-UTF-8 input, and it's pre-existing. Making it exact means track() taking bytes, which touches every caller; out of scope for this gate, but I can open a separate issue for it.

A plain `rtk read <file>` decoded the whole file into a String, so any file
that is not valid UTF-8 exited 1 with no output at all. The same file read
through --head-lines or --tail-lines already worked, because those windows
slice on byte offsets and never decode.

Both now go through raw_byte_window(), which also returns the whole input
when no window, filter level, line numbers or --max-lines is in play. Those
four keep decoding, since each of them operates on a &str.
run_stdin() carried its own copy of the old gate, so `rtk read -` still
decoded the whole stream into a String and exited 1 on anything that is
not valid UTF-8 -- the sibling of the bug the file path just fixed, and
the one that breaks pipelines like `curl ... | rtk read -`.

It now calls raw_byte_window() with the same arguments the file path
passes, so a plain stdin read and head/tail windows write bytes through
verbatim, while a filter level, line numbers or --max-lines keep
decoding and keep reporting the error.

Also drops --max-lines from test_raw_byte_window_keeps_line_windows: it
was paired with --tail-lines, which clap's conflicts_with_all makes
unreachable from the CLI, so the assertion covered a state that cannot
occur. The tail window itself is still asserted.
@sypsyp97
sypsyp97 force-pushed the fix/read-non-utf8-raw-fallback branch from af8174c to e5c79f4 Compare October 30, 2026 16:11
@sypsyp97

Copy link
Copy Markdown
Contributor Author

@aeppling @KuSh, could one of you take a look when you get a chance? It's rebased onto current develop with no conflicts, and the rtk read - stdin path dopaemon flagged is fixed in the same PR. CI needs a maintainer to approve the workflow run for this fork. Happy to adjust anything.

The file and stdin pass-through tests were `#[ignore]`, and CI runs `cargo test --all`
without `--include-ignored`, so reverting the fallback at either call site left CI green.
They now live in tests/read_window_bytes_test.rs next to the window tests, and also check
that --level, --line-numbers and --max-lines still report undecodable input on both paths.

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 1 — APPROVED (after maintainer fixup ea51119)

Claim: a plain rtk read <file> / rtk read - writes the bytes through unchanged when nothing downstream needs text, so a non-UTF-8 input reads like cat instead of exiting 1 with no output; --level, -n and --max-lines still decode and still report the error.
Scope: accept (narrow claim, as stated); maintainer PRs: checked against #4153 (KuSh): both test sets pass on the merge of the two onto develop.
Ran: rtk read on 15 inputs (Latin-1 incl. a real iconv -t ISO-8859-1 text, truncated multibyte at EOF, UTF-16 BOM, CRLF without final newline, an ELF binary, a gzip file, a 7.9 MB Latin-1 log, 4 valid UTF-8 shapes, empty, a path with a space) × file and stdin × develop, this head and native cat (bytes by md5, exit code, stderr apart); -l minimal, -l aggressive, -n, --max-lines 2, --head-lines 0|2, --tail-lines 2|1000000 × 3 inputs × file and stdin; several files with the non-UTF-8 one not first, - in the middle of the list, a directory and a missing file in the list; 13 hook forms through rtk rewrite then the rewritten command, plus a 243-spelling sweep of cat/head/tail flags (24 reach rtk read); a FIFO, /dev/zero and /dev/urandom under alarm; a broken pipe; tracking rows; -v/-vv. Invariants: non-default targets, under the hook, split streams, every decision. Savings: n/a, a plain read is a pass-through and books 0% on both sides, as a valid-UTF-8 plain read already did.
Pins: 14 decisions (4 in raw_byte_window, 5 per call site), 14 mutated; 3 survived CI's suite, closed by the fixup (below)
Matrix: executed this round; pin check: executed this round
CI @e5c79f48c: all green (15/15); fixup ea51119: all green (15/15; macOS rerun once for the known probe flake #4912)

Blocks merge (0)

Nothing. The one gap the pin check found was a missing test for behaviour that the matrix shows correct, so it is closed by a maintainer fixup rather than handed back.

Fixup ea51119 — test(read): run the plain-read non-UTF-8 tests in CI

CI runs cargo test --all without --include-ignored, so the three #[ignore] tests that spawn the binary never ran there. With them ignored, three mutations left CI green:

  • reverting the fallback at the run() call site (max_lines → max_lines.or(Some(usize::MAX)), i.e. develop's behaviour for a plain file read);
  • the same at the run_stdin() call site;
  • passing false for line_numbers at the run() call site, which makes rtk read -n f print the file raw, without numbers. No test caught that one, ignored or not.

The commit moves the file and stdin pass-through tests into tests/read_window_bytes_test.rs (not ignored, next to the window tests and their read_stdin helper) and replaces the "still errors when filtering" test with one that runs -l minimal, --level aggressive, --line-numbers and --max-lines 2 on both a file and stdin, asserting exit 1, empty stdout and rtk's own cat: <path>: line, and that the same options succeed on valid input. All three mutations above, and the four level/max_lines call-site mutations, turn it red. The three #[ignore] copies in read.rs are removed, since the new tests cover what they checked. Nothing in src/ changes.

Filed as follow-ups

  • cat -n <file> → rtk read -n <file> still exits 1 on a non-UTF-8 file where native cat -n prints it (also cat -n a b and cat -n -; the only hook-reachable spelling of the 243 swept that still fails). Same on v1.1.0, outside this claim; it is the second half of #4065, already described in the comment there, so #4065 stays open for it. I changed the description to Part of #4065 so that merging this leaves it open.
  • rtk read - --level aggressive prints nothing and exits 0 when the filter removes every line (the file path falls back to the raw content, stdin does not). Same on v1.1.0; absorbed by existing #3038.

Checked and correct — no need to re-verify

  • Every non-UTF-8 input above, from a file and from stdin, comes out byte-identical to cat with exit 0; develop exited 1 with empty stdout on each.
  • Valid UTF-8 input (source file, CRLF, no final newline, empty, 17 KB text) prints the same bytes as develop on the plain path and on every option form.
  • -l, -n and --max-lines on non-UTF-8 input still exit 1 with the decode error, from a file and from stdin; --head-lines / --tail-lines windows are unchanged.
  • Several files: rtk read a.rs latin1.log b.txt now matches cat (94 bytes, exit 0) where develop printed 58 bytes and exited 1; with a directory and a missing file in the list, stdout and exit 1 match cat.
  • Under the hook: cat f, cat a b c, cat 'my notes.txt', cat true.elf rewrite to rtk read … and now match native; head -n/tail -n forms unchanged.
  • A FIFO whose writer closes now reads byte-exact; /dev/zero and /dev/urandom block on both builds (the whole-file read was already there on develop, and cat f already rewrote to it).
  • rtk read big | head -c 10 ends with SIGPIPE (141) like cat.
  • hook.before_tool.read rules are still evaluated before the file is read.
  • Tracking: non-UTF-8 reads are now booked as 0% cat <file> / cat - (stdin) rows, as valid-UTF-8 plain reads already were.
  • -v / -vv on a plain read no longer print the Lines: N -> N (0.0% reduction) and Detected language lines, as already for the head and tail windows on develop.
  • fmt, clippy (0 warnings) and cargo test --all (5424 passed) on this head merged onto current develop; the same with the fixup (5426 passed).

Your questions

  • "6 positional params — Happy to do it if you'd rather see it." → drop: keep the signature as it is; it mirrors what run() and run_stdin() receive.
  • "from_utf8_lossy in tracking … I can open a separate issue for it." → no issue needed: #4153 books these rows by byte length (track_bytes), which makes them exact.

Next

fixup ea51119 pushed, code-reviewed: moves the plain-read tests into the CI suite and pins the text options on both paths; description now says Part of #4065 — approving.
Threads: 0 open, 0 resolved this round.

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

Labels

bug Something isn't working read

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants