Repository navigation
perf(unhead): resolver allocation fast paths - #833
Merged
harlan-zw merged 4 commits intoJul 14, 2026
Merged
Conversation
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)
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
…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)
…o perf/resolver-allocations
…o perf/resolver-allocations
1 of 6 tasks
harlan-zw
added a commit
that referenced
this pull request
Jul 15, 2026
This reverts commit 9a59b6f.
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stacks on #828 (
perf/ssr-default-init-hoist); diff shown here is against that branch.🔗 Linked issue
N/A
❓ Type of change
📚 Description
What
Allocation and hook-dispatch fast paths in
resolveTags(packages/unhead/src/utils/resolve.ts):[...head.entries.values()]is only built whenentries:resolveORentries:normalizelisteners 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). Theentries:resolvearray-mutation contract is preserved. Chosen scope:propResolvers/tagWeightdo not force the snapshot; they are pure value transforms and callinghead.push()from them is out of contract.entries:resolve/entries:normalizectx objects are only allocated behind listener checks (normalize is re-read per entry, so hooks (un)registered mid-resolve still take effect immediately).HeadTag[][]. Entry tags are pushed straight intoctx.tags; the defensive clone runs in place afterwards, and the tag-mutating-hook scan still happens after the entry loop so a listener registered duringentries:normalizeis never skipped._nonMutatingdeleted. 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.valuesToTagsreuses the pre-dedupe array, andresolveTagssanitizes in place via a module-privatesanitizeTagsInPlace. The publicsanitizeTagsexport keeps its returns-a-new-array, input-untouched contract (it copies then delegates); export snapshots unchanged._precomputedTagsfast path from perf(unhead): precompute SSR init tags #828 is preserved with identical guards, and still never cached one._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
callHookemits a one-timeconsole.warnnaming the hook. Warn (not throw) because asyncentries:resolvelisteners were historically tolerated (PromisesPlugin) and throwing would break upgraders whose hooks appear to work.This immediately caught a real one: schema-org's
tags:resolvelistener wasasyncwith 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 asbench/perf-ci.mjs, 3–7 rounds each, medians; new bench:bench/resolve-tags.bench.ts). Numbers below re-measured on the final commit (7f7f975):ssr-default-init.bench.ts)bench/perf-ci.mjs(repo's CI methodology, dist, 2 runs each):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/bundlefixtures locally on both branches (raw / gzip,last.jsonuntouched), final commit:Most of the growth is the thenable warning; it was slimmed (one-time boolean, short message) to fit the gate.
Verification
head.push()fromentries:normalize: passes on base, fails on the pre-fix commit, passes on this branchvue-tsc --noEmitclean,pnpm lintcleantest/exports.test.ts --pool=threads, 19 passed)