rtk icon indicating copy to clipboard operation
rtk copied to clipboard

Silent output corruption when stdout is piped or redirected (suggest isatty passthrough)

Open panwudi opened this issue 7 months ago • 17 comments

Summary

When rtk rewrites a command (e.g. grep, find, ls) and the output is piped into another program or redirected to a file, the compressed human-readable format silently corrupts the downstream consumer. The caller usually has no way to detect this until a downstream assertion fails.

We suggest RTK follow the same convention as ls --color=auto, git diff, grep --color=auto, etc.: check isatty(stdout) at runtime, and fall back to raw passthrough whenever stdout is not a TTY (pipe, redirect, or process substitution).

Reproduction

Environment: rtk 0.36.0, Claude Code PreToolUse hook (rtk-rewrite.sh v3), Linux.

# A file with exactly 83 lines matching the pattern                                                                                                                                                                                                                                                     
$ grep -cE '^- \[ \]' TODO.md                                                                                                                                                                                                                                                                             
83                                                                                                                                                                                                                                                                                                        
                                                                                                                                                                                                                                                                                                          
# Naive redirection through RTK hook rewrite                                                                                                                                                                                                                                                              
$ grep -n '^- \[ \]' TODO.md > /tmp/pending.txt                                                                                                                                                                                                                                                         
$ wc -l /tmp/pending.txt                                                                                                                                                                                                                                                                                  
136 /tmp/pending.txt   # <-- WRONG, expected 83                                                                                                                                                                                                                                                         
                                                                                                                                                                                                                                                                                                          
$ head -3 /tmp/pending.txt                                                                                                                                                                                                                                                                              
83 matches in 36F:                                                                                                                                                                                                                                                                                        
                                                                                                                                                                                                                                                                                                          
// ... 134 more lines (total: 136)...                                                                                                                                                                                                                                                                     

The file contains RTK's compressed human summary ("83 matches in 36F", "// ... 134 more lines", per-file headers like "[file] 921 (1):"), not raw grep output.

Using rtk proxy as a manual opt-out recovers correctness:

$ rtk proxy grep -n '^- \[ \]' TODO.md > /tmp/pending.txt                                                                                                                                                                                                                                               
$ wc -l /tmp/pending.txt                                                                                                                                                                                                                                                                                  
83 /tmp/pending.txt   # correct

Why this matters

  1. Silent failure. The downstream consumer (wc -l, jq, diff, curl -d @file) sees syntactically valid but semantically wrong input. No error message, no exit code hint — the only signal is a factual discrepancy the caller may or may not notice.

  2. Compounds through pipelines. If the corrupted output is fed to an LLM subagent (our case: classifying 83 TODO items via a MiniMax subagent), the downstream LLM receives garbage input and produces confidently wrong output. Correctness has to be verified via counts/diffs afterwards, because
    the corruption leaves no exception trail.

  3. AI agent risk. RTK's primary audience is LLM hooks (per the README). LLM agents frequently pipe grep/find output into jq/awk/other tools to build reasoning pipelines. A compression mode that is opt-out rather than opt-in is hostile to this use case.

Suggested fix

In the Rust code path that emits compressed output, add an IsTerminal check before applying compression:

use std::io::IsTerminal;                                                                                                                                                                                                                                                                                
                                                                                                                                                                                                                                                                                                          
if std::io::stdout().is_terminal() {
    print_compressed(output);                                                                                                                                                                                                                                                                             
} else {                                                                                                                                                                                                                                                                                                  
    print_raw_passthrough(output);
}                                                                                                                                                                                                                                                                                                         

std::io::IsTerminal is stable since Rust 1.70, so no external crate is needed.

This is the same contract as:

  • ls --color=auto
  • grep --color=auto
  • git diff (pager auto-detection)
  • cargo (coloring)

Users who explicitly want compression in a non-TTY context can still opt in via an env var (e.g. RTK_FORCE_COMPACT=1) or a rtk compact <cmd> subcommand.

Workaround we adopted

Until this is fixed upstream, we added a redirection/pipe detection layer to our rtk-rewrite.sh PreToolUse hook:

# Bypass RTK rewrite when the command shape indicates the output will be                                                                                                                                                                                                                                
# consumed by a program (file, pipe, substitution) instead of displayed.                                                                                                                                                                                                                                  
if [[ "$CMD" =~ [\>\|\`] ]] || [[ "$CMD" == *'$('* ]] || [[ "$CMD" == *'<('* ]]; then
  exit 0  # pass through unchanged — no RTK rewrite                                                                                                                                                                                                                                                       
fi                                                                                                                                                                                                                                                                                                        

This works at the hook layer but does not help users who invoke rtk directly from an interactive terminal and then pipe it somewhere unexpectedly. An upstream fix is strictly better.

Design note

RTK's current default is compress unless opted out via rtk proxy. We would gently suggest the inverted default is safer: raw passthrough unless stdout is a TTY. Compression is valuable for humans reading a terminal; it is actively harmful for machines reading a stream. The TTY boundary is the most reliable signal for which audience is on the other end.

Environment

  • rtk version: 0.36.0
  • OS: Linux 6.8.0-106-generic
  • Shell: zsh / bash
  • Consumer: Claude Code LLM hook (rtk-rewrite.sh v3)

Happy to file a PR implementing the IsTerminal check if the maintainers agree with the direction.

panwudi avatar Apr 14 '26 00:04 panwudi

Follow-up: anti-tamper UX for legitimate hook modifications

Filing this as a follow-up to the silent-corruption discussion above, since both are about the hook layer. We ran into a second design issue while implementing the workaround.

What happened

I added a redirect/pipe detection bypass to ~/.claude/hooks/rtk-rewrite.sh (the workaround mentioned in the original issue) and immediately hit:

rtk: hook integrity check FAILED                                                                                                                                                                                                                                                                        
  Expected hash: 742418d70728fc3b...                                                                                                                                                                                                                                                                      
  Actual hash:   243e9cf13ac35a0a...                                                                                                                                                                                                                                                                      
                                                                                                                                                                                                                                                                                                          
  The hook at ~/.claude/hooks/rtk-rewrite.sh has been modified.                                                                                                                                                                                                                                           
  This may indicate tampering. RTK will not execute.                                                                                                                                                                                                                                                      
                                                                                                                                                                                                                                                                                                          
  To restore:  rtk init -g --auto-patch                                                                                                                                                                                                                                                                   
  To inspect:  rtk verify                                                                                                                                                                                                                                                                                 

All bash commands in all Claude Code sessions (across all projects on this machine) immediately stopped working. The recovery suggestion (rtk init -g --auto-patch) would have overwritten my modification and lost the silent-corruption fix.

I worked around it by:

  1. chmod 644 ~/.claude/hooks/.rtk-hook.sha256 (the file is intentionally 444)
  2. Writing the new sha256 of the modified hook into the file
  3. chmod 444 to restore RTK's intent

This works but is hostile to legitimate users who have a valid reason to patch the hook (in our case, a bug fix that hasn't landed upstream yet).

Suggested UX improvements (any of these would help)

  1. rtk hook approve subcommand — computes the current hook's sha256 and writes it to .rtk-hook.sha256. Equivalent to "I have reviewed this modification and approve it." Doesn't require the user to know about the hidden hash file or its format.

  2. In-hook self-declaration — recognize a magic comment like # rtk-allow-modification: <reason> near the top of the hook script. RTK's integrity check sees this and skips (or downgrades to a one-line warning instead of refusing to run). The comment is auditable; users have to opt in
    explicitly per modification.

  3. Better recovery message — at minimum, the To restore line in the error should mention the alternative rtk hook approve (or whatever the equivalent becomes), not just the destructive auto-patch.

  4. Distinguish "tampering" from "modification" — the current language ("This may indicate tampering. RTK will not execute.") assumes a hostile threat model. A more neutral phrasing like "Hook checksum mismatch — review changes and run rtk hook approve if intended" would be both more accurate and less alarming.

Threat model sanity check

The current anti-tamper design is reasonable defense against a third-party that modifies the hook to insert malicious commands without the user knowing. But it provides no defense against:

  • The user themselves (root of trust) intentionally patching the hook
  • A genuinely malicious third-party that has shell access (they can also chmod the hash file, as I just demonstrated)

So the defense is mostly "alert the user that the hook changed and refuse to run until they acknowledge." That's a useful property to keep, but the acknowledgement path should be a one-line rtk hook approve rather than chmod gymnastics.

Combined with the original issue

The two findings together suggest the same underlying observation: RTK's hook layer is the seam where users with legitimate needs collide with RTK's defaults. Both the silent-corruption issue (binary-level fix needed) and the anti-tamper UX (CLI subcommand needed) would benefit from treating
"user has patched the hook for a real reason" as a first-class case rather than an edge case.

Happy to file separate issues if you'd prefer to track them independently — let me know.

panwudi avatar Apr 14 '26 00:04 panwudi

wshm · Automated triage by AI

🔍 Automated Triage

🐛 Category bug
🟠 Priority high
🎯 Confidence 88%

Summary

RTK silently corrupts piped/redirected output by applying human-readable formatting instead of raw passthrough; recommends isatty(stdout) check to match ls/git/grep color=auto convention


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

pszymkowiak avatar Apr 17 '26 15:04 pszymkowiak

This really gets to the heart of a huge design-problem.

gherghett avatar May 06 '26 14:05 gherghett

Another instance of this, and an argument that the isatty fix lands broader than it looks: cargo test piped to grep.

When the Claude Code hook rewrites cargo test 2>&1 | grep "test result" into rtk cargo test 2>&1 | grep "test result" (#1560), rtk cargo test's stdout is a pipe, not a TTY. So the IsTerminal check you're proposing would make it pass through raw cargo output there, and the grep matches again. The isatty fix resolves the pipe-rewrite bug too, without the rewrite layer having to special-case which downstream tools are "rtk-compatible."

Confirmed on 0.40.0:

raw:            test result: ok. 487 passed; 0 failed; ...; finished in 19.38s
rtk cargo test: cargo test: 487 passed (28 suites, 19.38s)

The reformatted line drops the test result token, so any downstream grep/awk built around cargo's real output gets nothing. +1 on raw-passthrough-unless-TTY as the default.

technicalpickles avatar Jun 01 '26 16:06 technicalpickles

One caution before isatty(stdout) passthrough lands as the fix: a literal isatty check is not equivalent to the string-level fix in #1639, and it breaks the Claude Code hook integration in the common case.

Under rtk hook claude, the harness captures the command's stdout via a pipe. So rtk's stdout is never a TTY — not just when the user wrote a pipe, but for every hook-rewritten command. A runtime isatty(stdout) passthrough would therefore fall back to raw for a bare rtk git status (no pipe, no redirect) too, i.e. it disables compaction for exactly the display commands the hook exists to compact. Net effect: ~0 token savings under the hook.

The cargo test | grep argument above is right that isatty happens to fix the within-pipe case, but only because there the pipe to grep is what makes stdout non-TTY. It can't distinguish "piped to another shell command (reformat = bad)" from "captured by the agent (reformat = the whole point)" — both are non-TTY.

That distinction lives in the command string, which the hook already parses. #1639's "leave pipe groups raw end-to-end" is the right shape: detect that the rtk segment feeds a pipe / redirect / process-substitution and skip the rewrite, while still compacting a segment whose output is the final result. Same signal the rewriter already has, no runtime TTY probe.

Verified on 0.42.0 (linux). Happy to test a candidate build.

antmid avatar Jun 02 '26 22:06 antmid

Guys, please help! i updated headroom, which includes RTK internally using headroom update.

% headroom -v
headroom, version 0.28.0

i restarted claude, which is wrapped by headroom and stiil see error:

 ▎ Fable 5 is back.                                                                                                                                                                                                                         
 ▎ Until July 7, you can use up to 50% of your plan's weekly usage limit on Fable 5. If you hit your limit, you can continue on Fable 5 with usage credits. Fable 5 draws down usage faster than Opus 4.8. Learn more                       
                                                                                                                                                                                                                                            
❯ ls                                                                                                                                                                                                                                        
                                                                                                                                                                                                                                            
⏺ Dir show. ls run now.                                                                                                                                                                                                                     
                                                                                                                                                                                                                                            
  Listed 1 directory                                                                                                                                                                                                                        
  ⎿  PreToolUse:Bash hook error                                                                                                                                                                                                             
  ⎿  Failed with non-blocking status code: [rtk: No such file or directory (os error 2)]                                                                                                                                                    
                                                                                                                                                                                                                                            
⏺ Hook fail block cmd. rtk-rewrite.sh hash mismatch — flagged tamper.                                                                                                                                                                       
                                                                                                                                                                                                                                            
  Expected: 7979f7ea0f8bedda...                                                                                                                                                                                                             
  Actual: a6f4fa957d0691ea...                                                                                                                                                                                                               
                                                                                                                                                                                                                                            
  Not my doing — first cmd this session. Could be legit update or real tamper. Options:                                                                                                                                                     
                                                                                                                                                                                                                                            
⏺ Claude asked:                                                                                                                                                                                                                             
  ⎿  · rtk hook integrity check fail block bash. How proceed? (Run rtk verify first / Restore now (rtk init -g --auto-patch) / I'll handle it myself)                                                                                       
     ⏺ No response after 60s — continued without an answer                                                                                                                                                                                  
                                                                                                                                                                                                                                            
⏺ No response — proceed careful. Inspect hook file via Read (not Bash, avoid triggering broken hook) first.                                                                                                                                 
                                                                                                                                                                                                                                            
  Read 2 files                                                                                                                                                                                                                              
  ⎿  PreToolUse:Bash hook error                                                                                                                                                                                                             
  ⎿  Failed with non-blocking status code: [rtk: No such file or directory (os error 2)]         

 Hook file corrupted. Lines 28-61 broken — missing | pipes, broken jq quotes, truncated strings (e.g. line 34 CMD=$(echo "$INPUT" -r '.tool_input.command — malformed, line 49-61 same). This is real damage, not just version bump. Hash  
  mismatch legit.                                                                                                                                                                                                                           
                                                                                                                                                                                                                                            
  Flagging: this looks like accidental corruption (partial write/edit) rather than malicious tamper — broken syntax, not added logic. But can't rule out tamper from content alone.                                                         
                                                                                                                                                                                                                                            
  Recommend: don't blind rtk init -g --auto-patch (auto-patch could just re-hash corrupted file, masking real state). Best path — reinstall/regenerate hook from known-good source:                                                         
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
 ☐ Corrupt hook                                                                                                                                                                                                                             
                                                                                                                                                                                                                                            
rtk-rewrite.sh hook corrupted (broken jq syntax, missing pipes lines 28-61). Confirmed real damage not just version diff. How fix?                                                                                                          
                                                                                                                                                                                                                                            
❯ 1. rtk init -g --auto-patch                                                                                                                                                                                                               
     Regenerate hook fresh from rtk binary + re-hash. Recommended: replaces broken file with known-good version                                                                                                                             
  2. Disable hook, move on                                                                                                                                                                                                                  
     Rename/move rtk-rewrite.sh aside so bash stops blocking; skip rtk token-saving rewrites this session                                                                                                                                   
  3. Leave as-is, I'll fix later                                                                                                                                                                                                            
     Stop here; bash stays blocked until user fixes manually                                                                                                                                                                                
  4. Type something.                                                                                                                                                                                                                        
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  5. Chat about this                      

so headroom changed rtk-rewrite.sh, but in some way claude doesn't like this new version. what i should to do to fix the issue?

thanks!

lon9man avatar Jul 01 '26 21:07 lon9man

Still reproducing in rtk 0.42.4, and the 0.43.0 source doesn't appear to have the isatty guard yet: src/cmds/system/search.rs and src/cmds/system/read.rs have no IsTerminal check in the filter path (only ls, curl, and gain have TTY checks; the never-worse guard in 9d9ad7c only touches pipe_cmd.rs). The resolved-pending-close label may be premature.

Adding a sharper variant I didn't see in the thread: a silent false-negative pipeline, not just redirect corruption.

Repro (rtk 0.42.4, via a PreToolUse hook that rewrites the first pipeline stage to rtk grep; ~68K-line application log):

# ground truth: 2 lines match both
$ awk '/scheduler task finished/ && /status=failed/' big.log | wc -l
2

# first stage rewritten to `rtk grep`; second grep is real, reads the pipe
$ grep "scheduler task finished" big.log | grep "status=failed"
# (no output, exit 1)

The first rtk grep stage emits its grouped/elided view (N matches in M files: + file:line:...context... + [+N more]) instead of raw lines, so status=failed (past the elided window) is dropped before the second grep sees it. The caller gets a confident empty result — harder to notice than the redirect line-count discrepancy in the OP.

Same root cause for head:

$ head -1 big.log | cut -c1-25
[68773 more lines]   # rtk read --max-lines 1 emits the "[N more lines]"
                     # footer instead of the first line

The isatty-passthrough fix from the OP, applied to the grep/read filter path, would close both the redirect case and this pipeline false-negative. Workaround we use: single-pass awk '/X/ && /Y/' (awk isn't rewritten) or rtk run grep … | grep ….

0xbentang avatar Jul 03 '26 06:07 0xbentang

Another instance of this, this time for jq (not yet mentioned in this thread) — and a variant that corrupts structured output rather than just line counts.

Repro (rtk 0.42.4, Linux, direct CLI invocation — no Claude Code hook in the loop):

$ jq -c '.[]' 41_items.json | wc -l
41

$ rtk jq -c '.[]' 41_items.json | wc -l
40

The 40th line of rtk jq's output isn't real data — it's the truncation marker:

$ rtk jq -c '.[]' 41_items.json | tail -2
"item_39"
... (1 lines truncated)

Per #1911, jq.toml is configured with max_lines=40, and that cap applies unconditionally — same class of bug as the grep/cargo test/head cases above, but worse for anything downstream expecting valid JSON: jq -c/-r output is machine-readable by definition (that's the whole point of those flags), and "... (N lines truncated)" is neither valid JSON nor a valid raw value. It silently poisons re-parsing (a second jq on the output errors on that line) and confuses non-JSON-aware consumers like wc -l/sort -u without any error — I only caught it because a downstream count looked implausibly low.

Also: the marker goes to stdout, not stderr:

$ rtk jq -c '.[]' 41_items.json 2>/dev/null | tail -1
... (1 lines truncated)

This particular repro is a direct CLI invocation (no hook involved), so at minimum an IsTerminal gate on rtk jq itself would fix this case without running into the hook-capture ambiguity discussed above.

Confirmed the only workaround is rtk proxy jq (bypasses the filter entirely, full output correct).

Environment:

  • rtk 0.42.4 (Linux)
  • Invoked directly via bash, not through rtk hook claude

🤖 Assisted-by: OpenCode (Claude Sonnet 5)

miabbott avatar Jul 14 '26 14:07 miabbott

+1 — hit this exact failure mode today via the Claude Code hook integration.

Repro (rtk diff rewrite):

printf "a\nb\nc\n" > /tmp/x1.txt; printf "a\nB\nc\n" > /tmp/x2.txt
diff /tmp/x1.txt /tmp/x2.txt   # (rewritten to rtk diff by the hook)
# -> custom -/+/~ summary format, exit code 0 despite differences
/usr/bin/diff /tmp/x1.txt /tmp/x2.txt
# -> standard format, exit code 1

Two independent breakages for scripts/pipelines: (1) downstream stages expecting standard diff markers (< / >) match nothing, silently; (2) if diff … / diff && … logic takes the "no differences" branch because the exit code is 0. Both fail with no error message — the worst kind.

Absolute paths bypass the rewrite as documented in #1699, which works as an interim escape.

As a stopgap we also added a guard in our local hook: commands containing pipeline/redirection/substitution metacharacters (|, >, <(, $() are passed through verbatim and never rewritten — compression only ever applies to top-level single commands whose output the model reads directly.

The IsTerminal passthrough proposed here would fix this properly at the binary level (raw output + faithful exit code whenever stdout is not a TTY). Happy to test a build.

Royyyylin avatar Jul 17 '26 22:07 Royyyylin

Confirming read.rs still has no TTY guard on develop today, and adding a data point for the rtk read path specifically — because it fails worse than the cases above and is unusually hard to reproduce.

Current default branch, is_terminal/IsTerminal references per file:

file refs
src/cmds/cloud/curl_cmd.rs 2 (let is_tty = std::io::stdout().is_terminal();)
src/cmds/system/search.rs 3
src/cmds/system/ls.rs 2
src/cmds/system/read.rs 0
src/cmds/system/pipe_cmd.rs 0

So curl is guarded now, but read is not — which matters a lot under the Claude Code hook, because the hook rewrites cat src > dst into rtk read src > dst. A file copy is not a thing anyone wants summarized.

Why this one is worse than the redirect cases already in this thread

Measured on a real ~948 KB HTML artifact served over loopback (rtk 0.28.2, macOS):

cat page.html > copy.html        # -> rtk read page.html > copy.html
source copy
bytes 948,303 308,719 (33%)
lines 3,893 1,280

Line-level accounting of what was removed:

dropped lines bytes
non-blank content lines 1,830 626,245
blank / whitespace-only 783 7,383

So it is deleting real content, not normalising indentation — whitespace is 1% of the loss.

The part that makes it dangerous:

  • No truncation marker anywhere in the output. rtk curl > f at least leaves ... (N more lines, N bytes total) at EOF. rtk read > f leaves nothing.
  • The copy ends at the true EOF (</html>), so it looks complete at both ends.
  • The loss is interior and scattered — 10 non-contiguous surviving runs spanning the whole file.
  • Exit status 0.

A file that starts right, ends right, and carries no marker is about the hardest corruption to notice. In our case a grep over the copy returned 0 hits for markup that was present 275 times in the original, which read as "the feature didn't deploy" rather than "the copy is broken."

Heads-up for whoever fixes this: synthetic repros come back clean

This is probably why it has survived. I could not reproduce the content loss with generated input at all:

input rtk read result
500 → 8,000 lines × 80 ch intact
2,000 lines × 400 / 2,000 / 8,000 ch (up to 16 MB) intact
50 lines × 20,000 ch intact
identical bytes as .txt / .html / .json / .md / .log intact
generated 939 KB real HTML document, 4,000 <div> rows intact
non-ASCII (emoji / em-dash / entities) injected intact
the real 948 KB document 33%

Also eliminated on the real file: transcoding it to pure ASCII still loses ~32%, and every half and quarter of it is independently lossy (19–83%).

So size, line count, line length, file extension and non-ASCII are all ruled out as the trigger — it is content-dependent in some way I did not isolate. A size-scaled test file will tell you the bug isn't there.

An is_terminal() passthrough in read.rs (matching what curl_cmd.rs/ls.rs/search.rs already do) would make the trigger moot for the redirect/pipe case, which is the one that silently corrupts data.

Note for other Claude Code hook users landing here

rtk rewrite is handed the whole command string including the redirect, and rewrites anyway:

in : curl -s $URL > out.html
out: rtk curl -s $URL > out.html

On older builds without the curl_cmd.rs guard (we were on 0.28.2) that writes the summary to the file — 1,870 bytes of a 948,303-byte response, exit 0. Upgrading picks up the curl guard; cat > file is still affected on current develop.

mactonicaaron avatar Jul 29 '26 00:07 mactonicaaron

Correcting my comment above. I upgraded off the old build and re-tested, and my behavioural conclusion was wrong — rtk read into a redirect is not broken on current. Apologies for the noise.

What I got right was only the grep: src/cmds/system/read.rs still has no IsTerminal reference. What I inferred from that — "so cat src > dst is still affected on current" — does not hold. Whatever suppresses the filtering there, it is not a missing guard in that file.

A/B on the same input file, same machine, both binaries present:

rtk read src > dst rtk curl URL > file
0.28.2 308,719 bytes / 87 markers 1,870 bytes / 0 markers
0.44.1 948,303 bytes / 275 markers — byte-identical to source (cmp clean) 963,471 / 280

Source was 948,303 bytes with 275 markers.

There is also a second, earlier layer of protection I missed: on 0.44.1 rtk rewrite declines outright once the command carries a redirect, so a hook never even produces rtk read … > …:

$ rtk rewrite 'curl -s $URL > f.html'   # rc=1, no output
$ rtk rewrite 'cat src.html > d.html'   # rc=1, no output
$ rtk rewrite 'git diff > p.diff'       # rc=1, no output
$ rtk rewrite 'git status'              # -> rtk git status

So for anyone landing here from a Claude Code hook: this is fixed, and the fix is in the rewriter as well as in the individual commands. My original report was against 0.28.2, which is what our tooling had pinned — that context was missing from my comment and it is the whole explanation.

The one durable point I'd still make is the testing note, which cost me a wrong conclusion in the other direction too: synthetic input did not reproduce the 0.28.2 read loss at all — generated files up to 16 MB, including real HTML, came back byte-perfect, while the real artifact lost 67%. If anyone does revisit the filter path, scale-up test files will look clean.

mactonicaaron avatar Jul 29 '26 01:07 mactonicaaron

Another data point, from a real session where this cost a ~9-minute re-run: the same corruption happens with test-runner output, and the loss is near-total rather than a reformat.

rtk 0.37.2, macOS (arm64), zsh, hook mode (rtk hook claude on PreToolUse/Bash).

$ npx playwright test --list > out.txt 2>&1
$ wc -c out.txt
31            # contents: "Time: 170ms"

$ rtk proxy npx playwright test --list | wc -c
17254

17,254 bytes of test listing become a 31-byte timing line in the redirected file. Same shape as #2807 (rsync), but for playwright/test filters.

Where it actually bit: npx playwright test > run.json with Playwright's JSON reporter. The file ended up 2,129 bytes of truncated JSON (cut mid-object, before the stats block) instead of ~155 KB, so parsing failed and the suite had to be re-run to recover the pass/fail summary. passthrough_max_chars = 2000 appears to be applied to the captured stream regardless of whether stdout is a TTY.

Two notes that may help scope a fix:

  1. It is specific to filtered commands, not redirects in general — git log --oneline -200 > f.txt produced the full 15,000 bytes here, so the git filter passes through while the test filter does not.
  2. The isatty passthrough suggested in the OP would fix both cases. A narrower stopgap that would have saved me: when the filter replaces (rather than trims) output, write the unfiltered bytes to the tee log and make the tee path discoverable from the redirected output, so a downstream consumer can recover.

Workaround for anyone hitting this with test runners: have the tool write its own file instead of redirecting stdout — e.g. PLAYWRIGHT_JSON_OUTPUT_NAME=run.json npx playwright test was unaffected.

dominikvoda avatar Aug 20 '26 13:08 dominikvoda

Confirming this on v0.42.0, with two details that I think sharpen the diagnosis.

1. It is not only piped output — the marker is written to disk.

The hook rewrite preserves redirections, so head -400 big.txt > out.txt becomes rtk read big.txt --max-lines 400 > out.txt. The resulting file contains 200 lines plus a literal final line:

[4800 more lines]

That string exists in no source file. Any subsequent read of out.txt ingests it as real content. The common head -N original > tmp && … && mv tmp original file-rebuild idiom therefore silently truncates and corrupts the original, with no error and no non-zero exit code.

2. The apparent intermittency has a cause: command complexity.

This defect is often reported as "not reproducible on demand". It is fully deterministic — the variable is the syntactic shape of the command, not size or timing:

head -400 big.txt > out.txt              # simple   → rewritten → 200 lines + marker
cd /tmp && head -400 big.txt > out.txt   # compound → NOT rewritten → 400 lines, correct

The rewrite engine fails to parse compound commands and passes the original through. The local history database records parse failures on roughly a fifth of all commands, which is consistent with how often the defect appears to "not reproduce".

The practical consequence is counter-intuitive and worth stating in the docs until this is fixed: simple commands are the dangerous ones; compound commands are safe.

Scope check (v0.42.0, isolated command + redirection):

Command Result
head -N f > out N/2 lines + marker written to file
tail -N f > out N lines, correct (--tail-lines unaffected)
cat f > out complete, correct (no cap applied without --max-lines)
sed -n '1,Np', awk 'NR<=N', /usr/bin/head -N correct — never rewritten

So the destructive path is specifically --max-lines, which is what head -N maps to.

An is_terminal() gate on smart_truncate (as already done in ls.rs:89 and curl_cmd.rs:47, and added to the TOML filter dispatcher in the #1060 commit) would close this. read.rs and filter.rs contain no IsTerminal usage at v0.42.0.

Padda-One avatar Aug 27 '26 15:08 Padda-One

This looks resolved on the current code (#1602 and follow-ups (curl/ls/search IsTerminal gates, redirect-aware rewrite)), but it could not be fully reproduced here. Marking it resolved-pending-close: it will be closed in a while unless someone reports it still happening on the latest version.

KuSh avatar Sep 05 '26 12:09 KuSh

This has carried the resolved-pending-close label with no new report of it happening, so closing it. This is fixed in v0.44.0 (PR #3128) on top of the TTY gates from #1602, though not as a literal isatty check: the rewrite layer now refuses to rewrite a command whose stdout is redirected to a file or feeds an unsafe pipeline consumer, and rewrites only the consuming stage of a pipe. Your original reproducer behaves correctly on the current release: rtk grep -cE '^- \[ \]' TODO.md prints the same count as grep whether piped or redirected, and the npx playwright test --list > out.txt case from later in the thread is left unrewritten. If you still see a downstream consumer getting compressed output on the latest version, please comment with the command and we will reopen.

KuSh avatar Sep 13 '26 00:09 KuSh

Hey — the 9-minute re-run from that stdout corruption on #1282 is a rough one. Trying to figure out how often that kind of silent data loss actually costs people real time versus being a one-off. Got 2 minutes for a couple questions on how you handle it when a tool does that?

Ezechis avatar Sep 21 '26 10:09 Ezechis

Hey — going into the actual source to check whether the IsTerminal guard was missing is more digging than most people do here. Trying to understand how much people actually trust these compression/rewrite tools versus verify them by hand. Open to 2-3 quick questions on that?

Ezechis avatar Sep 21 '26 10:09 Ezechis