Skip to content

rtk ruff cuts SARIF, JUnit, GitLab, JSON Lines and rule --output-format=json output at the passthrough cap #4655

Open

Description

@KuSh

rtk ruff sends every invocation it has no filter for through truncate(stdout.trim(), passthrough_max_chars) (2000 chars). That includes ruff check when the user picked a non-JSON --output-format, and ruff rule --output-format=json. Those outputs are documents, and cutting one at 2000 chars leaves something no consumer can parse. No hint says how to get the rest.

Reproduction (ruff 0.16.6, LC_ALL=C, a 301-file package big/ with one F401 per file)

args native ruff rtk on develop 83fea35
check --output-format=sarif big 408630 B, exit 1 2001 B ending in ..., exit 1
check --output-format=junit big 160916 B 2001 B
check --output-format=gitlab big 115486 B 2001 B
check --output-format json-lines big 147000 B 2001 B
rule --all --output-format=json 1572734 B, exit 0 2001 B, exit 0
rule E501 (text) 2302 B 2001 B, cut inside the # noqa example; the ## Options list and the PEP 8 link are gone

ruff analyze graph had the same problem (#3929) and is fixed by #3942, which exempts only that subcommand.

Direction

Under "Correctness VS Token Savings" in CONTRIBUTING.md, an output format the user asked for by name is detail they want to see. Pass these through uncapped, or give them a filter that keeps the document valid. If the cap stays anywhere, it needs the recovery hint that "Never Block" asks for. Related: #2204 (passthrough truncation with no marker).

Activity

  1. rtk-wshm-sync-bot commented on Oct 19, 2026

    @rtk-wshm-sync-bot

    wshm · Automated triage by AI

    🔍 Automated Triage

    🐛 Category bug
    🟠 Priority high
    🎯 Confidence 92%

    Summary

    rtk ruff truncates structured output formats (SARIF, JUnit, GitLab, JSON Lines, rule --output-format=json) at a 2000-char passthrough cap, producing unparseable documents with no recovery hint.

    This looks like a simple fix that could be auto-resolved. Repo maintainers can use /wshm fix to attempt it.

    📁 Relevant files
    • src/cmds/ruff.rs

    Suggested Actions

    1. Apply the fix(ruff): preserve analyze graph JSON output #3942 pattern: exempt non-default/structured --output-format values from the passthrough cap
    2. For rule --output-format=json, pass through uncapped since it's a parseable document, not display text
    3. If a cap must remain, add a truncation marker per passthrough_max_chars truncates output silently (no marker) — git log shows 50 of 252 commits, misleads scope #2204 and the 'Never Block' guidance in CONTRIBUTING.md
    4. Coordinate with rtk ruff reads the subcommand from fixed positions, so ruff global options make rtk ruff --isolated analyze graph truncate the JSON #4654, which also touches rtk ruff's subcommand/arg parsing

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

  2. Protocol-zero-0 commented on Oct 19, 2026

    @Protocol-zero-0
    Contributor

    PR delivery after #3968 merged: #4896 (consolidates the format/rule and completion patches on the merged router; the staged patch below is historical).

    I reproduced #4655 on develop 9a501c8d with Ruff 0.17.0 and prepared an incremental fix on top of the shared-router integration in #4654.

    The change reuses #3968's routing and #3964's tokenizer-based output-format lookup. Explicit --output-format requests and ruff rule documentation use the runner's existing native passthrough, preserving stdout, stderr and exit status. That also avoids captured filtering's 10 MiB limit and newline normalization. Default check invocations still produce the existing summary.

    With a 301-file fixture, the previous 2,001-byte truncated outputs become complete documents: SARIF 423,521 bytes, JUnit 174,407 bytes, GitLab 113,764 bytes, JSON Lines 152,306 bytes; rule --all --output-format=json returns all 1,584,699 bytes. rule E501 retains its complete 2,302-byte documentation.

    Validation on Linux:

    • 45 real Ruff cases / 180 native, current-develop, prior-rtk ruff reads the subcommand from fixed positions, so ruff global options make rtk ruff --isolated analyze graph truncate the JSON #4654 and fixed executions. Selected-format and rule stdout match native bytes exactly; exit codes 0/1/2 are preserved. JSON/XML consumers parse 23 structured-output cases.
    • Covers check and format's 12 supported output formats, both option spellings, leading global options, implicit checks, clean results, invalid/duplicate formats, missing config, graph/help/version controls, and a filename resembling --output-format=json after --.
    • 27 focused unit tests and 5 process tests, including an 11 MiB document with no final newline plus separate stderr and exit 1.
    • Full local cargo test --locked: 4,698 passed, 8 ignored; fmt and warnings-denied all-targets clippy pass. Other platforms/Ruff versions were not tested.

    The patch below applies after the #4654 patch linked above; both sequential application and the combined patch were checked against clean 9a501c8d. No runner changes or additional dependencies. #3964's format-summary changes remain separate.

    Incremental patch for #4655
    diff --git a/src/cmds/python/ruff_cmd.rs b/src/cmds/python/ruff_cmd.rs
    --- a/src/cmds/python/ruff_cmd.rs
    +++ b/src/cmds/python/ruff_cmd.rs
    @@ -58,9 +58,7 @@
         let mut cmd = resolved_command("ruff");
     
         // Both spellings: injecting a second --output-format makes ruff reject the call.
    -    let user_set_output_format = args
    -        .iter()
    -        .any(|a| a == "--output-format" || a.starts_with("--output-format="));
    +    let user_set_output_format = ruff_output_format(args).is_some();
     
         let clean_outputs: &[&str] = if is_check && !user_set_output_format {
             &["[]"]
    @@ -76,6 +74,17 @@
             eprintln!("Running: ruff {}", args.join(" "));
         }
     
    +    if ruff_output_is_document(route, args) {
    +        // Captured filters normalize line endings and cap input at 10 MiB.
    +        // Reuse the runner's native passthrough for complete documents.
    +        return runner::run(
    +            cmd,
    +            "ruff",
    +            &display_args(args),
    +            runner::RunMode::Passthrough,
    +            runner::RunOptions::default(),
    +        );
    +    }
         let owned_args = args.to_vec();
         runner::run_filtered(
             cmd,
    @@ -87,24 +96,20 @@
     }
     
     /// Choose the output treatment for a routed invocation: check runs get the
    -/// JSON summary, format runs the format summary, help and version requests
    -/// stay complete, and everything else is a bounded passthrough.
    +/// JSON summary by default, while explicitly selected formats and rule documents
    +/// remain intact. Help, version and graph requests stay complete too.
     fn filter_ruff_output(args: &[String], stdout: &str) -> String {
         let route = route_ruff_args(args);
         let is_check = matches!(route, RuffRoute::Check { .. });
         let is_format = matches!(route, RuffRoute::Subcommand { at } if args[at] == "format");
         let trimmed = stdout.trim();
     
    -    let user_set_output_format = args
    -        .iter()
    -        .any(|a| a == "--output-format" || a.starts_with("--output-format="));
    -    let user_json_format = args.iter().enumerate().any(|(i, a)| {
    -        a == "--output-format=json"
    -            || (a == "--output-format" && args.get(i + 1).is_some_and(|n| n == "json"))
    -    });
    -    let use_json_filter = !user_set_output_format || user_json_format;
    -
    -    if is_check && use_json_filter && !trimmed.is_empty() {
    +    let user_set_output_format = ruff_output_format(args).is_some();
    +    if ruff_output_is_document(route, args) {
    +        return stdout.to_string();
    +    }
    +
    +    if is_check && !user_set_output_format && !trimmed.is_empty() {
             filter_ruff_check_json(stdout)
         } else if is_format {
             filter_ruff_format(stdout)
    @@ -115,6 +120,31 @@
         } else {
             truncate(trimmed, config::limits().passthrough_max_chars)
         }
    +}
    +
    +/// An explicitly selected format is a document, including human-readable formats.
    +/// Reuse #3964's tokenizer/value lookup, consuming global option values too.
    +fn ruff_output_format(args: &[String]) -> Option<&str> {
    +    let tokens = tokenize_grammar(
    +        args,
    +        &|kind, name| {
    +            if kind == TokenKind::Long && name == "output-format" {
    +                Some(ValueSpec::value())
    +            } else {
    +                ruff_takes_value(kind, name)
    +            }
    +        },
    +        Dialect::Posix,
    +    );
    +    before_dashdash(&tokens)
    +        .iter()
    +        .filter(|t| t.kind == TokenKind::Long && t.text == "output-format")
    +        .find_map(|t| t.value(&tokens))
    +}
    +
    +fn ruff_output_is_document(route: RuffRoute, args: &[String]) -> bool {
    +    ruff_output_format(args).is_some()
    +        || matches!(route, RuffRoute::Subcommand { at } if args[at] == "rule")
     }
     
     /// Help, version and analyze graph requests must keep their full stdout.
    @@ -208,9 +238,7 @@
     
     /// The complete argument vector rtk passes to ruff.
     fn plan_ruff_command(args: &[String]) -> Vec<String> {
    -    let user_set_output_format = args
    -        .iter()
    -        .any(|a| a == "--output-format" || a.starts_with("--output-format="));
    +    let user_set_output_format = ruff_output_format(args).is_some();
         if let RuffRoute::Check { explicit_at } = route_ruff_args(args) {
             let forwarded: Vec<&str> = args
                 .iter()
    @@ -223,9 +251,13 @@
                 plan.push("--output-format=json".to_string());
             }
             plan.extend(forwarded.iter().map(|arg| (*arg).to_string()));
    -        if forwarded
    -            .iter()
    -            .all(|arg| arg.starts_with('-') || arg.contains('='))
    +        let tokens = tokenize_grammar(args, &ruff_takes_value, Dialect::Posix);
    +        let has_path_after_separator = dashdash_index(&tokens)
    +            .is_some_and(|at| tokens[at + 1..].iter().any(|t| t.is_free_positional()));
    +        if !has_path_after_separator
    +            && forwarded
    +                .iter()
    +                .all(|arg| arg.starts_with('-') || arg.contains('='))
             {
                 plan.push(".".to_string());
             }
    @@ -575,10 +607,9 @@
                 .expect("analyze graph output must remain valid JSON");
         }
     
    -    /// Only invocations starting `analyze graph` are exempt from the passthrough cap:
    -    /// `analyze help graph` and every other passthrough subcommand still get it.
    -    #[test]
    -    fn only_analyze_graph_skips_the_passthrough_cap() {
    +    /// Graph recognition stays narrow; rule documentation is independently complete.
    +    #[test]
    +    fn graph_recognition_stays_narrow_and_rule_documentation_is_complete() {
             let args = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
             let is_analyze_graph_invocation =
                 |args: &[String]| matches!(route_ruff_args(args), RuffRoute::AnalyzeGraph);
    @@ -598,12 +629,7 @@
             let raw = include_str!("../../../tests/fixtures/ruff_rule_e501_raw.txt");
             assert!(raw.len() > config::limits().passthrough_max_chars);
             let result = filter_ruff_output(&args(&["rule", "E501"]), raw);
    -        assert!(
    -            result.ends_with("...") && raw.starts_with(result.trim_end_matches("...")),
    -            "rule output must be a capped prefix of ruff's, got {} of {} bytes",
    -            result.len(),
    -            raw.len()
    -        );
    +        assert_eq!(result, raw);
         }
     
         #[test]
    @@ -879,8 +905,8 @@
         #[test]
         fn ruff_other_subcommands_keep_the_bounded_passthrough() {
             let max_chars = config::limits().passthrough_max_chars;
    -        let long = "rule F401: ".repeat(max_chars);
    -        let out = filter_ruff_output(&owned(&["rule", "F401"]), &long);
    +        let long = "config settings: ".repeat(max_chars);
    +        let out = filter_ruff_output(&owned(&["config"]), &long);
             assert!(out.len() < long.len());
             assert!(out.ends_with("..."));
         }
    @@ -940,4 +966,68 @@
                 );
             }
         }
    -}
    +    #[test]
    +    fn explicit_formats_preserve_large_documents_and_line_endings() {
    +        let raw = format!("  {}\n\n", "document ".repeat(1000));
    +        for command in ["check", "format", "rule"] {
    +            for format in ["json", "json-lines", "sarif", "junit", "gitlab", "concise"] {
    +                for args in [
    +                    owned(&[command, "--output-format", format, "target"]),
    +                    owned(&[command, &format!("--output-format={format}"), "target"]),
    +                ] {
    +                    assert_eq!(filter_ruff_output(&args, &raw), raw, "{args:?}");
    +                }
    +            }
    +        }
    +    }
    +
    +    #[test]
    +    fn output_format_lookup_respects_option_values_and_path_boundary() {
    +        for args in [
    +            owned(&["check", "--", "--output-format=json"]),
    +            owned(&["--config=--output-format=json", "check", "file.py"]),
    +        ] {
    +            assert_eq!(ruff_output_format(&args), None, "{args:?}");
    +        }
    +        let args = owned(&[
    +            "--config",
    +            "format",
    +            "check",
    +            "--output-format",
    +            "sarif",
    +            "big",
    +        ]);
    +        assert_eq!(ruff_output_format(&args), Some("sarif"));
    +        assert_eq!(
    +            plan_ruff_command(&args),
    +            owned(&[
    +                "check",
    +                "--config",
    +                "format",
    +                "--output-format",
    +                "sarif",
    +                "big"
    +            ])
    +        );
    +        assert_plan(
    +            &["check", "--", "--output-format=json"],
    +            &[
    +                "check",
    +                "--output-format=json",
    +                "--",
    +                "--output-format=json",
    +            ],
    +        );
    +    }
    +
    +    #[test]
    +    fn implicit_checks_keep_user_selected_documents() {
    +        let args = owned(&["--output-format", "json-lines", "file.py"]);
    +        let raw = "{\"code\":\"F401\"}\n";
    +        assert_eq!(filter_ruff_output(&args, raw), raw);
    +        assert_plan(
    +            &["--output-format", "json-lines", "file.py"],
    +            &["check", "--output-format", "json-lines", "file.py"],
    +        );
    +    }
    +}
    diff --git a/tests/ruff_passthrough_test.rs b/tests/ruff_passthrough_test.rs
    --- a/tests/ruff_passthrough_test.rs
    +++ b/tests/ruff_passthrough_test.rs
    @@ -1,7 +1,5 @@
    -//! `rtk ruff` passes subcommands it has no filter for through its passthrough cap,
    -//! except `analyze graph`, whose JSON is only useful whole. These run the real `run()`
    -//! path against a stub ruff that replays output captured with ruff 0.16.6: the graph of
    -//! a 300-module package (`ruff analyze graph big`) and `ruff rule E501`.
    +//! Complete Ruff documents bypass captured filtering. Replays graph/rule fixtures,
    +//! checks exact argv and line endings, and exercises both streams above 10 MiB.
     
     #![cfg(unix)]
     
    @@ -58,7 +56,7 @@
     #[test]
     fn analyze_graph_json_reaches_the_caller_whole() {
         let dir = common::tempdir();
    -    // `other_passthrough_subcommands_keep_the_cap` shows the cap is below RULE_E501's length.
    +    // Both fixtures exceed the old passthrough cap.
         assert!(GRAPH.len() > RULE_E501.len());
         fake_ruff(dir.path(), &["analyze", "graph", "big"], GRAPH);
     
    @@ -71,22 +69,12 @@
     }
     
     #[test]
    -fn other_passthrough_subcommands_keep_the_cap() {
    +fn rule_documentation_reaches_the_caller_whole() {
         let dir = common::tempdir();
         fake_ruff(dir.path(), &["rule", "E501"], RULE_E501);
    -
         let out = rtk_ruff(dir.path(), &["rule", "E501"]);
    -    let stdout = String::from_utf8_lossy(&out.stdout);
    -    let shown = stdout.trim_end();
    -
         assert_eq!(out.status.code(), Some(0), "{}", context(&out));
    -    assert!(
    -        shown.ends_with("...") && RULE_E501.starts_with(shown.trim_end_matches("...")),
    -        "rule output must be a capped prefix of ruff's, got {} of {} bytes; {}",
    -        shown.len(),
    -        RULE_E501.len(),
    -        context(&out)
    -    );
    +    assert_eq!(out.stdout, RULE_E501.as_bytes(), "{}", context(&out));
     }
     
     #[test]
    @@ -112,3 +100,34 @@
             );
         }
     }
    +
    +#[test]
    +fn selected_formats_reach_real_stdout_without_an_extra_newline() {
    +    let raw = format!("[{}]\n\n", " ".repeat(4096));
    +    for args in [
    +        vec!["check", "--output-format", "sarif", "big"],
    +        vec!["check", "--output-format=json", "big"],
    +        vec!["format", "--check", "--output-format=json-lines", "big"],
    +        vec!["rule", "--all", "--output-format=json"],
    +    ] {
    +        let dir = common::tempdir();
    +        fake_ruff(dir.path(), &args, &raw);
    +        let out = rtk_ruff(dir.path(), &args);
    +        assert_eq!(out.status.code(), Some(0), "{args:?}: {}", context(&out));
    +        assert_eq!(out.stdout, raw.as_bytes(), "{args:?}");
    +    }
    +}
    +
    +#[test]
    +fn documents_beyond_capture_limit_keep_both_streams_and_exit_status() {
    +    let dir = common::tempdir();
    +    let raw = format!("[\"{}\"]", "x".repeat(11 * 1024 * 1024));
    +    fs::write(dir.path().join("captured"), &raw).unwrap();
    +    let path = dir.path().join("ruff");
    +    fs::write(&path, "#!/bin/sh\ncat \"$(dirname \"$0\")/captured\"\nprintf 'diagnostic without newline' >&2\nexit 1\n").unwrap();
    +    fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
    +    let out = rtk_ruff(dir.path(), &["check", "--output-format=json", "big"]);
    +    assert_eq!(out.status.code(), Some(1), "{}", context(&out));
    +    assert_eq!(out.stdout, raw.as_bytes());
    +    assert_eq!(out.stderr, b"diagnostic without newline");
    +}
  3. KuSh commented on Oct 21, 2026

    @KuSh
    CollaboratorAuthor

    One more row from the #3968 review (ruff 0.16.6, LC_ALL=C), not in the list above: rtk ruff generate-shell-completion bash returns 2001 of ruff's 311361 bytes (exit 0). The script is cut mid-function, so eval "$(rtk ruff generate-shell-completion bash)" breaks.

    Also, once #3968 lands, rtk ruff --output-format concise src reaches the same cap as rtk ruff check --output-format concise src (byte-identical 2001 B; native 18363 B). Before #3968 it exited 2. The incremental patch above covers that spelling through the shared router.

  4. Protocol-zero-0 commented on Oct 24, 2026

    @Protocol-zero-0
    Contributor

    The two additional rows are now checked with real Ruff 0.17.0 on Linux.

    generate-shell-completion bash still hits the cap with my earlier #4655 patch: 2,001 bytes rather than Ruff's 311,984, and bash -n rejects the truncated script. The incremental change below treats the routed generate-shell-completion command as a document and uses the same native passthrough as selected output formats and rule documentation. No runner changes.

    Validation:

    • 22 real Ruff scenarios / 66 native, prior-patch and fixed executions. All five shell scripts match native stdout exactly; the five Bash rows (plain, --isolated, --config, --color, -q) also pass bash -n. The prior patch fails all five Bash syntax checks. This checks syntax without evaluating generated scripts.
    • --output-format concise big, its equals spelling, leading global options and explicit check preserve the complete 15,399-byte diagnostic output and exit 1. Clean/error controls retain stdout, stderr and exit codes 0/1/2. The format requests already worked with the earlier patch; completion is the new fix.
    • A config value named generate-shell-completion still routes to a normal summarized check; the same word after -- does not select document passthrough. New unit and process regressions cover these distinctions and exact CRLF/argv preservation. The new process regression fails before the change.
    • 28 Ruff unit tests, six process tests, full local workspace tests (4,998 passed, 8 ignored), fmt and warnings-denied all-targets clippy pass.

    This is a delta after the earlier #4655 patch, tested on its original 9a501c8d + #4654/#4655 staged combination. Exported patch application reproduces the tested source tree exactly. It is not a claim of integration with revised #3968 63454754 or current develop; that rebase remains to be checked. #4654's separate PR still waits for #3968 to merge, as agreed. Only Linux/Ruff 0.17.0 was run.

    Incremental completion patch after #4655
    diff --git a/src/cmds/python/ruff_cmd.rs b/src/cmds/python/ruff_cmd.rs
    --- a/src/cmds/python/ruff_cmd.rs
    +++ b/src/cmds/python/ruff_cmd.rs
    @@ -144,7 +144,7 @@
     
     fn ruff_output_is_document(route: RuffRoute, args: &[String]) -> bool {
         ruff_output_format(args).is_some()
    -        || matches!(route, RuffRoute::Subcommand { at } if args[at] == "rule")
    +        || matches!(route, RuffRoute::Subcommand { at } if matches!(args[at].as_str(), "rule" | "generate-shell-completion"))
     }
     
     /// Help, version and analyze graph requests must keep their full stdout.
    @@ -515,6 +515,27 @@
     #[cfg(test)]
     mod tests {
         use super::*;
    +
    +    #[test]
    +    fn completion_document_requires_the_routed_subcommand() {
    +        let raw = "completion() { :; }\r\n".repeat(300);
    +        for args in [
    +            vec!["generate-shell-completion", "bash"],
    +            vec!["--isolated", "generate-shell-completion", "bash"],
    +            vec!["--config", "ruff.toml", "generate-shell-completion", "bash"],
    +        ] {
    +            let args: Vec<String> = args.into_iter().map(String::from).collect();
    +            assert!(ruff_output_is_document(route_ruff_args(&args), &args));
    +            assert_eq!(filter_ruff_output(&args, &raw), raw);
    +        }
    +        for args in [
    +            vec!["--config", "generate-shell-completion", "check", "src"],
    +            vec!["check", "--", "generate-shell-completion"],
    +        ] {
    +            let args: Vec<String> = args.into_iter().map(String::from).collect();
    +            assert!(!ruff_output_is_document(route_ruff_args(&args), &args));
    +        }
    +    }
     
         #[test]
         fn known_ruff_subcommands_do_not_route_through_check() {
    diff --git a/tests/ruff_passthrough_test.rs b/tests/ruff_passthrough_test.rs
    --- a/tests/ruff_passthrough_test.rs
    +++ b/tests/ruff_passthrough_test.rs
    @@ -131,3 +131,23 @@
         assert_eq!(out.stdout, raw.as_bytes());
         assert_eq!(out.stderr, b"diagnostic without newline");
     }
    +
    +#[test]
    +fn shell_completion_is_a_complete_document() {
    +    let script = format!(
    +        "# generated completion\r\n{}\r\n",
    +        "completion() { :; }\r\n".repeat(300)
    +    );
    +    for args in [
    +        vec!["generate-shell-completion", "bash"],
    +        vec!["--isolated", "generate-shell-completion", "bash"],
    +        vec!["--config", "ruff.toml", "generate-shell-completion", "bash"],
    +    ] {
    +        let dir = common::tempdir();
    +        fake_ruff(dir.path(), &args, &script);
    +        let out = rtk_ruff(dir.path(), &args);
    +        assert_eq!(out.status.code(), Some(0), "{}", context(&out));
    +        assert_eq!(out.stdout, script.as_bytes(), "args: {args:?}");
    +        assert!(out.stderr.is_empty());
    +    }
    +}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:clibugpriority:high

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions