Repository navigation
perf(unhead): precompute SSR init tags - #828
Conversation
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.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughSSR default initialization now lazily precomputes normalized tags and reuses them when resolution invariants hold. Internal entry and resolver metadata support this path, with Vue integration, tests, and benchmarks covering behavior and performance. ChangesSSR resolution pipeline
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 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 |
📦 Bundle Size
All bundles (14)
⚡ Performance (directional)✅ No significant change (within CI noise) All benchmarks (14)
Baseline: main @ 179db94 · 2026-07-14 · gzipped is the headline size metric · perf is directional (shared-runner, gated) |
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.
* 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)
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/schema-org/src/plugin.ts (1)
124-132: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy liftPreserve the async
meta()contract before this synchronous hook runs.metacan return aPromise, buttags:resolvespreadsmeta()directly intograph.resolveGraph(...). That drops async metadata entirely and leaves rejected promises unhandled; resolve/cache the value before this phase or narrow the contract.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/schema-org/src/plugin.ts` around lines 124 - 132, Update the metadata flow used by the synchronous 'tags:resolve' listener so async meta() results are awaited and resolved or cached before this hook executes. Ensure graph.resolveGraph receives the resolved metadata rather than a Promise, and rejected meta() calls are handled without unhandled rejections; preserve synchronous metadata behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/unhead/src/plugins/promises.ts`:
- Around line 38-41: Update the walkPromises chain in the entries:resolve
handler to attach a rejection path, preventing unhandled nested-promise
failures. Ensure the error path explicitly decides the retry behavior by either
preserving the entry for retry or setting ctx.entries[k]._promisesProcessed
consistently with the intended render semantics, while retaining the existing
success assignment and processed flag.
- Around line 35-41: Update the entries:resolve handler to store ctx.entries[k]
in a local entry variable before calling walkPromises, then use that captured
entry in the promise callback for both input assignment and _promisesProcessed.
Add rejection handling to the asynchronous resolution so failures are explicitly
handled and do not become unhandled promise rejections.
---
Outside diff comments:
In `@packages/schema-org/src/plugin.ts`:
- Around line 124-132: Update the metadata flow used by the synchronous
'tags:resolve' listener so async meta() results are awaited and resolved or
cached before this hook executes. Ensure graph.resolveGraph receives the
resolved metadata rather than a Promise, and rejected meta() calls are handled
without unhandled rejections; preserve synchronous metadata behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 2d7ff5b7-e2e3-416a-856c-939c6c014d09
📒 Files selected for processing (7)
bench/resolve-tags.bench.tspackages/schema-org/src/plugin.tspackages/unhead/src/plugins/promises.tspackages/unhead/src/utils/hooks.tspackages/unhead/src/utils/resolve.tspackages/unhead/test/unit/hooks/async-listener-warn.test.tspackages/unhead/test/unit/hooks/entries-normalize-push.test.ts
| 'entries:resolve': (ctx) => { | ||
| for (const k in ctx.entries) { | ||
| if (!ctx.entries[k]._promisesProcessed) { | ||
| promises.push( | ||
| walkPromises(ctx.entries[k].input).then((val) => { | ||
| ctx.entries[k].input = val | ||
| ctx.entries[k]._promisesProcessed = true | ||
| }), | ||
| ) | ||
| walkPromises(ctx.entries[k].input).then((val) => { | ||
| ctx.entries[k].input = val | ||
| ctx.entries[k]._promisesProcessed = true | ||
| }) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
set -euo pipefail
printf '\n== File outline ==\n'
ast-grep outline packages/unhead/src/plugins/promises.ts --view expanded || true
printf '\n== Relevant file section ==\n'
sed -n '1,140p' packages/unhead/src/plugins/promises.ts
printf '\n== Search for entries:resolve listeners ==\n'
rg -n "entries:resolve|_promisesProcessed|walkPromises|promises" packages/unhead/src -g '!**/dist/**'Repository: unjs/unhead
Length of output: 3458
🏁 Script executed:
set -euo pipefail
# Show the file with line numbers around the comment
nl -ba packages/unhead/src/plugins/promises.ts | sed -n '1,140p'
# Find the type/source defining the hook payload and any other resolve listeners.
rg -n "entries:resolve|interface .*Entries|type .*Entries|ctx\.entries" packages/unhead/src packages/unhead -g '!**/dist/**'Repository: unjs/unhead
Length of output: 189
🏁 Script executed:
echo helloRepository: unjs/unhead
Length of output: 155
🏁 Script executed:
set -euo pipefail
printf '\n== resolve.ts excerpt ==\n'
sed -n '160,220p' packages/unhead/src/utils/resolve.ts
printf '\n== hooks.ts excerpt ==\n'
sed -n '1,120p' packages/unhead/src/types/hooks.ts
printf '\n== head.ts excerpt ==\n'
sed -n '60,100p' packages/unhead/src/types/head.tsRepository: unjs/unhead
Length of output: 6743
Capture the entry before resolving promises.
entries:resolve listeners may mutate the array, so re-reading ctx.entries[k] inside the .then() can write the resolved input onto the wrong entry or undefined. Store the entry in a local variable before scheduling the async work, and handle rejections so failed promise resolution doesn’t go unhandled.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/unhead/src/plugins/promises.ts` around lines 35 - 41, Update the
entries:resolve handler to store ctx.entries[k] in a local entry variable before
calling walkPromises, then use that captured entry in the promise callback for
both input assignment and _promisesProcessed. Add rejection handling to the
asynchronous resolution so failures are explicitly handled and do not become
unhandled promise rejections.
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.
This reverts commit 93725e8.
This reverts commit 9a59b6f.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/unhead/src/utils/resolve.ts`:
- Around line 161-166: In the pending-update branch of the resolve flow,
alongside the existing cleanup of e._tags, also delete e._precomputedTags after
assigning e._pending to e.input. This ensures the fast path recomputes tags from
the updated input rather than reusing stale precomputed data.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 45865d32-aa1b-46ce-a3f7-bc01f27b9bf3
📒 Files selected for processing (2)
packages/unhead/src/types/head.tspackages/unhead/src/utils/resolve.ts
💤 Files with no reviewable changes (1)
- packages/unhead/src/types/head.ts
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/unhead/src/utils/resolve.ts`:
- Around line 161-166: In the pending-update branch of the resolve flow,
alongside the existing cleanup of e._tags, also delete e._precomputedTags after
assigning e._pending to e.input. This ensures the fast path recomputes tags from
the updated input rather than reusing stale precomputed data.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 45865d32-aa1b-46ce-a3f7-bc01f27b9bf3
📒 Files selected for processing (2)
packages/unhead/src/types/head.tspackages/unhead/src/utils/resolve.ts
💤 Files with no reviewable changes (1)
- packages/unhead/src/types/head.ts
🛑 Comments failed to post (1)
packages/unhead/src/utils/resolve.ts (1)
161-166: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Clear
_precomputedTagswhen an entry is updated.When an entry has pending changes (
e._pending), itsinputis updated, making any_precomputedTagsinvalid since they were derived from the old input. If_precomputedTagsis not deleted here, the fast path below might still reuse the stale precomputed tags instead of normalizing the updatedinput.While this primarily applies to the default init entry (which is generally static), it is safest to clear
_precomputedTagswhenever an entry is patched to maintain correctness.💻 Proposed fix
if (e._pending !== undefined) { e.input = e._pending delete e._pending delete e._tags + delete e._precomputedTags }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.if (e._pending !== undefined) { e.input = e._pending delete e._pending delete e._tags delete e._precomputedTags }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/unhead/src/utils/resolve.ts` around lines 161 - 166, In the pending-update branch of the resolve flow, alongside the existing cleanup of e._tags, also delete e._precomputedTags after assigning e._pending to e.input. This ensures the fast path recomputes tags from the updated input rather than reusing stale precomputed data.
|
Fixed the stale precomputed-tag path in 22f6350. Pending updates now clear both |
🔗 Linked issue
N/A
❓ Type of change
📚 Description
Nuxt-style servers create a head instance per request, so the default language, charset, and viewport entry was normalized on every render. This hoists the immutable default input and lazily precomputes its normalized tags once, with fallbacks for custom weights, non-static resolvers, entry hooks, entry options, user init entries, and disabled defaults.
VueResolver and the built-in server resolver now carry an internal _static marker so plain JSON defaults can use the same path. Core and Vue tests cover output equivalence and cross-instance isolation; local benchmarks measured about 65% more defaults-only renders per second and 25% more with one pushed entry.
Follow-up work was split into #838 for resolver allocations and #839 for synchronous hook behavior.
Summary by CodeRabbit
Performance
Bug Fixes
Tests