Skip to content

tsrs-lint: a headless request still keeps every tsconfig project's arena memory until it ends (main after #624) #855

Closed

Description

@grmkris

Refs #624, #783, #848, #378.

Summary

On main (ce0b047, after #624), one tsrs-lint headless request keeps the arena memory of every tsconfig project
until the request ends. oxlint sends one request for a whole workspace, so the helper's peak memory is the sum
over the projects instead of the largest one. #783 reported this against the PR head; main is unchanged, and #848
reduces it, but its peak still grows with the number of projects.

Reproduction

The generator from #783 (repeated below) writes N independent projects of 24 files each, with lib: ["es2022", "dom", "dom.iterable"], 12 type-aware rules and one no-floating-promises finding per file, plus a V2 payload:

node gen-many-projects.mjs /tmp/many 120 24
cd /tmp/many && /usr/bin/time -v tsrs-lint headless < payload.json > frames.bin

Expected: peak RSS stays about the size of one project as projects are added. Actual: it grows linearly.

Linux x86-64, 16 vCPUs (KVM), helper only. Every build uses the release profile with
CARGO_PROFILE_RELEASE_LTO=false CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16. Peak RSS, median of three runs:

Projects main (ce0b047) #848 (765f97d) Per-project regions (below)
40 634 MiB 458 MiB 157 MiB
120 1,812 MiB 1,304 MiB 218 MiB

All three produce byte-identical frames (960 and 2,880 no-floating-promises findings).

gen-many-projects.mjs
#!/usr/bin/env node
// Generates a public repro for tsrs-lint's per-request memory growth: many independent tsconfig projects linted in
// one headless request (what oxlint sends for a monorepo). Every project includes the DOM lib, so each program parses,
// binds and type-checks a large declaration set of its own.
//
// Usage: node gen-many-projects.mjs <out-dir> [projects=40] [files-per-project=24]
// Writes <out-dir>/p<N>/{tsconfig.json,f<M>.ts} and <out-dir>/payload.json (V2), then prints the run command.
import { mkdirSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';

const [outArg, projectsArg = '40', filesArg = '24'] = process.argv.slice(2);
if (!outArg) {
  console.error('usage: node gen-many-projects.mjs <out-dir> [projects] [files-per-project]');
  process.exit(64);
}
const out = resolve(outArg);
const projects = Number(projectsArg);
const files = Number(filesArg);

const rules = [
  'await-thenable',
  'no-floating-promises',
  'no-misused-promises',
  'no-unnecessary-type-assertion',
  'no-unsafe-argument',
  'no-unsafe-assignment',
  'no-unsafe-call',
  'no-unsafe-member-access',
  'no-unsafe-return',
  'restrict-template-expressions',
  'strict-boolean-expressions',
  'switch-exhaustiveness-check',
].map((name) => ({ name }));

// Each file asks the checker about DOM, promise and generic types, so every worker checker resolves a large part of
// the lib graph. One floating promise per file gives a positive control.
const source = (project, file) => `export interface Item${file} { id: number; label: string; tags: readonly string[] }

export async function load${file}(url: string): Promise<Item${file}[]> {
  const response = await fetch(url, { headers: { accept: 'application/json' } });
  const items = (await response.json()) as Item${file}[];
  return items.filter((item) => item.tags.includes('p${project}'));
}

export function render${file}(root: HTMLElement, items: readonly Item${file}[]): void {
  const list = document.createElement('ul');
  for (const item of items) {
    const entry = document.createElement('li');
    entry.textContent = \`\${item.id}: \${item.label}\`;
    entry.addEventListener('click', () => root.dispatchEvent(new CustomEvent('pick', { detail: item })));
    list.append(entry);
  }
  root.replaceChildren(list);
  load${file}('/items');
}

export const byId${file} = new Map<number, Item${file}>();
export function kind${file}(value: 'a' | 'b' | 'c'): number {
  switch (value) {
    case 'a': return 1;
    case 'b': return 2;
    case 'c': return 3;
  }
}
`;

const configs = [];
for (let project = 0; project < projects; project++) {
  const directory = join(out, `p${project}`);
  mkdirSync(directory, { recursive: true });
  writeFileSync(
    join(directory, 'tsconfig.json'),
    JSON.stringify({
      compilerOptions: { strict: true, target: 'es2022', lib: ['es2022', 'dom', 'dom.iterable'], types: [], noEmit: true },
      include: ['*.ts'],
    }),
  );
  const paths = [];
  for (let file = 0; file < files; file++) {
    const path = join(directory, `f${file}.ts`);
    writeFileSync(path, source(project, file));
    paths.push(path);
  }
  configs.push({ file_paths: paths, rules });
}
writeFileSync(join(out, 'payload.json'), JSON.stringify({ version: 2, configs, report_syntactic: false, report_semantic: false }));
console.log(`${projects} projects x ${files} files -> ${out}`);
console.log(`cd ${out} && /usr/bin/time -v tsrs-lint headless < payload.json > frames.bin   # macOS: /usr/bin/time -l`);

Cause

crates/tsrs_lint/src/engine.rs allocates each project's program in regions that live as long as the request:

  • RequestRegions::loaders, one ProgramRegions set shared by every program (the parsed and bound files);
  • RequestRegions::workers, every lint worker's region (the worker checkers' types and links);
  • the main thread's request region, entered in run.

ProgramOwner::drop frees the Program, but not what these regions hold. #848 moves the checkers' memory to
checker_regions, freed with the program, which explains its smaller numbers. The loader set and the main region
stay request-wide, so the parsed and bound files of every project, including each project's own lib files, still
add up.

With compressed pointers this also has a hard limit: every arena chunk comes from the one 32 GiB reservation, so a
large enough workspace aborts with "the arena address range is exhausted" (#783 has the numbers).

A fix

Branch: grmkris/tsrs lint-project-regions, one commit
on main (diff): engine.rs
+27 −6, a lifecycle test, a note and the capability-table cell.

  • Each project gets ProjectRegions: its lint workers' regions, a main-thread region entered for the project, and a
    fresh ProgramRegions set. They drop after the project's program, loaders last (as the watcher's
    install_program frees them). The request region keeps only project discovery.
  • Nothing that outlives a project points into them. The payload, timings, writer, config host and cachedvfs caches
    are on the heap. What escapes the scratch regions (arena::escape_scratch: program caches, diagnostics, lazily
    filled shared data) goes to the thread arena, because the request region is the outermost scratch region. Every
    project builds an unshared program.
  • This revisits the request-wide loader set from notes/perf-tsgolint-parallel-load.md. Its reason, avoiding an arena
    tail per worker per tsconfig, only holds while those tails are retained. Freed with their project, they do not add
    up.

Instructions retired, single-threaded (RAYON_NUM_THREADS=1, perf stat -e instructions:u), 120 projects, three
runs each: 21.157 G on main, 21.069 G with the change (−0.4%), spread under 0.01%.

On a large private monorepo, through oxlint with its full configuration, the change on main reports the same
type-aware findings as the same patch on the 2026-10-25 PR head, apart from the tuple reports e720cf07e added to
require-array-sort-compare, at the same peak. On that head the helper's peak there fell from 18.5 GiB to 1.18 GiB
(#783).

Validation:

  • cargo test --locked --profile ci -p tsrs_lint: 118 passed, including the new lifecycle test (one request, six
    projects, serial and parallel paths).
  • The same with TSRS_ARENA_POISON=1: 118 passed.
  • The 40- and 120-project requests with TSRS_ARENA_POISON=1: byte-identical frames.
  • cargo clippy --locked -p tsrs_lint --all-targets --config 'build.warnings="deny"', cargo fmt --check and
    tools/lint/source.mjs: clean.

I know pull requests are closed (CONTRIBUTING.md), so the patch is on a fork branch for you to take, adapt or drop.
It conflicts with #848 in engine.rs. If #848 lands first, I can rebase it onto that.

Activity

  1. oxc-captain commented on Oct 30, 2026

    @oxc-captain
    Contributor
    • Reproduced: Yes
    • Exploration: Partial
    • Unit Test: No — this issue is a memory-lifetime problem, not a TypeScript parity defect, so the Go-reference triage path could not be followed to add a regression.
    • Priority: P2: Confirmed issue with normal priority. tsrs-lint headless is the interface used by tools like oxlint for whole-workspace linting, and retaining every project's arena for the full request can drive the helper to out-of-memory or arena-exhaustion crashes on moderate-sized monorepos.

    The problem is in crates/tsrs_lint/src/engine.rs: tsrs-lint headless allocates each project's program data in the request-wide RequestRegions::loaders, RequestRegions::workers, and main thread request region. When ProgramOwner::drop frees the Program, those underlying regions still hold every project's parsed/bound files and checker state until the entire request ends, so peak RSS grows roughly linearly with the number of projects.

    I wasn't able to find a fix, but I identified some areas that may be relevant. The likely place to change the allocation scope is crates/tsrs_lint/src/engine.rs, particularly how RequestRegions are created/entered around each project and how ProgramOwner::drop interacts with the loader set. The reporter's fork branch grmkris/tsrs:lint-project-regions proposes giving each project its own ProjectRegions and dropping them after the project's Program is freed, which would keep only project-discovery data in the request region.

    Full Triage Report

    Triage report: issue 855

    Issue claim

    tsrs-lint headless keeps the arena memory of every tsconfig project in a single
    headless request until the request ends. When a workspace contains many
    independent tsconfig projects, peak RSS grows with the number of projects instead
    of staying near the size of one project.

    Reported on main ce0b047 (Linux x86-64, helper only).

    Screening

    • Not a feature request, question, or explicitly unsupported capability.
    • Contains a runnable reproduction (gen-many-projects.mjs) and expected vs.
      actual behavior.
    • Checked-out revision matches the reported main (ce0b047).
    • Linux x86-64 host is available.
    • No maintainer override.

    Continued with reproduction.

    Build

    CARGO_PROFILE_RELEASE_LTO=false CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 \
      cargo build --locked --profile release -p tsrs_lint

    Built /home/runner/work/tsrs/tsrs/target/release/tsrs-lint at commit ce0b047a3f6b0fb8d5a7713bb744273cb50b41fa.

    Minimal reproduction input

    Copied the generator from the issue to triage/gh-855/gen-many-projects.mjs.
    Generated independent projects with lib: ["es2022", "dom", "dom.iterable"],
    12 type-aware rules, and one no-floating-promises finding per file:

    node triage/gh-855/gen-many-projects.mjs /tmp/many1   1  24
    node triage/gh-855/gen-many-projects.mjs /tmp/many4   4  24
    node triage/gh-855/gen-many-projects.mjs /tmp/many8   8  24
    node triage/gh-855/gen-many-projects.mjs /tmp/many40  40 24
    node triage/gh-855/gen-many-projects.mjs /tmp/many120 120 24

    Commands run

    cd /tmp/many1   && /usr/bin/time -v ./target/release/tsrs-lint headless < payload.json > frames.bin
    cd /tmp/many4   && /usr/bin/time -v ./target/release/tsrs-lint headless < payload.json > frames.bin
    cd /tmp/many8   && /usr/bin/time -v ./target/release/tsrs-lint headless < payload.json > frames.bin
    cd /tmp/many40  && /usr/bin/time -v ./target/release/tsrs-lint headless < payload.json > frames.bin
    cd /tmp/many120 && /usr/bin/time -v ./target/release/tsrs-lint headless < payload.json > frames.bin

    (Parallel runs used default worker count; a RAYON_NUM_THREADS=1 run for 120
    projects showed the same growth direction.)

    Observed results

    All runs exited with status 0 and produced frames.bin.

    Projects Files total Peak RSS (MiB) Wall time (s)
    1 24 32 0.03
    4 96 72 0.12
    8 192 120 0.25
    40 960 510 1.21
    120 2,880 1,491 3.81

    1 project -> 120 projects scaling:

    • Projects increased by 120x,
    • Peak RSS increased by ~46x.
    • The per-project retained cost is roughly 12 MiB after the first project
      (~33 + 12 * N fits the data well).

    Single-threaded (RAYON_NUM_THREADS=1) 120-project run:

    Projects Peak RSS (MiB) Wall time (s)
    120 1,389 4.25

    Again, peak RSS is proportional to the number of projects, not to one project.

    Note on TypeScript Go compiler reference

    The pinned Go compiler (workspace.metadata.typescript.commit in Cargo.toml)
    was not compared because tsrs-lint headless is a tsrs-specific linting
    interface with no equivalent in tsc. The issue being reproduced is tsrs's own
    memory behavior, not a parity difference in diagnostics or emit.

    Conclusion

    REPRODUCED: on ce0b047, tsrs-lint headless allocates memory that scales
    with the number of projects in a single request instead of staying bounded near
    the size of one project.

    Diagnosis

    DIAGNOSIS SKIPPED: no Go-versus-Rust difference

    This issue concerns tsrs-lint headless memory lifetime and region allocation
    inside crates/tsrs_lint/src/engine.rs. The pinned TypeScript Go compiler does
    not provide an equivalent headless linting request endpoint, so there is no
    Go-versus-Rust output or behavior divergence to isolate using the normal parity
    triage path.

    Verification

    Revisiting the issue claim: tsrs-lint headless should release memory after
    finishing each independent tsconfig project, so peak RSS should stay near the
    size of one project; instead it grows with the number of projects in the same
    request.

    The checked-out tsrs behavior was reproduced internally across 1, 4, 8, 40, and
    120 independent projects, with peak RSS scaling from ~32 MiB to ~1,491 MiB
    (default parallelism) and ~1,389 MiB (single-threaded). That is consistent with
    the reporter's claim.

    The pinned TypeScript Go compiler (workspace.metadata.typescript.commit in
    Cargo.toml) has no equivalent tsrs-lint headless command or headless linting
    request API, so there is no Go output, exit status, emitted file, or diagnostic
    set to compare against. docs/COMPATIBILITY.md also does not list tsrs-lint
    or headless linting as a supported or unsupported capability.

    Therefore, this triage verification cannot apply the Go parity contract. The
    internal reproduction is unambiguous, but the project contract that determines
    bug versus intended-behavior (pinned Go compiler behavior) is not available
    for this tsrs-specific linting interface.

    Verdict: unclear under the Go-parity contract due to the absence of a Go
    comparator; the issue is reproducible as an internal tsrs-lint memory-lifetime
    bug with medium confidence.

    Fix

    No fix was attempted.

    The fix step is limited to reproduced parity bugs with a specific, medium- or
    high-confidence Go diagnosis. This issue was reproducible internally, but the
    diagnosis step was skipped because the pinned TypeScript Go compiler does not
    provide a headless linting API comparable to tsrs-lint headless. Without a
    Go-defined expected behavior to port, implementing a fix from the triage path
    would not be safe under the project contract.

    A potential implementation is described in the issue body (branch
    grmkris/tsrs:lint-project-regions), but it would need to be evaluated by
    project maintainers independent of the Go-parity triage flow.

    This report was made by an LLM. The analysis may be wrong, and the potential fix might not work, but is intended as a starting point for exploring the issue.

  2. added
    triage: unable to fix
    - P2
    pkg: checker
    pkg: cli
    on Oct 30, 2026
  3. jasonkuhrt commented on Nov 6, 2026

    @jasonkuhrt

    Written by an AI agent (Claude) on behalf of @jasonkuhrt.

    The change from this issue, rebased onto main after #848. With #848's checker_regions, the checkers' memory already goes back with each program, so what a request still keeps for every project is the RequestRegions::loaders set (each project's parsed and bound files, its lib files included) and the main thread's request region. Giving each project its own loader set and main region, freed after its program, keeps one project's regions at a time instead of every project's. The output is byte-identical.

    sequenceDiagram
        participant R as run()
        participant L as loader regions
        participant P as project N program
        Note over R,P: main (b8b21271)
        R->>L: one set for the request
        loop each tsconfig project
            R->>P: create_program(.., Arc::clone(&regions.loaders))
            P->>L: parse and bind its files
            R->>P: run_program, then free_unshared_program
            Note over L: project N's files stay
        end
        Note over R,P: with the change
        loop each tsconfig project
            R->>L: ProjectRegions::new()
            R->>P: create_program(.., Arc::clone(&regions.loaders))
            P->>L: parse and bind its files
            R->>P: run_program, then free_unshared_program
            R->>L: drop: project N's files go
        end
    
    Loading

    Results

    The generator from the issue body, tsrs-lint headless < payload.json, built with --release, CARGO_PROFILE_RELEASE_LTO=false CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 as in the issue. macOS arm64, 10 cores, /usr/bin/time -l, median of three runs (one run for the --type-check row):

    Request main (b8b21271) With the change Frames
    40 projects × 24 files 461 MiB 61 MiB byte-identical (648,880 bytes)
    120 projects × 24 files 1,321 MiB 74 MiB byte-identical (1,950,480 bytes)
    120 projects, report_semantic and report_syntactic, TSRS_FAST=1 1,319 MiB 82 MiB byte-identical

    Instructions retired on the 120-project request with RAYON_NUM_THREADS=1, as /usr/bin/time -l reports them, three interleaved runs each: 22.32–23.10 G on main (median 22.68 G), 22.07–22.24 G with the change (median 22.14 G).

    With one TS2322 added to each of three projects, the 40-project --type-check request reports the same three errors on both builds, byte-identical. With TSRS_ARENA_POISON=1, the 120-project --type-check requests (default and TSRS_FAST=1) are byte-identical as well.

    Through Oxlint on a large private monorepo (vp lint --type-aware, TSRS_FAST=1, RAYON_NUM_THREADS=4), peak RSS of the published 0.22.0-ts7.1.0-beta against v0.22.0 with the change. A request over one package maps its files to a few tsconfig projects; a pre-commit hook or a root lint sends files from many packages at once:

    Request Published 0.22.0 v0.22.0 with the change
    One package, median of three 5.0 GiB 4.2 GiB
    Files from several packages 4.4 GiB 2.0 GiB
    Files from many packages 6.6 GiB 1.7 GiB

    The change

    engine.rs +25 −6 on main (b8b21271), the same lines on v0.22.0, and the lifecycle test from the issue's branch. The capability table's "request-owned allocation regions" becomes "per-project allocation regions".

    What outlives a project holds no pointer into its regions:

    Diff
    diff --git a/crates/tsrs_lint/src/engine.rs b/crates/tsrs_lint/src/engine.rs
    index 1a21775a..7fa30ea0 100644
    --- a/crates/tsrs_lint/src/engine.rs
    +++ b/crates/tsrs_lint/src/engine.rs
    @@ -32,11 +32,27 @@ pub struct Options {
         pub run_external_code: bool,
     }
     
    -#[derive(Default)]
    -struct RequestRegions {
    +/// What linting one project allocates: the main thread's target while its config is parsed and its program is built
    +/// and linted, and the file loaders' regions. The checkers' memory goes back with the program (`checker_regions`).
    +/// Lazily filled data of the program's objects goes to whichever region is the current target, so both live until the
    +/// program is freed, and nothing that outlives the project refers into them: every project builds its own program, and
    +/// the request's file system caches and type-checked paths are on the heap. Freeing them with the project keeps one
    +/// project's regions at a time instead of every project's.
    +struct ProjectRegions {
    +    // Dropped in declaration order, the loaders last.
    +    main: tsrs_core::arena::Region,
         loaders: Arc<tsrs_compiler::ProgramRegions>,
     }
     
    +impl ProjectRegions {
    +    fn new() -> ProjectRegions {
    +        ProjectRegions {
    +            main: tsrs_core::arena::Region::new_scratch(1 << 20),
    +            loaders: Arc::default(),
    +        }
    +    }
    +}
    +
     pub struct ConfigHost {
         fs: Arc<dyn FS>,
         cwd: String,
    @@ -148,11 +164,10 @@ pub fn run(
                 .then(|| CompilerOptions { run_external_code: Tristate::True, ..Default::default() }),
             ..ConfigHost::new(Arc::clone(&fs), cwd.into())
         };
    +    // Project discovery; each project's program gets regions of its own (`ProjectRegions`).
         let region = tsrs_core::arena::Region::new_scratch(1 << 20);
    -    // Shared caches can receive loader allocations, so the loader regions outlive every request program.
    -    let regions = RequestRegions::default();
         let _scope = region.enter();
    -    run_in_region(payload, options, cwd, writer, fs, &host, &regions)
    +    run_in_region(payload, options, cwd, writer, fs, &host)
     }
     
     struct ProgramOwner {
    @@ -217,7 +232,6 @@ fn run_in_region(
         writer: &mut dyn Write,
         fs: Arc<dyn FS>,
         host: &ConfigHost,
    -    regions: &RequestRegions,
     ) -> Result<(), String> {
         let mut programs: BTreeMap<String, Vec<String>> = BTreeMap::new();
         let mut unmatched = Vec::new();
    @@ -257,6 +271,9 @@ fn run_in_region(
         }
         drop(config_cache);
         for (config_path, files) in programs {
    +        // Locals drop in reverse order at the end of each iteration: the program, the scope, then its regions.
    +        let regions = ProjectRegions::new();
    +        let _scope = regions.main.enter();
             let (config, diagnostics) = tsrs_tsoptions::get_parsed_command_line_of_config_file(
                 &config_path,
                 host.existing_options.as_ref(),
    @@ -309,6 +326,8 @@ fn run_in_region(
             }
         }
         if !unmatched.is_empty() {
    +        let regions = ProjectRegions::new();
    +        let _scope = regions.main.enter();
             let config = tsrs_tsoptions::new_parsed_command_line(
                 P::new(CompilerOptions {
                     allow_js: Tristate::True,
    diff --git a/crates/tsrs_lint/tests/integration/lifecycle.rs b/crates/tsrs_lint/tests/integration/lifecycle.rs
    index c9795118..de12d58d 100644
    --- a/crates/tsrs_lint/tests/integration/lifecycle.rs
    +++ b/crates/tsrs_lint/tests/integration/lifecycle.rs
    @@ -14,6 +14,55 @@ impl Write for BrokenWriter {
         }
     }
     
    +#[test]
    +fn one_request_releases_project_regions_between_serial_and_parallel_programs() {
    +    std::thread::Builder::new()
    +        .stack_size(512 * 1024 * 1024)
    +        .spawn(|| {
    +            let cwd = std::env::current_dir().unwrap().to_string_lossy().into_owned();
    +            let base = format!("{cwd}/target/lint-project-region-lifecycle");
    +            let mut payload = Payload::default();
    +            let mut expected = 0;
    +            for project in 0..6 {
    +                let directory = format!("{base}/project{project}");
    +                let count = if project % 2 == 0 { 1 } else { 4 };
    +                payload.source_overrides.insert(
    +                    format!("{directory}/tsconfig.json"),
    +                    r#"{"compilerOptions":{"strict":true,"target":"es2022","lib":["es2022","dom","dom.iterable"],"types":[]},"include":["*.ts"]}"#.into(),
    +                );
    +                let mut files = Vec::new();
    +                for file in 0..count {
    +                    let path = format!("{directory}/file{file}.ts");
    +                    payload.source_overrides.insert(
    +                        path.clone(),
    +                        "export {}; function load(): Promise<Response> { return fetch('/items'); } load();".into(),
    +                    );
    +                    files.push(path);
    +                    expected += 1;
    +                }
    +                payload.configs.push(Config {
    +                    file_paths: files,
    +                    rules: vec![ConfiguredRule { name: "no-floating-promises".into(), ..Default::default() }],
    +                });
    +            }
    +            let mut output = Vec::new();
    +            engine::run(&payload, Options::default(), &cwd, &mut output).unwrap();
    +            let mut count = 0;
    +            let mut bytes = output.as_slice();
    +            while !bytes.is_empty() {
    +                let length = u32::from_le_bytes(bytes[..4].try_into().unwrap()) as usize;
    +                assert_eq!(bytes[4], 1);
    +                assert!(std::str::from_utf8(&bytes[5..length + 5]).unwrap().contains("no-floating-promises"));
    +                bytes = &bytes[length + 5..];
    +                count += 1;
    +            }
    +            assert_eq!(count, expected);
    +        })
    +        .unwrap()
    +        .join()
    +        .unwrap();
    +}
    +
     #[test]
     fn repeated_library_calls_release_request_state_on_success_and_failure() {
         std::thread::Builder::new()

    Validation on main with the change:

    • cargo test --locked --profile ci -p tsrs_lint: 125 passed, the lifecycle test above included.
    • The same with TSRS_ARENA_POISON=1: 125 passed.
    • cargo clippy --locked -p tsrs_lint --all-targets --config 'build.warnings="deny"' and cargo fmt --check -p tsrs_lint: clean.
  4. christianvuerings commented on Nov 9, 2026

    @christianvuerings
    Contributor

    Thanks for the write-up and the rebased change: I took its loader half, plus two more fixes for requests over many small composite projects that share the same libraries, in christianvuerings#12.

    One tsrs-lint headless request over many tsconfig programs no longer keeps every program in memory, and stops parsing referenced tsconfigs and declaration files again for each program.

    request tsrs main
    fc384313
    all three fixes tsgolint 7.0.2006
    public reproduction, 300 programs peak RSS 4.7 GB 98 MB 189 MB
    wall time 9.86 s 2.35 s 2.20 s
    CPU time 22.2 s 13.0 s 14.0 s
    our web monorepo, one rule peak RSS 19.9 GB 1.1 GB 1.8 GB
    wall time 44.4 s 11.2 s 13.8 s
    CPU time 116 s 49.4 s 146 s

    Medians of 5 runs, helper only, quiet 64-CPU Linux x86-64 machine.

    Reproduce our web monorepo numbers: https://github.com/christianvuerings/tsrs-lint-monorepo-repro generates a workspace with the same shape (175 overlapping programs, about 1,069 linted files) and gives numbers close to the monorepo rows above.

    The three fixes

    tsrs main
    fc384313
    + fix 1
    5245ecca
    + fix 2
    4a440b37
    + fix 3
    bbf1629f
    reproduction, 300 programs: peak RSS 4.7 GB 246 MB 124 MB 98 MB
    reproduction, 300 programs: wall time 9.86 s 9.09 s 7.48 s 2.35 s
    our web monorepo: peak RSS 19.9 GB 1.4 GB 901 MB 1.1 GB
    our web monorepo: wall time 44.4 s 45.3 s 17.7 s 11.2 s
    our web monorepo: CPU time 116 s 115 s 72.3 s 49.4 s
    1. 5245ecca Free each program's loader regions with the program (design by grmkris in tsrs-lint: a headless request still keeps every tsconfig project's arena memory until it ends (main after #624) #855, its loader half).
    2. 4a440b37 Parse a referenced project's tsconfig once per request, not once per program.
    3. bbf1629f Parse and bind a declaration file once per request, as tsc -b does.

    Still slower than tsgolint in wall time on the reproduction: 4% at 150 programs, 7% at 300 programs.

    Same output

    request frames result
    reproduction, 50, 150 and 300 programs 50, 150, 300 byte-identical after each commit
    reproduction, 300 programs, with report_semantic and report_syntactic (the --type-check request; the reproduction has no type errors, so the frames are the lint findings) 300 byte-identical after each commit
    reproduction, 300 programs, with TSRS_FAST=1 300 byte-identical after each commit
    reproduction, 50 programs, with singleThreaded in its tsconfig (the sequential loader) and all 61 type-aware rules 50 byte-identical after each commit
    4 singleThreaded programs that share a declaration file with #private class members, all 61 rules 48 byte-identical after each commit
    our web monorepo, the one-rule request 0 no findings from any build
    our web monorepo, the same files with all 61 type-aware rules 11,272 byte-identical after each commit, also with TSRS_FAST=1
    our web monorepo, a wider file set with all 61 rules 39,580 byte-identical after each commit
    our web monorepo, one program with all 61 rules (nothing is shared) 11,139 byte-identical after each commit; no extra cost (2.7 s of CPU time and 360 MB, against 2.7 s and 357 MB on main, medians of 3 on a second, shared 192-CPU machine)
    How each fix works

    oxlint sends such a request for a workspace of small composite projects that reference the same libraries: its files map to one tsconfig program per project. On main, tsrs-lint builds every program of a request from nothing, keeps each one's files until the request ends, and parses the tsconfig of every referenced project and every declaration file again for each program. tsgolint 7.0.2006 builds the programs one after the other too, but keeps the files it parsed in a process-wide cache (sourceFileCache in internal/utils/host.go), so a file is parsed once per request for each set of parse options.

    1. Free each program's loader regions with the program (5245ecca)

    engine.rs gave every program of a request the same ProgramRegions set, so each program's text, trees and binder data stayed until the request ended: the peak was the sum over the programs. Now the loop over the tsconfig programs makes a set for each program, before it parses the program's tsconfig, and drops it right after the program, as tsc -b frees a built project's. In engine.rs that is 3 lines added and 1 removed:

    for (config_path, files) in programs {
        // Dropped after the program: nothing that outlives a program points into its loader regions.
        let regions = RequestRegions::default();

    The local shadows the request's set and is declared before the program, so it is dropped after it. The inferred program for files outside every tsconfig is the last thing a request builds: it keeps the request's set, as before.

    Nothing that outlives a program points into its loader regions:

    • At this commit each program has its own compiler host, resolver, package.json cache and command lines. Of what a request owns, its programs share only the file system caches, which hold strings, and the type-checked paths and timings, which are on the heap. Fixes 2 and 3 add shared command lines and declaration files, each in a region of its own (below). The loader and checker threads are reused from program to program as on main; the lint tests pass with TSRS_ARENA_POISON=1, where a read of a freed region would not go unnoticed.
    • The comment that kept the set request-wide began as a comment on the lint workers' regions ("shared caches can receive worker allocations"). lint: run the rules on the program's checker pool #848 removed those regions and reworded it for the loader regions, without naming a cache.
    • The note that introduced the request-wide set (perf-tsgolint-parallel-load.md) gave one reason: it "avoids a new arena tail per worker per tsconfig". That tail only costs memory while it is kept. Freed with the program, the next program uses it again.

    Fixes 2 and 3 go through one small wrapper around the program's compiler host. What the programs share is kept by the request (Shared): each shared value is made once, in a registered region of its own that lives until the request ends, so its lazily filled data goes there too (arena::enter_owner) and not to a program's regions, which fix 1 frees with the program.

    2. Parse a referenced project's tsconfig once per request (4a440b37)

    The file loader parses the tsconfig of every project a program references, and theirs, through the compiler host, in queue order on the calling thread. The lint host had no cache, so every program read, parsed and expanded the include globs of the same projects again: by stack samples the reference parser is 61% of the request on our web monorepo on main.

    The programs of a request now share those command lines, as the projects of a tsc -b share them through its host.

    • A referenced command line is parsed from an absolute path with no command-line options, through the file system the request already caches. The host's current directory, which differs per program, only resolves relative names, and there are none. The cache key is the name as it was asked for, because on a case-insensitive file system two spellings are one path and a command line keeps its spelling.
    • A shared command line computes its common source directory lazily. Whoever asks first (the reference parser, or a checker), the diagnostics it may make land in the command line's own region, in the request's region or in a thread arena, never in memory that is freed with a program. That holds because the request thread has no per-program region. If one is added later (the other half of the proposal in tsrs-lint: a headless request still keeps every tsconfig project's arena memory until it ends (main after #624) #855), these diagnostics have to be made when the command line is cached.
    • Each program's own tsconfig is still parsed per program, with its command-line options.

    This also removes most of the growth fix 1 leaves, about 0.5 MB per program on the reproduction (0.1 MB after this commit). The lint process routes lazily filled data by owner, because the module resolver's package.json cache has a registered region. A command line in a program's unregistered loader region therefore left the entries of its name maps, one per file of the referenced project with two strings each, in the request thread's own arena, which is never freed.

    3. Parse and bind a declaration file once per request (bbf1629f)

    Every program parsed and bound its declaration files again. The 63 default library files of target: es2022 are 2.7 MB of text, and lib.dom.d.ts (2.3 MB) is one job on one pool thread: on the reproduction the request thread spent 68.5% of the request on main waiting for the pool while, in most of those samples, at most one of its threads worked.

    The programs of a request now share their declaration files, as the projects of a tsc -b do (build/host.rs): one parse per SourceFileParseOptions (file name, path and module-indicator options). The binder takes no options.

    • The file is bound where it is cached, in its own region. The loader would otherwise bind it in the current program's loader region, which is freed with that program. tsc -b gets this from bind_in_file_regions, a process-wide switch; binding at the cache keeps the lint library free of process-wide state.
    • Other source files are still parsed per program.

    Peak RSS rises with this fix on our web monorepo: the shared declaration files stay until the request ends.

    Looked at and left out
    • The other half of the proposal in tsrs-lint: a headless request still keeps every tsconfig project's arena memory until it ends (main after #624) #855 (by grmkris; a later comment there has it rebased after lint: run the rules on the program's checker pool #848): a region per program for what the request thread allocates. It changes peak RSS by no more than repeated runs differ (table below), and without it the request thread's allocations keep the lifetime they have today. By reading the code (an estimate, not a measurement), what it would free is mainly each program's own parsed tsconfig, under 0.1 MB for a typical one, plus its list of file names and the diagnostics made on the request thread, next to the copies find_tsconfig already leaves in the request's region on main.
    • Running several programs at once. It would use the cores, but multiply the peak by the number of programs in flight, and tsgolint does not do it either.
    • Sharing the other source files (the .ts sources the programs reach through project references), which tsgolint does. It is what is left. It needs the checker's use of shared source trees proven for more than declarations, so it is a separate change. tsrs-lint: a lint-only option to read referenced projects from their declarations #937 is a neighbouring idea.
    • New tests for fixes 2 and 3. No small test fails without them: they change how often work is done, not what a request reports. So nothing pins the sharing itself: a change that stopped it would pass every test. Their lifetime rules are covered by the existing suite when it runs with TSRS_ARENA_POISON=1 (see the memory-safety checks).

    Still slower than tsgolint: the reproduction at 150 programs, by 4% (1.22 s against 1.17 s); the reproduction at 300 programs, by 7% (2.35 s against 2.20 s). tsgolint also shares the source files that are not declarations, which these fixes leave alone.

    Peak RSS with each half of the proposal, on a second, shared 192-CPU machine (repeated runs, as marked):

    request tsrs main
    fc384313
    request-thread region only loader regions only, fix 1
    5245ecca
    both
    reproduction, 300 programs (medians of 5) 4,846.2 MB 4,831.9 MB 294.2 MB 287.9 MB
    our web monorepo, one rule (medians of 3; the first two columns one run) 20,493.4 MB 20,466.7 MB 1,595.8 MB 1,576.1 MB
    our web monorepo, wider file set, 61 rules (medians of 2; the first column one run) 22,549.1 MB not run 1,742.3 MB 1,742.3 MB
    The new test, and how it fails without fix 1

    a_request_frees_each_program_before_the_next runs alone in a child process (the isolated helper has the same code as the one four other crates' tests have) and reads how far into the arenas' address range chunks were ever carved. A request of 14 programs must carve less new address range than a request of 2 programs did before it. Each program is one large file of its own with no libraries, so the measure does not depend on what programs could share, and every program must report its one finding.

    engine a request of 2 programs carved a request of 14 programs then carved test
    fix 1 alone, and all three fixes 12.4 to 13.4 MB 0 to 1.0 MB passes
    main 19.6 to 20.6 MB 94.1 MB fails
    all three fixes with only fix 1 undone 19.6 to 20.6 MB 94.1 MB fails

    Each cell is the range over runs with 1, 4, 16 and 64 threads and with the default on a 192-CPU machine.

    Where the time went on main (stack samples)

    The request thread builds and lints one program after the other. gdb stack samples of it (89 on the reproduction, 146 on our web monorepo), taken on another machine than the timings (192 CPUs, shared with other jobs); the machines have no access to hardware counters:

    share of the request, tsrs main
    fc384313
    reproduction, 300 programs our web monorepo
    building programs (new_program) 96.6% 93.8%
    of that: parsing referenced tsconfigs (ProjectReferenceParser, on this thread) 18.0% 61.0%
    of that: the file loader's parallel step (FilesParser::prefetch) 69.7% 29.5%
    linting on the checker pool 3.4% 4.8%

    On our web monorepo 49.3% of the request is get_resolved_project_reference (32.9% the include globs, 9.6% extended configs) and 8.9% parse_input_output_names. Inside that parallel step the request thread waits for the pool (68.5% and 26.7% of the request), and in most of those samples at most one pool thread works.

    Every size, and one-thread CPU time

    Medians of 5 runs on the quiet machine. Wall time, CPU time (user plus system), peak RSS:

    programs tsrs main
    fc384313
    + fix 1
    5245ecca
    + fix 2
    4a440b37
    + fix 3
    bbf1629f
    tsgolint 7.0.2006
    50 1.70 s, 3.8 s, 840 MB 1.56 s, 3.5 s, 110 MB 1.27 s, 3.3 s, 90 MB 0.45 s, 2.2 s, 71 MB 0.46 s, 3.0 s, 175 MB
    150 4.97 s, 11.1 s, 2.4 GB 4.60 s, 10.5 s, 164 MB 3.75 s, 9.8 s, 109 MB 1.22 s, 6.5 s, 86 MB 1.17 s, 7.5 s, 182 MB
    300 9.86 s, 22.2 s, 4.7 GB 9.09 s, 21.3 s, 246 MB 7.48 s, 19.8 s, 124 MB 2.35 s, 13.0 s, 98 MB 2.20 s, 14.0 s, 189 MB

    CPU time with one thread (RAYON_NUM_THREADS=1, GOMAXPROCS=1), medians of 3 runs on the quiet machine:

    tsrs main
    fc384313
    + fix 1
    5245ecca
    + fix 2
    4a440b37
    + fix 3
    bbf1629f
    tsgolint 7.0.2006
    reproduction, 300 programs 11.7 s 10.8 s 9.2 s 3.7 s 9.1 s
    our web monorepo 66.4 s 67.5 s 40.2 s 21.6 s 86.8 s
    Public reproduction

    The reproduction is a generated workspace: gen.mjs writes N composite "suite" projects of 3 files each, 12 shared libraries of 121 files each and a core package, connected by project references and a paths mapping, and payload.json, the request oxlint 1.92.0 sends for oxlint --type-aware -A all -D typescript/no-floating-promises over the suite files (same files and options; oxlint lists the files in another order). Every suite has one floating promise.

    node gen.mjs ws300 300 && cd ws300
    /usr/bin/time -v tsrs-lint headless < payload.json > frames.bin       # or: tsrs --lint headless
    /usr/bin/time -v tsgolint headless < payload.json > frames-go.bin     # oxlint-tsgolint 7.0.2006

    Both helpers report the same 300 findings (tsgolint writes the keys of a frame in another order, and the frames in an order that changes from run to run).

    gen.mjs
    #!/usr/bin/env node
    // gen.mjs <dir> [suites=150] [filesPerSuite=3] [libs=12] [filesPerLib=120]
    // A generated monorepo: many small composite projects ("suites"), each with a few files to lint, each referencing
    // the same shared libraries through project references.
    // Linting every suite's files in one `oxlint --type-aware` run sends one headless request with one tsconfig
    // program per suite, and the programs overlap (they all reference the shared libraries and load three of them).
    // Also writes <dir>/payload.json, the request oxlint 1.92.0 sends for
    // `oxlint --type-aware -A all -D typescript/no-floating-promises` over every suite file, so the helper can be run
    // alone from <dir>: `tsrs-lint headless < payload.json > frames.bin` (or `tsgolint headless`).
    // Derived from the generator in https://github.com/oxc-project/tsrs/issues/932. No proprietary code.
    import fs from 'node:fs';
    import path from 'node:path';
    
    const [dir, suites = 150, filesPerSuite = 3, libs = 12, filesPerLib = 120] = process.argv
      .slice(2)
      .map((v, i) => (i ? Number(v) : v));
    if (!dir) throw new Error('usage: gen.mjs <dir> [suites] [filesPerSuite] [libs] [filesPerLib]');
    if (fs.existsSync(dir)) throw new Error(`${dir} exists: pick a new directory`);
    const write = (p, s) => {
      fs.mkdirSync(path.dirname(path.join(dir, p)), { recursive: true });
      fs.writeFileSync(path.join(dir, p), s);
    };
    const json = (v) => JSON.stringify(v, null, 2) + '\n';
    const pad = (i) => String(i).padStart(3, '0');
    const project = (name, references) =>
      write(
        `packages/${name}/tsconfig.json`,
        json({
          extends: '../../tsconfig.base.json',
          compilerOptions: { rootDir: 'src', outDir: 'dist' },
          include: ['src'],
          references: references.map((r) => ({ path: `../${r}` })),
        }),
      );
    
    write('package.json', json({ name: 'tsrs-lint-memory-repro', private: true }));
    write(
      'tsconfig.base.json',
      json({
        compilerOptions: {
          target: 'es2022',
          module: 'esnext',
          moduleResolution: 'bundler',
          strict: true,
          composite: true,
          declaration: true,
          skipLibCheck: true,
          types: [],
          paths: { '@repro/*': ['./packages/*/src/index.ts'] },
        },
      }),
    );
    write('.oxlintrc.json', json({ plugins: ['typescript'] }));
    
    project('core', []);
    let core = '';
    for (let i = 0; i < 200; i++) {
      core += `export interface Entity${i}<T = unknown> { id: string; kind: 'k${i}'; payload: T; next?: Entity${(i + 1) % 200} }\n`;
      core += `export async function load${i}(id: string): Promise<Entity${i}> { return { id, kind: 'k${i}', payload: undefined }; }\n`;
    }
    write('packages/core/src/index.ts', core);
    
    const libNames = [];
    for (let l = 0; l < libs; l++) {
      const name = `lib-${pad(l)}`;
      libNames.push(name);
      project(name, ['core']);
      let index = '';
      for (let f = 0; f < filesPerLib; f++) {
        const types = Array.from({ length: 8 }, (_, k) => `Entity${(f * 8 + k) % 200}`);
        write(
          `packages/${name}/src/m${pad(f)}.ts`,
          `import type { ${types.join(', ')} } from '@repro/core';\nimport { load${f % 200} } from '@repro/core';\n` +
            `export type Bag${f} = { ${types.map((t, k) => `f${k}: ${t}<Bag${f}>`).join('; ')} };\n` +
            `export async function fetch${f}(id: string): Promise<Bag${f} | undefined> { await load${f % 200}(id); return undefined; }\n` +
            `export class Page${f} { constructor(readonly id: string) {} async open(): Promise<void> {} async read(): Promise<Bag${f} | undefined> { return fetch${f}(this.id); } }\n`,
        );
        index += `export * from './m${pad(f)}';\n`;
      }
      write(`packages/${name}/src/index.ts`, index);
    }
    
    const files = [];
    for (let s = 0; s < suites; s++) {
      const name = `suite-${pad(s)}`;
      project(name, libNames);
      for (let f = 0; f < filesPerSuite; f++) {
        const lib = libNames[(s + f) % libNames.length];
        const k = (s * 7 + f) % filesPerLib;
        const p = `packages/${name}/src/test${f}.ts`;
        write(
          p,
          `import { Page${k}, fetch${k} } from '@repro/${lib}';\n` +
            `export async function run${f}(): Promise<void> {\n  const page = new Page${k}('${s}-${f}');\n  await page.open();\n` +
            (f === 0 ? `  page.read();\n` : `  await page.read();\n`) +
            `  await fetch${k}('x');\n}\n`,
        );
        files.push(p);
      }
    }
    write('files.txt', files.join('\n') + '\n');
    write(
      'payload.json',
      JSON.stringify({
        version: 2,
        configs: [
          {
            file_paths: files.map((p) => path.resolve(dir, p)),
            rules: [
              {
                name: 'no-floating-promises',
                options: {
                  allowForKnownSafeCalls: [],
                  allowForKnownSafePromises: [],
                  checkThenables: false,
                  ignoreIIFE: false,
                  ignoreVoid: true,
                },
              },
            ],
          },
        ],
        source_overrides: null,
        report_syntactic: false,
        report_semantic: false,
      }),
    );
    console.log(
      `wrote ${suites} suites x ${filesPerSuite} files, ${libs} libraries x ${filesPerLib} files to ${dir}`,
    );
    How it was measured
    • Helper only: the request oxlint sends was recorded once, and each helper was run as <helper> headless < payload.json > frames.bin, alone, in its own memory-capped cgroup scope, under /usr/bin/time -v. Peak RSS is its "Maximum resident set size", CPU time is user plus system. On the quiet machine every cell is the median of 5 runs (3 for the one-thread table): main and tsgolint ran interleaved, round by round, and the three fix builds ran interleaved among themselves after them, on the same morning. A run during which other processes used more than 2 cores was repeated and only the repeat counts: 73 of 203 runs, almost all of them runs under 2 s, where that reading is dominated by timer rounding. The tables from the second machine state their own run counts.
    • Machine for the timing tables and the one-thread table: Linux x86-64, 64 CPUs, other processes under 1.5 cores before every run, measured on Nov 8, 2026. The four-variant table, the test's numbers, the stack samples and the output comparisons are from a second machine (192 CPUs, shared with other jobs), on Nov 7 and 8, 2026.
    • Builds: main is fc384313 (Nov 6, 2026), the v0.23.0 release commit and still the tip of upstream main on Nov 8, 2026. Every build is cargo build --release --locked -p tsrs_cli with CARGO_PROFILE_RELEASE_LTO=thin, CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16, CARGO_PROFILE_RELEASE_DEBUG=line-tables-only and CARGO_PROFILE_RELEASE_STRIP=false, run as tsrs --lint.
    • Instructions retired were not measured: the machines have no access to hardware counters (perf_event_open is not available). CPU time with one thread stands in (the table is folded under "Every size"): with one thread no pool thread looks for work, so CPU time is work done.
    Why the output cannot change, and memory-safety checks

    Why it holds:

    Frames are compared as bytes, in the order written, against main, after each commit.

    • Fix 1 only changes when a program's loader memory is freed. Each program is still built and linted alone, by the same checkers, in the same order, and every frame is written before its program is freed.
    • Fix 2: a referenced command line is a function of its file name and the file system, and its lazily computed fields are functions of the command line.
    • Fix 3: a declaration file's tree is a function of its text and parse options, and binding takes no options. Checkers already share bound files inside one program: symbol merges clone, and what a checker allocates goes to its own region. Node and symbol ids come from process-wide counters either way.

    Memory safety:

    • cargo test -p tsrs_lint passes with TSRS_ARENA_POISON=1 (freed memory is filled and never used again): 125 tests pass at each commit. The existing tests are what guards the two lifetime rules of fixes 2 and 3 (both checked at the tip): with a shared command line left in the asking program's region, type_check_uses_transitive_custom_project_options_without_rules does not finish under poisoning; with shared files bound by the loader instead of at the cache, four existing tests fail.
    • The tip built without pointer compression and run with TSRS_ARENA_POISON=1: the reproduction at 300 programs writes the same bytes as main, also with type checking, and our web monorepo's one-rule request finishes with no findings, as on main.
    Validation
    • cargo fmt --all -- --check, cargo clippy --locked -p tsrs_lint --all-targets --config 'build.warnings="deny"' and node tools/lint/source.mjs, at each commit
    • cargo test --profile ci --locked -p tsrs_lint: 125 tests pass at each commit, including the imported rule baselines and the all-rules fixture; the same under TSRS_ARENA_POISON=1. The new test returns early there, because its measure needs freed memory to be used again.
    • cargo test --profile ci --locked -p tsrs_cli --test integration lint_mode (it runs the linter in process): passes at each commit

    Not run: the tests of the other crates (only crates/tsrs_lint changes, plus two lines of Cargo.lock for its new dependencies on tsrs_binder and tsrs_diagnostics, and one line of docs/COMPATIBILITY.md), bench/lint.mjs (its projects were not at hand; the one-program request above stands in), the determinism catalog, ThreadSanitizer and Miri. The fork has no access to the namespace-profile-linux-x64-default runners, so CI jobs that need them stay queued.

    Credit: tsrs-lint is by Cameron (camc314, "feat: tsrslint", #624) and Max Schwenk (maschwenk). The per-program regions design is the proposal in #855 by grmkris.

    Written with Claude Code on behalf of Christian Vuerings.

  5. self-assigned this
    on Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

- P2pkg: checkerpkg: clitriage: unable to fix

Type

No type

Fields

Priority

None yet

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions