Skip to content

Commit b722898

Browse files
ryansolidClaude via Cursorcursoragent
committed
fix(signals): lazily created companions and store keys carry the hold; every store channel answers like read() (#3336)
A `latest()` shadow or `isPending` companion created for a node whose write a live transaction already holds was backfilled through the ambient batch, so the backfill reverted at round end and the companion showed the committed value while its node was pending. `backfillCompanion` runs the backfill as the holding transaction's batch, where a companion that had existed at write time would have been placed. Stores: a key first read under a hold is born holding (`stageHeldKey` — committed value, the transaction's write staged), and the first tracked read serves the node's value rather than the backing. The backing-level visibility decision carries core read()'s committed clause (`heldFromReader`): while a live transaction holds the pending backing, a stale (render) reader and an owner-less reader see committed through every channel — untracked reads, `in`, `Object.keys`, `deep()`/`snapshot()`, the adoption-hold view — as the tracked read already did through the node. Non-stale owner-context readers keep speculation; a pending backing with no transaction keeps the snapshot peek. Pinned in tests/latest-held-till-flush.test.ts; SPEC A28 consequence (3), INTERNALS-ASYNC §4, INTERNALS-STORE invariants. Co-authored-by: Claude via Cursor <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent 304cacc commit b722898

7 files changed

Lines changed: 458 additions & 28 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solidjs/signals": patch
3+
---
4+
5+
A lazily created `latest()`/`isPending()` companion answers as if it had always existed (#3336). Its backfill is now the write of the transaction holding the owner's staged value rather than of the ambient window the creating read runs in — previously the override registered in a render effect's batch and reverted at that flush's end, so `latest(a)` fell back to committed and `isPending(a)` flipped false while the action still held the write, and two identical cells disagreed depending on whether some other reader had created a companion before the hold. One level down, a store key first read under a hold is born holding: the node takes the committed value with the held write staged as the holding transaction's, so a plain read of a never-before-observed key no longer leaks the held write while an observed sibling stays committed. Every other store read channel now answers the same way: untracked reads inside a render effect, `in`, `Object.keys`, `deep()` and `snapshot()` see committed while a live transaction holds the backing, exactly as core `read()` serves a stale reader of a foreign transaction's write — previously those channels served the pending backing to any owner-context reader.

‎packages/signals/docs/INTERNALS-ASYNC-STATE.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ Every path that produces a value for a node must maintain the companions via
6868
1. `setSignal` — direct write (line ~1033).
6969
2. `asyncWrite` — async resolution, four branches: setter / override-active / lane-routed / plain `setSignal` fallback.
7070
3. `recompute` — transition-held sync derivation (line ~334, `activeTransition || el._transition` guard).
71+
4. Companion creation — `getLatestValueComputed` / `getPendingSignal` backfill a companion created after the owner's state was already produced (`backfillCompanion`). The backfill is the write of the transaction holding that state (`runAsTransitionBatch(el._transition, …)`), not of the ambient window the creating read runs in: written ambiently, the override registered in the reader's batch and reverted at that flush's round end while the hold was still on (#3336). A hold with no transaction stays ambient.
7172

7273
Comparator (`_equals`) errors on any of these paths are node errors, routed
7374
through `notifyStatus(STATUS_ERROR)` `[ruled — #2837]`. `setSignal` checks

‎packages/signals/docs/INTERNALS-STORE-STATE.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,29 @@ there is nothing to diff.)
170170
record until flush commit — carries no subscriptions, discarded at fold.)
171171
- **(high)** A node is created by: first tracked read, first has/keys tracking,
172172
any transition/optimistic write, projection write to an observed property.
173+
- **(high)** A data node created while the target's pending backing is held
174+
by a live transaction (the #3089 `foldBatches` stamp; plain and projection
175+
families, outside the draft) is born as if it had always existed: committed
176+
value, the backing's value staged as that transaction's write
177+
(`stageHeldKey` — transition-stamped, no subscriber walk, not `UNFLUSHED`:
178+
the write already flushed with its setter). The first tracked read serves
179+
through the node like every later read, so whether a key was materialized
180+
before the hold is unobservable (#3336). Optimistic families hold at the
181+
backing instead (`heldTruthMasked`) and are excluded.
182+
- **(high)** The backing-level visibility decision carries core read()'s
183+
committed clause (`(stale && el._transition !== null && activeTransition !== el._transition) → _value`):
184+
while a live FOREIGN transaction holds the pending backing
185+
(`liveFoldTransition`, `foreignHold`), a stale (render) reader and an
186+
owner-less reader see committed through every channel — untracked reads,
187+
`in`, `Object.keys`, `deep()`/`snapshot()`, the adoption hold view
188+
(`heldFromReader`; `readSource`, `pendingBackingVisible`, `nodeValue`). A
189+
stale reader the holding transaction itself recomputes (its run is the
190+
transaction's to apply) sees the staged world, as it sees `_pendingValue`
191+
in core — otherwise it composes its view, and its deep() subscriptions,
192+
from the pre-hold backing and never re-derives at the silent commit.
193+
Non-stale owner-context readers keep speculation, as in core; a pending
194+
backing with no transaction (same-tick plain write) keeps the snapshot
195+
peek (#3336).
173196
- **(high)** After every flush with no active lanes: for every materialized
174197
node, node's committed view === raw value (single-home coherence).
175198
- **(medium)** Disposal of a store tears down only materialized nodes

‎packages/signals/docs/SPEC-ASYNC-SEMANTICS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ optimistic lanes.
4545

4646
| A26 | (**ruled 2026-07-17**, #2913; **enforcement hardened 2026-08-31**, #3141 — parking is flush-driven, and a transaction opened with no writes before its first suspension scheduled no flush, so `activeTransition` stayed ambient across the await window and captured exactly the unrelated work this ruling rejects: an optimistic store's authoritative landing on a still-live lane was adopted and held until the stranger action settled. `initTransition` now guarantees a flush, so the ambient window closes one flush later regardless of whether the transaction wrote anything) **`yield` is an action's only transaction-safe suspension point; internal `await` continuations run outside the transaction by platform necessity.** The driver regains control exclusively at yield boundaries (`it.next()` resumes the body synchronously, so `restoreTransition` wraps the segment); a post-`await` continuation is a bare promise job the runtime cannot hook — JavaScript has no ambient async context (TC39 AsyncContext, unshipped), and holding `activeTransition` open across the await window was rejected as strictly worse: unrelated ambient writes interleaving during `await fetch()` (a user click, a timer) would be captured into the action's transaction and held until it settles. Consequences, all accepted: (1) a write to a **fresh** signal between an `await` and the next `yield` escapes and commits ambiently; (2) a signal **already written under the transaction** rejoins it even after an `await` (its `_transition` stamp routes the write back) — containment is write-history-dependent by design, not by accident; (3) the supported idiom is `await` for typed results, then a **bare `yield` before any writes** — re-entry is what `yield` is for, and TypeScript ergonomics are exactly why `await` stays welcome (yield results are untyped; awaited results are typed); (4) calling public `flush()` inside an action body is out of contract — it drains and stashes the transaction mid-step, stranding later same-segment writes; follow the idiom and there is nothing to flush for. The doc block on `action()` teaches the idiom. | maintainer ruling 2026-07-17 ("2913 is not addressable… it is a known thing and it isn't detectable, otherwise we'd have a different solution"; "one reason to not yield the promise is TypeScript — we are set up so you can await typed results and then yield nothing the next line"; flush-in-body ruled out of contract: "if they follow that they shouldn't be flushing there") | `tests/action-await-contract.test.ts` (documented escape, the await-then-bare-yield idiom, yield-the-promise alternative, pre-await stamp rejoin); `tests/store/optimistic-ambient-capture.test.ts` (#3141 — the ambient window closes in one flush even for a writeless transaction) |
4747
| A27 | (**ruled 2026-08-10**) **The commit-#0 loading window is loading-class and verdict-quiet.** A node born committed via `loadingValue` (memos: `createMemo` / `createSignal(fn)` / `createOptimistic(fn)`) or `seedLoadingValue` (projections: `createProjection` / `createStore(fn)` / `createOptimisticStore(fn)`) starts with the loading value as commit #0 of its lineage instead of `STATUS_UNINITIALIZED`. While its first real answer is in flight, the window is loading-class on every axis: (1) **reads** — every consumer path serves commit #0 (no `NotReadyError`, no Loading-boundary suspension; `latest()` and `resolve()` return it; it is the compute's first `prev`); (2) **transitions** — the window never initiates or extends one (matching boundary-fallback semantics): ambient writes concurrent with the window commit immediately rather than being held, and a loading node mounted inside a live transition does not add to what that transition waits for; (3) **verdict** — `isPending` reads false at the source, upstream, and downstream, in both forms. The quiet ruling is not an exception to A19 but its question scoping applied: commit #0 answers the question **by declaration**, so the first flight is re-ask-shaped — the shown answer still answers the question (A24 family). The alternative was rejected as structurally unavailable: genuine pending is chain-shaped (the shadow of a held commit — held write upstream, in-flight async at the node, propagated non-finality downstream), and the window has no held commit to shadow, so a true verdict could only exist as a point anomaly at the probed node while upstream and downstream read false — and making it propagate would reintroduce exactly the status machinery the window exists to silence (and re-open the server/client split: `isPending` is always false on the server). First-load affordances are therefore the **value channel**'s job — the author encodes provenance (`null`, a `skeleton` flag) into the loading value itself — and `data.skeleton || isPending(data)` covers the two disjoint states. The window closes at the first real landing on any path (sync return, sync-resolved thenable, first iterator yield, async settle); a real error answers reads but does not close it — a retry serves commit #0 again. After close, A19 applies unchanged: refetches are pending-class forever. A25 is unchanged for plain seeds: without `seedLoadingValue` a derived store's seed remains an unobservable draft; `seedLoadingValue` is precisely the author promoting the seed to commit #0 — observable by declaration. | maintainer ruling 2026-08-10 ("the reason I had skeleton or isPending is because isPending would be false in my mind"; "it was false both upstream and downstream") | `tests/loading-value.test.ts` |
48-
| A28 | (**ruled 2026-09-08**; supersedes the #2922 mid-tick pull) **A write becomes visible at flush — to every channel.** Between `set(x)` and the next `flush()` the write is _unflushed_: it is not the committed value, not the staged value `latest()`/`isPending()` serve, and not an input to any recompute. `latest(x)` reads the **flushed staged world** — the newest value a flush has processed and no held lane withholds — so `setCount(30); latest(count)` is the pre-write answer until the flush that carries the write, after which `latest(count)` is 30 and `latest(doubled)` is 60 in the same instant (the derivation flushed with it). Nothing is ever 30 while its derivations are still 20-shaped: there is no "read your own write" channel that bypasses the flush, because no channel can show downstream of an unflushed write, and a channel that shows the write alone tears against every derivation. Consequences: (1) `latest` is one rule regardless of reader — event handler, memo, prop getter — so wrapping a `latest` read in a memo does not change what it answers (the visibility mismatch that motivated a separate `readStaged` does not arise); (2) `isPending(x)` is false for an unflushed write (nothing is observable yet to be pending _from_); (3) a companion created lazily after several flushes needs no retained history — the flushed staged value is the only answer it could ever have given; (4) `flush()` is the boundary, so the imperative idiom is `set(x); flush(); latest(x)`, and within a recompute or a flush every write issued is promoted at the end of that recompute/round so the graph never runs a round against a value it wrote but cannot see. Mechanically, writes take one path: stage + mark unflushed + schedule; consumers (`flush`, `recompute`) promote — clear the mark, restore the last-flushed staged view, sync companions, walk subscribers. There is no eager path. | maintainer ruling 2026-09-08 ("since we can't derive downstream before flush happens I do like latest being invisible until flush"; "nothing should be 30 pre flush… because double count can't be 60"; "latest opts into the tearing but really only after a flush") | `tests/latest-held-till-flush.test.ts`; `tests/latest-repeated-writes.test.ts` (#2922 re-pinned); `tests/latest-unobserved-memo.test.ts`; `tests/latest-probe-order-independence.test.ts`; `tests/isPending-memo-consistency.test.ts`; `tests/store/projection-transition-isolation.test.ts` |
48+
| A28 | (**ruled 2026-09-08**; supersedes the #2922 mid-tick pull) **A write becomes visible at flush — to every channel.** Between `set(x)` and the next `flush()` the write is _unflushed_: it is not the committed value, not the staged value `latest()`/`isPending()` serve, and not an input to any recompute. `latest(x)` reads the **flushed staged world** — the newest value a flush has processed and no held lane withholds — so `setCount(30); latest(count)` is the pre-write answer until the flush that carries the write, after which `latest(count)` is 30 and `latest(doubled)` is 60 in the same instant (the derivation flushed with it). Nothing is ever 30 while its derivations are still 20-shaped: there is no "read your own write" channel that bypasses the flush, because no channel can show downstream of an unflushed write, and a channel that shows the write alone tears against every derivation. Consequences: (1) `latest` is one rule regardless of reader — event handler, memo, prop getter — so wrapping a `latest` read in a memo does not change what it answers (the visibility mismatch that motivated a separate `readStaged` does not arise); (2) `isPending(x)` is false for an unflushed write (nothing is observable yet to be pending _from_); (3) a companion created lazily after several flushes needs no retained history — the flushed staged value is the only answer it could ever have given — and it answers **as if it had always existed** (#3336): its backfill is the write of the transaction _holding_ that value, not of the ambient window the reader happens to run in, so it lives and reverts with the hold instead of reverting at the reader's flush end; the same one level down for a store key first read under a hold — the node is born with the committed value and the held write staged as the holding transaction's, so plain reads and `latest()` answer for an unobserved key exactly as they do for one some other reader had materialized before the hold; (4) `flush()` is the boundary, so the imperative idiom is `set(x); flush(); latest(x)`, and within a recompute or a flush every write issued is promoted at the end of that recompute/round so the graph never runs a round against a value it wrote but cannot see. Mechanically, writes take one path: stage + mark unflushed + schedule; consumers (`flush`, `recompute`) promote — clear the mark, restore the last-flushed staged view, sync companions, walk subscribers. There is no eager path. | maintainer ruling 2026-09-08 ("since we can't derive downstream before flush happens I do like latest being invisible until flush"; "nothing should be 30 pre flush… because double count can't be 60"; "latest opts into the tearing but really only after a flush") | `tests/latest-held-till-flush.test.ts`; `tests/latest-repeated-writes.test.ts` (#2922 re-pinned); `tests/latest-unobserved-memo.test.ts`; `tests/latest-probe-order-independence.test.ts`; `tests/isPending-memo-consistency.test.ts`; `tests/store/projection-transition-isolation.test.ts` |
4949

5050
## Tier B (inferred — needs verdict)
5151

‎packages/signals/src/core/verdict.ts‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ import {
5252
dirtyQueue,
5353
GlobalQueue,
5454
insertSubs,
55+
runAsTransitionBatch,
5556
schedule,
5657
zombieQueue,
5758
type Transition
@@ -107,12 +108,38 @@ function getPendingSignal(el: Signal<any> | Computed<any>): Signal<boolean> {
107108
el._config |= CONFIG_HAS_COMPANIONS;
108109
markFirewallChildCompanions(el);
109110
ext(ps)._parentSource = el;
110-
if (computePendingState(el)) setSignal(ps, true);
111+
if (computePendingState(el)) backfillCompanion(el, ps, true);
111112
if (__DEV__) devTrackCompanionOwner(el);
112113
}
113114
return ps;
114115
}
115116

117+
/**
118+
* A lazily created companion's first write mirrors state the owner already
119+
* carries — a held write, a pending verdict. The companion is created
120+
* wherever the first latest()/isPending() read happens to run, but the write
121+
* belongs to whatever HOLDS that state: written in the ambient window (a
122+
* mainline render effect's flush), the override would register in the ambient
123+
* batch and revert when that flush's round ends — the shadow re-derived from
124+
* the committed view, the verdict flipped false — while the owner's hold was
125+
* still on (#3336: "spooky action at a distance", A and B differing only in
126+
* whether a companion existed before the hold). A companion created lazily
127+
* must answer as if it had always existed: its backfill is registered with the
128+
* owner's transaction, exactly where the sync path (syncCompanions at the
129+
* transaction's flush) would have put it, and lives and reverts with it. A
130+
* hold with no transaction (a pending async, a same-flush staged write) is
131+
* ambient and the write stays ambient.
132+
*/
133+
function backfillCompanion(
134+
el: Signal<any> | Computed<any>,
135+
companion: Signal<any> | Computed<any>,
136+
value: unknown
137+
): void {
138+
const transition = el._transition;
139+
if (transition) runAsTransitionBatch(transition, () => setSignal(companion, value));
140+
else setSignal(companion, value);
141+
}
142+
116143
function collectPendingSources(el: Signal<any> | Computed<any>): void {
117144
if (!pendingProbe) return;
118145
pendingProbe.sources.add(el);
@@ -383,7 +410,7 @@ function getLatestValueComputed<T>(el: Signal<T> | Computed<T>): Computed<T> {
383410
// FLUSHED staged value: an unflushed rewrite is not yet anyone's world,
384411
// and the flush that processes it pushes it here (promoteUnflushed).
385412
const staged = flushedStaged(el);
386-
if (staged !== NOT_PENDING && !hasActiveOverride(el)) setSignal(lvc, staged as T);
413+
if (staged !== NOT_PENDING && !hasActiveOverride(el)) backfillCompanion(el, lvc, staged);
387414
if (__DEV__) devTrackCompanionOwner(el);
388415
setContextInternal(prevContext);
389416
setPendingCheckActive(prevCheck);

0 commit comments

Comments
 (0)