Skip to content

Commit 5946c0e

Browse files
ryansolidclaude
andcommitted
feat(signals): close esbuild-shakeable gaps at the source level (#2883)
Rollup literal-tracks never-written module state and folds the dead branches; esbuild cannot, so these paths shipped only to esbuild-class consumers. Restructured so both bundlers land in the same place, all Rollup-neutral by measurement: - external-source wiring (computed setup + untrack) moves behind GlobalQueue hooks whose installs mirror enableExternalSource()'s config liveness exactly (installed on enable, removed on reset) - onlyMarkPending moves from async.ts into affects.ts behind the activeAffectsMarks-gated hook (mark-transparency is affects-only) - the optimistic-store settle loop moves inside the store-side hook (_clearOptimisticStores takes the batch; scheduler keeps a size-guarded call) esbuild minimal app: -77 gz from these + -194 gz from the companion dom-expressions hydration-hook change (ryansolid/dom-expressions#544). Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent acea30e commit 5946c0e

7 files changed

Lines changed: 87 additions & 48 deletions

File tree

‎.changeset/pay-for-use-treeshaking-phase-3.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,6 @@
55

66
Pay-for-use tree-shaking, phase 3 (#2883) — mechanical cleanups selected by cost/benefit audit. Signals: the effect re-enqueue block (four copies) and zombie/dirty queue selection dedupe into shared `enqueueSub`/`queueFor` helpers (hot-path microbenched, no regression); boundary/reveal internal method names are `_`-prefixed so property mangling reaches them; production error strings trim to their diagnostic codes (dev builds keep full sentences); and the prod dist build stops stripping `/*@__PURE__*/` annotations — rollup-plugin-prettier is off the prod tree, terser re-emits annotations, and a new `check-pure` build guard fails the build if they ever vanish again. solid-js client: `sharedConfig.getNextContextId` and `lazy()`'s hydration-module lookup install from `enableHydration()` instead of shipping in every CSR bundle, and MockPromise's class static block (which defeated dead-code elimination in every client bundle) becomes a PURE-annotated factory. CDN `unpkg`/`jsdelivr` fields now point at browser production ESM instead of CommonJS files.
77

8-
Measured: minimal app 10.9 → 10.4 KB gzip; CSR app with `<Loading>`/`lazy` 13.9 → 12.6 KB (includes the dom-expressions `DOMElements` dedup arriving through the rebuilt web runtime); signals floor 7.7 → 7.5 KB; and the full-featured bundle *shrinks* 272 gzip bytes, recovering a third of the phase-1/2 hook indirection tax. Cumulative across all three phases the minimal app is down 17.6% and the signals floor 15.4%, with all 1,941 tests across the affected packages passing unchanged.
8+
A last-mile pass closes part of the esbuild-vs-Rollup shaking gap at the source level (Rollup's literal tracking folds never-written state that esbuild retains): the external-source wiring in computed setup and `untrack` moves behind hooks that mirror `enableExternalSource()`'s config liveness, the affects-only `onlyMarkPending` read-path helper moves into the affects module, and the optimistic-store settle loop moves inside its store-side hook. All are Rollup-neutral by measurement.
9+
10+
Measured: minimal app 10.9 → 10.3 KB gzip under esbuild and **9.8 KB gzip / 9.0 KB brotli under Vite** (Solid's default toolchain — under the 10 KB mark); CSR app with `<Loading>`/`lazy` 13.9 → 12.6 KB; signals floor 7.7 → 7.4 KB; and the full-featured bundle *shrinks* ~330 gzip bytes, recovering a third of the phase-1/2 hook indirection tax. Cumulative across all three phases the minimal app is down ~19% with all 1,941 tests across the affected packages passing unchanged.

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,23 @@ function releaseAffectsMarks(nodes: MarkedNode[]): void {
158158
nodes.length = 0;
159159
}
160160

161+
/**
162+
* True when a node's pending status comes ONLY from affects() sentinels. A
163+
* mark is a promise of change, not an absence of value: reads of mark-pended
164+
* derived nodes stay value-transparent (verdicts report pending; the read
165+
* path must not suspend). Any real async source among the pending sources
166+
* keeps normal suspension semantics. Core's read path reaches this through
167+
* `GlobalQueue._onlyMarkPending`, gated on the `activeAffectsMarks` counter.
168+
*/
169+
function onlyMarkPending(el: Computed<any>): boolean {
170+
const sources = el._pendingSources;
171+
if (sources) {
172+
for (const s of sources) if (!s._affectsFor) return false;
173+
return true;
174+
}
175+
return !!el._pendingSource?._affectsFor;
176+
}
177+
161178
// Late installation (same pattern as `GlobalQueue._update`): the mark engine
162179
// lives with the feature so graphs that never declare a mark never ship it.
163180
// Each call site is gated by state only this module creates (`markedReads`
@@ -168,6 +185,7 @@ GlobalQueue._applyAffectsReads = applyAffectsReads;
168185
GlobalQueue._releaseAffectsMarks = releaseAffectsMarks;
169186
GlobalQueue._markAffects = markAffects;
170187
GlobalQueue._releaseAffectsMark = releaseAffectsMark;
188+
GlobalQueue._onlyMarkPending = onlyMarkPending;
171189

172190
/**
173191
* Declares that in-flight work will change the targeted data: the named

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

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -84,22 +84,6 @@ export function setPendingError(el: Computed<any>, source?: Computed<any>, error
8484
}
8585
}
8686

87-
/**
88-
* True when a node's pending status comes ONLY from affects() sentinels. A
89-
* mark is a promise of change, not an absence of value: reads of mark-pended
90-
* derived nodes stay value-transparent (verdicts report pending; the read
91-
* path must not suspend). Any real async source among the pending sources
92-
* keeps normal suspension semantics.
93-
*/
94-
export function onlyMarkPending(el: Computed<any>): boolean {
95-
const sources = el._pendingSources;
96-
if (sources) {
97-
for (const s of sources) if (!s._affectsFor) return false;
98-
return true;
99-
}
100-
return !!el._pendingSource?._affectsFor;
101-
}
102-
10387
export function forEachDependent(
10488
el: Computed<any>,
10589
fn: (node: Computed<any>, link: Link) => void

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

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { clearStatus, handleAsync, notifyStatus, onlyMarkPending } from "./async.js";
1+
import { clearStatus, handleAsync, notifyStatus } from "./async.js";
22
import {
33
$REFRESH,
44
CONFIG_AUTO_DISPOSE,
@@ -33,7 +33,6 @@ import {
3333
type Refreshable
3434
} from "./constants.js";
3535
import { NotReadyError } from "./error.js";
36-
import { externalSourceConfig } from "./external.js";
3736
import { link, trimStaleDeps, unobserved } from "./graph.js";
3837
import {
3938
deleteFromHeap,
@@ -556,17 +555,7 @@ function setupComputedNode<T>(self: Computed<T>, options: NodeOptions<T> | undef
556555
}
557556
if (__DEV__) DEV.hooks.onOwner?.(self);
558557
if (parent) self._height = parent._height + 1;
559-
if (externalSourceConfig) {
560-
const bridgeSignal = signal<undefined>(undefined, { equals: false, ownedWrite: true });
561-
const source = externalSourceConfig.factory(self._fn as any, () => {
562-
setSignal(bridgeSignal, undefined);
563-
});
564-
cleanup(() => source.dispose());
565-
self._fn = ((prev: any) => {
566-
read(bridgeSignal);
567-
return source.track(prev);
568-
}) as any;
569-
}
558+
if (GlobalQueue._wireExternalSource !== null) GlobalQueue._wireExternalSource(self);
570559
!options?.lazy && recompute(self, true);
571560
if (snapshotCaptureActive && !options?.lazy) {
572561
if (!(self._statusFlags & STATUS_PENDING) && !(self._config & CONFIG_NO_SNAPSHOT)) {
@@ -670,14 +659,18 @@ export function setStrictRead(v: string | false): string | false {
670659
* ```
671660
*/
672661
export function untrack<T>(fn: () => T, strictReadLabel?: string | false): T {
673-
if (!externalSourceConfig && !tracking && (!__DEV__ || (!strictRead && !strictReadLabel)))
662+
if (
663+
GlobalQueue._externalUntrack === null &&
664+
!tracking &&
665+
(!__DEV__ || (!strictRead && !strictReadLabel))
666+
)
674667
return fn();
675668
const prevTracking = tracking;
676669
const prevStrictRead = strictRead;
677670
tracking = false;
678671
if (__DEV__) strictRead = strictReadLabel || false;
679672
try {
680-
if (externalSourceConfig) return externalSourceConfig.untrack(fn);
673+
if (GlobalQueue._externalUntrack !== null) return GlobalQueue._externalUntrack(fn);
681674
return fn();
682675
} finally {
683676
tracking = prevTracking;
@@ -790,7 +783,7 @@ export function read<T>(el: Signal<T> | Computed<T>): T {
790783
// sentinels can't survive in pending sources past their last release.)
791784
if (
792785
owner._statusFlags & STATUS_PENDING &&
793-
!(activeAffectsMarks !== 0 && onlyMarkPending(owner as Computed<any>))
786+
!(activeAffectsMarks !== 0 && GlobalQueue._onlyMarkPending!(owner as Computed<any>))
794787
) {
795788
if (c && !(stale && owner._transition && activeTransition !== owner._transition)) {
796789
if (__DEV__ && c && c._config & CONFIG_CHILDREN_FORBIDDEN) {

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

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
import { read, setSignal, signal } from "./core.js";
2+
import { cleanup } from "./owner.js";
3+
import { GlobalQueue } from "./scheduler.js";
4+
import type { Computed } from "./types.js";
5+
16
export type ExternalSourceFactory = (fn: (prev: any) => any, trigger: () => void) => ExternalSource;
27

38
export interface ExternalSource {
@@ -45,6 +50,35 @@ export let externalSourceConfig: {
4550
* });
4651
* ```
4752
*/
53+
// Wires a freshly created computed through the active external-source bridge.
54+
// Lives here (installed on GlobalQueue while a config is active) rather than
55+
// inline in core: esbuild cannot literal-track the mutable config binding the
56+
// way rollup does, so an inline `if (externalSourceConfig)` block ships in
57+
// every bundle even though only enableExternalSource() can make it reachable.
58+
function wireExternalSource(self: Computed<any>): void {
59+
const bridgeSignal = signal<undefined>(undefined, { equals: false, ownedWrite: true });
60+
const source = externalSourceConfig!.factory(self._fn as any, () => {
61+
setSignal(bridgeSignal, undefined);
62+
});
63+
cleanup(() => source.dispose());
64+
self._fn = ((prev: any) => {
65+
read(bridgeSignal);
66+
return source.track(prev);
67+
}) as any;
68+
}
69+
70+
function externalUntrack<T>(fn: () => T): T {
71+
return externalSourceConfig!.untrack(fn);
72+
}
73+
74+
// The hooks mirror the config's liveness exactly (installed on enable,
75+
// removed on reset) so core's null checks stay equivalent to the old
76+
// `externalSourceConfig` truthiness checks.
77+
function syncExternalHooks(): void {
78+
GlobalQueue._wireExternalSource = externalSourceConfig ? wireExternalSource : null;
79+
GlobalQueue._externalUntrack = externalSourceConfig ? externalUntrack : null;
80+
}
81+
4882
export function enableExternalSource(config: ExternalSourceConfig): void {
4983
const { factory, untrack: untrackFn = fn => fn() } = config;
5084
if (externalSourceConfig) {
@@ -66,8 +100,10 @@ export function enableExternalSource(config: ExternalSourceConfig): void {
66100
} else {
67101
externalSourceConfig = { factory, untrack: untrackFn };
68102
}
103+
syncExternalHooks();
69104
}
70105

71106
export function _resetExternalSourceConfig(): void {
72107
externalSourceConfig = null;
108+
syncExternalHooks();
73109
}

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

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -313,7 +313,7 @@ export class GlobalQueue extends Queue {
313313
static _update: (el: Computed<unknown>) => void;
314314
static _dispose: (el: Computed<unknown>, self: boolean, zombie: boolean) => void;
315315
static _runEffect: (el: Computed<unknown>) => void;
316-
static _clearOptimisticStore: ((store: any) => void) | null = null;
316+
static _clearOptimisticStores: ((stores: Set<any>) => void) | null = null;
317317
// Store-side hook: drops a keyless affects() mark's identity scope when the
318318
// carrier node's last registration releases (wired by store.ts, mirroring
319319
// _clearOptimisticStore).
@@ -328,6 +328,11 @@ export class GlobalQueue extends Queue {
328328
static _releaseAffectsMarks: ((nodes: OptimisticNode[]) => void) | null = null;
329329
static _markAffects: ((node: OptimisticNode) => void) | null = null;
330330
static _releaseAffectsMark: ((node: OptimisticNode) => void) | null = null;
331+
static _onlyMarkPending: ((el: Computed<any>) => boolean) | null = null;
332+
// External-source bridge (wired by enableExternalSource(); null while no
333+
// config is active — including after _resetExternalSourceConfig()).
334+
static _wireExternalSource: ((self: Computed<any>) => void) | null = null;
335+
static _externalUntrack: (<T>(fn: () => T) => T) | null = null;
331336
// Verdict-layer hooks (wired by verdict.ts when isPending()/latest() are
332337
// imported; null in apps that never use them). Call sites either guard for
333338
// null or sit behind state only the verdict layer can create (`!` is safe
@@ -686,13 +691,10 @@ export function finalizePureQueue(
686691
const optimisticStores = completingTransition
687692
? completingTransition._optimisticStores
688693
: globalQueue._optimisticStores;
689-
if (GlobalQueue._clearOptimisticStore && optimisticStores.size) {
690-
for (const store of optimisticStores) {
691-
GlobalQueue._clearOptimisticStore(store);
692-
}
693-
optimisticStores.clear();
694-
schedule();
695-
}
694+
// A non-empty set means trackOptimisticStore ran, which installed the
695+
// hook; the hook iterates, clears, and schedules (keeping the loop out of
696+
// core lets esbuild shake it — rollup already folds the null guard).
697+
if (optimisticStores.size) GlobalQueue._clearOptimisticStores!(optimisticStores);
696698
sweepTransientStoreNodes();
697699
// Lanes only enter activeLanes through the engine's getOrCreateLane.
698700
if (activeLanes.size) GlobalQueue._cleanupLanes!(completingTransition);

‎packages/solid-signals/src/store/optimistic.ts‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ export function createOptimisticStore<T extends object = {}>(
9898
// STORE_OPTIMISTIC take the engine's write path, so install it before any
9999
// node can be created.
100100
installOptimisticEngine();
101-
GlobalQueue._clearOptimisticStore ||= clearOptimisticStore;
101+
GlobalQueue._clearOptimisticStores ||= clearOptimisticStores;
102102
const derived = typeof first === "function";
103103
const initialValue = (derived ? second : first) as T;
104104
const fn = derived
@@ -111,12 +111,16 @@ export function createOptimisticStore<T extends object = {}>(
111111
return [wrappedStore, (fn: (draft: T) => void): void => storeSetter(wrappedStore, fn)];
112112
}
113113

114-
// Clear optimistic override for a store and notify signals
115-
function clearOptimisticStore(store: any): void {
116-
const target = store[$TARGET] as StoreNode | undefined;
117-
if (!target?.[STORE_OPTIMISTIC_OVERRIDE]) return;
118-
119-
clearOptimisticOverride(target);
114+
// Clear the optimistic overrides of a settling batch of stores and notify
115+
// signals. Owns the whole batch (iterate + clear + reschedule) so the
116+
// scheduler's flush tail carries only a size-guarded hook call.
117+
function clearOptimisticStores(stores: Set<any>): void {
118+
for (const store of stores) {
119+
const target = store[$TARGET] as StoreNode | undefined;
120+
if (target?.[STORE_OPTIMISTIC_OVERRIDE]) clearOptimisticOverride(target);
121+
}
122+
stores.clear();
123+
schedule();
120124
}
121125

122126
function clearOptimisticOverride(target: StoreNode): void {

0 commit comments

Comments
 (0)