Skip to content

feat(plugin): time the user callbacks configured on the options - #10509

Merged
IWANABETHATGUY merged 2 commits into
feat/plugin-timings-js-measurementfrom
feat/plugin-timings-option-callbacks
Jul 31, 2026
Merged

IWANABETHATGUY merged 2 commits into
feat/plugin-timings-js-measurementfrom
feat/plugin-timings-option-callbacks

Conversation

@IWANABETHATGUY

@IWANABETHATGUY IWANABETHATGUY commented Jul 29, 2026 •

Copy link
Copy Markdown
Member

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.

@IWANABETHATGUY
IWANABETHATGUY force-pushed the feat/plugin-timings-option-callbacks branch from dbf99d3 to d82643f Compare July 29, 2026 02:17
@IWANABETHATGUY
IWANABETHATGUY force-pushed the feat/plugin-timings-option-callbacks branch from d82643f to c19be71 Compare July 29, 2026 02:33
@IWANABETHATGUY
IWANABETHATGUY force-pushed the feat/plugin-timings-option-callbacks branch from c19be71 to ba6d360 Compare July 29, 2026 06:04
@IWANABETHATGUY
IWANABETHATGUY force-pushed the feat/plugin-timings-option-callbacks branch from ba6d360 to d5ca3ef Compare July 29, 2026 06:25
@IWANABETHATGUY
IWANABETHATGUY force-pushed the feat/plugin-timings-option-callbacks branch from d5ca3ef to 4f399b1 Compare July 29, 2026 06:58
@IWANABETHATGUY
IWANABETHATGUY force-pushed the feat/plugin-timings-option-callbacks branch from 4f399b1 to e748ec2 Compare July 29, 2026 07:20
@IWANABETHATGUY
IWANABETHATGUY force-pushed the feat/plugin-timings-option-callbacks branch from e748ec2 to 75478c5 Compare July 29, 2026 08:12
@IWANABETHATGUY
IWANABETHATGUY marked this pull request as ready for review July 29, 2026 08:13
@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-option-callbacks (fddc326) with feat/plugin-timings-js-measurement (ac42bf6)2

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

  2. No successful run was found on feat/plugin-timings-js-measurement (dd0222d) during the generation of this report, so 5a0bb75 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@IWANABETHATGUY
IWANABETHATGUY force-pushed the feat/plugin-timings-option-callbacks branch from 75478c5 to 3d66561 Compare July 29, 2026 08:54
@IWANABETHATGUY
IWANABETHATGUY marked this pull request as draft July 29, 2026 08:54
@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-option-callbacks branch from 3d66561 to 3f7efa2 Compare July 30, 2026 03:54
Plugin hooks are not the only JavaScript the bundler calls. Every option-level
callback crosses the same boundary and can dominate a build while belonging to
no plugin's rows -- a customer's heavy `codeSplitting.name` was the case that
prompted this.

Seventeen of them reach napi unwrapped, so none of them could appear in
`[PLUGIN_TIMINGS]`. Auditing from the Rust side, by listing every field on
`BindingInputOptions` / `BindingOutputOptions` typed as a JS callback rather
than by reading the TypeScript:

- output: `codeSplitting` `groups[].name` and `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, so those two have the same fan-out as the classifier.

They report under `output options` / `input options`, and rows carry a `kind`
so a consumer can group them without matching on the owner string.

`assetFileNames` and `sanitizeFileName` are measured in `createBundlerOptions`
rather than at the binding, because `this.emitFile` in a plugin context reads
the user's option directly; wrapping at each consumer would count one call in
two places.

Rows can therefore sum past 100%: `this.emitFile` inside `buildStart` invokes
`assetFileNames`, and the nested time belongs to both. The headline figure is
the union of every span, so it cannot.

Verified by making each callback individually expensive enough to clear the
one-second row floor and checking every one of them appears. 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` -- they are used in `process_code_and_sourcemap.rs`, so they
are presumably reached on another path.

Claude-Session: https://claude.ai/code/session_014uFXkw62sNL4zjBeyRsW9K
`kind` 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-option-callbacks branch from b2188a7 to fddc326 Compare July 31, 2026 03:54
@IWANABETHATGUY
IWANABETHATGUY merged commit 84d18c3 into main Jul 31, 2026
51 of 53 checks passed
@IWANABETHATGUY
IWANABETHATGUY deleted the feat/plugin-timings-option-callbacks branch July 31, 2026 04:05
IWANABETHATGUY added a commit that referenced this pull request Jul 31, 2026
#10508)

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:

```rust
// 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 #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.

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
IWANABETHATGUY added a commit that referenced this pull request Jul 31, 2026
Sits on #10509.

## What

`BuildTimings` took an `Instant` on every build, whether or not anyone
would read it.

Before #10520 the two clocks lived on the hook timing collector, which
only existed when timing was on — so the `Option<Instant>` it handed
back *was* the gate. Giving the clocks their own type dropped that, and
`bundle.rs` went to a bare `std::time::Instant::now()` in three places.

The gate goes back, this time owned by the type that needs it:

- `BuildTimings::new(measured)` — decided once, where the driver is
built.
- `start()` returns `Option<Instant>`: `None` when the build is not
being measured.
- `record_total` / `record_link_stage` take what `start()` gave and do
nothing with `None`.

The call sites read as they did before the split.

## What decides it

`options.plugin_timings`. The JavaScript side registers that callback
only when `measureTimings && checks.pluginTimings !== false`, so its
presence is already how this side knows a report is coming. The two
halves cannot disagree about whether a build is measured, because a
report needs both of them.

## Tests

Two added: a build that is not measured hands back no instant and stores
nothing; a measured one does start a clock. The existing gate tests are
unchanged.

## Not in scope

The threshold and the ratio, and what any measured build reports. If
this PR changes what a build with `checks.pluginTimings` on reports, it
is wrong.
@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]>
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