Skip to content

Commit 0be1f6d

Browse files
ryansolidClaude via Cursor
andcommitted
fix(signals): a projection run's own draft writes arm the flush they withheld (#3585 follow-on)
A derive body only runs outside a flush at creation. Its own draft writes made schedule() withhold the microtask (projectionWriteActive) and, for a sync derive, nothing ever re-armed it: a projection created in a top-level createRoot left `scheduled` set with no microtask, so its root's effects and every unrelated write anywhere waited for an explicit flush(). Pre-existing on `next`; fixed here in the same mechanism as the late-write arming by dropping the run-returned gate on scheduleWithheld. Arming mid-body is safe: the microtask fires after the synchronous slice, when the body has returned or parked, and an initial async run's pre-await half drains before its landing exactly as it already does when the creation ran inside a flush — nothing reads it before the landing (the node is uninitialized, proj R23). Reruns are flush-driven, so the withhold never applies to them. Pinned: sync top-level projection no longer strands; an async one with a pre-await write no longer holds unrelated work until its landing, and the landing still reveals both halves together. Size: -13 B minified in projection.js; `every store family` brotli moved +105 on that removal (layout), cap 31.0 -> 31.1 KB with audit note; re-measured against the rebased `next`. Co-authored-by: Claude via Cursor <[email protected]>
1 parent cb20ea2 commit 0be1f6d

6 files changed

Lines changed: 121 additions & 22 deletions

File tree

‎.changeset/projection-draft-valid-until-superseded.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
"@solidjs/signals": patch
33
---
44

5-
Behavior change: a `createProjection` / `createStore(fn, seed)` / `createOptimisticStore(fn)` draft now stays valid until it is superseded by the next run of the derive or its owner is disposed — no longer "until no longer in flight" (#3585). A subscription set up inside a sync derive can write through the draft from its callback without the never-resolving-Promise workaround; the write applies, notifies subscribers, and arms the flush itself when no async run is in flight to do so (the scheduler used to strand on such writes). Writes through a superseded or disposed draft are dropped silently, so a previous run's leaked callback can no longer write into the current run's state (it did before, whenever nothing had read the projection yet).
5+
Behavior change: a `createProjection` / `createStore(fn, seed)` / `createOptimisticStore(fn)` draft now stays valid until it is superseded by the next run of the derive or its owner is disposed — no longer "until no longer in flight" (#3585). A subscription set up inside a sync derive can write through the draft from its callback without the never-resolving-Promise workaround; the write applies, notifies subscribers, and arms the flush itself when no async run is in flight to do so (the scheduler used to strand on such writes). Also fixes the pre-existing strand where a sync projection created in a top-level `createRoot` outside any flush left the scheduler armed with no microtask — its effects and every unrelated write waited for an explicit `flush()`. Writes through a superseded or disposed draft are dropped silently, so a previous run's leaked callback can no longer write into the current run's state (it did before, whenever nothing had read the projection yet).

‎packages/signals/docs/RULES-INDEX.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ Status legend: **live** stated and standing · **ruled** carries an explicit rul
178178
| CS-R34 | live | `docs/rules-mining/core-store.md:151` | store.ts×1 | visibility-oracle-store.states.ts×1 | ~~Optimistic writes visible immediately at write time (before flush)~~, never touch base raw; ambient (non-action) optimistic writes auto-revert at flush end.** _Visibility superseded 2026-09-10 by A2… |
179179
| CS-R35 | live | `docs/rules-mining/core-store.md:156` | — | — | Mid-refetch optimistic overlays are consumed when data lands — identical via direct reads, mapArray, wrapper views, Object.keys, snapshot.** |
180180
| CS-R36 | live | `docs/rules-mining/core-store.md:160` | — | — | An active optimistic hold on a wrapper view masks inner-store changes for the view's subscribers: mid-hold inner refresh landing causes ZERO re-runs of the view's structural subscribers; the reveal re… |
181-
| CS-R37 | live | `docs/rules-mining/core-store.md:165` | — | createProjection.draft-lifetime-3585.test.ts×1 visibility-oracle-store.states.ts×3 | Setting store state from effect callbacks and promise resolutions works, applying next flush.** |
181+
| CS-R37 | live | `docs/rules-mining/core-store.md:165` | — | visibility-oracle-store.states.ts×3 | Setting store state from effect callbacks and promise resolutions works, applying next flush.** |
182182
| CS-R38 | live | `docs/rules-mining/core-store.md:171` | — | — | Shallow stores: root keys reactive (per-key nodes, membership, length), values served raw by identity at every depth, arrays and objects.** |
183183
| CS-R39 | live | `docs/rules-mining/core-store.md:175` | — | visibility-oracle-store.states.ts×1 | Shallow setter-scope reads serve raws; in-place mutation of a served raw is reactively inert — records replaced, never edited.** |
184184
| CS-R40 | live | `docs/rules-mining/core-store.md:179` | — | — | Shallow reconcile is positional: per-index effects only where the reference changed; reference-identical rows skip entirely; length propagates; `key` option moot.** Aligned: unowned-reference skip rul… |
@@ -317,7 +317,7 @@ Status legend: **live** stated and standing · **ruled** carries an explicit rul
317317
| PJ-R20 | live | `docs/rules-mining/projections.md:70` | — | — | Chained backing works for array roots** (structural + row-level edits flow). |
318318
| PJ-R21 | live | `docs/rules-mining/projections.md:72` | — | — | `createStore(fn, seed)` is the same projection mechanism and chains identically.** |
319319
| PJ-R22 | live | `docs/rules-mining/projections.md:74` | — | — | `snapshot()` of a chained projection returns plain data equal to the current view and detached from future source writes.** |
320-
| PJ-R23 | live | `docs/rules-mining/projections.md:80` | store.ts×2 | createProjection.draft-lifetime-3585.test.ts×1 | The seed is a draft for the derive, never observable (#2897)**: until first settle/yield, every read — tracked, untracked, enumeration/spread — throws NotReadyError. |
320+
| PJ-R23 | live | `docs/rules-mining/projections.md:80` | projection.ts×1 store.ts×2 | createProjection.draft-lifetime-3585.test.ts×1 | The seed is a draft for the derive, never observable (#2897)**: until first settle/yield, every read — tracked, untracked, enumeration/spread — throws NotReadyError. |
321321
| PJ-R24 | live | `docs/rules-mining/projections.md:83` | — | — | Draft writes during an in-flight async run are invisible until that run settles** (per-run atomic visibility). |
322322
| PJ-R25 | live | `docs/rules-mining/projections.md:86` | — | — | Async generators publish one snapshot per yield**: bare `yield` publishes accumulated draft mutations; `yield value` replaces the entire state (no merge); each yield transforms again. |
323323
| PJ-R26 | live | `docs/rules-mining/projections.md:88` | projection.ts×1 | createProjection.draft-lifetime-3585.test.ts×1 | Latest-run-wins supersession**: superseded runs' later yields and pending draft writes are discarded entirely; if no run ever landed, stays NotReady. |
@@ -331,7 +331,7 @@ Status legend: **live** stated and standing · **ruled** carries an explicit rul
331331
| PJ-R34 | live | `docs/rules-mining/projections.md:104` | — | — | Errored derives follow async memo rules**: after rejection ALL readers (settle-time, late tracked, untracked) throw the error (StatusError-wrapped; boundaries unwrap). Seed never served uninitialized;… |
332332
| PJ-R35 | live | `docs/rules-mining/projections.md:107` | — | — | A genuine tracked read on a later cycle retries an errored derive** (memo parity: never untracked, never inside isPending probe, at most once per cycle); successful retry serves fresh value. |
333333
| PJ-R36 | live | `docs/rules-mining/projections.md:111` | — | — | Disposing the owning root stops the projection** (no recomputes, no notifications afterward). |
334-
| PJ-R37 | ruled | `docs/rules-mining/projections.md:113` | scheduler.ts×2 projection.ts×3 target.ts×1 | createProjection.draft-lifetime-3585.test.ts×1 | A draft is valid from the start of its run until it is superseded or its owner is disposed — not "until no longer in flight" (#3585, ruled 2026-09-22).** The draft handed to a run stays writable after… |
334+
| PJ-R37 | ruled | `docs/rules-mining/projections.md:113` | scheduler.ts×2 projection.ts×3 target.ts×1 | createProjection.draft-lifetime-3585.test.ts×3 | A draft is valid from the start of its run until it is superseded or its owner is disposed — not "until no longer in flight" (#3585, ruled 2026-09-22).** The draft handed to a run stays writable after… |
335335
## R — reconcile-snapshot (`RS-R<n>`)
336336

337337
| id | status | defined | cited in src | cited in tests | statement (at definition) |

‎packages/signals/docs/rules-mining/projections.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ Source suites: `sync` = `tests/store/createProjection.test.ts`, `async` = `tests
111111
**R36 — Disposing the owning root stops the projection** (no recomputes, no notifications afterward).
112112

113113
**R37 — A draft is valid from the start of its run until it is superseded or its owner is disposed — not "until no longer in flight" (#3585, ruled 2026-09-22).** The draft handed to a run stays writable after the derive returns — sync or async, whatever it returned — until (a) the NEXT run of the derive starts (including a run that throws NotReady or is parked on an `await`; latest-run-wins, R26), or (b) the projection's owner is disposed. This is the contract behind `createProjection(draft => { subscribe(id, item => draft.push(item)); onCleanup(unsubscribe) })` working without a never-resolving-Promise workaround; it applies equally to `createStore(fn, seed)` and `createOptimisticStore(fn)` drafts.
114-
- Late writes take the authoritative override channel (pending-backing write, per-op notification, fold at the next flush). When no flight is up to drain them at its landing, the write arms the drain itself (`scheduleWithheld`) — `schedule()` withholds its microtask under projectionWriteActive precisely because a landing normally follows, and a drain BEFORE the landing tears the run's pre- and post-`await` halves apart (async "notifies only changed paths", spec A22). A late write inside an `action` is stamped to that transaction and commits atomically with it.
114+
- Late writes take the authoritative override channel (pending-backing write, per-op notification, fold at the next flush). When no flight is up to drain them at its landing, the write arms the drain itself (`scheduleWithheld`) — `schedule()` withholds its microtask under projectionWriteActive precisely because a landing normally follows, and a drain BEFORE the landing tears the run's pre- and post-`await` halves apart (async "notifies only changed paths", spec A22). The run's own writes arm the same way: a derive body only runs outside a flush at creation, and a sync projection created in a top-level `createRoot` used to leave `scheduled` set with no microtask — its root's effects and every unrelated write stranded until an explicit `flush()` (pre-existing, fixed with R37). A late write inside an `action` is stamped to that transaction and commits atomically with it.
115115
- A write to a superseded or disposed draft is dropped silently — same fate as a superseded async run's pending draft writes (R26); no diagnostic (a stale `.then` continuation landing after supersession is the ordinary latest-run-wins race, not an authoring error).
116116
- Carve-out: a loading-window run (`seedLoadingValue`) works a detached shadow of the seed, not the draft (#2988). A callback that closes over the shadow writes into a dead clone once the window has closed (first commit). Ruled acceptable for now; a redirecting shadow would remove the carve-out.
117117
- The pre-R37 gate (`!settled || owner._x?._inFlight === result`) was timing-dependent: a sync derive's `undefined` result equalled a never-installed `_x`'s `undefined` `_inFlight`, so the "dead" draft was live exactly while nothing had read the projection, and a superseded run's leaked callback kept writing into the NEXT run's state. Nothing pinned it.

‎packages/signals/src/store/next/projection.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,6 @@ export function runProjectionComputedNext<T extends object>(
259259
// (`owner._x?._inFlight === result`) only admitted it by accident — while
260260
// nothing had read the projection yet (no `_x`), `undefined === undefined`.
261261
const run = (fam.run = (fam.run || 0) + 1);
262-
let settled = false;
263262
let result: void | T | Promise<void | T> | AsyncIterable<void | T>;
264263
// Open loading window (seedLoadingValue): the observable store IS commit #0
265264
// for the whole first flight — the derive works a detached shadow of the
@@ -277,15 +276,23 @@ export function runProjectionComputedNext<T extends object>(
277276
// backing + per-op notify + fold) and arms the drain itself when no
278277
// landing will: a flight still up — pending, or the loading window's
279278
// first flight — drains at its landing, and must not be drained early.
279+
// Not gated on the run having returned: the body's own writes withhold
280+
// the microtask too, and a derive body only ever runs outside a flush at
281+
// creation (reruns are flush-driven) — a top-level sync projection in a
282+
// createRoot stranded the scheduler until an explicit flush(). Arming
283+
// mid-body is safe: the microtask fires after this synchronous slice,
284+
// when the body has returned or parked, and an initial async run's
285+
// pre-await half drains before its landing exactly as it does when the
286+
// creation ran inside a flush — nothing reads it before the landing
287+
// (the node is uninitialized, proj R23).
280288
() => {
281-
if (settled && !(owner._statusFlags & STATUS_PENDING) && !owner._loading) scheduleWithheld();
289+
if (!(owner._statusFlags & STATUS_PENDING) && !owner._loading) scheduleWithheld();
282290
}
283291
);
284292
storeSetterNext(
285293
draft,
286294
s => {
287295
result = fn((shadow ?? s) as T);
288-
settled = true;
289296
const commit = (v: void | T) => {
290297
// Shadow run: commit a detached snapshot, never the shadow itself
291298
// (adoption takes the value by identity — handing it the live shadow

‎packages/signals/tests/createProjection.draft-lifetime-3585.test.ts‎

Lines changed: 87 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -581,7 +581,7 @@ describe("#3585 draft lifetime: valid until superseded or disposed", () => {
581581
});
582582
});
583583

584-
describe("seedLoadingValue carve-out (ruled with R37)", () => {
584+
describe("seedLoadingValue carve-out (ruled with proj R37)", () => {
585585
it("a loading-window run works a detached shadow; a late write to it after the first commit is lost", async () => {
586586
// The one place the one-draft-per-run model does not hold: in the open
587587
// loading window the derive receives a detached clone of the seed (the
@@ -615,4 +615,90 @@ describe("#3585 draft lifetime: valid until superseded or disposed", () => {
615615
dispose();
616616
});
617617
});
618+
619+
describe("a run's own writes do not strand the scheduler", () => {
620+
// Pre-existing (on `next` before proj R37), fixed in the same mechanism: a
621+
// derive run OUTSIDE any flush — a projection created in a top-level
622+
// createRoot — made schedule() withhold its microtask for its own draft
623+
// writes (projectionWriteActive), then returned with no landing to drain
624+
// them. `scheduled` stayed set with no microtask, so every later
625+
// schedule() early-returned: the root's own effects, and any unrelated
626+
// effect or write anywhere, waited for an explicit flush().
627+
it("a sync projection created in a top-level root outside any flush leaves the scheduler armed", async () => {
628+
let proj!: { x: number };
629+
const seenX: number[] = [];
630+
const dispose = createRoot(dispose => {
631+
proj = createProjection<{ x: number }>(
632+
draft => {
633+
draft.x = 1;
634+
},
635+
{ x: 0 }
636+
);
637+
createEffect(
638+
() => proj.x,
639+
x => {
640+
seenX.push(x);
641+
}
642+
);
643+
return dispose;
644+
});
645+
// No explicit flush anywhere in this test.
646+
const [s, setS] = createSignal(0);
647+
const seenS: number[] = [];
648+
const dispose2 = createRoot(dispose => {
649+
createEffect(s, v => void seenS.push(v));
650+
return dispose;
651+
});
652+
await tick();
653+
expect(seenX).toEqual([1]);
654+
expect(seenS).toEqual([0]);
655+
setS(1);
656+
await tick();
657+
expect(seenS).toEqual([0, 1]);
658+
dispose();
659+
dispose2();
660+
});
661+
662+
it("an async projection with a pre-await write, created outside any flush, does not strand unrelated work until its landing", async () => {
663+
let release!: () => void;
664+
let proj!: { a: number; b: number };
665+
const seen: Array<[number, number]> = [];
666+
const dispose = createRoot(dispose => {
667+
proj = createProjection<{ a: number; b: number }>(
668+
async draft => {
669+
draft.a = 1;
670+
await new Promise<void>(r => (release = r));
671+
draft.b = 1;
672+
},
673+
{ a: 0, b: 0 }
674+
);
675+
createEffect(
676+
() => [proj.a, proj.b] as [number, number],
677+
v => {
678+
seen.push(v);
679+
}
680+
);
681+
return dispose;
682+
});
683+
const [s, setS] = createSignal(0);
684+
const seenS: number[] = [];
685+
const dispose2 = createRoot(dispose => {
686+
createEffect(s, v => void seenS.push(v));
687+
return dispose;
688+
});
689+
await tick();
690+
// The flight is still up; unrelated work is not held behind it.
691+
expect(seenS).toEqual([0]);
692+
setS(1);
693+
await tick();
694+
expect(seenS).toEqual([0, 1]);
695+
// The projection's first landing still reveals both halves together.
696+
expect(seen).toEqual([]);
697+
release();
698+
for (let i = 0; i < 6; i++) await tick();
699+
expect(seen).toEqual([[1, 1]]);
700+
dispose();
701+
dispose2();
702+
});
703+
});
618704
});

‎scripts/size/.size-limit.js‎

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -654,14 +654,17 @@ module.exports = [
654654
// signals core, see the core floor note); the rest is mangler/brotli
655655
// layout. 0 B in the store.
656656
// Draft valid until superseded or disposed (#3585, proj R37,
657-
// 2026-09-22): 16,912 B against `next`'s 16,880 (+32 B; 38 B under the
657+
// 2026-09-22): 16,921 B against `next`'s 16,908 (+13 B; 29 B under the
658658
// cap, which is unchanged). Core: `schedule()` records the microtask it
659659
// withholds under projectionWriteActive and `scheduleWithheld` re-arms
660660
// it (+83 B minified in the scheduler). Store: the per-run token on the
661661
// family, `isDisposed(owner)` in the draft gate, and the after-write
662662
// arming closure, paid for by folding the three mutating draft traps
663-
// onto one bracket (-10 B minified in projection.js). The core floor
664-
// does not retain `scheduleWithheld` (-5 B, layout).
663+
// onto one bracket and dropping the run-returned gate on the arming
664+
// (the derive body only runs outside a flush at creation, and a
665+
// top-level sync projection stranded the scheduler behind it): -23 B
666+
// minified in projection.js. The core floor does not retain
667+
// `scheduleWithheld` (+8 B, layout).
665668
limit: "16.95 KB",
666669
modifyEsbuildConfig
667670
},
@@ -1431,16 +1434,19 @@ module.exports = [
14311434
// signals core, see the core floor note); the rest is mangler/brotli
14321435
// layout. 0 B in the store engine, solid, or web.
14331436
// Draft valid until superseded or disposed (#3585, proj R37,
1434-
// 2026-09-22): 30.95 -> 31.0 KB, measured at 30,978 B against `next`'s
1435-
// 30,905 (+73 B). Core: `schedule()` records the microtask it withholds
1436-
// under projectionWriteActive and `scheduleWithheld` re-arms it (+83 B
1437-
// minified in the scheduler — the one place the guard lives). Store:
1438-
// the per-run token on the family, `isDisposed(owner)` in the draft
1439-
// gate, and the after-write arming closure, paid for by folding the
1440-
// three mutating draft traps onto one bracket (-10 B minified in
1441-
// projection.js). The rest is brotli layout over the larger bundle
1442-
// (+ createStore, which retains the same bytes, moved +32 B).
1443-
limit: "31.0 KB",
1437+
// 2026-09-22): 30.95 -> 31.1 KB, measured at 31,058 B against `next`'s
1438+
// 30,901 (+157 B). Real bytes are +60 minified: `schedule()` records
1439+
// the microtask it withholds under projectionWriteActive and
1440+
// `scheduleWithheld` re-arms it (+83 B in the scheduler — the one place
1441+
// the guard lives); the store's per-run token, `isDisposed(owner)` in
1442+
// the draft gate and the after-write arming closure are paid for by
1443+
// folding the three mutating draft traps onto one bracket and dropping
1444+
// the run-returned gate on the arming (-23 B in projection.js). The
1445+
// other ~100 B is mangler/brotli layout: the same bytes measured 30,953
1446+
// with the gate still in place (+52) and 31,058 without it — a 13 B
1447+
// minified removal moved brotli +105. + createStore, which retains the
1448+
// same store engine, moved +13 B.
1449+
limit: "31.1 KB",
14441450
modifyEsbuildConfig
14451451
},
14461452
{

0 commit comments

Comments
 (0)