Skip to content

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

Merged
shulaoda merged 1 commit into
mainfrom
feat/plugin-timings-extract-build-clocks
Jul 30, 2026
Merged

shulaoda merged 1 commit into
mainfrom
feat/plugin-timings-extract-build-clocks

Conversation

@IWANABETHATGUY

@IWANABETHATGUY IWANABETHATGUY commented Jul 29, 2026 •

Copy link
Copy Markdown
Member

First of four. Pure refactor — no behaviour change — to make the three PRs above it smaller.

What

HookTimingCollector held two things that are not the same kind of thing:

  • what each plugin's hooks cost, accumulated per call, keyed by PluginIdx;
  • the build's total and link-stage wall clocks, set exactly once each.

The second pair also answers a different question. plugins_are_slow decides whether the build is worth reporting on at all, and it is asked before any per-plugin number is looked at — it does not read the plugin map.

So they split. BuildTimings owns the two clocks and the gate, and sits on PluginDriver beside the collector.

Also

is_plugin_bound(total, link) exposes the same test over totals the caller supplies. Nothing needs that yet; #10521 does, because a build that produced several outputs has to sum its clocks before asking.

The gate now has unit tests — the fast-build floor, the ratio, and the cases where there is no ratio to take. It had none before.

Not in scope

The threshold itself (3s, 100×) is unchanged, as is every caller. If this PR changes what any build reports, it is wrong.

@netlify

netlify Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for rolldown-rs ready!

Name Link
🔨 Latest commit 74290b4
🔍 Latest deploy log https://app.netlify.com/projects/rolldown-rs/deploys/6a6acadcc848720008c84d2b
😎 Deploy Preview https://deploy-preview-10520--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-extract-build-clocks (74290b4) with main (93c535d)

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

@shulaoda

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 0246cfeb15

ℹ️ About Codex in GitHub

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

`HookTimingCollector` held two things that are not the same kind of thing: what
each plugin's hooks cost, accumulated per call, and the build's total and
link-stage wall clocks, set once each. The second pair also answers a different
question -- whether the build is worth reporting on at all -- which is asked
before any per-plugin number is read.

Split them. `BuildTimings` owns the two clocks and `plugins_are_slow`, and sits
on the `PluginDriver` beside the collector. `is_plugin_bound` exposes the same
test over totals a caller supplies, which a build producing several outputs
needs.

No behaviour change: the same clocks, the same threshold, the same callers. The
gate now has unit tests, which it did not before.

Claude-Session: https://claude.ai/code/session_014uFXkw62sNL4zjBeyRsW9K
@IWANABETHATGUY
IWANABETHATGUY force-pushed the feat/plugin-timings-extract-build-clocks branch from 0246cfe to 74290b4 Compare July 30, 2026 03:54
@shulaoda
shulaoda merged commit ff108d6 into main Jul 30, 2026
35 checks passed
@shulaoda
shulaoda deleted the feat/plugin-timings-extract-build-clocks branch July 30, 2026 11:05
IWANABETHATGUY added a commit that referenced this pull request Jul 31, 2026
Second of four. Stacked on #10520.

## The bug

`closeBundle` is instrumented like every other hook — `output_hooks.rs`
brackets the call and records it. But the warning is pushed into
`output.warnings` from `Bundle::write` / `Bundle::generate`, and those
return **before** `BundleHandle::close()` invokes the hook.

So its cost is measured and then thrown away. A plugin whose expense is
concentrated in `closeBundle` can never appear in `[PLUGIN_TIMINGS]`,
however slow it is.

## The fix

Emit from `BindingBundler::close` instead, after the cleanup future
resolves. It still goes through the existing `handle_warnings`, so
`checks.pluginTimings` filters it like any other check and the message
renders through `Diagnostic::render_batch` as before.

## What deferring forces

One `RolldownBuild` may `generate` more than once. Until now each output
emitted its own self-consistent report; a single report at close has to
account for all of them. So `BindingBundler` keeps every `BundleHandle`
rather than only the last, and:

- **the gate** sums the build and link clocks across all outputs —
otherwise a slow first output followed by a fast one would fall under
the 3s floor and be suppressed entirely;
- **the rows** merge the per-plugin summaries by name — each output has
its own driver and so its own `PluginIdx`, so the same plugin arrives
once per output and would otherwise compete with itself for the five-row
cap and halve its own share.

## Verification

A plugin whose only cost is a slow `closeBundle`, alongside another that
makes the build qualify:

```
[PLUGIN_TIMINGS] Your build spent significant time in plugin `slow-closebundle`.
```

Before this PR it is absent from the report entirely. Plus unit tests
for the cross-output merge.
IWANABETHATGUY added a commit that referenced this pull request Jul 31, 2026
`BuildTimings` took an `Instant` on every build, whether or not anyone
would read it. Before the split in #10520 the clocks lived on the hook
timing collector, which only existed when timing was on, so the `Option`
it handed back was the gate. Giving them their own type dropped that,
and `bundle.rs` went to a bare `Instant::now()`.

Put the gate back where the type can own it. `BuildTimings::new` takes
whether the build is measured; `start()` hands back an instant only then,
and `record_total` / `record_link_stage` take what it gave and do nothing
with `None`. The call sites read the same as they did before.

What decides it is `options.plugin_timings` — the JavaScript side
registers that callback only when `checks.pluginTimings` leaves
measurement on, so its presence is already how this side knows a report
is coming. The two halves cannot disagree, because a report needs both.

Claude-Session: https://claude.ai/code/session_01S3RQeYwhJmEu4eLYkanvm1
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
`BuildTimings` took an `Instant` on every build, whether or not anyone
would read it. Before the split in #10520 the clocks lived on the hook
timing collector, which only existed when timing was on, so the `Option`
it handed back was the gate. Giving them their own type dropped that,
and `bundle.rs` went to a bare `Instant::now()`.

Put the gate back where the type can own it. `BuildTimings::new` takes
whether the build is measured; `start()` hands back an instant only then,
and `record_total` / `record_link_stage` take what it gave and do nothing
with `None`. The call sites read the same as they did before.

What decides it is `options.plugin_timings` — the JavaScript side
registers that callback only when `checks.pluginTimings` leaves
measurement on, so its presence is already how this side knows a report
is coming. The two halves cannot disagree, because a report needs both.

Claude-Session: https://claude.ai/code/session_01S3RQeYwhJmEu4eLYkanvm1
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