← Back to Pull requests

perf(linter/import/no-cycle): compare module records by interned path id #25324

Open
connorshea opened this pull request with 134 lines diff across 6 files
View on GitHub
connorshea connorshea commented on Aug 05, 2026 23:15 UTC
Author

AI Disclosure: Generated with Claude Code, Opus 5. Tested, reviewed, and stripped down by me.

The goal here is to have the most improvement for the rule with the smallest change.

  • If you have import/no-cycle enabled and a lot of cycles to find: -30 to -44%

  • If you have import/no-cycle enabled and few or no cycles: no change (-0.2 to -1.0%, within noise)

  • If you have other import rules enabled but not import/no-cycle: no change

  • If you don't use the import plugin at all: no change
  • This also speeds up import/no-self-import, which does the same identity comparison once per import (but it's already quite fast, so no real noticeable difference).

    This should be a net-win or fully neutral for all users with or without no-cycle enabled.

    Code in import/export and collect_star_exported_bindings can also be simplified/de-duped thanks to this change, but it has no real perf impact on any codebase I tested and so I've left it out of this PR. We can open a refactor PR later if desired.

    ---

    import/no-cycle walks the module graph, and profiling it showed the walk spending most of its time inside std::path rather than on graph traversal: parsing path components for the node_modules check once per edge, Path's PartialEq comparing components back-to-front, and cloning + hashing a PathBuf into the visitor's traversed set once per node visited.

    ModuleRecord now answers both questions up front:

  • is_node_module is computed once when the record is built, with a memmem byte search short-circuiting the component walk for the overwhelmingly common non-match.

  • path_id is a u32 interned per resolved path by Runtime, so the identity comparisons cross-module analysis does constantly become integer compares, and ModuleGraphVisitor::traversed becomes a FxHashSet<u32> that allocates nothing per node.
  • Two things keep interning itself from costing anything:

  • It is gated on a resolver being present, so runs that never build a module graph — no import plugin, no cross-module rules, no rules at all — skip it entirely.

  • The map is keyed on the Arc<OsStr> that Runtime::modules_by_path already owns for every module, so adding a path costs a refcount bump rather than a PathBuf copy.
  • import/no-self-import gets the cheaper comparison for free. It compares each imported module against the current one once per import, not once per violation, so the win does not depend on the codebase having any self-imports — the corpora below report zero and it still drops 28-59%.

    Measurements

    Seven real codebases, import/no-cycle alone, --features allocator, 18 threads, process wall clock, N=41 paired with rotating binary order. t is the paired t-statistic; positive means this PR is faster.

    | corpus | files | cycles | main | this PR | Δ | t |
    | ------ | ----: | -----: | ---: | ------: | -: | -: |
    | vscode/src | 8006 | 1630 | 1200.2 ms | 671.4 ms | −44.1% | +55.6 |
    | sentry/static | 8193 | 756 | 529.9 ms | 368.5 ms | −30.5% | +66.7 |
    | actual/packages | 1772 | 188 | 125.3 ms | 120.7 ms | −3.7% | +7.7 |
    | storybook/code | 4037 | 74 | 302.9 ms | 300.0 ms | −1.0% | +1.2 |
    | canvas-lms/ui | 8899 | 99 | 258.0 ms | 255.9 ms | −0.8% | +1.8 |
    | grafana/public | 6541 | 0 | 976.2 ms | 974.0 ms | −0.2% | +0.4 |
    | gitlab/app/assets/javascripts | 5194 | 5 | 109.0 ms | 108.7 ms | −0.2% | +0.9 |

    No corpus regresses. The four small rows are all within noise (t < 2), which is the intended outcome rather than a win — see "Earlier cost, now removed" below.

    The rule's own work drops consistently everywhere it runs (though this is mainly because it's bumming the work off on the module graph build, so it's not entirely a fair comparison). Single-threaded, from --debug=timings, median of 3 interleaved pairs:

    | corpus | main | this PR | Δ |
    | ------ | ---: | ------: | -: |
    | vscode/src | 9006.3 ms | 2481.1 ms | −72.4% |
    | sentry/static | 2696.8 ms | 781.9 ms | −71.0% |
    | canvas-lms/ui | 54.8 ms | 15.9 ms | −71.0% |
    | actual/packages | 71.2 ms | 27.5 ms | −61.3% |
    | storybook/code | 66.3 ms | 26.7 ms | −59.6% |
    | gitlab/app/assets/javascripts | 4.0 ms | 1.7 ms | −58.6% |
    | grafana/public | 0.22 ms | 0.22 ms | — |

    Wall-clock impact therefore tracks how much rule work a codebase has to begin with, not simply whether it has cycles. vscode spends 9 s of single-threaded rule time; gitlab spends 4 ms, and grafana has no cycles at all so can_be_in_cycle (already on main) rejects every file before the walk starts.

    Allocations, counted with a counting global allocator and the parse-only baseline subtracted to isolate graph + rule work:

    | corpus | allocations | bytes requested |
    | ------ | ----------- | --------------- |
    | vscode/src | 42.18M → 21.99M (−47.9%) | 4.951 → 3.323 GB (−32.9%) |
    | sentry/static | 9.32M → 5.80M (−37.7%) | 1.492 → 1.166 GB (−21.9%) |
    | storybook/code | 1.499M → 1.467M (−2.2%) | 1.596 → 1.593 GB (−0.2%) |
    | gitlab/app/assets/javascripts | 134,929 → 134,908 (−0.02%) | 206.6 → 207.0 MB (+0.2%) |

    Peak RSS: vscode −424.8 MB (1388 → 964), sentry −37.4 MB (441 → 403), every other corpus within ±1 MB.

    Earlier cost, now removed

    An earlier version of this PR moved work from the walk into graph construction: interning cloned a PathBuf per module record, which a codebase with a large module graph and few cycles never walked enough to repay. gitlab measured +0.4 to +0.9 ms on a ~100 ms run and +6,241 allocations, roughly one clone per file for 5,194 files.

    The second-to-last commit removes that by interning on the Arc<OsStr> key Runtime::modules_by_path already holds, so a map entry is a refcount bump. Allocations drop by exactly one per file — −5,181 on gitlab, −8,193 on sentry (which has exactly 8,193 files), −8,256 on vscode — and the same delta appears whether or not no-cycle is enabled, confirming the cost was always at graph construction.

    Measured on import rules with no-cycle disabled, versus main, N=61 paired:

    | corpus | before | after |
    | ------ | -----: | ----: |
    | gitlab | +0.4 ms (t = −0.7) | +0.1 ms (t = −0.4) |
    | sentry | +1.0 ms (t = −1.6) | −0.9 ms (t = +0.8) |
    | vscode | +0.4 ms (t = −0.5) | −3.2 ms (t = +2.6 ±2.4) |

    gitlab is now break-even at −21 allocations, and vscode is measurably slightly faster than main on a configuration that never runs no-cycle.

    Correctness

    Diagnostics are byte-identical to main on all seven corpora, including vscode's 1630 cycles / 47,818 diagnostic lines.

    Diff: 134 lines (+104 / -30) across 6 files Reviewer: connorshea Review duration: 107981m
    All Vouch review confidence checks passed
    Residual risk 0.14 = Change Risk (0.66) × (1 − Review Confidence (0.79)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.66 · 134 lines diff across 6 files
    0.66
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.92 · 5 substantive comment(s)
    0.92
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    78%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.293
    Self Review self_review
    0.140
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    12 items
    codspeed[bot] codspeed[bot] commented on Aug 05, 2026 23:24 UTC
    Bot

    <!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->

    Merging this PR will not alter performance

    ✅ 5 untouched benchmarks
    ⏩ 71 skipped benchmarks[^skipped]

    ---

    <sub>Comparing <code>perf/no-cycle-minimal</code> (a940fd2) with <code>main</code> (9d49d27)</sub>

    <a href="https://app.codspeed.io/oxc-project/oxc/branches/perf%2Fno-cycle-minimal?utm_source=github&utm_medium=comment-v2&utm_content=button">
    <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/pr-report/open-in-codspeed-dark.svg">
    <source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/pr-report/open-in-codspeed-light.svg">
    <img alt="Open in CodSpeed" src="https://codspeed.io/pr-report/open-in-codspeed-light.svg" width="169" height="32">
    </picture>
    </a>

    [^skipped]: 71 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

    Copilot Copilot commented on code on Aug 06, 2026 00:26 UTC
    Code Review
    crates/oxc_linter/src/service/runtime.rs:1
    @@ -269,10 +274,28 @@ impl Runtime {
                     .hasher(BuildHasherDefault::default())
                     .resize_mode(papaya::ResizeMode::Blocking)
                     .build(),
    +            path_ids: Mutex::new((FxHashMap::default(), 1)),
                 disable_directives_map: Arc::new(Mutex::new(FxHashMap::default())),
             }
         }
     
    +    /// Id for `path`, shared by every [`ModuleRecord`] resolving to it. See
    +    /// [`ModuleRecord::path_id`].
    +    ///
    +    /// # Panics
    +    ///
    +    /// * If the mutex is poisoned (which only happens if a thread panicked while holding it).
    +    fn intern_path(&self, path: &Path) -> u32 {
    +        let (ids, next) = &mut *self.path_ids.lock().unwrap();
    +        if let Some(id) = ids.get(path) {
    +            return *id;
    +        }
    +        let id = *next;
    +        *next += 1;
    +        ids.insert(path.to_path_buf(), id);
    +        id

    intern_path increments the next id with *next += 1, which will wrap on u32 overflow in release builds and could silently cause path_id collisions. Even if this is extremely unlikely in practice, it’s cheap to make the behavior explicit (panic) and prevents theoretical misbehavior.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Aug 06, 2026 00:26 UTC
    Reviewer

    Pull request overview

    This PR optimizes cross-module import lint rules by shifting expensive per-edge/path operations into ModuleRecord construction and using interned u32 path identities for fast equality checks during module graph traversal.

    Changes:

  • Add path_id (interned per resolved path) and is_node_module (precomputed node_modules membership) to ModuleRecord.

  • Intern resolved paths in Runtime (when a resolver is present) so cross-module comparisons become u32 compares and traversal sets avoid PathBuf cloning/hashing.

  • Update import/no-cycle, import/no-self-import, and the module graph visitor to use path_id/is_node_module.
  • Reviewed changes

    Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

    <details>
    <summary>Show a summary per file</summary>

    | File | Description |
    | ---- | ----------- |
    | crates/oxc_linter/src/service/runtime.rs | Adds path-id interning storage and assigns interned path_id during module record creation when the resolver is enabled. |
    | crates/oxc_linter/src/rules/import/no_self_import.rs | Switches self-import detection from PathBuf equality to path_id equality. |
    | crates/oxc_linter/src/rules/import/no_cycle.rs | Replaces path/component-based comparisons with path_id and uses cached is_node_module to avoid repeated path parsing. |
    | crates/oxc_linter/src/module_record.rs | Introduces path_id and is_node_module fields and computes is_node_module once during record creation. |
    | crates/oxc_linter/src/module_graph_visitor.rs | Changes the traversal “visited” set key from PathBuf clones to path_id to reduce allocations and hashing work. |
    </details>

    connorshea connorshea commented on code on Aug 06, 2026 01:16 UTC
    Code Review
    crates/oxc_linter/src/module_record.rs:1
    @@ -13,6 +17,22 @@ use oxc_span::Span;
     use oxc_str::CompactStr;
     pub use oxc_syntax::module_record::RequestedModule;
     
    +/// Ids for records built outside a lint run, counting down from `u32::MAX` so they never collide
    +/// with the ids `Runtime` interns (which count up from 1). Such records are not part of a linked
    +/// graph, so they only need to be distinct from each other.
    +static NEXT_UNSHARED_PATH_ID: AtomicU32 = AtomicU32::new(u32::MAX);

    Note that this part only exists because linking is part of the public interface. The oxlint crate is not public API, so we don't need to care about this and I'll strip out this nonsense.

    camc314 camc314 commented on Aug 06, 2026 13:22 UTC
    Contributor

    @codex review

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Aug 06, 2026 13:28 UTC
    Code Review
    crates/oxc_linter/src/service/runtime.rs:1
    @@ -269,10 +275,28 @@ impl Runtime {
                     .hasher(BuildHasherDefault::default())
                     .resize_mode(papaya::ResizeMode::Blocking)
                     .build(),
    +            path_ids: Mutex::new((FxHashMap::default(), 1)),
                 disable_directives_map: Arc::new(Mutex::new(FxHashMap::default())),
             }
         }
     
    +    /// Id for `path`, shared by every [`ModuleRecord`] resolving to it. See
    +    /// [`ModuleRecord::path_id`]. Counts from 1, leaving 0 to mean "never interned".
    +    ///
    +    /// # Panics
    +    ///
    +    /// * If the mutex is poisoned (which only happens if a thread panicked while holding it).
    +    fn intern_path(&self, path: &Arc<OsStr>) -> u32 {
    +        let (ids, next) = &mut *self.path_ids.lock().unwrap();
    +        if let Some(id) = ids.get(&**path) {
    +            return *id;
    +        }
    +        let id = *next;
    +        *next += 1;
    +        ids.insert(Arc::clone(path), id);

    <sub><sub>!P2 Badge</sub></sub> Preserve Path equality when interning IDs

    When LintService receives lexically different spellings that Path considers equal, such as /repo/src/./a.js and /repo/src/a.js, this lookup hashes the raw OsStr bytes and assigns different IDs. The replaced PathBuf comparisons normalize . and repeated separators through component-based equality, so an import resolving back to the same file under a normalized spelling can now evade no-cycle/no-self-import diagnostics and be traversed as a distinct module. Normalize the path before interning or use a key with Path equality semantics.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Aug 06, 2026 13:28 UTC
    Reviewer

    💡 Codex Review

    Here are some automated review suggestions for this pull request.

    Reviewed commit: 1437f06c97

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review".
  • If Codex has suggestions, it will comment; otherwise it will react with 👍.

    Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

    </details>

    connorshea connorshea commented on code on Aug 08, 2026 00:37 UTC
    Code Review
    crates/oxc_linter/src/service/runtime.rs:1
    @@ -269,10 +275,28 @@ impl Runtime {
                     .hasher(BuildHasherDefault::default())
                     .resize_mode(papaya::ResizeMode::Blocking)
                     .build(),
    +            path_ids: Mutex::new((FxHashMap::default(), 1)),
                 disable_directives_map: Arc::new(Mutex::new(FxHashMap::default())),
             }
         }
     
    +    /// Id for `path`, shared by every [`ModuleRecord`] resolving to it. See
    +    /// [`ModuleRecord::path_id`]. Counts from 1, leaving 0 to mean "never interned".
    +    ///
    +    /// # Panics
    +    ///
    +    /// * If the mutex is poisoned (which only happens if a thread panicked while holding it).
    +    fn intern_path(&self, path: &Arc<OsStr>) -> u32 {
    +        let (ids, next) = &mut *self.path_ids.lock().unwrap();
    +        if let Some(id) = ids.get(&**path) {
    +            return *id;
    +        }
    +        let id = *next;
    +        *next += 1;
    +        ids.insert(Arc::clone(path), id);

    I'm fairly certain this comment is mostly wrong, we normalize the path elsewhere before we pass it to this rule in (almost) all cases. oxc_resolver returns paths built from normalize_with which handles a/./b.js-style paths, and lint.rs also normalizes paths coming from the CLI: https://github.com/oxc-project/oxc/blob/9e93ba6908243fc6fa2d388c8781c9ef15405fcf/apps/oxlint/src/lint.rs#L124-L126

    The only case where this could happen is in the LSP (we don't fully normalize paths that come from it), and /repo/src/./a.js would require sending a path without normalization to the Oxlint language server, which none of the major LSP implementations seem to do. That can be fixed in the oxlint language server code if we care about it.

    I pushed up an extra test to cover the a/./b.js problem though, so we can't break it in the future.

    connorshea connorshea commented on Aug 15, 2026 17:07 UTC
    Author

    @camc314 were there any further concerns here?

    camc314 camc314 commented on Aug 15, 2026 17:09 UTC
    Contributor

    Ah yeah, i'm not convinced the added overhead of this change is worth the perf difference:

    If you have import/no-cycle enabled and a lot of cycles to find: -30 to -44%

    If you have import/no-cycle enabled and few or no cycles: no change (-0.2 to -1.0%, within noise)

    Most users who have the rule enabled will have no cycles in their code (or a few cycles with disable comments), so the extra code+ maintenance overhead doesn't oughtweigh the perf increase in the common case.

    connorshea connorshea commented on Aug 15, 2026 17:27 UTC
    Author

    Most users who have the rule enabled will have no cycles in their code (or a few cycles with disable comments), so the extra code+ maintenance overhead doesn't oughtweigh the perf increase in the common case.

    In our monorepo with separate teams owning separate parts of the app, new rules with lots of violations are enabled as warnings globally, and then specific teams opt into them as errors with the goal of eventually having them fully resolved so we can mark them as global errors.

    With no-cycle specifically in my current job, we had it enabled for a long time when we were using ESLint to discourage new cycles from being added, but kept it as warn to avoid CI failures and because we didn't want to put in the work to fix existing cycles all at once. We eventually turned it off because it was too slow in the ESLint implementation. Fixing cycles is complex enough that that seems more likely with this rule than others, but that's less of a problem nowadays with Claude and Codex being able to fix these for you.

    Having said that, I don't know that this is a particularly common practice and I definitely agree that in 80+% of cases, this improvement will do nothing for users. If you're not convinced of the value of this relative to the complexity of this PR, I'm fine to close this.

    Reviewers
    Assignees
    connorshea connorshea
    Labels
    risk: low confidence: 78.6% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 65.7% (HIGH) · Higher = larger blast radius
    65.7%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 78.6% · Lower = rushed or shallow review
    78.6%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 14% · Safe to merge
    14%