Skip to content

perf: speed up JS hook filter evaluation - #10408

Closed
IWANABETHATGUY wants to merge 4 commits into
mainfrom
perf/js-hook-filter-eval
Closed

IWANABETHATGUY wants to merge 4 commits into
mainfrom
perf/js-hook-filter-eval

Conversation

@IWANABETHATGUY

@IWANABETHATGUY IWANABETHATGUY commented Jul 23, 2026 •

Copy link
Copy Markdown
Member

What this solves

The plugin hook filter interpreter (filter_exprs_interpreter in rolldown_utils) runs on the Rust side once per (module, hook, plugin-with-filter) — it's the cheap gate that decides whether to cross into a JS hook. This speeds up that gate.

I started from the question "should the tree-walk interpreter become a stack VM?" — but a local criterion benchmark showed the cost is in the leaf tests, not the interpretation dispatch (the trees are tiny and short-circuit already). A VM would optimize the ~1% that is dispatch, and a naïve postfix VM would even regress by losing short-circuiting. So this PR targets the actual cost instead.

Reorder And/Or operands cheapest-first (optimize_filter_expr)

Compile-time (once, in parse) stable sort of And/Or children by a static cost rank (ModuleType < Query < Id < Code-string < Code-regex). Short-circuit evaluation then skips an expensive Code regex — which scans the entire module source — whenever a cheaper operand already decides the result.

  • Pathological and(code, id): 461 ns → 292 ns (−36%) (8 ids/iter), landing on the ideal and(id, code) reference.
  • Semantics-preserving: the boolean operators are pure over side-effect-free predicates (the only state, parsed_url_cache, is order-independent), and it only ever moves cheaper operands earlier — so it can only make short-circuiting skip an expensive leaf more often, never less.

Why a VM was the wrong lever

  • Dispatch is ~1% of the cost; the trees are tiny and stay hot in L1. A single Code regex over module source is 100–1000× a node dispatch.
  • Short-circuiting is load-bearing: And stops on first false, Or on first true — that's what lets a cheap Id test skip an expensive Code regex. A naïve postfix stack VM evaluates every leaf and loses that (net slower); preserving it needs jump opcodes for no dispatch win that matters.

Follow-up (not in this PR)

There's a second win — hoisting the per-call Path::join(cwd, glob) + normalize allocation in get_matcher_string for relative-glob id filters (measured ~1246 ns → ~546 ns). An earlier revision cached the cwd-resolved matcher on the leaf, but that changed Id/ImporterId matching semantics for relative globs (it baked in the first cwd). It's reverted here and will be stacked on top as a separate PR that caches the compiled glob rather than the cwd-resolved string.

Tests

  • optimize_reorders_operands_cheapest_first — verifies the reorder.
  • optimize_preserves_semantics — asserts reordered vs. original agree across all input combinations.

No public signatures changed (parse, filter_exprs_interpreter, FilterExprKind), so rolldown_binding is untouched. Net diff is a single file, crates/rolldown_utils/src/filter_expression.rs.

@netlify

netlify Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for rolldown-rs ready!

Name Link
🔨 Latest commit c8a1ef0
🔍 Latest deploy log https://app.netlify.com/projects/rolldown-rs/deploys/6a64aa6c64a9010008afd3b1
😎 Deploy Preview https://deploy-preview-10408--rolldown-rs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@IWANABETHATGUY
IWANABETHATGUY marked this pull request as draft July 23, 2026 08:54
@IWANABETHATGUY
IWANABETHATGUY marked this pull request as ready for review July 23, 2026 09:15
@IWANABETHATGUY
IWANABETHATGUY marked this pull request as draft July 23, 2026 09:16
@codspeed

codspeed Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 7 untouched benchmarks
⏩ 10 skipped benchmarks1


Comparing perf/js-hook-filter-eval (b449b9b) with main (959002b)

Open in CodSpeed

Footnotes

  1. 10 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. ↩

@IWANABETHATGUY
IWANABETHATGUY changed the base branch from main to fix/resolveid-id-filter-regex-only July 23, 2026 10:41
IWANABETHATGUY added a commit that referenced this pull request Jul 23, 2026
> **Bottom of the stack.** Base is `main`. The filter perf PRs (#10408
reorder, #10410 glob-cache) stack on top of this.

## What this solves

In `resolveId`, the `id` given to the filter is the **raw import
specifier** (`./foo`, `lodash`, `virtual:x`), not a resolved path. But a
`string` `id` filter is compiled to a **glob** — which is
path/cwd-oriented (`get_matcher_string` even anchors relative globs onto
cwd). Matching a specifier against a cwd-anchored glob is meaningless
and silently never matches the way a user expects. Per the docs,
resolveId `id` filters must be a `RegExp` (`hook-filters.md:80`).

The **object form** already enforces this at the type level —
`HookFilterExtension<'resolveId'>` types `id` as
`GeneralHookFilter<RegExp>` (`index.ts:774`). But the **composable
form** (`filter: [include(id('glob'))]`, typed
`TopLevelFilterExpression[]`) is not hook-restricted:
`@rolldown/pluginutils`'s `id()` accepts `string | RegExp`, and
`bindingifyResolveIdFilter` passed it straight through to the Rust glob
matcher.

## The fix

Add `assertNoStringId` in `bindingifyResolveIdFilter`, mirroring the
existing `assertNoImporterId` guard. It walks the filter expressions and
throws a clear error if any `id` node uses a string, covering **both**
forms (the composable form, and the object form defensively in case the
type is bypassed):

```
A string `id` filter is not supported for the `resolveId` hook, because its
`id` is the import specifier rather than a resolved path. Use a RegExp instead.
```

`importerId` is intentionally **not** rejected — for resolveId it
matches the *importer's* resolved id, which is a real path, so a glob is
appropriate there.

## Tests

- `tests/fixtures/plugin/resolve-id/filter-string-id-error/` — a
resolveId hook with `filter: [include(id('**/main.js'))]`, asserting the
build throws an error mentioning `id`, `resolveId`, and `RegExp`.
Mirrors the existing `filter-importer-id-error` fixture.

Typecheck passes. (The fixture runs in CI; it wasn't run locally because
no napi binding is built in this worktree.)

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Base automatically changed from fix/resolveid-id-filter-regex-only to main July 23, 2026 11:58
@IWANABETHATGUY
IWANABETHATGUY force-pushed the perf/js-hook-filter-eval branch 2 times, most recently from d9e9ea5 to 488f4b4 Compare July 23, 2026 12:12
@IWANABETHATGUY
IWANABETHATGUY marked this pull request as ready for review July 23, 2026 12:51

@hyfdev hyfdev left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The operand reordering can evaluate a filter leaf whose hook input is unavailable even when the authored expression would have short-circuited before it. That turns a type-accepted renderChunk filter from a normal non-match into a panic.

— Review by @hyfdev, assisted by GPT-5

@graphite-app

graphite-app Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

How to use the Graphite Merge Queue

Add the label graphite: merge-when-ready to this PR to add it to the merge queue.

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

IWANABETHATGUY added a commit that referenced this pull request Jul 25, 2026
Operand reordering changes which leaves short-circuit evaluation reaches,
so a leaf reading an input the hook doesn't supply could be hoisted ahead
of one that used to decide the result first. `renderChunk` evaluates with
`id: None` and its binding accepts an arbitrary `TopLevelFilterExpression[]`
(only `importerId` is rejected), so `include(and(code(...), id(...)))` went
from a normal non-match to a panic.

Make `Code`/`Id`/`Query` report "no match" when their input is unavailable,
matching what `ImporterId` already did. The expression is then a pure boolean
function of its leaves, so its value no longer depends on evaluation order —
which is what makes the reordering safe.

Also drop `Query` back to the same rank as `Id`: the parsed-URL map is cached
on the shared `InterpreterCtx`, so an earlier top-level rule can leave it warm
and `Query` cheaper than an `Id` regex. Equal ranks keep their authored order
while both stay ahead of `Code`.

Both issues reported by @hyfdev in review of #10408.

Claude-Session: https://claude.ai/code/session_01R256otFrmyhUonwsdhWFfN
Reorder `And`/`Or` filter operands cheapest-first at compile time
(`optimize_filter_expr`, called once from `parse`) so short-circuit evaluation
skips an expensive `Code` regex -- which scans the entire module source --
whenever a cheaper operand already decides the result. Operand cost rank:
`ModuleType` < `Query` < `Id` < `Code`-string < `Code`-regex.

Semantics-preserving: the boolean operators are pure over side-effect-free
predicates (the only state, `parsed_url_cache`, is order-independent), and it
only ever moves cheaper operands earlier -- so it can only make short-circuiting
skip an expensive leaf more often, never less.

Pathological `and(code, id)`: ~461ns -> ~292ns per 8 ids (measured locally).

Claude-Session: https://claude.ai/code/session_01XhkX6gZcHU9Lto7ddA5izm
Two cost-model regressions in the cheapest-first `And`/`Or` reordering:

- `Query` was ranked below `Id`, so `and(id(/target/), query('raw', true))` moved
  the query ahead of the id. The first query eval parses/decodes the id's URL into a
  param map, so non-target modules with query-bearing ids did that parse instead of
  short-circuiting at the cheap id. Rank `Query` above the cheap id/moduleType checks.

- A compound (`And`/`Or`) was ranked by its cheapest leaf (`min`), so a nested
  `or(moduleType('css'), code(/needle/))` took rank 0 from `moduleType` and jumped
  ahead of a cheap `id`; a non-matching JS module then ran the full-source `Code`
  scan before the id could reject it. Rank a compound by its costliest reachable
  leaf (`max`) instead.

Adds regression tests for both shapes.

Claude-Session: https://claude.ai/code/session_01XhkX6gZcHU9Lto7ddA5izm
Ranking `Code`-string below `Code`-regex reordered e.g.
`or(code(/^import/), code('rare-marker'))` to run the string check first — a
full-source `memmem` for an absent low-hit string before the anchored regex that
would have matched immediately, an O(source) regression on large modules.

Neither `Code` variant is reliably cheaper (an anchored regex fails fast; an
absent string scans everything), so give both one tier and let the stable sort
keep their authored order. `Code` still outranks the cheap `Id`/`Query`/
`ModuleType` checks, so those still short-circuit before any full-source scan.

Claude-Session: https://claude.ai/code/session_01XhkX6gZcHU9Lto7ddA5izm
Operand reordering changes which leaves short-circuit evaluation reaches,
so a leaf reading an input the hook doesn't supply could be hoisted ahead
of one that used to decide the result first. `renderChunk` evaluates with
`id: None` and its binding accepts an arbitrary `TopLevelFilterExpression[]`
(only `importerId` is rejected), so `include(and(code(...), id(...)))` went
from a normal non-match to a panic.

Make `Code`/`Id`/`Query` report "no match" when their input is unavailable,
matching what `ImporterId` already did. The expression is then a pure boolean
function of its leaves, so its value no longer depends on evaluation order —
which is what makes the reordering safe.

Also drop `Query` back to the same rank as `Id`: the parsed-URL map is cached
on the shared `InterpreterCtx`, so an earlier top-level rule can leave it warm
and `Query` cheaper than an `Id` regex. Equal ranks keep their authored order
while both stay ahead of `Code`.

Both issues reported by @hyfdev in review of #10408.

Claude-Session: https://claude.ai/code/session_01R256otFrmyhUonwsdhWFfN
@IWANABETHATGUY
IWANABETHATGUY force-pushed the perf/js-hook-filter-eval branch from b449b9b to c8a1ef0 Compare July 25, 2026 12:22

@hyfdev hyfdev left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The leaves are now total over the inputs each hook supplies, so the expression is a pure boolean function of its leaves and reordering And/Or operands cannot change its value. Restoring the three old expect calls makes both new missing_* tests fail, and every behavior change I could find is confined to configurations that panicked before — nothing that worked behaves differently. Ranking Query alongside Id/ImporterId also keeps the authored order when the URL cache may already be warm.

Three non-blocking notes inline: no test pins the reorder to parse, the order-independence claim in the optimize_filter_expr doc comment does not hold for a Query under a CleanUrl, and query(k, false) and not(query(k, true)) disagree on renderChunk. The description is also stale — it still lists the cost rank as ModuleType < Query < Id < Code-string < Code-regex, and it does not mention the leaf-totality change, which is the most user-visible part of the PR.

The red checks on this head were cancelled before executing a single step, so they need a rerun rather than investigation.

— Review by @hyfdev, assisted by Claude Opus 5 (1M context)

Some(Token::Exclude) => Ok(FilterExprKind::Exclude(rec(&mut tokens)?)),
Some(Token::Include) => {
let mut expr = rec(&mut tokens)?;
optimize_filter_expr(&mut expr);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deleting both optimize_filter_expr calls here leaves all ten filter_expression tests green, so nothing pins the reorder to the only path that reaches production — pre_compile_filter_expr → parse. The six optimize_* tests call optimize_filter_expr directly, and the parse-based tests assert booleans that the reorder is designed not to change.

Asserting on parse's output shape would close that: for example, that include(and(code(/x/), id(/y/))) parses to an And whose first operand is the Id.

missing_id_is_a_non_match_not_a_panic has the same blind spot in the other direction. Without the reorder, Code(/__never__/) returns false and the Id leaf is never reached, so it passes on the merge base too — its missing_code_ sibling is the one that fails there. Asserting include(id(/target/)) with id: None directly would pin leaf totality on its own.

Comment on lines +71 to +73
/// side-effect-free predicates. The only interpreter state, the lazily-populated
/// [`InterpreterCtx::parsed_url_cache`], is keyed by the (fixed) id's query and so
/// is order-independent. Reordering only ever moves *cheaper* operands earlier, so

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The id is not fixed across an evaluation: the CleanUrl arm re-enters with clean_url(id) while passing the same ctx, so a Query leaf underneath it caches an empty param map that every later Query then reads. That makes parsed_url_cache order-dependent, and reordering decides which Query populates it.

and(and(query('raw', true), code(/x/)), cleanUrl(query('raw', true))) on /t.js?raw is true in authored order and false after cost_rank sorts the rank-1 cleanUrl operand ahead of the rank-2 inner and.

Nothing reachable through the public API builds that shape — bindingify-hook-filter.ts emits CleanUrl only directly around an Id/ImporterId leaf, and those are its only two producers — so this does not block this approval. Stating that as the actual precondition, rather than claiming the cache is order-independent, would keep the invariant honest for whoever generalizes cleanUrl later; clearing the cache when entering CleanUrl would make the claim true as written.

),
FilterExpr::Query(key, value) => {
// When id is None (e.g. the `renderChunk` hook) there is no query to test
let Some(id) = id else { return false };

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

query('raw', false) and not(query('raw', true)) both mean "the id does not carry ?raw", and on renderChunk they now disagree: this early return makes the first false, so the hook never fires, while the second is true and it fires for every chunk. With an id present the two spellings always agree.

Both panicked before, so nothing regresses. Returning *v == false for the boolean form is one way to make them agree; a comment saying the "missing input is a non-match" rule deliberately wins over the boolean's natural reading would settle it just as well.

One compatibility datapoint for whichever way you settle it: exprInterpreter in @rolldown/pluginutils 1.0.1 still throws for a missing id or code, so the two interpreters of the same filter language now disagree where they previously both errored. moduleType already diverged that way, so this follows the existing Rust convention rather than breaking a new one.

@IWANABETHATGUY

Copy link
Copy Markdown
Member Author

Closing this one.

@hyfdev's review was right that the operand reordering can evaluate a leaf whose hook input is unavailable, and rather than patch around that I'm dropping the reordering optimisation for now.

The two pieces worth keeping have been split out onto main:

Thanks for the careful review — both the reordering hazard and the Query-vs-Id cost point were correct.

@TheAlexLichter
TheAlexLichter deleted the perf/js-hook-filter-eval branch July 25, 2026 14:46
IWANABETHATGUY added a commit that referenced this pull request Jul 25, 2026
> **Stacked on top of #10408** (base branch `perf/js-hook-filter-eval`).
Review/merge that one first; the diff here is just the glob-matcher
cache.

## What this solves

For a `string` (glob) `id`/`importerId` filter, `get_matcher_string`
allocates on **every module tested** when the glob is *relative*: it
does `Path::join(cwd, glob)` + normalize to anchor the glob to cwd.
`IdMatcher` now memoizes the resolved matcher so that resolution happens
**once** instead of once per module.

- Relative-glob `id` filter: **~1246 ns → ~562 ns** per 8 ids (measured
locally; no bench committed).
- `**`-prefixed / absolute globs and regex ids: unchanged (they never
allocated per call).

## The cwd-correctness design (the fix for the earlier revert)

The first attempt cached the cwd-resolved matcher on a plain `OnceLock`
keyed on the **first cwd seen**, which baked in a "cwd constant per
compiled filter" assumption and changed relative-glob matching if that
filter was ever evaluated under a different cwd. That was reverted.

This version caches by **classifying the glob**, so nothing
cwd-dependent is ever assumed:

```rust
enum ResolvedGlob {
  CwdIndependent(Box<str>),                       // `**` / absolute: valid for any cwd
  ScopedToCwd { cwd: Box<str>, matcher: Box<str> }, // relative: valid only for this cwd
}
```

- **`**` / absolute globs** resolve independently of cwd → cached once,
reused for any cwd.
- **Relative globs** are cached together with the cwd they were resolved
for. If a later call presents a different cwd, we **re-resolve from
scratch** (never returning a stale, wrong-cwd matcher).

So matching is **behaviorally identical to resolving on every call** —
the cache only removes the repeated allocation in the common case where
cwd is constant for a build. It's a lock-free `OnceLock`, so it's safe
under the concurrent (rayon) filter path, and the common `**`/absolute
case is routed around the cwd comparison entirely (zero regression).

## Note on `fast_glob`

`fast_glob` (1.0.1) exposes only `glob_match(pattern, path)` — there's
no compiled-matcher type to cache, so the only hoistable per-call cost
is the string resolution above. (If we later switch to a crate with a
compiled `GlobMatcher`, the glob *parsing* per call could also be
hoisted — that's a separate change.)

## Tests

- `id_matcher_relative_glob_is_cwd_correct` — evaluates one `IdMatcher`
under two different cwds and asserts each resolves correctly. This
**fails** against the earlier baking cache and passes here.
- Existing `test_filter_expr_interpreter` / `parse_test` continue to
exercise the `Id`/`ImporterId` path through `IdMatcher`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants