Skip to content

fix(plugin): measure plugin hooks in JavaScript, report them from Rust - #10508

Merged
IWANABETHATGUY merged 3 commits into
mainfrom
feat/plugin-timings-js-measurement
Jul 31, 2026
Merged

IWANABETHATGUY merged 3 commits into
mainfrom
feat/plugin-timings-js-measurement

Conversation

@IWANABETHATGUY

@IWANABETHATGUY IWANABETHATGUY commented Jul 29, 2026 •

Copy link
Copy Markdown
Member

Third of four, on #10521. #10509 sits on top and adds the remaining option-level callbacks.

Two prefactors were split out below to keep this one to its actual subject: #10520 gives the
build's clocks their own type, and #10521 moves the report to close (fixing a bug where
closeBundle's cost was measured and discarded) and makes it account for multi-output
builds. Both stand on their own; this PR is then only where the number comes from.

Problem

[PLUGIN_TIMINGS] is timed from Rust, which can only bracket dispatch and completion. For a hook the core dispatches concurrently — resolveId, load, transform, moduleParsed, renderChunk — those two points are separated mostly by the queue the call waited in on JavaScript's single thread, and the queue is deepest behind whichever callback is doing the most work.

The failure is a sign inversion, not noise:

  • a hook that blocks the thread creates the backlog that dilutes its own credit;
  • a cheap hook called thousands of times sits in that backlog collecting credit for work it is not doing.

At hand-checkable scale: one callback holds the thread for 100ms while a hundred trivial ones queue behind it and drain in 1ms total. Truth — the expensive one is 99% of the work. Measured — every queued call's stopwatch ran for the whole 100ms it waited, so the trivial hook looks a hundred times more expensive.

On a real build, gated A/B so the cost reads straight off the wall clock, a hook worth ~15s ranked below one worth ~0s.

Why no arithmetic fixes it

The callback's execution start lives in the JS event loop and is never sampled. Two schemes were built and both failed in the same direction: rescaling every row by a common factor cannot reorder them, and dividing by the in-flight count charges the running callback a 1/n sliver of what it is actually consuming (Node is run-to-completion — one callback runs at 100% while the others run at 0%).

Approach

The missing quantity is known inside the JS wrapper, so the clock moves there. A wrapper around each handler records entry-to-exit, which excludes the dispatch queue by construction.

Collection is split by necessity — only Rust can see the link stage, only JavaScript can see when a callback began running — so the two halves meet at the sink rather than one side accumulating the other's numbers.

Rust pulls; JavaScript does not push. pluginTimings is a JS callback on the options, modelled on the existing deferSyncScanData, invoked while the build closes:

// crates/rolldown_binding/src/binding_bundler.rs
let res = cleanup_fut.await;                          // runs closeBundle
handle_result(res)?;
handle_result(report_plugin_timings(&handles).await)?; // asks JavaScript

Pulling is what lets the measurement include closeBundle, which runs inside close() and would already be over by the time a push could reach anyone.

Reporting therefore stays where the rest of the diagnostics live. EventKind::PluginTimings is constructed again rather than merely generating an option name, so checks.pluginTimings is honoured by filter_out_disabled_diagnostics like every other check, and the message renders through Diagnostic::render_batch like every other warning.

The trust rule

Spans may be summed only if they never overlap. A synchronous callback cannot — it holds the thread until it returns. An async one can suspend at an await and let another call of the same hook begin, and then both spans cover the same wall clock. Overlap also changes what the span measures: a hook awaiting this.resolve is measuring the bundler. So overlap is counted per hook rather than assumed:

  • never overlapped — the sum is execution time, and the row gets a number;
  • overlapped — the row is named as needing node --cpu-prof, with no number.

That narrows "cannot measure" from a property of the call site to a property of the callback, which is where it lives. A concurrently dispatched hook whose body never overlaps is now measured exactly — the case a call-site rule has to reject.

Also here, because it cannot be anywhere else

output.codeSplitting.groups[].name is timed today on main, from Rust. This PR deletes
that Rust-side timing, so the JS wrapping for it has to land in the same commit — wrapping
it earlier would double count against the Rust clock, and wrapping it later would leave a
window on main with no coverage of a callback that runs once per module. Its groups[].test
sibling is not timed on main, so that one waits for #10509.

Unchanged

The gate: build over 3s, non-link time over 100× link time, summed across every output. It
lives on BuildTimings as of #10520 and gained the multi-output summing in #10521; this PR
does not touch it.

Verification

Gated A/B against a plugin burning a known amount of CPU — same build with and without the burn, so the cost reads off the wall clock:

gated off   : wall   27ms, warned=false
gated on    : wall 5608ms, reported 5600ms
wall delta  : 5581ms   <- ground truth
error       :   19ms   (0.3%)

Plus: unit tests for the collector (overlap, busy time, settle-on-throw/reject, the payload shape), Rust tests for the gate and the rendered message, and end-to-end runs asserting a blocking sync transform ranks first while an overlapping async moduleParsed lands in the un-measurable list.

Rows are keyed on identity, not name

Two configured instances of one plugin share a name — normalizePlugins allows it — but
are different culprits, and merging them would also let one instance's overlap mark the
other's clean measurement unrankable. TimingOwner carries key (the user's plugin object,
stable across a build's outputs) separately from the displayed name.

For reviewers

  • report_plugin_timings in binding_bundler.rs — the ordering against cleanup_fut is load-bearing; the close-time emission and clock summing themselves arrive in fix(plugin): report plugin timings after closeBundle has run #10521.
  • The overlap rule in plugin-timings.ts: overlapMs accumulates (inFlight - 1) × dt at each transition, which is exactly the double-counted amount, and a row stays reportable while that is under 1% of its span. A boolean on peak in-flight was too brittle — one incidental overlap among thousands of calls discarded a good measurement and made the report depend on scheduling.
  • busyMs (union of spans) is maintained as the recorder's in-flight count crosses zero.
  • Native builtin: plugins have no JS callback and so are not covered. They never got a row before either, being filtered by name, but their cost is honestly measurable from Rust — no shared single thread to queue on — and that is the natural next step.

@IWANABETHATGUY IWANABETHATGUY changed the title feat/plugin timings js measurement fix(plugin): measure plugin hooks in JavaScript, report them from Rust Jul 29, 2026
@netlify

netlify Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for rolldown-rs ready!

Name Link
🔨 Latest commit dd0222d
🔍 Latest deploy log https://app.netlify.com/projects/rolldown-rs/deploys/6a6c1c735d146e00085026af
😎 Deploy Preview https://deploy-preview-10508--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.

@codspeed

codspeed Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 7 untouched benchmarks
⏩ 10 skipped benchmarks1


Comparing feat/plugin-timings-js-measurement (dd0222d) with main (ed4e7cc)

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 force-pushed the feat/plugin-timings-js-measurement branch from 69a332e to 2e962c7 Compare July 29, 2026 08:53
@IWANABETHATGUY
IWANABETHATGUY marked this pull request as draft July 29, 2026 08:54
@IWANABETHATGUY
IWANABETHATGUY changed the base branch from main to feat/plugin-timings-report-at-close July 29, 2026 08:55
@IWANABETHATGUY
IWANABETHATGUY marked this pull request as ready for review July 29, 2026 09:03
@shulaoda

Copy link
Copy Markdown
Member

@cidex review

@IWANABETHATGUY
IWANABETHATGUY force-pushed the feat/plugin-timings-js-measurement branch from 2e962c7 to 9cc5341 Compare July 30, 2026 03:54
@shulaoda
shulaoda force-pushed the feat/plugin-timings-js-measurement branch from 4a319fc to c7c6f24 Compare July 30, 2026 11:05
@IWANABETHATGUY
IWANABETHATGUY force-pushed the feat/plugin-timings-js-measurement branch from c7c6f24 to 57dc7ed Compare July 31, 2026 03:07
Base automatically changed from feat/plugin-timings-report-at-close to main July 31, 2026 03:25
@IWANABETHATGUY
IWANABETHATGUY force-pushed the feat/plugin-timings-js-measurement branch from 57dc7ed to ac42bf6 Compare July 31, 2026 03:25
IWANABETHATGUY and others added 3 commits July 31, 2026 11:51
`[PLUGIN_TIMINGS]` was timed from Rust, which can only bracket *dispatch* and
*completion*. For a hook the core dispatches concurrently -- `resolveId`,
`load`, `transform`, `moduleParsed`, `renderChunk` -- those two points are
separated mostly by the queue the call waited in on JavaScript's single thread,
and the queue is deepest behind whichever callback is doing the most work. A
hook that blocks the thread creates the backlog that dilutes its own credit,
while a cheap hook called thousands of times sits in that backlog collecting
credit for work it is not doing. On a real build, gated A/B so the cost reads
straight off the wall clock, a hook worth ~15s ranked below one worth ~0s.

No arithmetic over dispatch/completion pairs undoes that, because the
callback's execution start lives in the JS event loop and is never sampled.
Rescaling every row by a common factor cannot reorder them, and dividing by the
in-flight count charges the running callback a 1/n sliver of what it is actually
consuming. Both were tried.

But the missing quantity is known inside the JS wrapper, so the clock moves
there: a wrapper around each handler records entry-to-exit, which excludes the
dispatch queue by construction.

Collection is split by necessity -- only Rust can see the link stage, only
JavaScript can see when a callback began running -- so the two halves meet at
the sink rather than one side accumulating the other's numbers. Rust *pulls*:
`pluginTimings` is a JS callback on the options, modelled on
`deferSyncScanData`, invoked while the build closes. Pulling rather than being
pushed to is what lets the measurement include `closeBundle`, which runs inside
`close()` and would already be over by the time a push could reach anyone.

Reporting therefore stays where the rest of the diagnostics live.
`EventKind::PluginTimings` is constructed again rather than merely generating an
option name, so `checks.pluginTimings` is honoured by
`filter_out_disabled_diagnostics` like every other check and the message renders
through `Diagnostic::render_batch` like every other warning. The measurement
crosses once, as data, so another consumer can render the same rows without
parsing prose.

Whether a total means anything is observed rather than asserted. Spans may be
summed only if they never overlap: a synchronous callback cannot, an `async` one
can suspend at an `await` and let another call of the same hook begin, and then
both spans cover the same wall clock. Overlap also changes what the span
measures -- a hook awaiting `this.resolve` is measuring the bundler. So overlap
is counted per hook:

- never overlapped: the sum is execution time, and the row gets a number;
- overlapped: the row is named as needing `node --cpu-prof`, with no number.

That narrows "cannot measure" from a property of the call site to a property of
the callback. A concurrently dispatched hook whose body never overlaps is
measured exactly -- the case a call-site rule has to reject.

The gate is unchanged -- build over 3s, non-link time over 100x link time -- and
now lives on `BuildTimings`, next to the clocks it reads.

Verified by gated A/B against a plugin burning a known amount of CPU: reported
5600ms against a 5581ms wall-clock delta.

Not covered: native plugins have no JS callback and never appear, though they
never got a row before either, being filtered as `builtin:`; parallel plugins
run on worker threads; and the report is produced as the build closes, so watch
and dev rebuilds do not emit it -- as they did not before, having never reached
the emission point.

Claude-Session: https://claude.ai/code/session_014uFXkw62sNL4zjBeyRsW9K
`BindingPluginTiming`, `BindingPluginTimingsMeasurement` and the
`pluginTimings` option reached the native `binding.d.cts` but not the
WASI one, which only the browser build regenerates. `Node Validation`
builds both and diffs the tree, so it caught it.

Generated by `just build-browser`; not hand-written.

Claude-Session: https://claude.ai/code/session_01S3RQeYwhJmEu4eLYkanvm1
@IWANABETHATGUY
IWANABETHATGUY force-pushed the feat/plugin-timings-js-measurement branch from ac42bf6 to dd0222d Compare July 31, 2026 03:54
@IWANABETHATGUY
IWANABETHATGUY merged commit 03e75d3 into main Jul 31, 2026
55 of 57 checks passed
@IWANABETHATGUY
IWANABETHATGUY deleted the feat/plugin-timings-js-measurement branch July 31, 2026 04:05
IWANABETHATGUY added a commit that referenced this pull request Jul 31, 2026
Stacked on #10508, which moves the measurement into the JavaScript
callback. This adds the callbacks that are not plugin hooks.

## Problem

Plugin hooks are not the only JavaScript the bundler calls. Every
option-level callback crosses the same boundary, and any of them can
dominate a build while belonging to no plugin's rows — a heavy
`codeSplitting.name` in a real project was what prompted this.

Sixteen of them reach napi unwrapped, so none could appear in
`[PLUGIN_TIMINGS]` at all. (`groups[].name` is the seventeenth and lands
in #10508, because `main` already times it there and that PR removes the
Rust-side timing it relies on.)

## What is now measured

Audited from the Rust side — every field on `BindingInputOptions` /
`BindingOutputOptions` typed as a JS callback — rather than by reading
the TypeScript, so the list is complete rather than the ones I happened
to think of:

| | |
|---|---|
| **output** | `codeSplitting` `groups[].test`, `entryFileNames`,
`chunkFileNames`, `assetFileNames`, `sourcemapFileNames`,
`sanitizeFileName`, `banner`/`footer`/`intro`/`outro` and their `post`
variants, `globals`, `paths`, `sourcemapPathTransform`,
`sourcemapIgnoreList` |
| **input** | `external`, `treeshake.moduleSideEffects` |

`external` runs once per import specifier and
`treeshake.moduleSideEffects` once per module — the same fan-out as the
classifier, so both are just as capable of dominating a build.

They report under `output options` / `input options`, and rows carry a
`kind` discriminator supplied by the wrapping call site — not derived
from the owner's name, since a plugin may legally be called `output
options`.

## Two things worth review attention

**`assetFileNames` and `sanitizeFileName` have two call paths.** Besides
the binding, `PluginContextImpl` calls the user's option *directly* for
`this.emitFile`. Wrapping at each consumer would count one call in two
places, so those two are measured once in `createBundlerOptions` and
passed on already wrapped.

**Rows can now sum past 100%.** `this.emitFile` inside `buildStart`
invokes `assetFileNames`, so the nested time belongs to both rows. The
headline figure is the union of every span, so it cannot exceed the
build. Documented in the check's docs.

## Verification

Each callback made individually expensive enough to clear the one-second
row floor, so the wiring is checked by execution rather than by
inspection:

```
  - virtual-fs buildStart                        - output options intro
  - output options paths                         - output options chunkFileNames
  - output options sanitizeFileName              - output options entryFileNames
  - input options treeshake.moduleSideEffects    - output options outro
  - input options external                       - output options footer
  - output options codeSplitting groups[].name   - output options banner
  - output options codeSplitting groups[].test   - output options assetFileNames
  - output options globals                       - output options sourcemapFileNames
```

The motivating case in isolation: 61 calls, 3.1s, `output options
codeSplitting groups[].name` at 60% of a 5.1s build.

**Two exceptions, stated rather than implied:** `sourcemapPathTransform`
and `sourcemapIgnoreList` are wrapped but I could not get the core to
invoke them under `generate` with `sourcemap: true` — zero calls. They
are used in `process_code_and_sourcemap.rs`, so they are presumably
reached on another path; wrapped either way, but unverified by
execution.
@rolldown-guard rolldown-guard Bot mentioned this pull request Aug 3, 2026
shulaoda added a commit that referenced this pull request Aug 3, 2026
## [1.2.2] - 2026-08-03

### 🚀 Features

- code-splitting: support inlining of shared deps in dynamic entries (#10526) by @nicolo-ribaudo
- plugin: time the user callbacks configured on the options (#10509) by @IWANABETHATGUY

### 🐛 Bug Fixes

- dev: force `cleanDir` off in dev mode (#10579) by @shulaoda
- dev: keep `?rolldown-lazy` proxy ids out of user `resolveId` hooks (#10580) by @btea
- initialize re-exported wrapped ESM modules at the entry chunk (#10567) by @hyfdev
- link: resolve circular star reexports as null (#10445) by @Nic-Polumeyv
- transform: transformer gate skips newer syntax that oxc can lower (#10564) by @sekyungk
- code-splitting: materialize consumer-local barrel routing when the order-wrap plan is empty (#10544) by @hyfdev
- plugin: measure plugin hooks in JavaScript, report them from Rust (#10508) by @IWANABETHATGUY
- plugin: include external dynamic imports in chunk metadata (#10557) by @hyfdev
- plugin: report plugin timings after closeBundle has run (#10521) by @IWANABETHATGUY
- browser: avoid using node builtin modules (#10542) by @sapphi-red

### 🚜 Refactor

- plugin: give the build's own clocks their own type (#10520) by @shulaoda

### 📚 Documentation

- correct stale `buildStart` comment in `ScanStageCache::merge` (#10577) by @shulaoda
- update outdated pluginutils references (#10574) by @dogledogle

### ⚡ Performance

- external: drop the runtime import from chunks that never wrap (#10517) by @IWANABETHATGUY
- plugin: clock the build only when it is being measured (#10558) by @IWANABETHATGUY

### 🧪 Testing

- vite-tests: drop the dead `@rolldown/pluginutils` pnpm override (#10575) by @IWANABETHATGUY
- transform: group the transform-target fixtures and say why each exists (#10569) by @IWANABETHATGUY
- dev: fix hmr-hot-update-hook-vite fixture on Windows (#10565) by @h-a-n-a
- dev: match Vite's renamed full-reload log (#10547) by @shulaoda

### ⚙️ Miscellaneous Tasks

- deps: update napi (#10576) by @renovate[bot]
- deps: bump `@napi-rs/wasm-runtime` to 1.2.2 (#10570) by @shulaoda
- deps: update npm packages (#10583) by @renovate[bot]
- deps: update dependency rolldown-plugin-dts to ^0.28.0 (#10588) by @renovate[bot]
- deps: update taiki-e/install-action action to v2.85.5 (#10587) by @renovate[bot]
- deps: update codspeedhq/action action to v5 (#10584) by @renovate[bot]
- deps: update github actions (#10582) by @renovate[bot]
- deps: update rust crates (#10581) by @renovate[bot]
- deps: update dependency vite-plus to v0.2.7 (#10568) by @renovate[bot]
- deps: update dependency rolldown-plugin-dts to v0.27.14 (#10531) by @renovate[bot]
- deps: update pnpm to v11.17.0 (#10571) by @renovate[bot]
- deps: update @napi-rs/wasm-runtime to 1.2.1 (#10545) by @sapphi-red

### ❤️ New Contributors

* @sekyungk made their first contribution in [#10564](#10564)
* @nicolo-ribaudo made their first contribution in [#10526](#10526)

Co-authored-by: shulaoda <[email protected]>
Brooooooklyn added a commit that referenced this pull request Aug 9, 2026
72 upstream commits; 33 conflicted files resolved by composition:

- binding_bundler.rs: keep main's report_plugin_timings() (#10508/#10521)
  but wire it into both close paths — our JS layer calls closeTerminal(),
  where main's close()-only placement would have been dead code.
- devtools (#10622) and watch registration (#10548): our rewrites already
  subsume main's fixes (cwd baked into DevtoolsSessionKey; non-aborting
  watch adds with retained errors); kept ours.
- JS timing plumbing composed with the runtime-lease layer: measure
  innermost, error wrapper middle, lease outermost; workers stay
  unmeasured per main.
- CI: main's browser/WebContainer jobs + full-suite WASI node test folded
  into our per-flavor lanes (single-thread step runs test:wasi).
- pnpm-workspace: main's bumps adopted (@napi-rs/wasm-runtime ~1.2.2,
  oxc 0.143, plugin-dts ^0.28); @napi-rs/cli stays patched 3.7.2;
  check-workerd-packed-consumer.mjs range aligned to ~1.2.2.
- Cargo.lock: re-pinned napi/derive/backend/build/sys to git ad23bdeb
  (registry 3.12.0 from main's lock left the patch unused).
- Regenerated binding.cjs + WASI loaders/dts (wasi dts kept byte-equal
  to binding.d.cts, matching both parents' invariant).

Validated: cargo check/test clean; tsc src+tests clean; vitest
1550 passed / 30 skipped + watcher 68 / 1.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
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