Compare commits

...
Author SHA1 Message Date
patrickandClaude Opus 4.7 83b5505fc8 fix(toml-filter): skip filtering when stdout is piped (#1060)
`rtk ps aux | wc -l` returned 31 lines instead of the host's ~374
processes because the TOML filter for `ps` (`max_lines = 30`,
`truncate_lines_at = 120`) fired unconditionally, even when stdout was
piped or redirected to another program. Downstream consumers like
`grep`, `wc`, `jq` or shell scripts then saw a truncated view and
silently lost data.

This was the same shape on every truncating TOML filter (top, lsof,
df, netstat, ...), but the dispatcher in `main.rs` never checked
`stdout().is_terminal()` before applying the filter — unlike the
hand-rolled Rust filters in `curl_cmd` and `ls` which already gate on
TTY (PR #1602, PR #503).

Fix:
- Extract the dispatch decision into a pure `should_apply_toml_filter`
  helper that takes (env_disabled, stdout_is_tty) and bypasses the
  filter when stdout is not a terminal.
- Wire `std::io::stdout().is_terminal()` into the dispatcher.

Tests:
- Unit matrix `test_toml_filter_*` covers the four
  (env_disabled, stdout_is_tty) combinations and pins the new
  pipe-bypass behaviour.
- `test_multiple_toml_filters_are_registered` documents that the
  bypass protects more than just `ps` (top, lsof, df, netstat, ...).
- New integration test `rtk_ps_aux_piped_preserves_raw_line_count`
  spawns the rtk binary with `Stdio::piped()` (the exact shape of
  `rtk ps aux | ...`) and asserts the line count is close to raw
  `ps aux`. Skips gracefully on hosts with fewer than 35 processes
  (small containers) and when `ps` is unavailable.

End-to-end verification on the release build:
  $ /usr/bin/ps aux | wc -l                              # 374
  $ target/release/rtk ps aux | wc -l                    # 375  ✓
  $ RTK_NO_TOML=1 target/release/rtk ps aux | wc -l      # 375  ✓
Before this commit `rtk ps aux | wc -l` returned 31.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 21:07:58 +02:00
3 changed files with 146 additions and 4 deletions

No files matched your search

Generated
+1 -1
View File
@@ -892,7 +892,7 @@ dependencies = [
[[package]]
name = "rtk"
version = "0.36.0"
version = "0.34.3"
dependencies = [
"anyhow",
"automod",
+72 -3
View File
@@ -28,6 +28,7 @@ use anyhow::{Context, Result};
use clap::error::ErrorKind;
use clap::{Parser, Subcommand, ValueEnum};
use std::ffi::OsString;
use std::io::IsTerminal;
use std::path::{Path, PathBuf};
/// Target agent for hook installation.
@@ -49,6 +50,17 @@ pub enum AgentTarget {
Hermes,
}
/// Decide whether to look up and apply a TOML filter for the current command.
///
/// Returns `false` when `RTK_NO_TOML=1` is set (existing escape hatch), or when
/// stdout is not a terminal (piped / redirected to a file). In the piped case
/// the consumer of our output is another program that expects the unfiltered
/// raw command output — applying `max_lines` / `truncate_lines_at` would
/// silently corrupt pipelines like `rtk ps aux | grep opencode` (issue #1060).
fn should_apply_toml_filter(env_disabled: bool, stdout_is_tty: bool) -> bool {
!env_disabled && stdout_is_tty
}
#[derive(Parser)]
#[command(
name = "rtk",
@@ -1160,10 +1172,12 @@ fn run_fallback(parse_error: clap::Error) -> Result<i32> {
.collect::<Vec<_>>()
.join(" ")
};
let toml_match = if std::env::var("RTK_NO_TOML").ok().as_deref() == Some("1") {
None
} else {
let env_disabled = std::env::var("RTK_NO_TOML").ok().as_deref() == Some("1");
let stdout_is_tty = std::io::stdout().is_terminal();
let toml_match = if should_apply_toml_filter(env_disabled, stdout_is_tty) {
core::toml_filter::find_matching_filter(&lookup_cmd)
} else {
None
};
if let Some(filter) = toml_match {
@@ -3139,4 +3153,59 @@ mod tests {
_ => panic!("Expected Commands::Npx for unknown tool"),
}
}
// Regression tests for issue #1060: TOML filters must not fire when
// stdout is piped or redirected, otherwise pipelines like
// `rtk ps aux | grep opencode` silently lose data.
//
// These tests pin the full (env_disabled, stdout_is_tty) decision matrix.
#[test]
fn test_toml_filter_runs_in_tty_mode_when_not_disabled() {
// Default interactive usage: filter must apply.
assert!(should_apply_toml_filter(false, true));
}
#[test]
fn test_toml_filter_skipped_when_env_disabled_in_tty() {
// RTK_NO_TOML=1 escape hatch wins over TTY.
assert!(!should_apply_toml_filter(true, true));
}
#[test]
fn test_toml_filter_skipped_when_env_disabled_in_pipe() {
// RTK_NO_TOML=1 still wins when piped.
assert!(!should_apply_toml_filter(true, false));
}
/// Issue #1060: `rtk ps aux | grep opencode` loses processes because the
/// TOML filter truncates to 30 lines before the pipe sees them. When
/// stdout is not a terminal the filter must be bypassed so downstream
/// consumers receive the raw command output.
#[test]
fn test_toml_filter_skipped_when_stdout_piped() {
assert!(
!should_apply_toml_filter(false, false),
"TOML filter must be skipped when stdout is piped/redirected (issue #1060)"
);
}
/// Issue #1060 has the same shape on every TOML filter that truncates
/// output (ps, top, lsof, df, netstat, ...). Confirm the registry actually
/// matches several commands so the pipe-bypass fix protects more than
/// just `ps`.
#[test]
fn test_multiple_toml_filters_are_registered() {
let truncating_commands = ["ps aux", "top -b -n 1", "lsof -i", "df -h", "netstat -an"];
let matched: Vec<&str> = truncating_commands
.iter()
.copied()
.filter(|cmd| core::toml_filter::find_matching_filter(cmd).is_some())
.collect();
assert!(
matched.len() >= 2,
"expected at least two truncating TOML filters in the registry, got {:?}",
matched
);
}
}
+73
View File
@@ -0,0 +1,73 @@
//! Integration test for issue #1060: `rtk <cmd> | <consumer>` must preserve
//! the raw command output. The TOML filter on `ps` (and similar commands)
//! truncates to 30 lines, which silently breaks pipelines such as
//! `rtk ps aux | grep opencode` or `rtk ps aux | wc -l`.
//!
//! This test spawns the rtk binary with stdout captured (i.e. piped, not a
//! terminal) so it reproduces the user-visible failure mode end-to-end. It
//! gracefully skips on hosts that either lack `ps aux` or run too few
//! processes to make the truncation observable (small Docker images, etc.).
use std::process::{Command, Stdio};
const SKIP_THRESHOLD: usize = 35;
const TOLERANCE_LINES: usize = 5;
fn line_count(buf: &[u8]) -> usize {
if buf.is_empty() {
return 0;
}
let mut n = buf.iter().filter(|&&b| b == b'\n').count();
if *buf.last().unwrap() != b'\n' {
n += 1;
}
n
}
fn run_piped(program: &str, args: &[&str]) -> Option<Vec<u8>> {
let output = Command::new(program)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.ok()?;
if !output.status.success() {
return None;
}
Some(output.stdout)
}
/// Spawns `rtk ps aux` with a piped stdout (the exact shape of
/// `rtk ps aux | grep ...`) and compares its line count to the raw
/// `ps aux` output. With issue #1060 in place the TOML filter caps
/// `rtk ps aux` at ~30 lines regardless of how many processes the host
/// actually runs, breaking downstream consumers.
#[test]
fn rtk_ps_aux_piped_preserves_raw_line_count() {
let raw = match run_piped("ps", &["aux"]) {
Some(r) => r,
None => {
eprintln!("Skipping: `ps aux` is unavailable on this host");
return;
}
};
let raw_lines = line_count(&raw);
if raw_lines < SKIP_THRESHOLD {
eprintln!(
"Skipping: host runs only {raw_lines} processes — too few to \
observe `max_lines=30` truncation"
);
return;
}
let rtk_bin = env!("CARGO_BIN_EXE_rtk");
let rtk_out = run_piped(rtk_bin, &["ps", "aux"]).expect("`rtk ps aux` failed");
let rtk_lines = line_count(&rtk_out);
assert!(
rtk_lines + TOLERANCE_LINES >= raw_lines,
"issue #1060: `rtk ps aux` piped should preserve raw output \
(got {rtk_lines} lines, expected close to {raw_lines})"
);
}