fix: stop crashes, slowdowns, and behavior-changing --fix rewrites

Merged
DS
1mo ago
+3920-922

This pull request was posted by Claude Code using claude-opus-5-5 on behalf of David.

What

This PR fixes crashes and quadratic slowdowns on unusual source files, makes --fix keep what the rewritten code does, and fixes exit codes, discovery, report formats, the language server transport, and API and docs drift. Each commit covers one area and can be reviewed on its own.

Why

A single source file could abort every host: a long left-deep expression such as a + a + ... + a overflowed the stack (SIGABRT from the Rust binaries, SIGSEGV in the Python interpreter, the language server exits), and a file with lone CR line endings panicked whenever refactor plans were built. Separately, --fix could write a rewrite that parses but changes behavior, for example a continue guard that skips a while loop's counter and turns the loop infinite.

Changes

Crashes and slow paths

  • CR line endings. LineIndex and the line helpers now break lines on \r\n, \r, and \n, as the tokenizer and LSP 3.17 do. Files with CR line endings no longer panic in the loop guard rule or in the caret under a suggestion, report every function on line 1, let one ignore marker silence the whole file, or take quadratic time and output. --fix keeps a file's CR line endings. The caret column now counts characters, not bytes.
  • Deeply chained expressions. Every parse goes through a new syntax_tree module whose trees free long chains (a + a + ..., a.b.b..., f()()..., a[0][0]...) with an explicit stack instead of recursive drops. The direct-recursion finder and the free-name collector use an explicit-stack walk. A 300,000-term chain now analyzes on every host, in a directory run on a rayon worker, and in the wasm build. A repository test keeps production code from calling the parser outside that module.
  • Boolean sequences. A boolean operation nested in another one was compared against every sibling of its parent, which took quadratic time and inflated scores. Each operation now adds one when its operator differs from the one directly around it, or when not wraps it.
  • Plan selection. Selecting non-overlapping plans no longer rescans every kept plan for each candidate, and else branches come from the syntax tree instead of a rescan of the region at every chain step.

--fix keeps behavior

  • C002 loop guards offer a replacement only when the nested if chain is the last statement of the loop body and each member the last statement of its parent. Statements that follow the chain get help text instead, because a guard would skip them. A chain inside a nested function is refused, and an inner if with its body on the header line stays as written.
  • Else branches and condition grouping come from the syntax tree, so else : and quote runs inside a condition no longer hide an else, and a or(b) or not a or(b) are parenthesized and inverted correctly.
  • Indentation keeps each line's own whitespace and moves it from the inner block's prefix to the outer one, so files that mix tabs and spaces stay valid for CPython. Tab-indented files get tab-indented replacements.
  • Comments. A single comment on a merged if line, such as # type: ignore, moves to the merged line. Two or more comments, or an inner if with an inline body, get help text. A # inside a string no longer hides a following multi-line string from the refusal check.
  • The --fix gating rule is unchanged: a plan is written only when its tier is MachineApplicable and its suggestion is spliceable, inside a function over the threshold.

Exit codes and the console

  • complexipy . | head no longer panics. A closed stdout ends the output and the run keeps its exit code.
  • A --diff ref wider than the terminal no longer underflows the banner width and panics.
  • --quiet --ignore-complexity now exits 0, like --ignore-complexity.
  • Color is decided on every run, so a long-lived Python host that calls run_cli several times sees each run's own terminal and NO_COLOR. Suggestion snippets now honor --color no, NO_COLOR, and piped output, and a comment no longer colors every following snippet line.
  • --report-ignored lists each suppressed path:line # comment, as its help text and the docs say, followed by the count.

Discovery and exclusion

  • A file reached through several path arguments or a symlink next to it is analyzed, reported, and fixed once.
  • Ignored-location reports and complexipy-ignored.json use the same paths as the results for files inside the working directory, instead of prefixing the analyzed directory's name. A reported file name always matches its path.
  • With paths = ["src", "legacy"] and exclude = ["legacy/**"], the CLI and the language server excluded opposite files. The CLI now also matches each pattern relative to the directory it runs in, and the server also matches relative to each paths entry. The server resolves .. in document paths before matching, and a nested workspace folder without a config uses the nearest configured ancestor. helpers/exclude/tests.rs pins the walker and the matcher to the new rule.
  • A pattern that starts with /, ./, or ../, or ends with /, never matches; the CLI and the server now warn about it. What explicit file arguments bypass is unchanged.

Language server

  • Frames are capped at 256 MiB and read as they arrive, so a huge Content-Length no longer allocates or aborts.
  • A body that is not JSON gets a parse error (-32700), and a body that is not a JSON-RPC message, or a request whose id is not an integer or a string, gets InvalidRequest (-32600); the session continues. A broken frame is reported on stderr before the server stops.
  • Requests after shutdown get InvalidRequest instead of no answer. After a failed handshake the process exits instead of waiting for stdin to close, and the logged error is shortened.
  • file://localhost/... resolves to the local path, and a remote authority resolves to a UNC path on Windows and to no path elsewhere.
  • Hover escapes Markdown in function names, so Box::__init__ renders literally.

Report formats

  • SARIF artifactLocation.uri is percent-encoded, $schema points at the published OASIS schema, and results carry partialFingerprints.
  • GitLab fingerprints no longer hash the line number, so a line added above a function keeps every fingerprint below it.

Python API, docs, and tooling

  • A Rust panic raises ValueError from the analysis functions and RuntimeError from run_cli and run_lsp, instead of pyo3_runtime.PanicException, which except Exception does not catch.
  • compute_diff(current, "origin/main") works as documented: invocation_path defaults to None.
  • Ctrl-C ends the console script at once instead of after the Rust call returns. main() sets that handler only on the main thread, so calling it from another thread no longer raises ValueError.
  • A process forked after a parallel call no longer hangs on its next parallel call: parallel work runs on a pool owned by the current process.
  • The stubs and docs now state the error types the API raises, drop the nonexistent DiffEntry.delta, fix the exclude example that matched nothing, and show the real snapshot entry format. tests/test_stubs.py now checks function signatures and defaults.
  • benchmarks/benchmark-cli.sh runs each workload from an empty directory, so the repo's own complexipy.toml and a shared cache no longer reach the timed runs. benchmarks/results.md still holds the earlier numbers.
  • The VS Code extension gives up on a server that does not start within 30 seconds, stops it, and shows an error, so later restarts are not blocked. It creates one output channel instead of one per restart.
  • The web demo loads a fresh wasm instance after a trap instead of failing every later analysis.

Deliberate behavior changes

  • Scores: no total in tests/main.py moves. Expressions that mix boolean operators across sibling groups score lower; (a or b) and (c and d) drops from 4 to 2.
  • GitLab fingerprints: every existing fingerprint changes once with this release, so a stored Code Quality baseline churns once.
  • SARIF: the $schema URL and the encoding of uri change, and partialFingerprints is new.
  • Exit codes: --quiet --ignore-complexity exits 0 instead of 1. A closed stdout keeps the gate's exit code instead of 101 (Rust) or 1 (Python). The language server answers a malformed message and continues instead of exiting 1.
  • Plans: C002 gives help text instead of a replacement when statements follow the nested chain. C007 keeps a single header comment and gives help text for two or more, or for an inline inner body.
  • Exclusion: the CLI may exclude more files when a path argument differs from the working directory, because patterns also match relative to that directory.
  • Paths: complexipy-ignored.json and the stale-ignore lines no longer prefix the analyzed directory's name for files inside the working directory.

Open questions

  1. Exclusion: a pattern now matches relative to the analyzed path or to the working directory. Should the CLI instead match only relative to the directory that holds the config, which would drop exclusions some users rely on today?
  2. Explicit file arguments still bypass exclude, gitignore, and hidden filters, which makes the config exclude inert under pre-commit. Is that intended?
  3. Should C002 skip loops whose nested chain is followed by statements, instead of offering help text?
  4. Panics map to ValueError and RuntimeError. Would you prefer a dedicated exception class? It would be a new public name.
  5. Files outside the working directory still get absolute paths in SARIF, GitLab, and JSON. GitLab expects repo-relative paths.

Verification

  • cargo test --workspace, cargo clippy --workspace --all-targets, cargo fmt --check, cargo check -p complexipy-core --no-default-features, a wasm32 build of complexipy-wasm, uv run pytest, uv run ruff check ., uv run ruff format --check ., and uv run ty check . pass locally.
  • A set of crafted inputs was rerun on the release CLI (file argument, and directory run on a rayon worker, each with and without --suggest-refactors), the Python API, and both language server entry points (open plus hover): files with CR or mixed line endings, 40,000 to 300,000-term chains, long boolean expressions, a 195-deep if chain, mixed tab and space indentation, and thousands of spliceable plans. None crashes on any host. The long boolean expressions dropped from about 8 s to 0.02 s of CPU, the deep if chain with plans from about 25 s to 0.1 s, and 8,000 functions with CR line endings from about 3 s to 0.04 s.
  • Not verified live: the VS Code start timeout and the web demo's reload after a trap were tested only through unit tests and by reading the code, not in a running editor or browser.
  • This PR leaves plan measurement alone. #289, now merged into this branch, measures each plan on its own function instead of re-scoring the whole file.
  • New regression tests cover each fix, including a --fix test that runs each crafted fixture before and after the rewrite and compares results for every input.