Skip to content

Commit 587cf48

Browse files
ryansolidclaudecursoragent
authored
feat(signals): pay-for-use tree-shaking for affects() and isPending/latest (#2883 phase 1) (#2885)
* feat(signals): pay-for-use tree-shaking for affects() and isPending/latest (#2883) Converts the two explicitly-imported verdict-side features to the nullable GlobalQueue hook pattern and splits the published dist into per-module trees so consumer bundlers can actually drop them: - affects(): the sentinel/propagation trio moves out of async.ts and the mark engine out of scheduler.ts into affects.ts, which installs _applyAffectsReads/_releaseAffectsMarks/_markAffects/_releaseAffectsMark on import. The old _propagateAffects/_settleAffects hooks become direct calls and are gone. - isPending()/latest(): the whole verdict layer (probe, companions, reask classification, repoll, latest read path) moves to core/verdict.ts, installing nine hooks behind the same guards the direct calls used. store.ts reaches witnessAffects through a hook so plain stores no longer retain any of it. - dist: rollup preserveModules for the dev/prod/node triplet; property mangling (^_) is now a single sequential terser pass with one shared nameCache per tree (per-chunk workers would mangle the same property to different names across modules). Flat-file statement shaking can never drop the top-level hook installs; per-module trees make them pay-for-use. - @__PURE__ on storePath's Object.assign and boundaries' reveal context; drops projection.ts's dead writeTraps export. - tests/treeshake.test.ts guards the module graph and a floor byte ceiling. Measured (esbuild, minify, mangle-props ^_, gzip -9), HEAD -> here: - core floor from src: 21,836/8,885 -> 20,128/8,154 min/gz - plain-store subset: 35,280/13,676 -> 33,476/12,939 - minimal app from published dist: 31,728/12,656 -> 28,805/11,366 - full package: +747 min (hook shims), the only regression Design rulings applied: createStore's derived overload keeps its static projection/reconcile coupling (API symmetry), and promise-returning computeds stay core (the appearance of a promise is the trigger) — so handleAsync and the transition machinery remain in the floor for now. Co-Authored-By: Claude Fable 5 <[email protected]> * chore: add changeset for pay-for-use tree-shaking phase 1 Co-Authored-By: Claude Fable 5 <[email protected]> * refactor(signals): chunk only the prod ESM dist, keep dev/node flat The per-module tree only pays off for bundlers, which are the sole consumers of the prod ESM path and scope-hoist it back into one module. Serving the tree everywhere charged real costs elsewhere: vitest's per-module SSR transform made the flush hot path ~2x slower (the CodSpeed -47% on update-partial was this artifact, not the hook refactor, which measures 0-5% in flat-vs-flat comparison), and unbundled node consumers paid ~10% per-module-boundary overhead that CJS require can't ever recoup through tree-shaking. Dev and node CJS return to flat single files; dist/prod stays a preserveModules tree. Co-authored-by: Cursor <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent 24bca49 commit 587cf48

17 files changed

Lines changed: 878 additions & 799 deletions
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
"@solidjs/signals": patch
3+
---
4+
5+
Make `affects()` and `isPending()`/`latest()` pay-for-use (#2883, phase 1). The affects mark engine and sentinel propagation move out of `async.ts`/`scheduler.ts` into the `affects` feature module, and the whole isPending/latest verdict layer (probe, companions, re-ask classification, the `latest()` read path) moves to a new internal `verdict` module; both install nullable `GlobalQueue` hooks on import, so bundles that never import these APIs never ship their machinery. The prod ESM dist is now a per-module tree (`dist/prod/`) instead of one flat file — statement-level tree-shaking can never drop a flat file's top-level hook installs, so the split is what makes the hooks pay off for npm consumers. It is the only output that changes shape: bundlers are its sole consumers and scope-hoist it back into one module, so nobody pays the per-module-boundary call cost at runtime. Dev (`dist/dev.js`) and node CJS (`dist/node.cjs`) stay flat single files — dev bundle size doesn't matter and CJS can't tree-shake, while the flat hot path stays fast for unbundled and test-transformed consumers. `_`-prefixed property mangling runs as a single sequential pass with one shared name cache per prod output, keeping mangled names consistent across module files.
6+
7+
Measured on a minimal app (render + one signal) bundled from the published dist: 12.7 → 11.4 KB gzip. Core-primitives floor from src: 8.9 → 8.2 KB gzip. Apps importing every feature pay ~0.7 KB min of hook shims. A new `treeshake` test guards the retained-module graph and the floor's byte ceiling so re-coupling fails CI.
8+
9+
No public API changes: `createStore`'s derived overload intentionally keeps its static projection/reconcile coupling, and promise-returning computeds remain handled by core in every build — the appearance of a promise is the trigger, not an import.

‎packages/solid-signals/package.json‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
"access": "public"
1515
},
1616
"main": "./dist/node.cjs",
17-
"module": "./dist/prod.js",
17+
"module": "./dist/prod/index.js",
1818
"types": "./dist/types/index.d.ts",
1919
"type": "module",
2020
"sideEffects": false,
@@ -28,7 +28,7 @@
2828
"types": "./dist/types/index.d.ts",
2929
"test": "./dist/dev.js",
3030
"development": "./dist/dev.js",
31-
"default": "./dist/prod.js"
31+
"default": "./dist/prod/index.js"
3232
},
3333
"require": {
3434
"types": "./dist/types-cjs/index.d.cts",
@@ -39,8 +39,8 @@
3939
},
4040
"scripts": {
4141
"build": "npm-run-all -nl build:* && pnpm types",
42-
"build:clean": "rimraf dist/dev.js dist/prod.js dist/node.cjs",
43-
"build:js": "rollup -c",
42+
"build:clean": "rimraf dist/dev dist/prod dist/node dist/dev.js dist/prod.js dist/node.cjs",
43+
"build:js": "rollup -c && node ./scripts/mangle-props.mjs dist/prod dist/node.cjs",
4444
"types": "tsc -p tsconfig.build.json && node ../../scripts/sync-dual-types.mjs ./dist/types ./dist/types-cjs",
4545
"test": "vitest run",
4646
"test:watch": "vitest watch tests",
@@ -52,12 +52,12 @@
5252
"devDependencies": {
5353
"@ianvs/prettier-plugin-sort-imports": "^4.1.1",
5454
"@rollup/plugin-replace": "^6.0.3",
55-
"@rollup/plugin-terser": "^0.4.4",
5655
"@rollup/plugin-typescript": "^12.3.0",
5756
"@types/node": "^25.0.8",
5857
"rimraf": "^5.0.1",
5958
"rollup": "^4.53.4",
6059
"rollup-plugin-prettier": "^4.1.2",
60+
"terser": "^5.49.0",
6161
"tslib": "^2.8.1",
6262
"typescript": "^6.0.3",
6363
"vite": "^7.0.0",

‎packages/solid-signals/rollup.config.js‎

Lines changed: 23 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,21 @@
11
import replace from "@rollup/plugin-replace";
2-
import terser from "@rollup/plugin-terser";
32
import typescript from "@rollup/plugin-typescript";
43
import prettier from "rollup-plugin-prettier";
54

5+
// Only the prod ESM build is a per-module tree (`preserveModules`); it is
6+
// consumed exclusively by bundlers, which can drop whole feature modules —
7+
// including their top-level GlobalQueue hook installs, which statement-level
8+
// shaking of a flat file can never remove (#2883) — and scope-hoist the rest
9+
// back into one module. Dev and node stay flat single files: dev bundle size
10+
// doesn't matter (and vitest's per-module SSR transform makes a chunked tree
11+
// ~2x slower in the flush hot path, poisoning CI benches), and CJS `require`
12+
// can't tree-shake, so a tree would charge unbundled SSR the per-module-
13+
// boundary cost (~10% native ESM) for nothing.
14+
//
15+
// `_`-prefixed property mangling for prod outputs runs as a single sequential
16+
// post-pass (scripts/mangle-props.mjs) with one shared nameCache per output;
17+
// per-chunk terser would mangle the same property to different names in
18+
// different modules and break every cross-module member access.
619
export default [
720
{
821
input: "src/index.ts",
@@ -24,10 +37,6 @@ export default [
2437
moduleResolution: "bundler",
2538
verbatimModuleSyntax: true
2639
}),
27-
terser({
28-
compress: false,
29-
mangle: false
30-
}),
3140
prettier({
3241
parser: "typescript"
3342
})
@@ -36,8 +45,10 @@ export default [
3645
{
3746
input: "src/index.ts",
3847
output: {
39-
file: "dist/prod.js",
40-
format: "esm"
48+
dir: "dist/prod",
49+
format: "esm",
50+
preserveModules: true,
51+
preserveModulesRoot: "src"
4152
},
4253
plugins: [
4354
replace({
@@ -47,23 +58,12 @@ export default [
4758
}),
4859
typescript({
4960
declaration: false,
50-
outDir: "dist",
61+
outDir: "dist/prod",
5162
module: "esnext",
5263
target: "esnext",
5364
moduleResolution: "bundler",
5465
verbatimModuleSyntax: true
5566
}),
56-
terser({
57-
compress: false,
58-
mangle: {
59-
keep_classnames: true,
60-
keep_fnames: true,
61-
module: false,
62-
properties: {
63-
regex: /^_/
64-
}
65-
}
66-
}),
6767
prettier({
6868
parser: "typescript"
6969
})
@@ -73,7 +73,8 @@ export default [
7373
input: "src/index.ts",
7474
output: {
7575
file: "dist/node.cjs",
76-
format: "cjs"
76+
format: "cjs",
77+
exports: "named"
7778
},
7879
plugins: [
7980
replace({
@@ -84,22 +85,11 @@ export default [
8485
typescript({
8586
declaration: false,
8687
outDir: "dist",
87-
module: "NodeNext",
88+
module: "esnext",
8889
target: "esnext",
89-
moduleResolution: "NodeNext",
90+
moduleResolution: "bundler",
9091
verbatimModuleSyntax: true
9192
}),
92-
terser({
93-
compress: false,
94-
mangle: {
95-
keep_classnames: true,
96-
keep_fnames: true,
97-
module: false,
98-
properties: {
99-
regex: /^_/
100-
}
101-
}
102-
}),
10393
prettier({
10494
parser: "typescript"
10595
})
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#!/usr/bin/env node
2+
/**
3+
* Mangles `_`-prefixed property names across a per-module dist tree with ONE
4+
* shared terser nameCache per tree, processing files in sorted order so the
5+
* assignment is deterministic. This must be a single sequential pass:
6+
* @rollup/plugin-terser runs per-chunk in worker processes with serialized
7+
* options, so `_pendingValue` could mangle to different names in different
8+
* modules and break cross-module member access at runtime (#2883).
9+
*
10+
* Flat single-file bundles are self-contained consistency domains, so each
11+
* argument (directory tree or single file) gets its own nameCache.
12+
*
13+
* Usage: node scripts/mangle-props.mjs <dist-dir-or-file> [<dist-dir-or-file> ...]
14+
*/
15+
import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
16+
import { join } from "node:path";
17+
import { minify } from "terser";
18+
19+
function walk(dir) {
20+
if (statSync(dir).isFile()) return [dir];
21+
const files = [];
22+
for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) =>
23+
a.name.localeCompare(b.name)
24+
)) {
25+
const path = join(dir, entry.name);
26+
if (entry.isDirectory()) files.push(...walk(path));
27+
else if (/\.(js|cjs)$/.test(entry.name)) files.push(path);
28+
}
29+
return files;
30+
}
31+
32+
for (const dir of process.argv.slice(2)) {
33+
const nameCache = {};
34+
for (const file of walk(dir)) {
35+
const code = readFileSync(file, "utf8");
36+
const result = await minify(code, {
37+
compress: false,
38+
nameCache,
39+
mangle: {
40+
keep_classnames: true,
41+
keep_fnames: true,
42+
module: false,
43+
properties: { regex: /^_/ }
44+
},
45+
format: { beautify: true, comments: true }
46+
});
47+
writeFileSync(file, result.code);
48+
}
49+
console.log(`mangled _-props across ${walk(dir).length} files in ${dir}`);
50+
}

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

Lines changed: 168 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,173 @@
1-
import { $REFRESH, type Computed, type Signal } from "./core/index.js";
1+
import {
2+
addPendingSource,
3+
forEachDependent,
4+
notifyStatus,
5+
setPendingError,
6+
settlePendingSource
7+
} from "./core/async.js";
8+
import { STATUS_PENDING } from "./core/constants.js";
29
import { emitDiagnostic } from "./core/dev.js";
3-
import { registerAffectsMark } from "./core/scheduler.js";
4-
import { $TARGET, getStoreAffectsNodes, type Store, type StoreNode } from "./store/store.js";
10+
import { NotReadyError } from "./core/error.js";
11+
import { $REFRESH, type Computed, type Signal } from "./core/index.js";
12+
import { devTrackAffects } from "./core/invariants.js";
13+
import {
14+
GlobalQueue,
15+
globalQueue,
16+
queuePendingNode,
17+
schedule,
18+
shiftAffectsMarks
19+
} from "./core/scheduler.js";
520
import type { Accessor } from "./signals.js";
21+
import { $TARGET, getStoreAffectsNodes, type Store, type StoreNode } from "./store/store.js";
22+
23+
type MarkedNode = Signal<any> | Computed<any>;
24+
25+
/**
26+
* The pending-source identity of a live `affects()` mark on `node` (lazy,
27+
* one per node, shared by overlapping registrations via the refcount).
28+
*
29+
* A mark rides the SAME status rails as real in-flight async — downstream
30+
* subscribers hold the sentinel in `_pendingSources` — but under its own
31+
* identity so the two channels can't clear each other:
32+
* - `_reask` is permanently `false`: a mark is by definition a declared
33+
* value change, so `quietPending` never silences a window it participates
34+
* in — even when the mark rides over an otherwise-quiet `refresh()`
35+
* re-ask of the same node (the whole point of declaring one).
36+
* - A landing on the marked node settles only the node's OWN source entry;
37+
* the sentinel entry survives until the mark's transaction releases it.
38+
* - The sentinel itself never carries `STATUS_PENDING`, so
39+
* `transitionComplete` never counts a mark as a blocker of its own
40+
* transaction (release happens AT settle — self-blocking would deadlock),
41+
* and reads of the marked node never throw (marks are value-transparent
42+
* at the source; pendingness is what propagates).
43+
*/
44+
function getAffectsSentinel(node: MarkedNode): Computed<any> {
45+
return (node._affectsSentinel ??= {
46+
_name: __DEV__ ? "affects-sentinel" : undefined,
47+
// Brand + backref: lets the scheduler's settlement checks recognize
48+
// mark-sourced pending (which must never block its own transaction —
49+
// release happens AT settle).
50+
_affectsFor: node,
51+
_flags: 0,
52+
_statusFlags: 0,
53+
_reask: false,
54+
_error: undefined,
55+
_subs: null,
56+
_deps: null
57+
} as unknown as Computed<any>);
58+
}
59+
60+
/**
61+
* Push a live mark's pendingness downstream from the marked node through the
62+
* normal status rails. Runs on every registration (dedup in `notifyStatus`
63+
* stops re-descent at already-covered subscribers). Subscribers that
64+
* recompute mid-window shed this via `clearStatus` and re-acquire it through
65+
* the read path (`applyAffectsReads`) — the same shape as real async, where
66+
* the re-throw on read re-establishes the source.
67+
*/
68+
function propagateAffectsMark(node: MarkedNode): void {
69+
if (!node._subs && !(node as Computed<any>)._child) return;
70+
const sentinel = getAffectsSentinel(node);
71+
const error = new NotReadyError(sentinel);
72+
forEachDependent(node as Computed<any>, sub => {
73+
if (sub._pendingSource !== sentinel && !sub._pendingSources?.has(sentinel)) {
74+
if (!sub._transition) queuePendingNode(sub);
75+
notifyStatus(sub, STATUS_PENDING, error);
76+
}
77+
});
78+
}
79+
80+
/**
81+
* Re-establish mark pendingness on a computed that read marked sources
82+
* during its recompute (`clearStatus` at the top of the commit path wiped
83+
* any sentinel entries it held). Called by `recompute` after the commit —
84+
* not before, because setting `_error` earlier would make the commit path
85+
* treat the node as errored and skip the value write.
86+
*/
87+
function applyAffectsReads(el: Computed<any>, sources: MarkedNode[]): void {
88+
let applied = false;
89+
for (let i = 0; i < sources.length; i++) {
90+
const src = sources[i];
91+
if (!src._affectsCount) continue;
92+
const sentinel = getAffectsSentinel(src);
93+
if (addPendingSource(el, sentinel)) {
94+
el._statusFlags |= STATUS_PENDING;
95+
setPendingError(el, sentinel);
96+
applied = true;
97+
}
98+
}
99+
if (applied && GlobalQueue._updatePendingSignal !== null) GlobalQueue._updatePendingSignal(el);
100+
}
101+
102+
/**
103+
* The counting half of a mark, shared by direct registration and store-scope
104+
* inheritance (a node created inside a live keyless mark's identity scope):
105+
* bumps the refcount and pokes the node's verdict companions so an
106+
* already-materialized `false` flips reactively.
107+
*/
108+
function markAffects(node: MarkedNode): void {
109+
node._affectsCount = (node._affectsCount || 0) + 1;
110+
shiftAffectsMarks(1);
111+
if (__DEV__) devTrackAffects(node);
112+
// Companions only exist once the verdict layer (isPending/latest) loaded;
113+
// without them there is no materialized verdict to flip.
114+
if (node._affectsCount === 1 && GlobalQueue._updatePendingSignal !== null)
115+
GlobalQueue._updatePendingSignal(node);
116+
}
117+
118+
/**
119+
* Registers one `affects()` mark on a node: counts it, records the
120+
* registration with the current transaction (after initTransition the queue's
121+
* array aliases the active transition's, mirroring `_optimisticNodes`), and
122+
* propagates STATUS_PENDING downstream on the status rails so everything
123+
* DERIVED from the marked data reads pending too. Propagation runs on every
124+
* registration (not just the first): subscribers gained since an earlier
125+
* overlapping registration get covered, and dedup stops re-descent early.
126+
*/
127+
function registerAffectsMark(node: MarkedNode): void {
128+
markAffects(node);
129+
globalQueue._affectsNodes.push(node);
130+
propagateAffectsMark(node);
131+
schedule();
132+
}
133+
134+
/**
135+
* Releases one registration. When the node's last mark drops, settles the
136+
* mark's sentinel out of every downstream `_pendingSources` (waking blocked
137+
* nodes and re-deriving verdicts along the walk). Companion writes go through
138+
* the settlement snap (committed, not transition-scoped) so releasing a mark
139+
* can't open a fresh override window that would itself need settlement.
140+
*/
141+
function releaseAffectsMark(node: MarkedNode): void {
142+
shiftAffectsMarks(-1);
143+
node._affectsCount!--;
144+
if (!node._affectsCount) {
145+
const sentinel = node._affectsSentinel;
146+
if (sentinel) settlePendingSource(node as Computed<any>, sentinel, true);
147+
GlobalQueue._snapCompanions !== null && GlobalQueue._snapCompanions(node);
148+
GlobalQueue._releaseAffectsScope?.(node);
149+
}
150+
}
151+
152+
/**
153+
* Releases one batch of affects marks (a settling transaction's, or the
154+
* ambient batch at a plain flush end).
155+
*/
156+
function releaseAffectsMarks(nodes: MarkedNode[]): void {
157+
for (let i = 0; i < nodes.length; i++) releaseAffectsMark(nodes[i]);
158+
nodes.length = 0;
159+
}
160+
161+
// Late installation (same pattern as `GlobalQueue._update`): the mark engine
162+
// lives with the feature so graphs that never declare a mark never ship it.
163+
// Each call site is gated by state only this module creates (`markedReads`
164+
// collection under `activeAffectsMarks`, a non-empty `_affectsNodes` batch,
165+
// a live scope in the store's `affectsScopes`), so the hooks are installed
166+
// before the first time any of them can fire.
167+
GlobalQueue._applyAffectsReads = applyAffectsReads;
168+
GlobalQueue._releaseAffectsMarks = releaseAffectsMarks;
169+
GlobalQueue._markAffects = markAffects;
170+
GlobalQueue._releaseAffectsMark = releaseAffectsMark;
6171

7172
/**
8173
* Declares that in-flight work will change the targeted data: the named

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ function createBoundChildren<T>(
8484
}
8585

8686
const ON_INIT: unique symbol = Symbol();
87-
const RevealControllerContext = createContext<RevealController | null>(null);
87+
const RevealControllerContext = /* @__PURE__ */ createContext<RevealController | null>(null);
8888
let _revealUsed = false;
8989

9090
type RevealSlot = CollectionQueue | RevealController;

0 commit comments

Comments
 (0)