Skip to content

fix(signals): a ref's read during hydration no longer discards and rebuilds the served element (#5232) - #5235

Merged
ryansolid merged 4 commits into
solidjs:mainfrom
yumemi-thomas:fix/hydration-ref-snapshot-replay
Nov 27, 2026
Merged

ryansolid merged 4 commits into
solidjs:mainfrom
yumemi-thomas:fix/hydration-ref-snapshot-replay

Conversation

@yumemi-thomas

Copy link
Copy Markdown
Contributor

Summary

Fixes #5232.

During hydration, when a ref callback reads a signal whose current value differs from the hydration snapshot, the served element was discarded and rebuilt, and the ref ran twice: first on the served node, which ended up detached, then on a new node. This is a regression from #4768, which shipped in 2.0.0-rc.22.

After this change, hydration keeps the served element and calls its ref once. The ref sees the snapshot value, as it did in rc.21.

function App() {
  const [n, setN] = createSignal(0);
  return () => <p ref={el => { setN(1); calls.push([el, n()]); }}>target</p>;
}
before after
hydrate 2 calls: n=0 on the served node (detached), then n=1 on a new node 1 call: n=0 on the served node, which is kept
client render 1 call, n=1 unchanged

Cause

Since #4768, runRefCallback runs a ref untracked but in the creating pass's context, so the ref's reads see that pass's staging and holds (#4761, #4767). During a hydration claim, any read whose owner is in a snapshot scope is served the snapshot. If the node's current or pending value differs from the snapshot, the owner gets REACTIVE_SNAPSHOT_STALE (in read() in core/core.ts, and in verdictValue() in core/verdict.ts for latest/isPending). That happens even when tracking is off. When the snapshot scope is released, releaseSubtree queues every stale computation to run again. For a ref, the owner is the pass that created the element: an insert effect, a <Show> branch, and so on. Running it again builds a new element in place of the served one and calls the ref again.

The mark is how a claim catches up to client state: the pass read a value the server rendered with, so it runs again with the current one. That doesn't fit a ref. A ref is one-shot imperative work, like an event handler (#5098). Running its creating pass again doesn't update the element; it replaces it.

Fix

runRefCallback records the owner it runs in (refOwner, saved and restored, so nested refs work). A read whose owner is that ref's own owner, made untracked (context === refOwner && !tracking), is still served the snapshot but no longer marks the pass stale. This applies to both snapshot paths: the plain read and the verdict-window read. Outside a hydration claim neither path is reached, so latest() and isPending() are unchanged there.

The test is on the owner rather than on "inside a ref" (refCallbackDepth && !tracking) so that work a ref parents elsewhere keeps its catch-up. A computation a ref creates with runWithOwner (the allowed way to create one there) has its own owner, so its untracked reads still mark it, and it still catches up at release. On the broader test it kept the server's value after the snapshot was released (see the signals test below).

refOwner also replaces the refCallbackDepth counter. It is set for exactly as long as the counter was above 0, so the existing in-ref tests (inRefCallback, the pending-read exemption, serve()'s held-staging path) now compare refOwner !== 0, with the same behaviour. The pending-read exemption keeps its broader "inside any ref" scope. This PR doesn't narrow it.

What doesn't change:

No rule in packages/signals/docs/ covers hydration snapshot replay, so the new code comments cite #5232. That may be a missing rule (a ref's own read is served the snapshot and doesn't replay its creating pass) for the maintainer to decide.

Tests

  • packages/signals/tests/ref-snapshot-read-5232.test.ts (8 tests). These test the engine directly with markSnapshotScope, runRefCallback and releaseSnapshotScope:
    • a ref's plain read, latest() read and isPending() read don't re-run the pass, and the plain and latest() reads are served the snapshot;
    • a ref's read after a nested ref run under another owner still doesn't re-run the pass (refOwner is restored);
    • controls:
      • the pass's own untracked read and its own tracked read still re-run it at release;
      • the pass's untracked read after a ref that threw still re-runs it;
      • a computation a ref creates with runWithOwner still re-runs at release with the current value.
  • packages/web/test/hydration/ref-snapshot-read-5232.spec.tsx (14 tests). Server markup is inline. It was checked against renderToString of the same components in both LOWER_SHOW modes, and a lowered <Show> numbers its _hk keys differently.
    • Each case below hydrates and checks for one ref call on the served node, that the node stays connected, and that no warnings are logged:
      • the minimal repro;
      • App writing before it returns the accessor;
      • <Show when={true}>;
      • the issue's ref={setAnchor} + <Show> popover (anchor null);
      • an earlier sibling ref's write read by an accessor's ref;
      • the same sibling write read through a ref array, a ref forwarded through a component's props, a ref beside a reactive spread (whose class still updates to the client value), and a ref inside <Loading>, inside <Errored>, and on <Dynamic>;
      • a tracked text binding of the written signal, which still updates to 1 on the served node.
    • Controls:
      • a ref that only reads;
      • client render, which is unchanged: one call with the current value (1, anchor set).

Before the fix:

  • signals test, on upstream/main: 4 failed (the plain, latest(), isPending() and nested-ref cases), 4 passed. On the first, broader version of this fix, only the runWithOwner control fails.
  • web spec, with packages/signals rebuilt from upstream/main: 12 failed, 2 passed. With LOWER_SHOW=1: 11 failed, 3 passed, because a lowered <Show when={true}> compiles static and doesn't reproduce.

After the fix, all pass.

A throwaway probe beyond these, not committed: a server-streamed async memo under <Loading>, read in the ref alongside the written signal, hydrated with the stream either already loaded or arriving after hydration starts. On upstream/main it rebuilds the served node in both modes. With this change it keeps the node and calls the ref once. A ref in a <For> row doesn't reproduce on main, as the issue says, and is unchanged.

Commands, each with NODE_OPTIONS=--max-old-space-size=2048 and --maxWorkers=3:

command result
packages/signals: vitest run 574 files, 7297 passed, 17 expected fail, 2 skipped
packages/signals: node scripts/rules-index.mjs --check ok, RULES-INDEX.md current
packages/web: vitest run 330 files, 2042 passed, 6 expected fail, 1 skipped
packages/web: vitest run --config vite.config.server.mjs 236 files, 2223 passed, 3 expected fail, 3 skipped
packages/web: vitest run --config vite.config.hydrate.mjs 151 files, 807 passed, 7 expected fail, 3 skipped
packages/web: LOWER_SHOW=1 server, then hydrate (CI order) 236 files / 2223 passed; 150 files / 806 passed
packages/solid: vitest run 59 files, 942 passed
packages/signals: tsc -p tsconfig.build.json --noEmit clean
packages/web: pnpm run types, pnpm run test-types clean
prettier --check on changed files clean

Size

Measured locally on macOS with scripts/size (node size.mjs --json, then node gate.mjs head.json base.json) against upstream/main, with each signals build measured by the same harness. Minified growth:

  • 0 B on the signals-only, simple/CSR app floors, compiled floor, frames and server scenarios;
  • +12 B: both hydrating apps, the base page, the compiled base page, base + router;
  • +15 B: compiled CSR;
  • +24 B: the live page;
  • +28 B: compiled hydrating;
  • +34 B: live + router;
  • +62 B: the compiled live page. The first, broader version was already +40 B there.

Most of the cost is the save and restore of refOwner in runRefCallback. Against the first, broader version, narrowing the test to the ref's own owner costs +12 B on most scenarios (+16 B to +24 B on the live pages). Folding the old counter into refOwner already won back 8 B of that.

Gate locally: upstream/main is over its brotli cap on 3 scenarios (signals: + until/refresh, the base page and the live page). With this change, 3 scenarios are over cap: signals: + until/refresh (+0 B), page: base + router (+12 B minified over base) and page: live + router (+34 B). The base and live pages move back under their caps. The two router pages are already 86 B and 162 B past their recorded minified sizes on upstream/main locally, so they pass or fail on brotli layout alone. The local set is platform-specific, so CI may flag the router pages. If it does, that is real growth of the size above, and it needs a reviewed cap raise or a further cut.

Behaviour change

  • During hydration, a ref that reads a signal written earlier in the same claim (by an earlier ref, the component body, or itself) now gets one call on the served element with the snapshot value. Before, it got two calls on two elements. This matches 2.0.0-rc.21.
  • A client render is unchanged: the ref sees the current value. So the value a ref sees can still differ between hydrate (snapshot) and render (current), as it did in rc.21. The <For> row difference described in the issue is unchanged.

Public API changes

None. Internal to @solidjs/signals: the module-private refCallbackDepth counter is replaced by refOwner, which core.ts exports to verdict.ts. It isn't re-exported from the package entry. runRefCallback's signature and behaviour are unchanged.

The changeset (.changeset/hydration-ref-snapshot-read.md, @solidjs/signals patch) covers the whole PR. The follow-up commits don't add a second one, which would duplicate the changelog entry.

🤖 Generated with Claude Code

yumemi-thomas and others added 4 commits November 27, 2026 11:30
…solidjs#5232)

Since solidjs#4768 a compiled ref callback runs untracked in the creating pass's
context. During a hydration claim its read of a signal whose current value
differs from the snapshot marked that pass REACTIVE_SNAPSHOT_STALE, so
releasing the snapshot scope re-ran it: the served element was discarded,
a new one built, and the ref called a second time on it.

A ref's own untracked read (refCallbackDepth && !tracking) is still served
the snapshot but no longer marks the pass stale, in both the plain read
and the verdict-window read (latest/isPending). Untracked reads by the
pass itself, tracked reads and writes to tracked sources still replay it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ner (solidjs#5232)

`refCallbackDepth && !tracking` also covered untracked reads a ref makes
under another owner: a computation it parents with `runWithOwner` (the
allowed way to create one there) was served the snapshot and never marked,
so it kept the server's value after the snapshot was released. The
exemption now applies only to reads whose owner is the running ref's own
(`refOwner`, saved and restored by `runRefCallback`), in both read() and
the verdict window.

Tests: isPending() in a ref, a read after a nested ref under another owner,
a throwing ref, and the runWithOwner computation (fails on the previous
commit, passes on its parent).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…djs#5232)

`refOwner` is set for exactly as long as `refCallbackDepth` was > 0, so
the counter goes: the in-ref tests compare against a `0` sentinel instead.
-8 B minified on every hydrating scenario against the previous commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… Loading, Errored and Dynamic

Each case hydrates server markup (checked against renderToString in both
LOWER_SHOW modes) in which an earlier sibling's ref writes the signal the
target ref reads. All six rebuild the served node and call the ref twice
on upstream/main; with the fix the served node stays, the ref runs once,
and the spread's class binding still catches up to the client value.

The tracked-text case loses its "control:" prefix: it pins the single
ref call too, so it fails before the fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@changeset-bot

changeset-bot Bot commented Nov 27, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 62f386d

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 5 packages
Name Type
@solidjs/signals Patch
@solidjs/web Patch
@solidjs/diagnostics Patch
solid-js Patch
@solidjs/universal Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@codspeed

codspeed Bot commented Nov 27, 2026

Copy link
Copy Markdown

Merging this PR will improve performance by 8.11%

3 warnings

⚠️ Upgrade your CodSpeed plugin for Node.js 24

@codspeed/* 5.4.0 is only tested on Node.js 18, 20, and 22, so your Node.js 24 measurements may be inaccurate. Upgrade your @codspeed/* packages to 6.0.0 or later.

See affected benchmarks

⚠️ 1 benchmark is dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

⚠️ 2 benchmarks with a significant change ran on different hardware

Their base and head results were measured on machines with a different CPU, core count or memory, so the changes might not come from the code. Run base and head on the same runner type.

Learn more about Macro Runners

See affected benchmarks

⚡ 2 improved benchmarks
✅ 203 untouched benchmarks
⏩ 5 skipped benchmarks1

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ memo + sync render effect only (reference) 33.3 ms 30 ms +10.97%
⚡ selection map: toggle 2 of 1000 subscribed keys 3 ms 2.9 ms +5.34%

Tip

Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.


Comparing yumemi-thomas:fix/hydration-ref-snapshot-replay (62f386d) with main (3448597)

Open in CodSpeed

Footnotes

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

@ryansolid
ryansolid merged commit cc4b6cf into solidjs:main Nov 27, 2026
13 of 14 checks passed
ryansolid pushed a commit that referenced this pull request Nov 27, 2026
After #5221, #5225, #5228, #5235 and #5236, until/refresh, compiled base
server components, base + router and live + router sat 6-92 B brotli over
their caps. Caps move to CI's measure on main @ f7b6b9c + 10 B and recorded
minified resets to the measure. No floors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117BoWMR7ndYUnqBW5NjTbC
ryansolid added a commit that referenced this pull request Nov 27, 2026
…cenarios over their caps (#5241)

* fix(release): skip already-published packages in artifact verification

Since #4985, h, html and element version on their own, so a core release
leaves them at a version already on npm. verify-release-artifacts.mjs
dry-run-published every public package, and npm refuses even a dry run over
a published version, so the 2.0.1 release failed before publishing anything.
It now skips a published version the same way release.mjs does, with
packageIsPublished shared from release-packages.mjs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117BoWMR7ndYUnqBW5NjTbC

* fix(signals): a reader linked to a settled source no longer stays pending on it

retryReaches counted a dep that is the source itself as a path even after
that source settled, so settleFamily and the re-park sweep in recompute
kept a settled derive node in a reader's pending sources. With an
optimistic store over one async memo and a slower sibling memo whose
re-ask answers unchanged, the reader stayed pending and the action's
transaction never landed. A direct link now counts only while the source
is pending.

Claude-Session: https://claude.ai/code/session_01CP9T3j2CTCEPyTS2bcKsBu

* fix(web): send an empty revalidate declaration as a non-empty header

* fix(compiler): treat only a leading comment equal to the static marker as the marker

* fix(web): a server function's ReadableStream result stays a ReadableStream

The top-level abort wrapper for streamed results matched any async
iterable, so a decoded ReadableStream (which is one in Node and Chrome)
was replaced by a plain iterable and lost getReader/pipeTo/tee. Leave a
ReadableStream out of that check; it passes through as it already does
when nested. Test shape from #5175.

Co-authored-by: Marve10s <igrimanigroman@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117BoWMpyUtA1ZFwzKmr1sg

* fix(web): check getReader instead of instanceof ReadableStream

The instanceof check with its typeof guard cost +59 B minified on every
server-function page and put three page scenarios over their caps. A
decoded ReadableStream is told apart from an async generator's result by
its getReader method.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117BoWMpyUtA1ZFwzKmr1sg

* fix(web): write the empty revalidate header once; digest it to no keys

Send `,` in one header write when the joined keys are only whitespace,
and digest `X-Revalidate` with empty keys filtered, so an empty
declaration reads as `[]` on the outcome instead of `[""]` or
`["", ""]`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117BoWMR7ndYUnqBW5NjTbC

* fix(release): wait for the dispatched compiler binary run before watching it

The 2.0.4 publish stopped at `gh run watch`: `gh workflow run` printed
the new run's URL, and watching it one second later returned 404 because
the run was not readable yet. Poll `gh run view` until it resolves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117BoWMR7ndYUnqBW5NjTbC

* fix(release): poll the compiler binary run instead of gh run watch

The 2.0.4 re-run got past the run lookup, then `gh run watch` failed on
the run's jobs (HTTP 404) before GitHub had created them. Poll
`gh run view --json status,conclusion` until the run completes, retrying
failed reads, and check the conclusion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117BoWMR7ndYUnqBW5NjTbC

* fix(signals): a re-parked reader drops a pending source disposed while loading

The re-park prune in recompute kept any carried source still flagged
STATUS_PENDING, on the assumption that its own settle walk is still to
come. A source disposed while loading keeps that flag but never lands, so
no walk comes. When a reader parked on an async memo whose owner then
re-ran in the same hold, disposing it and creating a replacement that
failed, the reader stayed pending on the disposed memo: the hold never
landed and its staged error never reached the boundary. A disposed source
is now dropped whatever its status, as retryReaches and holdsOn already
treat a disposed node as holding nothing (F-3).

* chore(size): re-record the six scenarios over their caps on main

After the 11-24 fix batch and 2.0.4, six scenarios sat over their brotli
caps with 9-14 B of minified allowance left (warnings on main, but the
next ~10 B client fix would fail the gate). Caps move to CI's measure on
5420b4a + 10 B and recorded minified resets to the measure. No floors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117BoWMR7ndYUnqBW5NjTbC

* chore(signals): pin Sparkplug tiering in the signals bench lane

Same flag as the web server lane (#5157). In #5141's fork runs it took
the signals lane from one benchmark varying by more than 5% across
fresh runners to none, and #4906's omit ownKeys -63% reads 226k vs 235k
instructions pinned (673k vs 237k unpinned). Benchmark mode only: the
test suite runs in worker threads, which reject V8 flags in execArgv.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117BoWMR7ndYUnqBW5NjTbC

* chore(size): re-record the three scenarios over their caps on main

After #4906, #5209 and #5218, until/refresh, base server components and
live server components sat 5-15 B brotli over their caps, so the size gate
failed on every PR. Caps move to CI's measure on main @ 50a4bfd + 10 B and
recorded minified resets to the measure. The two page scenarios are frozen
floors (floor-caps.json).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117BoWMR7ndYUnqBW5NjTbC

* test(signals): gate the affects(list) holder test on a promise, not a 20 ms timer

The test checked the marks after three settle() ticks while the action
waited on a 20 ms timer. On a loaded CI machine the ticks can outlast the
timer, so the action landed first and the check saw [false, false, false]
(failed on #5230's CI). The action now waits on a gate the test releases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117BoWMR7ndYUnqBW5NjTbC

* chore(size): re-record the four scenarios over their caps on main

After #5221, #5225, #5228, #5235 and #5236, until/refresh, compiled base
server components, base + router and live + router sat 6-92 B brotli over
their caps. Caps move to CI's measure on main @ f7b6b9c + 10 B and recorded
minified resets to the measure. No floors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117BoWMR7ndYUnqBW5NjTbC

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: gnovotny <g.novotny@gmx.ch>
Co-authored-by: Marve10s <igrimanigroman@gmail.com>
Co-authored-by: gnovotny <990945+gnovotny@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants