Skip to content

Commit e16371f

Browse files
perf(signals): reduce effect overhead, add sync opt-in, fix nested flush
Effect creation: introduce createEffectNode with the full hidden-class shape baked into one literal, share notifyEffectStatus across instances instead of allocating a closure per effect, register the disposal cleanup lazily on first cleanup-fn return, and hoist Root.dispose into a shared disposeRootSelf. Adds a fast path in storeTraps.get for tracked reads of absent plain-object properties so subscribers do not pay the full override/optimistic resolution chain. CONFIG_SYNC opt-in: new sync? option on MemoOptions/EffectOptions skips the async-shape probe in recompute for nodes that provably never return Promise/AsyncIterable. Compiler-emitted _$effect/_$memo (via @solidjs/web wrappers) opt in by default. Dev keeps the probe and surfaces SYNC_NODE_RECEIVED_ASYNC when a sync: true node returns an awaitable; production silently stores the value as-is, by contract. flush(fn) drains at every nesting level instead of only the outermost, so nested flush(fn) calls each honor their own contract. Updates the js-reactivity-benchmark fixture and adds coverage in flush.test.ts / diagnostics.test.ts. Engineering standards: document the changeset-target convention so the header lists the package(s) that actually changed, by directory, rather than always defaulting to solid-js. Co-authored-by: Cursor <[email protected]>
1 parent 47c0e6f commit e16371f

16 files changed

Lines changed: 353 additions & 107 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+
Reduce effect creation overhead by sharing status notification logic, registering effect cleanups lazily, and avoiding generic store proxy work for tracked reads of absent plain-object properties.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
"@solidjs/signals": patch
3+
"@solidjs/web": patch
4+
---
5+
6+
Performance: add `CONFIG_SYNC` opt-in for sync-only computeds/effects. New `sync?: boolean` option on `MemoOptions`/`EffectOptions` skips the async-shape probe in `recompute` for nodes that provably never return Promise/AsyncIterable. Compiler-emitted `_$effect` and `_$memo` (via `@solidjs/web`'s `effect`/`memo` wrappers) opt in by default — `01_run1k` mean −0.62 ms and `08_create1k-after1k_x2` mean −0.80 ms in `js-framework-benchmark`. User-authored `createMemo`/`createEffect`/`createRenderEffect` keep full async-aware behavior unless they explicitly pass `sync: true`. Returning a Promise from a `sync: true` node throws `SYNC_NODE_RECEIVED_ASYNC` in dev (production silently stores the unawaited value, by contract).
7+
8+
Correctness: `flush(fn)` now drains at every nesting level instead of only the outermost. Nested `flush(fn)` calls each honor their own contract — writes inside an inner `flush(fn)` propagate before it returns, rather than being held until the outer `flush(fn)` exits. Microtask scheduling and arg-less `flush()` are unchanged. Code that depended on the old hold-until-outermost behavior should switch to a harness-layer depth counter (see `js-reactivity-benchmark`'s `r3` / `r3-solid-target` adapters for the pattern).

‎.cursor/rules/engineering-standards.mdc‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,14 +36,14 @@ Since `pnpm changeset` is interactive and cannot be used from the agent, create
3636
```markdown
3737
// .changeset/<descriptive-name>.md
3838
---
39-
"solid-js": patch
39+
"@solidjs/signals": patch
4040
---
4141

4242
Short summary of the change
4343
```
4444

4545
- Use `patch` for bug fixes, `minor` for features, `major` for breaking changes.
46-
- All packages in the `fixed` group version together — only list the primary package affected (usually `solid-js`).
46+
- List the package(s) that actually changed, by directory. Source under `packages/solid/src/` → `solid-js`; `packages/solid-signals/src/` → `@solidjs/signals`; `packages/solid-web/src/` → `@solidjs/web`; etc. If a single change touches multiple package sources, list each one. (All packages in the `fixed` group still version together; the changeset header is documenting *what* changed, not *what bumps*.)
4747
- If a commit only touches examples, tests, or tooling config (not source under `packages/`), no changeset is needed.
4848
- The changeset file name should be descriptive (e.g., `fix-ssr-async-error-handling.md`), not random words.
4949

‎packages/solid-signals/src/core/async.ts‎

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {
2+
CONFIG_SYNC,
23
EFFECT_TRACKED,
34
EFFECT_USER,
45
NOT_PENDING,
@@ -10,6 +11,7 @@ import {
1011
STATUS_UNINITIALIZED
1112
} from "./constants.js";
1213
import { context, setSignal, untrack, updatePendingSignal } from "./core.js";
14+
import { emitDiagnostic } from "./dev.js";
1315
import { NotReadyError, StatusError } from "./error.js";
1416
import { insertIntoHeap } from "./heap.js";
1517
import { hasActiveOverride, resolveLane, resolveTransition, type OptimisticLane } from "./lanes.js";
@@ -134,16 +136,43 @@ export function handleAsync<T>(
134136
result: T | PromiseLike<T> | AsyncIterable<T>,
135137
setter?: (value: T) => void
136138
): T {
137-
const isObject = typeof result === "object" && result !== null;
138-
const iterator = isObject && untrack(() => result[Symbol.asyncIterator]);
139-
const isThenable =
140-
!iterator && isObject && untrack(() => typeof (result as any).then === "function");
139+
let iterator: any = false;
140+
let isThenable = false;
141+
if (typeof result === "object" && result !== null) {
142+
untrack(() => {
143+
iterator = (result as any)[Symbol.asyncIterator];
144+
isThenable = !iterator && typeof (result as any).then === "function";
145+
});
146+
}
141147

142148
if (!isThenable && !iterator) {
143149
el._inFlight = null;
144150
return result as T;
145151
}
146152

153+
// Dev-only contract enforcement for `sync: true` nodes. In production these
154+
// never reach `handleAsync` (the recompute fast path skips the call), but in
155+
// dev they do — we run the full async-shape probe and diagnose if a Promise
156+
// / AsyncIterable comes through. The fast-path semantics in production would
157+
// silently store the unawaited value, which is what the user opted out of by
158+
// passing `sync: true`; the diagnostic surfaces that mistake immediately.
159+
if (__DEV__ && el._config & CONFIG_SYNC) {
160+
const message =
161+
`[SYNC_NODE_RECEIVED_ASYNC] A computed/effect created with \`sync: true\` returned ` +
162+
`${isThenable ? "a Promise" : "an AsyncIterable"}. The value would be stored as-is and ` +
163+
`never awaited in production; remove \`sync: true\` to use async-aware behavior, or ` +
164+
`unwrap the value before returning.`;
165+
emitDiagnostic({
166+
code: "SYNC_NODE_RECEIVED_ASYNC",
167+
kind: "lifecycle",
168+
severity: "error",
169+
message,
170+
ownerId: el.id,
171+
ownerName: (el as any)._name
172+
});
173+
throw new Error(message);
174+
}
175+
147176
el._inFlight = result as PromiseLike<T> | AsyncIterable<T>;
148177
let syncValue: T;
149178

‎packages/solid-signals/src/core/constants.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ export const CONFIG_TRANSPARENT = 1 << 2;
1818
export const CONFIG_IN_SNAPSHOT_SCOPE = 1 << 3;
1919
export const CONFIG_CHILDREN_FORBIDDEN = 1 << 4;
2020
export const CONFIG_AUTO_DISPOSE = 1 << 5;
21+
export const CONFIG_SYNC = 1 << 6;
2122

2223
export const STATUS_NONE = 0;
2324
export const STATUS_PENDING = 1 << 0;

‎packages/solid-signals/src/core/core.ts‎

Lines changed: 106 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,11 @@ import {
66
CONFIG_IN_SNAPSHOT_SCOPE,
77
CONFIG_NO_SNAPSHOT,
88
CONFIG_OWNED_WRITE,
9+
CONFIG_SYNC,
910
CONFIG_TRANSPARENT,
1011
defaultContext,
1112
EFFECT_TRACKED,
13+
EFFECT_USER,
1214
NO_SNAPSHOT,
1315
NOT_PENDING,
1416
REACTIVE_CHECK,
@@ -205,18 +207,26 @@ export function recompute(el: Computed<any>, create: boolean = false): void {
205207
}
206208
}
207209
}
210+
const isStaleEffect = isEffect && isEffect !== EFFECT_USER;
211+
const prevStale = stale;
212+
if (isStaleEffect) stale = true;
208213
try {
209-
// Snapshot `_inFlight` so we can detect whether `_fn` self-registered an async
210-
// subscription (e.g. `createProjection` calls `handleAsync` from inside its body
211-
// with a setter callback). In that case, the outer `handleAsync` call below would
212-
// clobber the fresh subscription, so we skip it and let the internally-registered
213-
// iteration drive updates.
214-
const prevInFlight = el._inFlight;
215-
const fnResult = el._fn(value);
216-
const isAsyncResult = typeof fnResult === "object" && fnResult !== null;
217-
const inFlightChanged = el._inFlight !== prevInFlight;
218-
value = inFlightChanged || !isAsyncResult ? fnResult : handleAsync(el, fnResult);
219-
if (!inFlightChanged && !isAsyncResult) el._inFlight = null;
214+
if (!__DEV__ && el._config & CONFIG_SYNC) {
215+
value = el._fn(value);
216+
el._inFlight = null;
217+
} else {
218+
// Snapshot `_inFlight` so we can detect whether `_fn` self-registered an async
219+
// subscription (e.g. `createProjection` calls `handleAsync` from inside its body
220+
// with a setter callback). In that case, the outer `handleAsync` call below would
221+
// clobber the fresh subscription, so we skip it and let the internally-registered
222+
// iteration drive updates.
223+
const prevInFlight = el._inFlight;
224+
const fnResult = el._fn(value);
225+
const isAsyncResult = typeof fnResult === "object" && fnResult !== null;
226+
const inFlightChanged = el._inFlight !== prevInFlight;
227+
value = inFlightChanged || !isAsyncResult ? fnResult : handleAsync(el, fnResult);
228+
if (!inFlightChanged && !isAsyncResult) el._inFlight = null;
229+
}
220230
clearStatus(el, create);
221231
if (el._optimisticLane) {
222232
const resolvedLane = resolveLane(el);
@@ -247,6 +257,7 @@ export function recompute(el: Computed<any>, create: boolean = false): void {
247257
} finally {
248258
tracking = prevTracking;
249259
if (__DEV__) strictRead = prevStrictRead;
260+
if (isStaleEffect) stale = prevStale;
250261
el._flags = REACTIVE_NONE | (create ? el._flags & REACTIVE_SNAPSHOT_STALE : 0);
251262
context = oldcontext;
252263
}
@@ -269,6 +280,16 @@ export function recompute(el: Computed<any>, create: boolean = false): void {
269280
const valueChanged =
270281
(!isEffect && wasUninitialized) || !el._equals || !el._equals(compareValue, value);
271282

283+
// Effects use `_equals: false` (no per-effect closure). The side effects that
284+
// the equals closure used to perform — flagging the effect dirty and enqueueing
285+
// its runner — happen here instead. `!create` matches the previous `initialized`
286+
// gate: the explicit recompute(node, true) inside effect() does not enqueue, so
287+
// effect() can call its runner synchronously for the first run.
288+
if (isEffect && valueChanged) {
289+
(el as any)._modified = !el._error;
290+
if (!create) el._queue.enqueue(isEffect, GlobalQueue._runEffect.bind(null, el));
291+
}
292+
272293
if (valueChanged) {
273294
const prevVisible = hasOverride ? el._overrideValue : undefined;
274295

@@ -354,6 +375,7 @@ export function computed<T>(
354375
(transparent ? CONFIG_TRANSPARENT : 0) |
355376
(options?.ownedWrite ? CONFIG_OWNED_WRITE : 0) |
356377
(!context || options?.lazy ? CONFIG_AUTO_DISPOSE : 0) |
378+
(options?.sync ? CONFIG_SYNC : 0) |
357379
(snapshotCaptureActive && ownerInSnapshotScope(context) ? CONFIG_IN_SNAPSHOT_SCOPE : 0),
358380
_equals: options?.equals != null ? options.equals : isEqual,
359381
_unobserved: options?.unobserved,
@@ -385,6 +407,79 @@ export function computed<T>(
385407
_transition: null
386408
} as Computed<T>;
387409
if (__DEV__) (self as any)._name = options?.name ?? "computed";
410+
setupComputedNode(self, options);
411+
return self;
412+
}
413+
414+
/**
415+
* Build an Effect node with all effect-specific fields baked into a single object literal,
416+
* so V8 sees the full hidden class shape at construction time. Effects always run in lazy
417+
* mode (recompute is called explicitly by `effect()`), so we hardcode the lazy bits and skip
418+
* the auto-dispose CONFIG bit (effect() previously cleared it post-construction).
419+
*/
420+
export function createEffectNode<T>(
421+
fn: (prev?: T) => T,
422+
effectFn: (val: T, prev: T | undefined) => void | (() => void),
423+
errorFn: ((err: unknown, cleanup: () => void) => void | (() => void)) | undefined,
424+
type: number,
425+
notifyStatus: ((status?: number, error?: any) => void) | undefined,
426+
options: NodeOptions<T> | undefined
427+
): any {
428+
const transparent = options?.transparent ?? false;
429+
const self = {
430+
id:
431+
options?.id ??
432+
(transparent ? context?.id : context?.id != null ? getNextChildId(context) : undefined),
433+
_config:
434+
(transparent ? CONFIG_TRANSPARENT : 0) |
435+
(options?.ownedWrite ? CONFIG_OWNED_WRITE : 0) |
436+
(options?.sync ? CONFIG_SYNC : 0) |
437+
(snapshotCaptureActive && ownerInSnapshotScope(context) ? CONFIG_IN_SNAPSHOT_SCOPE : 0),
438+
_equals: false as unknown as Computed<T>["_equals"],
439+
_unobserved: options?.unobserved,
440+
_disposal: null,
441+
_queue: context?._queue ?? globalQueue,
442+
_context: context?._context ?? defaultContext,
443+
_childCount: 0,
444+
_fn: fn,
445+
_value: undefined as T,
446+
_height: 0,
447+
_child: null,
448+
_nextHeap: undefined,
449+
_prevHeap: null as any,
450+
_deps: null,
451+
_depsTail: null,
452+
_subs: null,
453+
_subsTail: null,
454+
_parent: context,
455+
_nextSibling: null,
456+
_prevSibling: null,
457+
_firstChild: null,
458+
_flags: REACTIVE_LAZY,
459+
_statusFlags: STATUS_UNINITIALIZED,
460+
_time: clock,
461+
_pendingValue: NOT_PENDING,
462+
_pendingDisposal: null,
463+
_pendingFirstChild: null,
464+
_inFlight: null,
465+
_transition: null,
466+
_modified: false,
467+
_prevValue: undefined as T | undefined,
468+
_effectFn: effectFn,
469+
_errorFn: errorFn,
470+
_cleanup: undefined as (() => void) | undefined,
471+
_cleanupRegistered: false,
472+
_type: type,
473+
_notifyStatus: notifyStatus
474+
} as any;
475+
if (__DEV__) self._name = options?.name ?? "effect";
476+
setupComputedNode(self, lazyOptions);
477+
return self;
478+
}
479+
480+
const lazyOptions = { lazy: true } as const;
481+
482+
function setupComputedNode<T>(self: Computed<T>, options: NodeOptions<T> | undefined): void {
388483
self._prevHeap = self;
389484
const parent = (context as Root)?._root
390485
? (context as Root)._parentComputed
@@ -430,8 +525,6 @@ export function computed<T>(
430525
snapshotSources!.add(self);
431526
}
432527
}
433-
434-
return self;
435528
}
436529

437530
export function signal<T>(v: T, options?: NodeOptions<T>): Signal<T>;

‎packages/solid-signals/src/core/dev.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ export type DiagnosticCode =
2121
| "NO_OWNER_EFFECT"
2222
| "NO_OWNER_BOUNDARY"
2323
| "ASYNC_OUTSIDE_LOADING_BOUNDARY"
24-
| "MISSING_EFFECT_FN";
24+
| "MISSING_EFFECT_FN"
25+
| "SYNC_NODE_RECEIVED_ASYNC";
2526

2627
export type DiagnosticKind = "strict-read" | "async" | "write" | "lifecycle" | "owner";
2728

0 commit comments

Comments
 (0)