Skip to content

perf(unhead): resolver allocation fast paths - #833

Merged
harlan-zw merged 4 commits into
perf/ssr-default-init-hoistfrom
perf/resolver-allocations
Jul 14, 2026
Merged

harlan-zw merged 4 commits into
perf/ssr-default-init-hoistfrom
perf/resolver-allocations

Conversation

@harlan-zw

@harlan-zw harlan-zw commented Jul 13, 2026 •

Copy link
Copy Markdown
Collaborator

Stacks on #828 (perf/ssr-default-init-hoist); diff shown here is against that branch.

🔗 Linked issue

N/A

❓ Type of change

  • 📖 Documentation
  • 🐞 Bug fix
  • 👌 Enhancement
  • ✨ New feature
  • 🧹 Chore
  • ⚠️ Breaking change

📚 Description

What

Allocation and hook-dispatch fast paths in resolveTags (packages/unhead/src/utils/resolve.ts):

  • Entries snapshot is lazy. [...head.entries.values()] is only built when entries:resolve OR entries:normalize listeners exist — i.e. whenever user hook code can run inside the entry loop (a live Map iterator would feed entries pushed mid-resolve back into the same resolve; the snapshot defers them to the next resolve, exactly as before — regression-tested). The entries:resolve array-mutation contract is preserved. Chosen scope: propResolvers / tagWeight do not force the snapshot; they are pure value transforms and calling head.push() from them is out of contract.
  • Hook contexts are lazy. The entries:resolve / entries:normalize ctx objects are only allocated behind listener checks (normalize is re-read per entry, so hooks (un)registered mid-resolve still take effect immediately).
  • No intermediate HeadTag[][]. Entry tags are pushed straight into ctx.tags; the defensive clone runs in place afterwards, and the tag-mutating-hook scan still happens after the entry loop so a listener registered during entries:normalize is never skipped.
  • _nonMutating deleted. It was read in the clone scan but never set anywhere in the repo. Wiring it instead was audited and rejected: every built-in tag-hook plugin (TemplateParams, AliasSorting, safe, canonical, schema-org) mutates tags in place, so there is nothing to mark.
  • valuesToTags reuses the pre-dedupe array, and resolveTags sanitizes in place via a module-private sanitizeTagsInPlace. The public sanitizeTags export keeps its returns-a-new-array, input-untouched contract (it copies then delegates); export snapshots unchanged.
  • The _precomputedTags fast path from perf(unhead): precompute SSR init tags #828 is preserved with identical guards, and still never cached on e._tags.

Async listeners on the sync pipeline now fail visibly

A hook listener returning a thenable was silently ignored — worse, hookable defers later listeners of that hook past the render. Now callHook emits a one-time console.warn naming the hook. Warn (not throw) because async entries:resolve listeners were historically tolerated (PromisesPlugin) and throwing would break upgraders whose hooks appear to work.

This immediately caught a real one: schema-org's tags:resolve listener was async with zero awaits. Making it sync removes per-render promise machinery (−28% CPU on the cached schema.org perf-ci bench) and fixes the latent listener-deferral hazard. PromisesPlugin likewise no longer returns its never-awaited promise (same fire-and-forget semantics as before, minus the deferral bug). Tests: async-listener-warn.test.ts, entries-normalize-push.test.ts.

Benchmarks (gate 1)

Interleaved A/B on built dist (node --expose-gc, same technique as bench/perf-ci.mjs, 3–7 rounds each, medians; new bench: bench/resolve-tags.bench.ts). Numbers below re-measured on the final commit (7f7f975):

scenario (per-request createHead + renderSSRHead) alloc B/op base → branch CPU µs/op base → branch
defaults only (ssr-default-init.bench.ts) 7,209 → 6,122 (−15.1%) 2.9 → 2.5 (−13%)
defaults + 1 push 11,269 → 10,229 (−9.2%) ~7.1 → ~7.1 (noise)
20 entries, no plugins 143,666 → 132,838 (−7.5%) ~77 → ~79 (noise)
20 entries + TemplateParamsPlugin 171,746 → 155,365 (−9.5%) 98–111 → 74–89 (−13% to −21% across rounds)

bench/perf-ci.mjs (repo's CI methodology, dist, 2 runs each):

bench base → branch
ssr-medium-cpu 0.238 → 0.209 ms (−12.2%)
ssr-medium-alloc 281.2 → 261.7 KB (−6.9%)
schema-org-cached-cpu 0.196 → 0.140 ms (−28.5%)
schema-org-cached-alloc 148.9 → 152.2 KB (+2.2%)
csr-nav-mutations 38 → 38 (unchanged)

Gate read: −15.1% allocation on the ssr-default-init bench and −13…−21% CPU on the many-entries+plugins resolve bench clear the ≥15% bar. Caveat stated plainly: vitest wall-clock benches (vite-transformed src) show only +2–4% across the board; the dist CPU wins are consistent across interleaved process runs but µs-scale CPU is noise-dominated on this machine. Allocation numbers are deterministic and reproducible to <1%. The schema-org-cached-alloc +2.2% is the promise-machinery accounting shift from de-asyncing its listener (its CPU dropped 28%).

SSR output verified byte-identical between base and branch dists on all bench scenarios (incl. JSON-LD/script escaping).

Bundle size (gate 2, ≤2%)

Rebuilt bench/bundle fixtures locally on both branches (raw / gzip, last.json untouched), final commit:

bundle base branch delta
client minimal 13,250 / 5,289 13,440 / 5,388 +1.43% / +1.87%
server minimal 12,093 / 4,823 12,277 / 4,914 +1.52% / +1.89%
client full 22,669 / 8,689 22,860 / 8,791 +0.84% / +1.17%

Most of the growth is the thenable warning; it was slimmed (one-time boolean, short message) to fit the gate.

Verification

  • full repo suite: 1,581 passed / 8 skipped (no tests modified or weakened)
  • regression test for mid-resolve head.push() from entries:normalize: passes on base, fails on the pre-fix commit, passes on this branch
  • vue-tsc --noEmit clean, pnpm lint clean
  • export snapshots unchanged (test/exports.test.ts --pool=threads, 19 passed)

Per-resolve fast paths in the tag resolver, gated on registered hooks:

- only snapshot `head.entries` into an array when an `entries:resolve`
  listener will see it; the `_pending` sweep and entry loop iterate the
  map directly otherwise
- allocate hook context objects (`entries:resolve`, `entries:normalize`)
  lazily behind listener checks instead of before every callHook
- drop the intermediate `entryTags: HeadTag[][]`; entry tags are pushed
  straight into the resolve context and defensively cloned in place only
  when a tag-mutating hook is registered (scan still runs after the entry
  loop so mid-resolve registrations are honored)
- remove the dead `_nonMutating` check (read but never set anywhere)
- reuse the pre-dedupe tags array in valuesToTags and compact in place
  in sanitizeTags instead of allocating fresh output arrays

A listener returning a promise on the synchronous pipeline is now
surfaced with a one-time console.warn naming the hook (previously
silently dropped, with later listeners deferred past the render):

- PromisesPlugin no longer returns its (never-awaited) promise, so it
  can't defer later-registered `entries:resolve` listeners
- schema-org's `tags:resolve` listener was needlessly async (no awaits);
  making it sync also removes per-render promise machinery (-22% CPU on
  the cached schema.org render bench)
@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1a82de4a-3978-4cdd-a311-0e55d8788948

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch perf/resolver-allocations

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

…ooks exist

Review follow-ups for the resolver allocation work:

- `sanitizeTags` is public API (`unhead/utils`): restore its
  returns-a-new-array contract. The in-place compaction moves to a
  module-private `sanitizeTagsInPlace` used by `resolveTags`; the export
  delegates via a copy. Export snapshots unchanged.
- iterating the live entries Map let an `entries:normalize` listener that
  calls `head.push()` feed the new entry back into the same resolve (a
  per-entry push would loop forever). Snapshot the entries whenever
  `entries:resolve` OR `entries:normalize` listeners exist; the live Map
  is only iterated when no user hook code can run inside the loop.
  propResolvers / tagWeight do not force the snapshot: they are pure
  value transforms and calling head.push from them is out of contract.
- regression test: an entry pushed by an entries:normalize listener must
  defer to the next resolve (passes on base, fails on the previous
  commit, passes now)
@harlan-zw
harlan-zw merged commit 9a59b6f into perf/ssr-default-init-hoist Jul 14, 2026
harlan-zw added a commit that referenced this pull request Jul 15, 2026
harlan-zw added a commit that referenced this pull request Jul 15, 2026
* perf(unhead): precompute SSR default init tags once per process

Nuxt-style servers call createHead() per request, and the default init
entry (htmlAttrs lang, charset, viewport) was re-normalized through
normalizeEntryToTags + weight/dedupe assignment on every request since
the entry tag cache is per instance.

Hoist the default init object to module scope and lazily normalize it
once, mirroring the resolveTags first-resolve path exactly. The shared
array is attached as entry._precomputedTags and only used when nothing
can observe or alter normalization:

- default capoTagWeight (no tagWeight option, no per-resolve override)
- no custom propResolvers (the entry has no on* handlers so the
  built-in server resolver is a no-op)
- no entries:normalize or entries:resolve hooks at resolve time
- no entry options
- disableDefaults and user init entries keep the normalize path

The array is never cached on entry._tags so entries:resolve listeners
can never reach the shared array, and tag-mutating hooks are already
covered by the existing needsClone defensive copy.

* perf(vue): enable SSR default init fast path via static resolver marker

Add an internal _static marker to PropResolver for resolvers that are
the identity function for plain non-reactive JSON values. VueResolver
(pure isRef/toValue unwrap) and the built-in server on* resolver are
marked, and the attach-time guard now only requires every custom
propResolver to be static instead of requiring none, so @unhead/vue
(Nuxt-style per-request createHead) gets the precomputed default init
entry too. Resolve-time guards are unchanged.

* fix: pure-annotate serverPropResolver marker for import-inert

* perf(unhead): resolver allocation fast paths (#833)

* perf(unhead): reduce per-resolve allocations in resolveTags

Per-resolve fast paths in the tag resolver, gated on registered hooks:

- only snapshot `head.entries` into an array when an `entries:resolve`
  listener will see it; the `_pending` sweep and entry loop iterate the
  map directly otherwise
- allocate hook context objects (`entries:resolve`, `entries:normalize`)
  lazily behind listener checks instead of before every callHook
- drop the intermediate `entryTags: HeadTag[][]`; entry tags are pushed
  straight into the resolve context and defensively cloned in place only
  when a tag-mutating hook is registered (scan still runs after the entry
  loop so mid-resolve registrations are honored)
- remove the dead `_nonMutating` check (read but never set anywhere)
- reuse the pre-dedupe tags array in valuesToTags and compact in place
  in sanitizeTags instead of allocating fresh output arrays

A listener returning a promise on the synchronous pipeline is now
surfaced with a one-time console.warn naming the hook (previously
silently dropped, with later listeners deferred past the render):

- PromisesPlugin no longer returns its (never-awaited) promise, so it
  can't defer later-registered `entries:resolve` listeners
- schema-org's `tags:resolve` listener was needlessly async (no awaits);
  making it sync also removes per-render promise machinery (-22% CPU on
  the cached schema.org render bench)

* fix(unhead): keep sanitizeTags contract, snapshot entries when loop hooks exist

Review follow-ups for the resolver allocation work:

- `sanitizeTags` is public API (`unhead/utils`): restore its
  returns-a-new-array contract. The in-place compaction moves to a
  module-private `sanitizeTagsInPlace` used by `resolveTags`; the export
  delegates via a copy. Export snapshots unchanged.
- iterating the live entries Map let an `entries:normalize` listener that
  calls `head.push()` feed the new entry back into the same resolve (a
  per-entry push would loop forever). Snapshot the entries whenever
  `entries:resolve` OR `entries:normalize` listeners exist; the live Map
  is only iterated when no user hook code can run inside the loop.
  propResolvers / tagWeight do not force the snapshot: they are pure
  value transforms and calling head.push from them is out of contract.
- regression test: an entry pushed by an entries:normalize listener must
  defer to the next resolve (passes on base, fails on the previous
  commit, passes now)

* chore: dedupe async-hook warning per instance (#837)

The warn-once flag for async listeners on the sync hook pipeline was
module state, violating the CONTRIBUTING module-state policy (input
originates from user hook behavior, not module constants). Move it to
the head instance so each head (e.g. each SSR request's) warns
independently and test runs can't bleed state into each other.

* Revert "chore: dedupe async-hook warning per instance (#837)"

This reverts commit 93725e8.

* Revert "perf(unhead): resolver allocation fast paths (#833)"

This reverts commit 9a59b6f.

* fix(unhead): clear stale precomputed tags
harlan-zw added a commit that referenced this pull request Jul 19, 2026
* perf(unhead): precompute SSR default init tags once per process

Nuxt-style servers call createHead() per request, and the default init
entry (htmlAttrs lang, charset, viewport) was re-normalized through
normalizeEntryToTags + weight/dedupe assignment on every request since
the entry tag cache is per instance.

Hoist the default init object to module scope and lazily normalize it
once, mirroring the resolveTags first-resolve path exactly. The shared
array is attached as entry._precomputedTags and only used when nothing
can observe or alter normalization:

- default capoTagWeight (no tagWeight option, no per-resolve override)
- no custom propResolvers (the entry has no on* handlers so the
  built-in server resolver is a no-op)
- no entries:normalize or entries:resolve hooks at resolve time
- no entry options
- disableDefaults and user init entries keep the normalize path

The array is never cached on entry._tags so entries:resolve listeners
can never reach the shared array, and tag-mutating hooks are already
covered by the existing needsClone defensive copy.

* perf(vue): enable SSR default init fast path via static resolver marker

Add an internal _static marker to PropResolver for resolvers that are
the identity function for plain non-reactive JSON values. VueResolver
(pure isRef/toValue unwrap) and the built-in server on* resolver are
marked, and the attach-time guard now only requires every custom
propResolver to be static instead of requiring none, so @unhead/vue
(Nuxt-style per-request createHead) gets the precomputed default init
entry too. Resolve-time guards are unchanged.

* fix: pure-annotate serverPropResolver marker for import-inert

* perf(unhead): resolver allocation fast paths (#833)

* perf(unhead): reduce per-resolve allocations in resolveTags

Per-resolve fast paths in the tag resolver, gated on registered hooks:

- only snapshot `head.entries` into an array when an `entries:resolve`
  listener will see it; the `_pending` sweep and entry loop iterate the
  map directly otherwise
- allocate hook context objects (`entries:resolve`, `entries:normalize`)
  lazily behind listener checks instead of before every callHook
- drop the intermediate `entryTags: HeadTag[][]`; entry tags are pushed
  straight into the resolve context and defensively cloned in place only
  when a tag-mutating hook is registered (scan still runs after the entry
  loop so mid-resolve registrations are honored)
- remove the dead `_nonMutating` check (read but never set anywhere)
- reuse the pre-dedupe tags array in valuesToTags and compact in place
  in sanitizeTags instead of allocating fresh output arrays

A listener returning a promise on the synchronous pipeline is now
surfaced with a one-time console.warn naming the hook (previously
silently dropped, with later listeners deferred past the render):

- PromisesPlugin no longer returns its (never-awaited) promise, so it
  can't defer later-registered `entries:resolve` listeners
- schema-org's `tags:resolve` listener was needlessly async (no awaits);
  making it sync also removes per-render promise machinery (-22% CPU on
  the cached schema.org render bench)

* fix(unhead): keep sanitizeTags contract, snapshot entries when loop hooks exist

Review follow-ups for the resolver allocation work:

- `sanitizeTags` is public API (`unhead/utils`): restore its
  returns-a-new-array contract. The in-place compaction moves to a
  module-private `sanitizeTagsInPlace` used by `resolveTags`; the export
  delegates via a copy. Export snapshots unchanged.
- iterating the live entries Map let an `entries:normalize` listener that
  calls `head.push()` feed the new entry back into the same resolve (a
  per-entry push would loop forever). Snapshot the entries whenever
  `entries:resolve` OR `entries:normalize` listeners exist; the live Map
  is only iterated when no user hook code can run inside the loop.
  propResolvers / tagWeight do not force the snapshot: they are pure
  value transforms and calling head.push from them is out of contract.
- regression test: an entry pushed by an entries:normalize listener must
  defer to the next resolve (passes on base, fails on the previous
  commit, passes now)

* chore: dedupe async-hook warning per instance (#837)

The warn-once flag for async listeners on the sync hook pipeline was
module state, violating the CONTRIBUTING module-state policy (input
originates from user hook behavior, not module constants). Move it to
the head instance so each head (e.g. each SSR request's) warns
independently and test runs can't bleed state into each other.

* Revert "chore: dedupe async-hook warning per instance (#837)"

This reverts commit 93725e8.

* Revert "perf(unhead): resolver allocation fast paths (#833)"

This reverts commit 9a59b6f.

* perf(unhead): reduce resolver allocations

* fix(unhead): clear stale precomputed tags

* fix(unhead): guard large resolver tag arrays

Keep the spread fast path for normal entry tag arrays and use indexed copying above a safe argument-count threshold. This avoids a RangeError for large cached entries without slowing the common path.\n\nUpdate the resolver benchmark to use head.render() and cover cached renders.

* perf(unhead): skip unused entries resolve payload

Avoid constructing the entries:resolve context when only entries:normalize listeners require the entry snapshot. Add FlatMetaPlugin first and cached render cases to the resolver benchmark.

* perf(unhead): tighten resolver size tradeoff

Drop the unrealistic 32k-tag spread fallback, reducing the bundle cost while retaining the allocation fast path. Mark async stream heap deltas informational because repeated unchanged runs are bimodal due to ReadableStream cleanup.

* fix(unhead): align adapter and hook cache lifecycle
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.

1 participant