Skip to content

perf(unhead): reduce resolver allocations - #838

Merged
harlan-zw merged 15 commits into
mainfrom
perf/resolver-allocation-fast-paths-split
Jul 19, 2026
Merged

harlan-zw merged 15 commits into
mainfrom
perf/resolver-allocation-fast-paths-split

Conversation

@harlan-zw

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

Copy link
Copy Markdown
Collaborator

🔗 Linked issue

Related to #828

❓ Type of change

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

📚 Description

Builds on #828, which is now in main. resolveTags still created an entry snapshot, hook contexts, an intermediate tag matrix, and fresh compaction arrays on every render when no relevant hooks were registered.

This PR creates those structures only when listeners need them and reuses owned arrays through dedupe and sanitization. Cached entry normalization is invalidated when the active entries:resolve and entries:normalize listener count changes.

Client and streaming heads now use the same private adapter and decorate one core head object. The previous streaming wrapper copied the core, so its renderer could not see hooks attached to the wrapper. Push, patch, dispose, onRendered, auto-render, and hydration locking now share one lifecycle implementation.

The allocation benchmark uses 40 ordinary head entries and head.render(). The 32k-tag case is only a regression guard for large cached arrays; it is not the source of the reported allocation win.

📊 Benchmarks

GitHub same-runner, built-dist comparison against main:

Scenario main PR Change
Medium SSR allocation 262.1 KiB/render 252.7 KiB/render 9.3 KiB less (3.6%)
Cached schema.org allocation 144.7 KiB/render 139.9 KiB/render 4.8 KiB less (3.3%)

CPU and wall-clock results remain within noise. Streaming allocation is also within noise. The bundle matrix adds 1.2 kB gzip in aggregate; each consumed bundle grows by 88 B to about 0.1 kB (0.9% to 2.1%).

✅ Verification

  • all 9 GitHub checks pass
  • 896 Unhead tests passed, 8 skipped locally
  • pnpm lint
  • pnpm typecheck
  • pnpm build
  • pnpm test:import-inert
  • all 14 bundle fixtures rebuilt and compared

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.
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)
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.
@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

resolveTags now reduces intermediate allocations through in-place tag compaction, conditional cloning, and sanitization. SSR benchmarks cover plugin and entry-count scenarios, while tests verify deferred normalization entries and large cached tag arrays.

Changes

Tag resolution flow

Layer / File(s) Summary
In-place tag processing
packages/unhead/src/utils/resolve.ts
Tag cloning, compaction, spread handling, and sanitization now use owned arrays while exported sanitizeTags preserves its non-mutating behavior.
Hook-aware resolution flow
packages/unhead/src/utils/resolve.ts, packages/unhead/test/unit/hooks/entries-normalize-push.test.ts, packages/unhead/test/unit/client/resolveTags.test.ts
resolveTags conditionally snapshots entries, appends tags safely, clones once for mutating hooks, and defers entries pushed during normalization to the next render.
SSR resolution benchmarks
bench/resolve-tags.bench.ts
Adds first-render and cached-render benchmarks for 20-entry and 5-entry heads, with and without TemplateParamsPlugin or FlatMetaPlugin.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related PRs

  • unjs/unhead#776: Both adjust defensive cloning in resolveTags based on registered mutating hooks.
  • unjs/unhead#794: Both refactor tag accumulation, cloning, and sanitization in resolve.ts.
  • unjs/unhead#828: Both modify the tag resolution flow and _precomputedTags handling in resolveTags.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise, conventional, and accurately summarizes the main change: reducing resolver allocations.
Description check ✅ Passed The description includes the linked issue, change type checkboxes, a detailed summary, benchmarks, and verification.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch perf/resolver-allocation-fast-paths-split

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.

@harlan-zw harlan-zw mentioned this pull request Jul 15, 2026
1 of 6 tasks
@harlan-zw

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
bench/resolve-tags.bench.ts (1)

2-2: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider replacing the deprecated renderSSRHead API.

As per the provided code snippets from packages/unhead/src/server/renderSSRHead.ts, renderSSRHead is deprecated in favor of head.render(). Consider updating the benchmark to use the newer API, unless the legacy synchronous wrapper is intentionally being used to isolate CPU/memory allocations without introducing Promise overhead.

🤖 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 `@bench/resolve-tags.bench.ts` at line 2, Replace the deprecated renderSSRHead
usage in the benchmark with the newer head.render() API, updating the
surrounding benchmark flow to handle its return value as needed. If this
benchmark intentionally measures the legacy synchronous wrapper without Promise
overhead, retain renderSSRHead and document that intentional exception.
🤖 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.

Nitpick comments:
In `@bench/resolve-tags.bench.ts`:
- Line 2: Replace the deprecated renderSSRHead usage in the benchmark with the
newer head.render() API, updating the surrounding benchmark flow to handle its
return value as needed. If this benchmark intentionally measures the legacy
synchronous wrapper without Promise overhead, retain renderSSRHead and document
that intentional exception.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2b37f15a-c29a-47ed-97bc-79251fae0f2e

📥 Commits

Reviewing files that changed from the base of the PR and between bfaa39b and 416d08f.

📒 Files selected for processing (3)
  • bench/resolve-tags.bench.ts
  • packages/unhead/src/utils/resolve.ts
  • packages/unhead/test/unit/hooks/entries-normalize-push.test.ts

@harlan-zw
harlan-zw changed the base branch from perf/ssr-default-init-hoist to main July 15, 2026 08:26
…ion-fast-paths-split

# Conflicts:
#	packages/unhead/src/utils/resolve.ts
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.
@github-actions

github-actions Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

📦 Bundle Size

⚠️ 12 bundles grew · net +1.2 kB gz

Bundle Gzipped Δ
Client (Minimal) 5.2 kB → 5.3 kB 🔴 +0.1 kB (+2.0%)
Client (Full) 8.6 kB → 8.6 kB 🔴 +88 B (+1.0%)
Client (Self-Contained) 5.6 kB → 5.6 kB 🔴 +95 B (+1.7%)
Server (Minimal) 4.7 kB → 4.8 kB 🔴 +0.1 kB (+2.1%)
Server (Self-Contained) 5.1 kB → 5.2 kB 🔴 +93 B (+1.8%)
Vue Client (Minimal) 5.7 kB → 5.8 kB 🔴 +0.1 kB (+1.7%)
Vue Client (Full) 9.3 kB → 9.4 kB 🔴 +96 B (+1.0%)
Vue Server (Minimal) 5.2 kB → 5.3 kB 🔴 +0.1 kB (+2.0%)
React Client (Minimal) 5.6 kB → 5.7 kB 🔴 +0.1 kB (+1.8%)
React Client (Full) 9.4 kB → 9.5 kB 🔴 +90 B (+0.9%)
React Server (Minimal) 5 kB → 5.1 kB 🔴 +0.1 kB (+2.0%)
Schema.org (Minimal) 9.8 kB → 9.9 kB 🔴 +0.1 kB (+1.2%)
All bundles (14)
Bundle Gzipped Brotli Raw
Core
Client (Minimal) 5.3 kB 4.8 kB 13.3 kB 🔴
Client (Full) 8.6 kB 7.9 kB 22.5 kB 🔴
Client (Self-Contained) 5.6 kB 5.1 kB 14.1 kB 🔴
Server (Minimal) 4.8 kB 4.4 kB 12.1 kB 🔴
Server (Self-Contained) 5.2 kB 4.6 kB 12.8 kB 🔴
Vue
Vue Client (Minimal) 5.8 kB 5.3 kB 14.4 kB 🔴
Vue Client (Full) 9.4 kB 8.5 kB 24.5 kB 🔴
Vue Server (Minimal) 5.3 kB 4.8 kB 13.1 kB 🔴
React
React Client (Minimal) 5.7 kB 5.2 kB 14.3 kB 🔴
React Client (Full) 9.5 kB 8.6 kB 24.9 kB 🔴
React Server (Minimal) 5.1 kB 4.6 kB 12.8 kB 🔴
Schema.org
Schema.org (Minimal) 9.9 kB 9 kB 27.1 kB 🔴
Schema.org Imports 0.1 kB 0.1 kB 0.1 kB ✅
Schema.org Vue Meta 0.4 kB 0.3 kB 0.8 kB ✅

⚡ Performance (directional)

🟢 2 faster

Benchmark base → PR Δ
SSR allocated / render 262.1 KiB → 252.7 KiB 🟢 -9.3 KiB (-3.6%)
Schema.org cached allocated / render 144.7 KiB → 139.9 KiB 🟢 -4.8 KiB (-3.3%)
All benchmarks (14)
Benchmark PR Δ RME
SSR render (CPU) 0.358 ms ~ noise ±9.6%
SSR render (wall) 0.264 ms ~ noise ±4.9%
SSR allocated / render 252.7 KiB 🟢 -9.3 KiB (-3.6%) —
Schema.org cached render (CPU) 0.375 ms ~ noise ±5.4%
Schema.org cached render (wall) 0.248 ms ~ noise ±1.7%
Schema.org cached allocated / render 139.9 KiB 🟢 -4.8 KiB (-3.3%) —
Streaming wrapStream drain (CPU) 0.250 ms ~ noise ±4.2%
Streaming wrapStream drain (wall) 0.154 ms ~ noise ±4.3%
Streaming allocated / drain 160.1 KiB ~ noise —
Streaming suspense chunk (CPU) 0.011 ms ~ noise ±7.7%
Streaming allocated / suspense chunk 4.6 KiB ~ noise —
CSR DOM mutations / nav 38 ~ noise —
CSR re-render (CPU) 0.841 ms ~ noise ±5.2%
CSR re-render (wall) 0.476 ms ~ noise ±2.0%

Baseline: main @ 1d8b0e1 · 2026-07-19 · gzipped is the headline size metric · perf is directional (shared-runner, gated)

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.
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.
@harlan-zw
harlan-zw merged commit 2a3cd44 into main Jul 19, 2026
9 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Jul 19, 2026
1 of 6 tasks
@harlan-zw harlan-zw mentioned this pull request Jul 23, 2026
1 of 6 tasks
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