Repository navigation
fix(tsc): handle pretty diagnostics - #2232
Conversation
|
Confirming this fix also covers a related trigger: missing binary entirely (not just --pretty ANSI codes) Ran into the same underlying failure mode on rtk 0.42.4 (before this PR), but triggered differently than the ANSI-parsing case in #1772. Setup: npx tsc --noEmit / npx next lint via rtk npx, run inside a git worktree with no node_modules (worktrees don't inherit node_modules from the main checkout). Actual raw output (confirmed via rtk proxy npx tsc --noEmit, unfiltered): To get access to the TypeScript compiler, tsc, from the command line either:
What the rtk npx wrapper reported instead: Same root cause as #1772 — 0 parsed diagnostics → wrapper falls back to a fabricated success summary — just triggered by a missing binary rather than ANSI-wrapped --pretty output. From the PR description, the general fallback ("avoid reporting 'No errors found' when the compiler exits non-zero and RTK parsed no diagnostics") looks like it fixes this case too, since it's exit-code-driven rather than specific to the ANSI-stripping fix. Just wanted to confirm that broader coverage and flag it as an additional real-world repro — this failure mode is fairly dangerous for pre-push typecheck workflows (agents/devs get a false "all green" and push broken code). Repro environment: rtk 0.42.4, Ubuntu 24.04, Node v22, pnpm-based Next.js project. |
Adopt upstream rtk-ai#2232: tsc - handle pretty diagnostics
KuSh
left a comment
There was a problem hiding this comment.
Thanks for this — I fetched the branch, built it, and ran it against real tsc (TypeScript 6.0.3) with the repro from #1772. The core fix works: rtk tsc --noEmit --pretty now reports TypeScript: 1 errors in 1 files and exits 2 instead of claiming No errors found. cargo fmt --check, cargo clippy --all-targets and the 12 tsc_cmd tests all pass.
Two things need to change before merge.
1. Unbounded raw dump makes rtk emit more than the wrapped command (src/cmds/js/tsc_cmd.rs:115)
The new "exited non-zero, parsed no diagnostics" branch appends the entire raw (stdout+stderr, capped only by RAW_CAP = 10 MiB) to the summary. Unlike run_captured_filter, the RunMode::Streamed path in src/core/runner.rs:180 applies no guard::never_worse, so nothing clamps it.
Measured with a failing run producing ~3000 unparseable lines:
- raw: 322,989 bytes
- rtk output: 323,060 bytes (~80k tokens into the context, negative savings recorded by
timer.track)
That's the inverse of RTK's contract, and tee_and_hint already persists the raw output and prints a [full output: ~/path] pointer for exactly this case. Please cap it — truncate is already imported here, and tee::force_tee_tail_hint exists. #3295 solves this half by appending only the last 10 non-empty lines; that bounded approach is strictly better than the full dump and is worth porting into this PR.
2. ANSI is stripped for matching but not for output (src/cmds/js/tsc_cmd.rs:89)
is_block_start / is_block_continuation return a bool, and BlockStreamFilter::feed_line pushes the original line — so every emitted --pretty diagnostic keeps its escapes. Real output from the branch:
^[[96mrtk-test.ts^[[0m:^[[93m3^[[0m:^[[93m5^[[0m - ^[[91merror^[[0m^[[90m TS2322: ^[[0mType 'number'…
Eight escape sequences per error line, on the very path this PR fixes, and inconsistent with filter_tsc_output, which now strips them. test_tsc_stream_failed_unparsed_output_not_success asserts !result.contains("\x1b["), but test_tsc_stream_pretty_ansi_errors doesn't — so the gap is untested. Emitting the stripped line (a normalize_line hook, or stripping in feed_line) plus an assertion in that second test would close it.
Minor (non-blocking)
:154—filter_tsc_outputstrips the whole output intoclean_output, thenparse_tsc_errorstrips each already-clean line again. In the streaming path it's worse:should_skip(:86) andis_block_start(:90) each callstrip_ansi, so every line — including the thousands that match nothing — costs twoRegex::replace_allpasses and two allocations where the old code allocated none. Strip once per line and pass the clean&strto both.:31—parse_tsc_errorallocateslineandmessagefor every diagnostic, butis_block_startuses onlyfileandcode.
Mechanical
The PR is currently CONFLICTING: develop has since migrated this file from lazy_static! to std::sync::LazyLock and removed the ═══… separator lines, while this branch adds TSC_PRETTY_ERROR inside the now-deleted lazy_static! block. Needs a rebase onto develop with TSC_PRETTY_ERROR converted to static TSC_PRETTY_ERROR: LazyLock<Regex> = LazyLock::new(|| …).
Related work
This PR is the oldest of the cluster and the only one fixing both halves (ANSI stripping and the exit-code guard), so it's the one to land:
- #3221 — duplicate of this PR (exit-code half only), newer.
- #3295 — duplicate of this PR (exit-code half only), newer; its bounded "last 10 non-empty lines" dump is the better implementation and should be adopted here (see point 1).
- #3294, #3222 — already closed, no action.
- #3220 — also fixed by this PR; adding
Fixes #3220to the description. - #3738 (ANSI escapes pass through,
strip_ansiopt-in) — point 2 above is a concrete instance of it, but this PR only fixes it for thetscpath, so it's a partial fix, not a close.
f7e806c to
f571b75
Compare
|
Rebased onto develop (TSC_PRETTY_ERROR is a LazyLock now) and addressed both blocking points plus the two minor ones. The non-zero-exit/no-diagnostics branch keeps only the last CAP_WARNINGS non-empty raw lines with a ... +N more lines marker, relying on the runner's tee hint for the rest. ANSI handling moved to a new BlockHandler::normalize_line hook (identity by default) so the tsc handler strips once per line and the emitted block is clean; plain lines are borrowed, not allocated. is_block_start and the batch filter now read capture groups directly instead of building a struct per line. Added assertions for the emitted --pretty block and a tail-cap test, plus a hook test in stream.rs. Verified against TypeScript 7.0.2 with the #1772 repro, a TS5058 config error, and an unknown flag. |
KuSh
left a comment
There was a problem hiding this comment.
Thanks for the quick turnaround — I re-reviewed at f571b75. All five points from my last pass are genuinely resolved:
- Raw dump is bounded to
CAP_WARNINGSlines with a... +N moremarker. BlockHandler::normalize_lineis a clean opt-in hook, and the emitted block is now stripped — the lifetime split (&selfvs&'a str -> Cow<'a, str>) keeps the later&mut self.handlercalls legal, and the identity default leaves every existing handler unchanged.- ANSI is stripped once per line, guarded by
contains('\x1b'), borrowing plain lines. tsc_error_capturesdrops the per-line struct allocation; the two regexes have aligned capture groups, so indexing is safe for both layouts.- Rebased onto
develop,LazyLock, no conflicts.
cargo fmt --check, cargo clippy --all-targets and cargo test --all all pass here.
The deeper pass turned up two things that I think still block, both about diagnostics that carry no file prefix (error TS5023:, error TS5058:) — they match neither regex, so they're invisible to error_count, and the new guard only fires when error_count == 0. One of them is a live #3220 repro on the rtk pipe tsc path, which matters now that the description says Fixes #3220. Details inline, plus three non-blocking notes on the tail direction, two strip_ansi full-buffer copies, and the synthetic --pretty fixtures.
One suggestion I want to explicitly argue against, in case it comes up: guarding the failure branch with !clean.contains("Found 0 errors") to avoid a false red on a Ctrl-C'd watch-mode run (exit 130). It fixes a rare case at the cost of reopening the false green whenever a compiler prints Found 0 errors and then fails for an unrelated reason — the exact bug this PR exists to kill. The current exit-code-driven logic is the right call.
`tsc --pretty` prints `file:line:col - error TSxxxx: message` with every field wrapped in ANSI escapes, so no diagnostic ever matched and rtk reported "No errors found" on a failing compile (rtk-ai#1772). The same false green appeared whenever tsc exited non-zero without a parseable line (missing binary under npx, TS5058 config errors, rtk-ai#3220). - add a `--pretty` regex next to the default layout - `BlockHandler::normalize_line` hook (identity by default); the tsc handler strips ANSI once per line, so matching and the emitted block both see plain text, and plain lines pass through without allocating - `format_summary` reports the failure when tsc exits non-zero with no diagnostics, keeping only the last CAP_WARNINGS non-empty raw lines (the runner already tees the full output); previously the whole raw output was appended - match on captures instead of building a diagnostic struct per line - `filter_tsc_output` strips ANSI once for the whole batch Fixes rtk-ai#1772 Fixes rtk-ai#3220 Co-Authored-By: Claude Fable 5 <[email protected]>
Review round 2 of rtk-ai#2232. - Diagnostics without a file prefix (`error TS5023:`, `error TS5058:`, `error TS2688:`) match a third pattern, so they are counted, emitted as blocks on the streaming path and grouped under `global (N errors)` on the `rtk pipe --filter tsc` path. Output made only of global diagnostics no longer reports "TypeScript compilation completed" (rtk-ai#3220); the summary reads `TypeScript: N errors` when no file-scoped diagnostic exists. - `parse_diagnostic` returns a borrowed `Diagnostic` instead of raw captures indexed by position. - The exit-non-zero/no-diagnostics branch keeps the first and the last `reduced(CAP_WARNINGS, 5)` non-empty lines instead of a plain tail: tsc and npx print the cause first and boilerplate after it. Only retained lines are ANSI-stripped, and the pipe path borrows plain input instead of copying it. - `--pretty` tests use a real TypeScript 6.0.3 capture and state that the code frame after the blank line is dropped on purpose. New fixtures cover a global config error and bare `tsc` without a project.
f571b75 to
6232c37
Compare
KuSh
left a comment
There was a problem hiding this comment.
LGTM overall — this is in good shape, and thank you for the thorough turnaround. All seven threads from my last review are genuinely fixed, and I've resolved them individually with a note on each:
TSC_GLOBAL_ERROR+parse_diagnosticreturningDiagnostic { file: Option<&str>, .. }is a cleaner answer to the file-less-diagnostic problem than what I suggested, and degrading the summary toTypeScript: N errorswhen there's no file to group under is the right call.- The head+tail split via
reduced(MAX_UNPARSED_LINES, 5)keeps the cause, andtest_tsc_stream_failed_without_project_keeps_causeproves it against a real capture rather than an assumption. - Swapping the synthetic
--prettystrings fortests/fixtures/tsc_pretty_raw.txt— real gutter, real blank separators — and then changing the assertions to match reality (!result.contains("const x: number"), with a comment explaining why) is exactly right. Capturing real output instead of bending the fixture to fit the code is the harder and better choice.
cargo fmt --check, cargo clippy --all-targets and cargo test --all (2662+) all pass here. I also checked the things most likely to bite and found them correct: the head/tail arithmetic can't underflow (head_len + tail_len == MAX_UNPARSED_LINES by construction, and the branch is only reached when lines.len() exceeds it), regex precedence holds on Windows drive-letter and colon-containing paths, the Cow lifetimes keep the later &mut self.handler borrow legal, and normalize_line's identity default leaves every other BlockHandler untouched.
One change requested, inline at line 161: the blank-line filter now runs before ANSI stripping, so escape-only lines survive it and render as blanks — which can empty out the failure dump. That one is a direct consequence of the per-line-stripping optimisation I asked for last round, so it's on me as much as anyone.
Three low-priority bonuses also inline (tee size floor in the doc, no width truncation on dump lines, unbounded Vec for a 10-line window) — all optional, fold them in if convenient, none of them should hold the PR.
Finally: the exit-0 counterpart — rtk tsc --showConfig / --listFiles / --init / --help returning TypeScript: No errors found and discarding the real output, unrecoverably, since TeeMode::Failures writes nothing on a zero exit — is real but pre-existing (develop returned that unconditionally on error_count == 0). I've filed it separately as #3750 rather than letting it grow this PR. No action needed here.
… dump Review round 3 of rtk-ai#2232. - Lines are ANSI-stripped before the blank check, so escape-only spinner lines take no head/tail slot and never render as blanks. - The dump is built in one pass with a fixed-size head and a bounded tail deque instead of materialising every line of the raw capture. - Output under `MIN_TEE_SIZE` bytes is printed whole: no tee is written for it, so a cap there would hide lines with no recovery path. `MIN_TEE_SIZE` becomes `pub(crate)` for that check. - Every dump line is width-capped at 120 characters like the other emissions in this filter.
The failure-dump comment claimed only the retained lines are ANSI-stripped. clean_line now runs on every line before the blank filter, so that no longer describes the code. Trim the rest to the reason each one exists, per CONTRIBUTING.md's "no obvious comments": - MAX_UNPARSED_LINES narrated tee.rs and restated the `raw.len() < MIN_TEE_SIZE` branch in prose; keep only why both ends are worth keeping. - MAX_UNPARSED_HEAD_LINES opened with "Deviation:" without saying from what; keep the cause-first ordering that motivates the split. - push_dump_line's body is already truncate(line, 120). - normalize_line's second sentence repeated clean_line's borrowed branch. - The stream test cannot show "exactly once": uppercasing is idempotent. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01GnsGBTdn8jP8DNAy2goX3V
KuSh
left a comment
There was a problem hiding this comment.
LGTM — approving. Thanks for the persistence across four rounds; this landed in good shape.
On the last commit: I verified the fix rather than taking the tests at face value, because the new MIN_TEE_SIZE branch is a behaviour change and a mismatch there would silently discard the only surviving copy of a failure.
- Escape-only lines —
clean_linenow runs before the blank check in both dump branches, so the shadowed binding is whattrim()sees. I probed escapes interleaved throughout the stream rather than bunched at the head, which is what a real--prettycapture looks like: no blanks leak, no ESC leaks, and head/tail still hold real content. - The tee floor matches exactly, not approximately.
tee.rs:111bails onraw_len < MIN_TEE_SIZE; the new branch fires on the same operator and constant.stream.rs:530buildsrawonce and hands the same value toon_exitand out viaStreamResult.raw→runner.rs:193→tee_and_hint, so the two lengths cannot diverge. Probed 499 bytes → dumps whole, 500 → head/tail. hiddencannot underflow: every counted line lands inhead, intail, or is dropped by thetail_len == 0guard, sohead.len() + tail.len() <= totalalways holds. The newif hidden > 0guard is load-bearing — without it, a raw over the floor with 8 real lines would print... +0 more lines. That case emits all 8, contiguous and in order.- Width cap:
truncateis char-based, so 600 CJK chars plus emoji neither panic nor exceed 120. - Worst case at
RAW_CAP: 10 MiB → 1203 bytes, 12 lines, 56 ms, constant memory.
Real effect on the fixture that started this: tsc_no_project_raw.txt goes 5240 → 481 bytes, every line ≤120 chars.
cargo fmt --check, clippy --all-targets (zero warnings) and test --all (2665) all pass locally.
I pushed one commit on top of yours (docs(tsc): correct the ANSI note and drop restated comments) rather than send you round five for comments alone. It is comments only — no behaviour change, and the suite is unchanged at 2665. One of them had gone stale under your own fix: the failure-dump comment still said "only the retained lines are ANSI-stripped", which stopped being true the moment clean_line moved ahead of the blank filter. The others were restating the code they sat on, per CONTRIBUTING.md's "no obvious comments" — MAX_UNPARSED_LINES had grown into prose for the raw.len() < MIN_TEE_SIZE branch and a narration of tee.rs, so it now keeps only the reason both ends are worth having. Revert or reword any of it if you disagree; none of it is load-bearing.
Note the red benchmark check is not yours — it fails identically on develop (d9a5893, 322db4d).
Nice work, in particular capturing real fixtures and adjusting the assertions to match reality rather than bending the fixture to fit the code.
Summary
tsc --prettydiagnostics infile:line:col - error TSxxxxform.TypeScript: No errors foundwhen the compiler exits non-zero and RTK parsed no diagnostics.Test plan
cargo fmt --all --checkcargo test --bin rtk -- cmds::js::tsc_cmdcargo test --bin rtkcargo run --quiet --bin rtk -- tsc --noEmit --pretty -p /tmp/rtk-1772/tsconfig.jsonexits 2 and reportsTS2322plusTypeScript: 1 errors in 1 filesFixes #1772
Fixes #3220
Partially addresses #3738 (ANSI escapes are stripped on the
tscpath only).