@zakkster/lite-signal 1.5.0-beta.1 → 1.6.0-alpha
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +235 -0
- package/README.md +115 -30
- package/Signal.d.ts +84 -0
- package/Signal.js +165 -9
- package/llms.txt +141 -31
- package/package.json +7 -3
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,241 @@ All notable changes to `@zakkster/lite-signal` are documented here.
|
|
|
4
4
|
Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
5
5
|
This project follows [Semantic Versioning](https://semver.org/).
|
|
6
6
|
|
|
7
|
+
## [1.6.0-alpha.0] -- 2026-07-XX
|
|
8
|
+
|
|
9
|
+
The observability-and-lifecycle minor, shipping on the `alpha` dist-tag while it
|
|
10
|
+
settles. Three additions: `stats()` gains a twelfth key, **`flushPasses`**, plus two
|
|
11
|
+
flush-profiling mutation-hook opcodes -- the flush/recompute dimension
|
|
12
|
+
lite-devtools 1.2 / lite-studio 1.2 read through `watchAllocations`;
|
|
13
|
+
**`createScope(fn)`**, the disposable-owner counterpart to
|
|
14
|
+
`createRoot` that a keyed-list / scene reconciler needs for per-item teardown;
|
|
15
|
+
and **`getOwner` / `runWithOwner`** carried forward from 1.5.0-beta.2 as the
|
|
16
|
+
capture-and-restore companion to `createRoot`. The engine hot path is **no
|
|
17
|
+
longer byte-identical to 1.5** for the first time since 1.2.2 -- `markDownstream`
|
|
18
|
+
and `flushEffects` picked up hook-gated fires for the two new opcodes -- but
|
|
19
|
+
the gate is a single branch-predicted `null` check per fire site and the
|
|
20
|
+
observable cost only shows on the cheapest propagation shapes (KAIROS, DEEP
|
|
21
|
+
CHAIN); the wide-aggregation and dynamic-DAG wins are unchanged. Drop-in over
|
|
22
|
+
1.5.1-beta.1.
|
|
23
|
+
|
|
24
|
+
### Added -- `flushPasses` on `stats()` + flush-profiling opcodes
|
|
25
|
+
|
|
26
|
+
`stats()` now returns **12 keys**: the 11 from 1.4.x plus `flushPasses`, a counter
|
|
27
|
+
that advances once per effect-flush drain pass. Two `onGraphMutation` opcodes back
|
|
28
|
+
the flush dimension:
|
|
29
|
+
|
|
30
|
+
- **`6` flush pass** -- `(passCount, effectsToRun)`, at the top of each drain pass.
|
|
31
|
+
- **`7` effect run in pass** -- `(id, 0)`, before each effect re-run inside a pass.
|
|
32
|
+
|
|
33
|
+
Both the counter bump and the opcode dispatch sit behind the existing
|
|
34
|
+
`if (mutationHook !== null)` gate, so when no profiler is attached they are inert:
|
|
35
|
+
`flushPasses` is frozen and the flush loop is byte-identical to 1.5.0 EXCEPT for
|
|
36
|
+
the added `null` check itself. The residual cost is one branch-predicted `null`
|
|
37
|
+
check per fire site (per pass in `flushEffects`, per enqueued dirty subscriber
|
|
38
|
+
in `markDownstream`'s inner loop). Measurable on the very cheapest propagation
|
|
39
|
+
shapes where every iteration matters -- KAIROS moves from -7% -> -12% vs alien
|
|
40
|
+
on the 1.6.0-alpha sweep, DEEP CHAIN from -14% -> -21% -- and invisible on the
|
|
41
|
+
allocation-dominated shapes where the ratio of pool retracking to marker walks
|
|
42
|
+
favors lite by orders of magnitude (SELECTIVE DAG +49%, DYNAMIC DAG +43%, MUX
|
|
43
|
+
+35%, SMALL SELECTIVE +29% -- all unchanged from the 1.5.0-beta sweep). When a
|
|
44
|
+
profiler is actually attached the observable becomes the profiler's own cost and
|
|
45
|
+
the gate itself disappears from the picture. This is what lets `watchAllocations`
|
|
46
|
+
chart recompute/flush activity alongside the 1.4.0 allocation counters
|
|
47
|
+
(`totalAllocations` / `poolGrowths` / `totalDisposals`), which remain available
|
|
48
|
+
from 1.4.0 on every engine -- only the flush series requires 1.6.
|
|
49
|
+
|
|
50
|
+
The `03-pool` test for the `stats()` shape is bumped from "11-key 1.4.0 shape"
|
|
51
|
+
to "12-key 1.6 shape" with `flushPasses` in the expected key list.
|
|
52
|
+
|
|
53
|
+
### Added -- `createScope(fn)` (disposable owner scope)
|
|
54
|
+
|
|
55
|
+
`createScope` runs `fn(dispose)` in a detached scope and returns whatever `fn`
|
|
56
|
+
returns, having handed `fn` a single `dispose` that **cascade-disposes every effect
|
|
57
|
+
and computed created inside `fn`**. It is the lifecycle complement to `createRoot`:
|
|
58
|
+
|
|
59
|
+
- `createRoot(fn)` only **detaches** -- nodes created inside are unowned and the
|
|
60
|
+
caller must dispose each one by hand (there is no owner to do it automatically).
|
|
61
|
+
Correct for spawning one known long-lived watcher (lite-query's pattern).
|
|
62
|
+
- `createScope(fn)` **adopts** -- it owns whatever `fn` builds, so one disposer tears
|
|
63
|
+
down a subtree of *unknown* shape. This is what a per-item scope in a keyed-list or
|
|
64
|
+
scene reconciler requires, where the item's reactive graph is the consumer's
|
|
65
|
+
`mapFn`, not something the reconciler can enumerate.
|
|
66
|
+
|
|
67
|
+
**Semantics.** `fn` runs once in a detached, untracked context: no ownership and no
|
|
68
|
+
dependency leak from `fn`'s direct body into the enclosing scope, and the scope owner
|
|
69
|
+
never re-runs. Reactive bindings belong in inner effect/computed bodies inside `fn`
|
|
70
|
+
(those track normally and are owned by the scope); direct-body reads are untracked.
|
|
71
|
+
Consistent with the 1.2.0 ownership rule, **plain signals created directly in `fn` are
|
|
72
|
+
not adopted** -- dispose those explicitly (the creator holds the handle) or let them
|
|
73
|
+
fall out of reference; computeds and effects are adopted and cascade.
|
|
74
|
+
|
|
75
|
+
**Implementation.** The scope owner is backed by a never-re-running effect node, so it
|
|
76
|
+
counts as one effect in `stats()` and its disposer is the same gen-guarded, ABA-safe,
|
|
77
|
+
introspection-stamped handle `effect()` returns (`describe` / `nodeId` / `forEachOwned`
|
|
78
|
+
resolve it to the owner). No new node kind, flag, or `stats()` key -- the pinned
|
|
79
|
+
`signals + computeds + effects === activeNodes` invariant is untouched. The API
|
|
80
|
+
(`fn => dispose`) is the stable contract; a future engine may swap in a lighter
|
|
81
|
+
pure-owner node transparently.
|
|
82
|
+
|
|
83
|
+
Exported as a registry method and a top-level helper bound to the default registry,
|
|
84
|
+
mirroring `createRoot`.
|
|
85
|
+
|
|
86
|
+
### Added -- `getOwner` / `runWithOwner` (carried forward from 1.5.0-beta.2)
|
|
87
|
+
|
|
88
|
+
The re-attach companion to `createRoot`, ported forward from 1.5.0-beta.2
|
|
89
|
+
unchanged. `getOwner()` returns the current owner as an **opaque, gen-stamped
|
|
90
|
+
handle** (or `undefined` outside any effect/computed body); `runWithOwner(handle,
|
|
91
|
+
fn)` runs `fn` with the captured lifecycle scope reinstated so effects/computeds
|
|
92
|
+
created directly in `fn` are adopted by that owner. Nulls the tracking observer
|
|
93
|
+
for the duration of `fn` (same pairing as `createRoot`) so accidental cross-async
|
|
94
|
+
edges cannot form.
|
|
95
|
+
|
|
96
|
+
Handles are gen-stamped (the same `NODE_GEN` ABA-guard machinery
|
|
97
|
+
`describe` / `nodeId` / `forEachOwned` / `ownerOf` have used since 1.2.1) --
|
|
98
|
+
safe to hold across async boundaries. If the captured owner is disposed and
|
|
99
|
+
its pool slot recycled by an unrelated effect via the LIFO free list, the gen
|
|
100
|
+
no longer matches and `runWithOwner` degrades to **rooted execution** rather
|
|
101
|
+
than corrupting the graph. Two hazards on the raw-pointer alternative were
|
|
102
|
+
empirically reproduced against a 1.5.0-beta engine patched with the naive
|
|
103
|
+
implementation (`Publications/owner-hazard-repro.mjs`) and are pinned in
|
|
104
|
+
`test/28-run-with-owner.test.mjs`:
|
|
105
|
+
|
|
106
|
+
- **Recycled-slot cascade death** -- capture, dispose owner, allocate a stranger
|
|
107
|
+
effect that reuses the slot, `runWithOwner(captured)` silently adopts
|
|
108
|
+
continuation into the stranger, stranger's re-run cascade-disposes it.
|
|
109
|
+
- **Corpse adoption = engine crash** -- capture, dispose owner but not-yet-
|
|
110
|
+
recycled, `runWithOwner(captured, () => effect(...))` splices a child into
|
|
111
|
+
a disposed owner's `firstOwned` and the next disposal walk recurses without
|
|
112
|
+
termination (`RangeError: Maximum call stack size exceeded`).
|
|
113
|
+
|
|
114
|
+
Both fail on the raw-pointer sketch; both pass on the shipped `describeNode` /
|
|
115
|
+
`liveNode` implementation. Test coverage: 16 tests in `test/28-run-with-owner`
|
|
116
|
+
(basic shape, degradation, and the three hazard pins with allocation pressure
|
|
117
|
+
applied so the ABA guard is genuinely exercised).
|
|
118
|
+
|
|
119
|
+
Exported as registry methods and top-level helpers, mirroring `createRoot` /
|
|
120
|
+
`createScope`.
|
|
121
|
+
|
|
122
|
+
### Added -- characterization harnesses (`burst-dag.mjs`, `pull-stress.mjs`)
|
|
123
|
+
|
|
124
|
+
Two root-level standalone harnesses that exercise the new 1.6.0 instrumentation
|
|
125
|
+
surface against the engine's two main hot paths. Both are engine-agnostic
|
|
126
|
+
(`./Signal.js` + public `onGraphMutation` only), both expose a CLI + module
|
|
127
|
+
exports, both stay out of `npm test` and the published tarball.
|
|
128
|
+
|
|
129
|
+
**`burst-dag.mjs`** (`npm run profile:burst`, also `node --expose-gc burst-dag.mjs
|
|
130
|
+
[--width=512 --layers=32 ...]`) reconstructs the published
|
|
131
|
+
`js-reactivity-benchmark` burst shape (sources -> width x layers, fanIn 8, burst
|
|
132
|
+
16) and characterizes lite-signal's own flush behavior. The standalone path uses
|
|
133
|
+
the new `stats().flushPasses` counter as a cross-check against the opcode-6 pass
|
|
134
|
+
count -- by construction they must match when the hook is attached for exactly
|
|
135
|
+
one burst, which the harness asserts inline. Also exports `burstDagScenario`
|
|
136
|
+
(for plugging into a steady-state allocation gate) and `multiPassProbe` (a
|
|
137
|
+
controlled two-effect write-back that forces a `passes > 1` case so the opcode
|
|
138
|
+
dispatch can be smoke-tested on an engine where multi-pass actually occurs).
|
|
139
|
+
|
|
140
|
+
**`pull-stress.mjs`** (`npm run profile:pull`, also `node --expose-gc
|
|
141
|
+
pull-stress.mjs [--maxDepth=3584 --step=512 ...]`) is the pull-path companion:
|
|
142
|
+
characterizes how the recursive pull scales with chain depth and binary-searches
|
|
143
|
+
the exact overflow point. Three answers per run: (1) the exact deepest chain
|
|
144
|
+
that pulls successfully (the roadmap's "~5,000 chained computeds" pinned to a
|
|
145
|
+
number for the current engine), (2) per-level cold cost across a depth sweep
|
|
146
|
+
(should be roughly linear; superlinear flags a per-node bookkeeping cost
|
|
147
|
+
growing with depth), and (3) cached-read cost (should be O(1) regardless of
|
|
148
|
+
depth via the 1.1.4 `markEpoch` short-circuit). Structure pass at a safe fixed
|
|
149
|
+
depth confirms the opcode triple (0 flush passes, 0 effect runs, recomputes ==
|
|
150
|
+
depth) -- the pull path is doing nothing it shouldn't. Also exports
|
|
151
|
+
`pullStressScenario` for steady-state allocation gates and `probeOverflow`
|
|
152
|
+
for the binary search alone. Both `--kind=callable` and `--kind=box` are
|
|
153
|
+
supported and surface a real engine difference (box pulls overflow earlier
|
|
154
|
+
because `box.get()` adds a prototype-method frame per level, and cached box
|
|
155
|
+
reads are several times more expensive than cached callable reads).
|
|
156
|
+
|
|
157
|
+
Both files import only `./Signal.js`, so the same harness runs against any
|
|
158
|
+
engine build: point `Signal.js` at 1.5.x to compare without the counters
|
|
159
|
+
(`burst-dag` adapts -- only opcode 5 fires on that engine -- and `pull-stress`
|
|
160
|
+
works identically), or at a rejected candidate to re-verify on. The numbers
|
|
161
|
+
they produce are reproducible, comparable, and engine-version-aware.
|
|
162
|
+
|
|
163
|
+
### Verified
|
|
164
|
+
|
|
165
|
+
- **Full suite green** against the 1.6.0-alpha engine (getOwner + runWithOwner
|
|
166
|
+
merged in from 1.5.0-beta.2): **447 tests**, 436 pass, 0 fail, 1 skip
|
|
167
|
+
(only the architecturally-N/A SSR case in `17-reactivity`), 10 cancelled
|
|
168
|
+
(the `25-devtools-real-boot` cases that need `@zakkster/lite-devtools`
|
|
169
|
+
installed as a peer -- pre-existing, unrelated to any 1.6 change). +4
|
|
170
|
+
`createScope` tests in `test/28-scope_test.mjs`; +16 `getOwner` /
|
|
171
|
+
`runWithOwner` tests in `test/28-run-with-owner.test.mjs` (basic shape,
|
|
172
|
+
degradation, and the three hazard pins -- recycled-slot cascade / corpse
|
|
173
|
+
adoption / composed with allocation pressure); the 1.5.0 box and createRoot
|
|
174
|
+
suites carry forward unchanged. `test/03-pool` "stats() shape" test
|
|
175
|
+
updated from the 11-key 1.4.0 shape to the 12-key 1.6 shape (adds
|
|
176
|
+
`flushPasses`). **Coverage** (c8@11, Node 22): `Signal.js` 100% statements /
|
|
177
|
+
96.96% branches / 100% functions / 100% lines; `Watch.js` 100% across all
|
|
178
|
+
four. The branch drop vs 1.5.0 (97.35% -> 96.96%) is the zero-cost gate on
|
|
179
|
+
`flushPasses` / opcode 6 / opcode 7 -- the `if (mutationHook !== null)`
|
|
180
|
+
mutation-hook-attached branch is not exercised by the active test suite,
|
|
181
|
+
which never attaches a hook; the inert path is covered.
|
|
182
|
+
- **`createScope` behavior** (4 tests, `node --expose-gc`): returns `fn`'s value and
|
|
183
|
+
runs the owner exactly once even when `fn` reads signals in its direct body
|
|
184
|
+
(untracked); inner effects/computeds track and update; `dispose()` cascade-disposes
|
|
185
|
+
the owned subtree (effects + computeds) while an un-adopted signal correctly
|
|
186
|
+
survives; a disposed scope's inner effects stop firing; **a scope created inside a
|
|
187
|
+
consumer effect survives that consumer's re-run** (the reconciler-critical detach
|
|
188
|
+
property); `dispose()` is an idempotent no-op on the second call; the disposer is
|
|
189
|
+
introspection-stamped to its owner effect; and `totalAllocations - totalDisposals
|
|
190
|
+
=== activeNodes` holds after teardown. Plus a smoke confirming signal -> computed ->
|
|
191
|
+
effect is unaffected by the additive change.
|
|
192
|
+
- **`getOwner` / `runWithOwner` port**: sha256 over the extracted function bodies of
|
|
193
|
+
`pullComputed`, `executeEffect`, `allocateLink`, `severTail`, `createNode`,
|
|
194
|
+
`runCleanup`, `disposeNode`, `createRoot`, `createScope` matches the pristine
|
|
195
|
+
1.6.0-alpha engine byte-for-byte -- port touched no hot path. `Publications/
|
|
196
|
+
owner-hazard-repro.mjs` reports **`VERDICT: SAFE`** on the merged engine on both
|
|
197
|
+
hazards (continuation runs 2 times before stranger disposal, 3 after; corpse
|
|
198
|
+
case runs 2 without `RangeError`).
|
|
199
|
+
- **Instrumentation is zero-cost when unobserved**: `flushPasses` advances and opcodes
|
|
200
|
+
6/7 fire only while a mutation-hook listener is attached; with none, the two hook
|
|
201
|
+
fire sites are pure `null`-check branches (branch-predicted-free after warmup).
|
|
202
|
+
|
|
203
|
+
### Verified -- fresh 1.6.0-alpha bench sweep
|
|
204
|
+
|
|
205
|
+
Both benches re-run on the 1.6.0-alpha engine and committed to
|
|
206
|
+
`bench/results.txt` (isolated propagation, 9 scenarios) and
|
|
207
|
+
`bench/resultsReactive.txt` (cross-framework reactivity, median-of-10, 34
|
|
208
|
+
tests). The 10 raw reactive-suite runs sit under `bench/bench-runs-reactive/
|
|
209
|
+
run_1.txt` ... `run_10.txt` so anyone can re-median independently.
|
|
210
|
+
|
|
211
|
+
- **Propagation bench (results.txt):** lite +49% / +43% / +35% / +29% on the four
|
|
212
|
+
allocation-heavy scenarios (SELECTIVE DAG / DYNAMIC DAG / MUX / SMALL
|
|
213
|
+
SELECTIVE) -- unchanged in character from the 1.5.0-beta sweep, the gate is
|
|
214
|
+
round-off on allocation-dominated shapes. Parity on LARGE WEB APP (-3%) and
|
|
215
|
+
WIDE DENSE (-6%), inside host noise. **Alien-signals ahead on BROADCAST
|
|
216
|
+
(-10%), KAIROS (-12%, was -7% on 1.5.0-beta), and DEEP CHAIN (-21%, was -14%
|
|
217
|
+
on 1.5.0-beta)** -- the KAIROS and DEEP CHAIN widening is the observable
|
|
218
|
+
gate cost on shapes where every branch matters. Speed wins vs alien: **4/9**
|
|
219
|
+
(was 5/9); heap wins: **8/9** (unchanged).
|
|
220
|
+
- **Reactive suite (resultsReactive.txt):** fastest of five frameworks on all
|
|
221
|
+
five `dyn` rows (simple +19%, dynamic +13%, large web app +11%, wide dense
|
|
222
|
+
+4%, deep +16%). On the `S: updateComputations` micro-rows lite trades the
|
|
223
|
+
lead with alien: **4/7 wins this sweep** (was 7/7 on 1.5.0-beta), consistent
|
|
224
|
+
with the gate cost on 50-70ms rows that iterate many thousands of times per
|
|
225
|
+
measurement.
|
|
226
|
+
- **Andrii Volynets js-reactivity-benchmark position holds at 4th of 15** with
|
|
227
|
+
geomean **73.1ms** (raw log `bench/AndriiVolynetsReactiveBench.log`, all 15
|
|
228
|
+
x 47 rows); lite is ahead of 5th-place Preact Signals (79.9) by ~9%.
|
|
229
|
+
Outright-fastest-of-15 wins jumped to **6 shapes**: `broadPropagation`,
|
|
230
|
+
`manyEffectsFromOneSource`, `manySourcesIntoOneComputedEffect`,
|
|
231
|
+
`manySourcesIntoOneComputedEffectWithDirect`, `molBench`, and the `32x8 - 4
|
|
232
|
+
sources - pull` DAG. Top-3 count: 23/47. (Outright wins swing at the top of
|
|
233
|
+
a very tight leaderboard; the stable metric across every sweep is the
|
|
234
|
+
geomean rank at 4th of 15.)
|
|
235
|
+
- **Third-party engine versions carried forward** from the 1.5.0-beta sweep
|
|
236
|
+
(alien-signals 3.2.1, @preact/signals-core 1.14.2, @vue/reactivity 3.5.35,
|
|
237
|
+
solid-js 1.9.13). No peer bumps this cycle -- the deltas here are the 1.6
|
|
238
|
+
engine's own footprint plus host noise.
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
|
|
7
242
|
## [1.5.0] -- 2026-06-XX
|
|
8
243
|
|
|
9
244
|
The API-surface minor: two new **non-callable, allocation-light** reactive
|
package/README.md
CHANGED
|
@@ -15,21 +15,21 @@
|
|
|
15
15
|
|
|
16
16
|
## 4th of 15 on the community reactivity benchmark -- and the only zero-GC engine in the field
|
|
17
17
|
|
|
18
|
-
On the independent [js-reactivity-benchmark](https://github.com/volynetstyle/js-reactivity-benchmark) (Andrii Volynets' fork; 15 reactive libraries, 47 tests), `lite-signal` places **4th overall by geomean (
|
|
18
|
+
On the independent [js-reactivity-benchmark](https://github.com/volynetstyle/js-reactivity-benchmark) (Andrii Volynets' fork; 15 reactive libraries, 47 tests), `lite-signal` places **4th overall by geomean (73.1ms)** -- ahead of 5th-place Preact Signals (79.9) by ~9%, behind only three push-eager engines: alien-signals (48.1), reflex (49.8), and @reactively (58.3). Raw log: [`bench/AndriiVolynetsReactiveBench.log`](./bench/AndriiVolynetsReactiveBench.log) (all 15 x 47 rows, checked in for audit).
|
|
19
19
|
|
|
20
20
|
It is the **only object-pooled, zero-GC engine in the entire field**, and it gets that result without giving up glitch-freedom or lazy evaluation. Against the mainstream reactivity libraries it leads decisively:
|
|
21
21
|
|
|
22
22
|
| vs | lite-signal is |
|
|
23
23
|
| ---------------------- | -------------- |
|
|
24
|
-
| **@vue/reactivity** | **1.
|
|
25
|
-
| **Signia** | **
|
|
26
|
-
| **MobX** | **2.
|
|
27
|
-
| **@solidjs/signals** | **
|
|
28
|
-
| **SolidJS** | **4.
|
|
29
|
-
| Preact Signals | **1.
|
|
30
|
-
| alien-signals | 0.
|
|
24
|
+
| **@vue/reactivity** | **1.6x faster** |
|
|
25
|
+
| **Signia** | **2.0x faster** |
|
|
26
|
+
| **MobX** | **2.3x faster** |
|
|
27
|
+
| **@solidjs/signals** | **2.8x faster** |
|
|
28
|
+
| **SolidJS** | **4.2x faster** |
|
|
29
|
+
| Preact Signals | **1.09x faster** (~9% ahead) |
|
|
30
|
+
| alien-signals | 0.66x (the field leader) |
|
|
31
31
|
|
|
32
|
-
`lite-signal` finishes **top-3 on
|
|
32
|
+
`lite-signal` finishes **top-3 on 23 of the 47 tests** and, on this run, is **outright fastest of all 15** on **six shapes** -- `broadPropagation` (wide fan-out from one source), `manyEffectsFromOneSource` (1 source -> many effects), `manySourcesIntoOneComputedEffect` and `manySourcesIntoOneComputedEffectWithDirect` (both wide fan-in aggregation shapes), `molBench` (the mixed-app graph the suite uses as its realistic-workload proxy), and `32x8 - 4 sources - pull (pure pull)` (a stable rectangular DAG pulled from the tip). The wide-aggregation and mixed-app-graph pattern is where lite's zero-allocation retracking pays off most; those six shapes together are the ones that dominate live dashboards, scoreboards, and HUDs under input churn. The three engines ahead of it are all push-eager designs that allocate on the hot path; `lite-signal` is the only top-4 finisher that allocates **nothing** in steady state. (Note: this suite measures reactivity *libraries* -- Vue's reactivity core, MobX, Solid, Preact Signals, etc. -- not full UI frameworks like React or Angular.)
|
|
33
33
|
|
|
34
34
|
```bash
|
|
35
35
|
npm install @zakkster/lite-signal
|
|
@@ -245,6 +245,8 @@ import {
|
|
|
245
245
|
signalBox, computedBox, // 1.5.0 -- allocation-light, non-callable
|
|
246
246
|
batch, untrack, onCleanup, isTracking,
|
|
247
247
|
createRoot, // 1.5.0 -- detached ownership scope
|
|
248
|
+
getOwner, runWithOwner, // 1.5.0-beta.2 -- capture + restore ownership across async gaps
|
|
249
|
+
createScope, // 1.6.0 -- adopting scope; single disposer tears down the subtree
|
|
248
250
|
// Registry / lifecycle
|
|
249
251
|
createRegistry, setDefaultRegistry, dispose, destroy,
|
|
250
252
|
stats, CapacityError,
|
|
@@ -357,7 +359,55 @@ dispose();
|
|
|
357
359
|
|
|
358
360
|
Runs `fn` in a **detached ownership scope** and returns whatever `fn` returns. Effects and computeds created directly inside `fn` are not adopted by the enclosing owner, so they survive the enclosing effect's re-runs and disposal -- there is no parent to auto-dispose them, so the caller is responsible (typically `fn` returns a disposer or the created handle). Both ownership *and* tracking are detached for the duration of `fn`'s direct body; inner effect/computed bodies still establish their own scopes as usual. Mirrors Solid's `createRoot` on the lifecycle axis.
|
|
359
361
|
|
|
360
|
-
The problem it solves: lazily spawning a *long-lived* node from *inside* a consumer effect is otherwise a footgun -- the spawned node is adopted by the consumer, so the consumer's next re-run cascade-disposes it. That is the ownership model working as designed (owned children dispose with their parent); `createRoot` is the sanctioned opt-out. Any consumer that creates a watcher/subscription inside a reactive scope and expects it to outlive that scope wraps the spawn in `createRoot(() => effect(...))` -- `lite-query`'s query-watcher being the first in the ecosystem.
|
|
362
|
+
The problem it solves: lazily spawning a *long-lived* node from *inside* a consumer effect is otherwise a footgun -- the spawned node is adopted by the consumer, so the consumer's next re-run cascade-disposes it. That is the ownership model working as designed (owned children dispose with their parent); `createRoot` is the sanctioned opt-out. Any consumer that creates a watcher/subscription inside a reactive scope and expects it to outlive that scope wraps the spawn in `createRoot(() => effect(...))` -- `lite-query`'s query-watcher being the first in the ecosystem. The companion primitives `getOwner` / `runWithOwner` -- for capturing the current owner and restoring it across an async boundary -- ship in **1.5.0-beta.2** and are carried forward into 1.6 unchanged; see the next section. **1.6.0 adds `createScope`** as the third member of the family: where `createRoot` *detaches* and leaves you to dispose each child by hand, `createScope` *adopts* and returns one disposer that tears down the subtree at once -- see the `createScope` section further below.
|
|
363
|
+
|
|
364
|
+
### getOwner / runWithOwner (1.5.0-beta.2, carried into 1.6)
|
|
365
|
+
|
|
366
|
+
The re-attach half of the ownership escape hatch. `createRoot` detaches; `getOwner` + `runWithOwner` **capture and restore**. Together they give you the Solid-shaped ownership API for the async pattern that comes up whenever you have to leave a synchronous reactive scope, do work, and come back:
|
|
367
|
+
|
|
368
|
+
```javascript
|
|
369
|
+
import { effect, getOwner, runWithOwner, signal } from '@zakkster/lite-signal';
|
|
370
|
+
|
|
371
|
+
const s = signal(0);
|
|
372
|
+
effect(() => {
|
|
373
|
+
const owner = getOwner(); // opaque, gen-stamped handle
|
|
374
|
+
fetch('/data').then(res => res.json()).then(data => {
|
|
375
|
+
runWithOwner(owner, () => { // re-enter the captured scope
|
|
376
|
+
effect(() => { console.log(s(), data); });
|
|
377
|
+
});
|
|
378
|
+
});
|
|
379
|
+
});
|
|
380
|
+
```
|
|
381
|
+
|
|
382
|
+
`getOwner()` returns the current owner as an **opaque, gen-stamped handle** (or `undefined` outside any effect/computed body). `runWithOwner(handle, fn)` runs `fn` with the captured lifecycle scope reinstated: effects and computeds created directly in `fn` are adopted by that owner and cascade-dispose when it re-runs or is disposed. Reads directly in `fn` do not link -- tracking is detached the same way `createRoot` detaches it, so accidental cross-async edges cannot form. Compose with an inner effect if you want tracking under the restored owner.
|
|
383
|
+
|
|
384
|
+
**Handles are safe to hold across async boundaries.** This is where a raw-pointer implementation would corrupt the graph: node objects are pooled and the LIFO free list recycles a disposed owner's slot into whatever effect/computed is allocated next. A stale raw pointer would silently adopt continuations into that stranger. Instead, `getOwner` returns a `describeNode` handle stamped with the pool slot's generation; `runWithOwner` resolves via `liveNode()`, and if the gen has moved (slot recycled) or the handle refers to a signal (not a tracker), it degrades to **rooted execution** -- the continuation runs, stays alive, and is simply not owned by anyone. That is the only honest semantics for "the scope you captured no longer exists": the alternative was a silent cascade-dispose by an unrelated stranger, or, if the slot was disposed but not yet recycled, a `RangeError: Maximum call stack size exceeded` inside the cleanup recursion. Both hazards are pinned in `test/28-run-with-owner.test.mjs` and empirically demonstrated in `Publications/owner-hazard-repro.mjs`.
|
|
385
|
+
|
|
386
|
+
The handles do **not** keep owners alive -- they are snapshots, not references. Node lifetime is controlled by the owner tree, not by outstanding handles.
|
|
387
|
+
|
|
388
|
+
### createScope (1.6.0)
|
|
389
|
+
|
|
390
|
+
The third member of the ownership family. `createRoot` **detaches** (no owner survives; caller disposes each child); `runWithOwner` **restores a captured owner**; `createScope` **creates a new scope owner** and returns a single disposer that cascade-disposes everything created inside it. The lifecycle primitive a keyed-list or scene reconciler needs for per-item scopes of unknown internal shape:
|
|
391
|
+
|
|
392
|
+
```javascript
|
|
393
|
+
import { createScope, effect, signal } from '@zakkster/lite-signal';
|
|
394
|
+
|
|
395
|
+
function renderItem(item) {
|
|
396
|
+
return createScope(dispose => {
|
|
397
|
+
const local = signal(item.initial);
|
|
398
|
+
effect(() => { renderTo(item.node, local()); });
|
|
399
|
+
return { dispose, update: (v) => local.set(v) };
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// Per-item teardown is one disposer, no matter what the item created inside.
|
|
404
|
+
const handle = renderItem(item);
|
|
405
|
+
handle.dispose(); // -> the effect above stops; local falls out of scope
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
`fn` receives its own `dispose` and runs ONCE in a detached, untracked context: no ownership leaks in, no dependency leaks out from `fn`'s direct body, and the scope owner itself never re-runs. Put reactive bindings in **inner** effect/computed bodies inside `fn` -- those establish their own tracking scopes AND are owned by this scope, so they update normally and are cascade-disposed on `dispose()`. Reads in `fn`'s direct body are untracked; `createScope` returns whatever `fn` returns.
|
|
409
|
+
|
|
410
|
+
Plain signals created directly in `fn` are NOT adopted -- the engine never owner-adopts signals (the lazy-alloc rule, 1.2.0) -- so dispose those explicitly (the creator holds the handle) or let them fall out of reference. Computeds and effects ARE adopted and cascade. The scope owner is backed by a never-re-running effect node, so it counts as one effect in `stats()`; its disposer is the same gen-guarded handle `effect()` returns, so ABA-safety and introspection (`describe`, `nodeId`, `forEachOwned`) match effects exactly. A scope created inside a consumer effect **survives that consumer's re-run** -- the reconciler-critical detach property. The API (`fn => dispose`) is the stable contract; a future engine may swap in a lighter pure-owner node transparently.
|
|
361
411
|
|
|
362
412
|
### isTracking
|
|
363
413
|
|
|
@@ -696,25 +746,25 @@ These are the questions you'd ask in a code review, with the answers:
|
|
|
696
746
|
|
|
697
747
|
## Benchmarks
|
|
698
748
|
|
|
699
|
-
Honest numbers, against the same workload, with anti-DCE sinks and verified effect execution. All measurements: Node 22, **2016-era Intel MacBook Pro (4 cores, ~10 yr old hardware)**, **one engine per cold process**, median across reps. Newer/faster machines shift all libs up proportionally; the relative ordering between libs is what matters. Numbers below are the **fresh 1.
|
|
749
|
+
Honest numbers, against the same workload, with anti-DCE sinks and verified effect execution. All measurements: Node 22, **2016-era Intel MacBook Pro (4 cores, ~10 yr old hardware)**, **one engine per cold process**, median across reps. Newer/faster machines shift all libs up proportionally; the relative ordering between libs is what matters. Numbers below are the **fresh 1.6.0-alpha bench sweep** (default `prealloc: "eager"`) vs alien-signals on the same `benchmark.mjs` loop -- the harness reports **median execution time + transient heap** rather than ops/s. 1.5.0 -> 1.6.0-alpha changes the hot path for the first time since 1.2.2: two new mutation-hook opcodes fire under a `null`-check gate -- op 6 (`flush-pass-start`) once per pass in `flushEffects`, op 7 (`effect-enqueue`) inside `markDownstream`'s inner loop when a dirty subscriber is enqueued -- so the sha256 of those two function bodies no longer matches 1.5. Both gates are branch-predicted-free when the hook is null; the residual cost is one predicted branch per fire site. The `flushPasses` counter on `stats()` (the new 12th key) advances only while a hook is attached. Everything else is byte-identical to 1.5.1-beta.1 (sha256-verified over `pullComputed`, `executeEffect`, `runCleanup`, `disposeNode`, `allocateLink`, `severTail`, `createNode`, `createRoot`, `createScope`). Third-party engine versions carried forward from the 1.5.0-beta sweep. Full per-engine tables: [`results.txt`](bench/results.txt) (this propagation suite) and [`resultsReactive.txt`](bench/resultsReactive.txt) (the cross-framework reactivity suite). The 10 raw reactive-suite runs are checked into [`bench/bench-runs-reactive/`](./bench/bench-runs-reactive/) so anyone can re-median them independently.
|
|
700
750
|
|
|
701
751
|
| Scenario | What it stresses | lite-signal | alien-signals | lite vs alien | transient heap (lite / alien) |
|
|
702
752
|
| ---------- | -------------------------------- | ----------- | ------------- | ------------- | ----------------------------- |
|
|
703
|
-
| **SELECTIVE DAG** | sqrt-layered, set churn, 2 read/iter | **
|
|
704
|
-
| **DYNAMIC DAG** | sqrt-layered, FAN=6, read flips each iter | **
|
|
705
|
-
| **MUX** | 256 signals -> 1 sum -> 1 effect (fan-in) | **67 ms** |
|
|
706
|
-
| **SMALL SELECTIVE** | 6 layers × 64 wide, 6 cand / 3 read | **
|
|
707
|
-
| **LARGE WEB APP** | 12 layers × ~80 wide, conditional reads |
|
|
708
|
-
| **WIDE DENSE** | 5 layers × ~200 wide, dense fan-in |
|
|
709
|
-
| **
|
|
710
|
-
| **
|
|
711
|
-
| **DEEP CHAIN** | 256-deep computed chain -> 1 effect |
|
|
753
|
+
| **SELECTIVE DAG** | sqrt-layered, set churn, 2 read/iter | **4717 ms** | 9261 ms | **+49% faster** | **1.6 MB / 29 MB** (19x less) |
|
|
754
|
+
| **DYNAMIC DAG** | sqrt-layered, FAN=6, read flips each iter | **9770 ms** | 17238 ms | **+43% faster** | **4.9 MB / 27 MB** (5.5x less) |
|
|
755
|
+
| **MUX** | 256 signals -> 1 sum -> 1 effect (fan-in) | **67 ms** | 103 ms | **+35% faster** | **38 KB / 3.9 MB** (104x less) |
|
|
756
|
+
| **SMALL SELECTIVE** | 6 layers × 64 wide, 6 cand / 3 read | **1972 ms** | 2787 ms | **+29% faster** | **0.3 KB / 22.9 MB** (>=22888x less) |
|
|
757
|
+
| **LARGE WEB APP** | 12 layers × ~80 wide, conditional reads | 2825 ms | 2733 ms | -3% (parity) | **0.3 KB / 41 KB** (41x less) |
|
|
758
|
+
| **WIDE DENSE** | 5 layers × ~200 wide, dense fan-in | 2888 ms | 2729 ms | -6% (parity) | **0.3 KB / 11.6 MB** (>=11605x less) |
|
|
759
|
+
| **BROADCAST** | 1 signal -> 1000 effects (fan-out) | 1177 ms | 1066 ms | -10% | 73 KB / 21 KB |
|
|
760
|
+
| **KAIROS** | 1 signal -> 1000 computeds -> 1 effect | 1450 ms | 1293 ms | -12% | 179 KB / 1.1 MB (6.4x less) |
|
|
761
|
+
| **DEEP CHAIN** | 256-deep computed chain -> 1 effect | 397 ms | **329 ms** | -21% | 18 KB / 942 KB (52x less) |
|
|
712
762
|
|
|
713
763
|
*(lower time = faster; transient heap = average delta-heap per rep, lower = less GC pressure)*
|
|
714
764
|
|
|
715
|
-
**Reading the table:** lite-signal's time wins cluster exactly where its zero-GC design pays off -- the **allocation-heavy dynamic shapes** (**SELECTIVE DAG +
|
|
765
|
+
**Reading the table:** lite-signal's time wins cluster exactly where its zero-GC design pays off -- the **allocation-heavy dynamic shapes** (**SELECTIVE DAG +49%**, **DYNAMIC DAG +43%**, **SMALL SELECTIVE +29%**), where alien-signals churns the nursery and lite's object pool allocates near-nothing, plus **MUX +35%** (fan-in aggregation). These four allocation-dominated wins are unchanged from the 1.5.0-beta sweep -- the mutation-hook gate is round-off on shapes where the ratio of pool retracking to marker walks favors lite by orders of magnitude. On the cheap, low-allocation **stable** shapes (LARGE WEB APP, WIDE DENSE) lite runs at **parity** with alien -- within a 3-6% band inside this old host's run-to-run noise. The three shapes where alien edges lite are BROADCAST (-10%, pure fan-out with no retracking to amortize), KAIROS (-12%, was -7% on 1.5.0-beta), and the 256-deep pipeline **DEEP CHAIN (-21%**, was -14% on 1.5.0-beta): the gate cost is measurable on shapes that iterate 1000-25000 times per rep with tiny per-iteration work, where a single extra predicted branch per iter is a visible fraction of total time. That gate cost disappears when a profiler is actually attached -- the observable then is the profiler's own cost, not the gate itself.
|
|
716
766
|
|
|
717
|
-
On allocation pressure, `lite-signal` wins **8 of 9 scenarios** and is alone in the zero-alloc band: **~0.3 KB** of transient garbage on the stable app shapes (large web app, wide dense, small selective) across the whole run. The contrast is starkest on the dynamic DAGs -- lite allocates 1.
|
|
767
|
+
On allocation pressure, `lite-signal` wins **8 of 9 scenarios** and is alone in the zero-alloc band: **~0.3 KB** of transient garbage on the stable app shapes (large web app, wide dense, small selective) across the whole run. The contrast is starkest on the dynamic DAGs -- lite allocates 1.6-4.9 MB (genuine retracking re-links) where alien-signals allocates 27-29 MB on the same shapes, and that allocation gap is the mechanism behind lite's +43-49% wins there once each engine is measured in isolation. The one scenario where lite allocates more is **BROADCAST** (73 KB vs alien's 21 KB), a pure fan-out with no retracking. `prealloc: "lazy"` trades a little extra first-construction allocation on the dynamic shapes for a smaller resident heap and faster cold start; the steady state is identical. preact and solid trail both engines on the dynamic shapes by 1-2 orders of magnitude on transient heap.
|
|
718
768
|
|
|
719
769
|
> Note on the +70.8 KB retained that lite-signal shows on KAIROS specifically: that's the pre-allocated pool sitting in memory holding the live graph (1002 nodes + ~2000 links). The pool *is* the working memory -- see the [Case for object pooling](#case-for-object-pooling) section. On the other benches the graph is small enough that the same pool floats below baseline after GC.
|
|
720
770
|
|
|
@@ -894,11 +944,45 @@ npm run test:harness
|
|
|
894
944
|
|
|
895
945
|
The setup script pins specific package versions via tarball install so the harness can be re-run reproducibly without depending on whatever happens to be in the public registry on the day. Treat the setup as a one-time per-checkout cost.
|
|
896
946
|
|
|
947
|
+
### `test/zgc/` -- zero-GC regression gate (1.5.1)
|
|
948
|
+
|
|
949
|
+
A CI-wireable, engine-agnostic gate that proves the steady-state hot path allocates nothing and **fails on an injected allocation.** Promoted from `futureVersions/zgc/` in 1.5.1 and carried forward into 1.6. Three signals -- `perf_hooks` scavenge count (the only detector that catches transient garbage; retained-heap-only and V8 sampling profiler were both rejected as producing false passes), the exact `stats()` counters (`poolGrowths`, `totalAllocations`, `activeNodes`, and now `flushPasses` on 1.6), and retained-heap delta as a leak check -- measured at N and k*N iterations so the verdict scales rather than depending on one absolute threshold. Seven scenarios in the test file: positive control (must flag), negative control (must not), three steady-state graphs (deep chain x16, wide fan-out x32, batched 8-signal writes), create/dispose churn on `signalBox` (asserts pool recycles), and an injected-allocation self-test the verdict MUST fail. Detector calibration: N=200000, k=8 (1.6M updates per scenario); positive control uses a `{x,y,z,w}` four-field object shape.
|
|
950
|
+
|
|
951
|
+
```bash
|
|
952
|
+
npm run test:zgc # what CI runs; passes --expose-gc + --max-semi-space-size=4
|
|
953
|
+
npm run test:zgc:report # human-readable standalone report (re-execs with the small young-gen)
|
|
954
|
+
```
|
|
955
|
+
|
|
956
|
+
Both flags are required (`--expose-gc` for the explicit `gc()` calls in the meter, `--max-semi-space-size=4` for per-iteration sensitivity); the scripts set both so a caller cannot invoke the gate under-powered. Verified against 1.6.0-alpha: all seven scenarios pass, positive control forces scavenges well above the threshold, the churn scenario recycles 1.6M node allocations through the free list with 0 pool growths. The mutation-hook gate opcodes added in 1.6 do not perturb the zero-GC contract because they are hook-gated (`if (mutationHook !== null)`) -- with no profiler attached the gate is a no-op and the pool churn is unchanged.
|
|
957
|
+
|
|
958
|
+
### `harness/burst-dag.mjs` and `harness/pull-stress.mjs` -- 1.6 profiling harnesses
|
|
959
|
+
|
|
960
|
+
Two standalone profiling harnesses that consume the new op 6/7 mutation-hook counters to characterise **shape**-specific engine behaviour that the throughput benches can only aggregate over. Both are engine-agnostic (import `./Signal.js` only) and dual-mode: standalone runners with a human-readable verdict, or mountable as scenarios in the zero-GC gate. Wired as `npm run profile:burst` and `npm run profile:pull`.
|
|
961
|
+
|
|
962
|
+
**`burst-dag.mjs`** -- the burst-flush characterisation harness. Reconstructs the [js-reactivity-benchmark] burst shape from its published parameters (256->512x32, `fanIn 8`, `burst 16`) and answers **one** question the roadmap hinges on: is the ~2x gap on that shape **redundant work** (multi-pass flush re-marking already-clean cones, fixable by coalescing) or **locality at scale** (touching ~16k nodes' worth of marks + pulls per burst, not fixable without a layout change -- and layout changes have been shown to deopt the propagation hot path)? The structure probe reports `flush passes per burst` and `max recomputes per node` via the op 6/7 counters; if both are 1, there is nothing to coalesce and the gap is pure locality. It then runs a median-of-N timed pass with the profiler detached (the comparable number) and prints a verdict.
|
|
963
|
+
|
|
964
|
+
**`pull-stress.mjs`** -- the pull-mode recursion characterisation harness. Answers three questions on the current engine:
|
|
965
|
+
|
|
966
|
+
1. **Exact overflow depth** -- binary-searched via `try`/`catch` on `read()` for a linear chain `c[0] <- c[1] <- ... <- c[N-1]`. The number reported is the deepest chain that pulls successfully (not the first that throws); both ends of the search interval are reported. Roadmap names this as the pull-mode recursion depth limit (~5,000 chained computeds); this pins the exact number on the current engine and becomes the before/after baseline for the eventual iterative-pull rewrite.
|
|
967
|
+
2. **Per-level cost** -- median cold-pull us / depth across a sweep. Should be roughly linear; a knee flags a per-node bookkeeping cost that grows with depth (effect-set walk, owner chain, dep-list scan).
|
|
968
|
+
3. **Steady-state pull cost** -- median cached-read us. Should be O(1) via the 1.1.4 `markEpoch` / version short-circuit, INDEPENDENT of depth.
|
|
969
|
+
|
|
970
|
+
Also verifies the structure of the cold-pull correctness: opcode 6 (flush pass) MUST be 0, opcode 7 (effect enqueued) MUST be 0, opcode 5 (recompute) MUST equal depth. A correct engine produces this exact triple; deviation is a real finding, reported as a STRUCTURE FAILED verdict that suppresses the timing summary.
|
|
971
|
+
|
|
972
|
+
```bash
|
|
973
|
+
npm run profile:burst # 256->512x32 burst shape: passes/recomputes + median timed run
|
|
974
|
+
npm run profile:pull # per-level cost + exact overflow depth + O(1) cached-read sanity
|
|
975
|
+
```
|
|
976
|
+
|
|
977
|
+
Both harnesses land in 1.6 alongside the mutation-hook opcodes they consume; they are not test files (no assertion budget beyond the structure invariants), they are characterisation tools intended to make the "is this shape's cost redundant work or locality?" question answerable reproducibly on any engine build.
|
|
978
|
+
|
|
897
979
|
### Notes
|
|
898
980
|
|
|
899
|
-
- The hardening suite and the profiler integration do **not** run on `npm test` from the root. They opt in through the `test:hardening` / `test:harness` scripts (and `test:all`, which chains everything).
|
|
981
|
+
- The hardening suite and the profiler integration do **not** run on `npm test` from the root. They opt in through the `test:hardening` / `test:harness` scripts (and `test:all`, which chains everything including `test:zgc`).
|
|
900
982
|
- The **VersionMatrix gate**, by contrast, IS wired into `prepublishOnly` -- a regression on the four reference workloads blocks `npm publish`. Diagnostic runs (`node diff.mjs`) are opt-in from the harness directory.
|
|
901
|
-
-
|
|
983
|
+
- The **zero-GC gate** is wired into `test:zgc` and chained by `test:all` / `verify`; on 1.6 it also validates that the two new hook-gated opcodes have not perturbed the steady-state contract.
|
|
984
|
+
- The **profiling harnesses** (`burst-dag.mjs`, `pull-stress.mjs`) are characterisation tools, not assertion gates; run them via `profile:burst` / `profile:pull` when investigating a specific shape's cost model.
|
|
985
|
+
- All harness subdirectories have their own `package.json` with local scripts where appropriate, so you can also `cd` in and run `npm test` directly -- the root scripts are just shortcuts.
|
|
902
986
|
- The `npm --prefix <dir> test` form used in the root scripts is the cross-platform replacement for `cd && npm test` -- works identically on Linux, macOS, and Windows.
|
|
903
987
|
|
|
904
988
|
---
|
|
@@ -906,7 +990,7 @@ The setup script pins specific package versions via tarball install so the harne
|
|
|
906
990
|
## Performance Trade-offs & Topology Scaling
|
|
907
991
|
|
|
908
992
|
<details>
|
|
909
|
-
<summary>Stable vs dynamic topologies; Andrii Volynets' matrix, the 1.1.4 result, the 1.
|
|
993
|
+
<summary>Stable vs dynamic topologies; Andrii Volynets' matrix, the 1.1.4 result, the 1.6.0-alpha ranking, and the roadmap.</summary>
|
|
910
994
|
|
|
911
995
|
`lite-signal` was built with a strict mandate: **absolute zero garbage collection**. By packing the dependency graph into a flat, pre-allocated memory arena, we eliminate the Scavenger GC pauses that plague 120fps Canvas/WebGL loops.
|
|
912
996
|
|
|
@@ -914,7 +998,7 @@ Through **v1.1.2**, that came with a mathematical trade-off: while memory alloca
|
|
|
914
998
|
|
|
915
999
|
**Andrii Volynets** (author of the phenomenal [Alien Signals](https://github.com/stackblitz/alien-signals)) generously ran `lite-signal` through his advanced topology matrix on the **v1.1.2** engine. Those numbers -- the *pre-rewrite baseline* -- are below, followed by the 1.1.4 result.
|
|
916
1000
|
|
|
917
|
-
**1.
|
|
1001
|
+
**1.6.0-alpha on the official [js-reactivity-benchmark](https://github.com/volynetstyle/js-reactivity-benchmark) (15 libraries, 47 tests):** `lite-signal` holds **4th overall by geomean (73.1ms)**, behind only alien-signals (48.1, the field leader at 0.66x), reflex (49.8), and @reactively (58.3), and **ahead of 5th-place Preact Signals (79.9, ~9%)**. Preact recovered from the anomalous 99.8 it hit on the 1.5.0-beta sweep (that was a Preact-side artifact of the 1.14.2 bump), so the gap narrowed from 21% to 9% -- but lite's own geomean improved (79.3 -> 73.1) at the same time, so the direction stays positive. It finishes **top-3 on 23 of 47 tests** and, on this run, is **outright fastest of all 15 on SIX shapes**: `broadPropagation`, `manyEffectsFromOneSource` (wide fan-out from one source), `manySourcesIntoOneComputedEffect` and `manySourcesIntoOneComputedEffectWithDirect` (wide fan-in), `molBench` (mixed app graph), and `32x8 - 4 sources - pull (pure pull)` (a stable rectangular DAG pulled from the tip). That is the biggest outright-win count across every sweep published (was 5 on 1.4.0, 2 on 1.5.0-beta -- outright wins swing at the top of a very tight leaderboard where alien / reflex / lite trade sub-percent margins). The stable metric across every sweep is the geomean rank at 4th of 15, and lite remains the only object-pooled, zero-GC engine in the field. Raw log with all 15 x 47 rows: [`bench/AndriiVolynetsReactiveBench.log`](./bench/AndriiVolynetsReactiveBench.log).
|
|
918
1002
|
|
|
919
1003
|
#### 1. Stable Topologies (Fan-in / Fan-out / Broadcast)
|
|
920
1004
|
In stable environments (game engines, particle systems, visualizers), `lite-signal` is blisteringly fast and maintains a near-zero allocation profile, keeping frame times perfectly flat -- unchanged through 1.1.4.
|
|
@@ -948,17 +1032,18 @@ In stable environments (game engines, particle systems, visualizers), `lite-sign
|
|
|
948
1032
|
> engine changes. lite remains the only zero-alloc library on every stable scenario
|
|
949
1033
|
> (see [`results.txt`](bench/results.txt)).
|
|
950
1034
|
|
|
951
|
-
The cross-framework reactivity suite agrees independently, re-run on **1.
|
|
1035
|
+
The cross-framework reactivity suite agrees independently, re-run on **1.6.0-alpha** (default eager, median-of-10, isolated): lite-signal is the **fastest of five frameworks on all five `dyn` rows** -- `dyn: large web app` **536ms** (+11% vs alien-signals' 600ms) and `dyn: wide dense` **903ms** (+4% vs 939ms), plus simple component (+19%), dynamic component (+13%), and deep (+16%) -- with preact 6-19x slower and vue 15-33x slower on the app-shaped graphs (see [`resultsReactive.txt`](bench/resultsReactive.txt); the 10 raw runs are checked into [`bench/bench-runs-reactive/`](./bench/bench-runs-reactive/)). On the `S: updateComputations` micro-rows lite trades the lead with alien within a few percent (4/7 wins on this sweep, was 7/7 on 1.5.0-beta -- the shift is consistent with the two new hook-gated branches in `markDownstream` / `flushEffects`, each a single predicted `null` check per fire site but visible on 50-70ms rows that iterate many thousands of times). The retracking is verified correct by `retracking.difftest.mjs` -- 20,000 direct + 10,000 batched writes, 0 disagreements against the **published 1.1.5** reference (re-pinned for v1.2).
|
|
952
1036
|
|
|
953
|
-
**The Takeaway:** as of 1.1.4 you no longer have to choose, and 1.
|
|
1037
|
+
**The Takeaway:** as of 1.1.4 you no longer have to choose, and 1.6.0-alpha extends the story -- the engine still ranks **4th of 15** on the official js-reactivity-benchmark (the only zero-GC library in the field, now with **6 outright wins** across wide-aggregation and mixed-app shapes). `lite-signal` keeps the zero-GC, flat-arena profile for 120fps Canvas/WebGL **and** wins decisively on the high-churn dynamic and fan-in topologies that dominate live UI -- the shapes where zero allocation pays off most. On the cheap propagation shapes (KAIROS, DEEP CHAIN, BROADCAST) the new mutation-hook gate costs a few percent (measurable because those shapes have almost no allocation for the gate to disappear into); on the wide-aggregation shapes the gate is round-off. The one shape where alien's flatter representation still leads is the 256-deep computed pipeline (DEEP CHAIN, -21% on the 1.6.0-alpha isolated run -- widened from -14% on 1.5.0-beta by the added per-level gate cost; when a profiler is attached the observable becomes the profiler's own cost and the gate itself disappears from the picture).
|
|
954
1038
|
|
|
955
1039
|
### Roadmap
|
|
956
1040
|
- **1.1.5** -- additions in service of `lite-devtools` (node identity/traversability on the introspection walkers, for full auto-discovered graph rendering). *Shipped.*
|
|
957
1041
|
- **1.2.0** -- the **ownership hybrid**: an owner tree so nested effects/computeds auto-dispose with their parent (closes conformance #209 / #210, matching Solid's `createRoot` ergonomics). Plus three additive features built on the same internal split: pre-batch revert (`batch(() => { a.set(99); a.set(10); })` doesn't re-fire), multi-throw `AggregateError`, and scheduler-thunk caching with an ABA gen guard. *Shipped.*
|
|
958
1042
|
- **1.3.0** -- the **pool minor**: node and link pools become growable and incrementally populated. New `prealloc` config (`"eager"` default | `"lazy"`) chooses up-front vs on-demand construction; `onCapacityExceeded: "grow"` extends pools via chunked refill (runs of up to 1024 links / 256 nodes, ledger doubles) bounded by the 16x link ceiling; `maxFlushPasses` is now a public config. Internally the propagation mark phase moved to an intrusive linked-list stack (a `nextMark` field) -- the only node-shape change. The hot paths and public callable API are byte-identical to 1.2.2; steady-state zero-GC is unchanged. *Shipped.*
|
|
959
1043
|
- **1.4.0** -- the **observability minor**: `stats()` gains three cumulative lifecycle counters (`totalAllocations`, `totalDisposals`, `poolGrowths`), the surface reserved for it in the 1.2.x/1.3.0 notes. Monotonic over the registry's life, reset by `destroy()`, bumped on the existing acquire/dispose/grow edges -- no hot-path change, no public callable API change. This is what lite-devtools / lite-studio read to chart allocation rate, pool-reuse ratio, and graph churn. Also adds the `harness/VersionMatrix/` regression gate (cold-process, same-host, two baselines) as a `prepublish` step, so a release that regresses `frame.avg` on the four reference workloads (reactive-graph-mix, deep-chain, broadcast-fanout, dynamic-dep-churn) fails the publish. Drop-in over 1.3.0. *Shipped.*
|
|
960
|
-
- **1.5.0** -- the **API-surface minor**: two non-callable, allocation-light primitives `signalBox` / `computedBox` land alongside the callable `signal` / `computed` (same `ReactiveNode`, full interop, ~1.7x cheaper construction), and **`createRoot`** lands as the ownership escape hatch the owner tree was designed for (detached scope for lazily spawning long-lived nodes from inside a consumer effect -- the pattern `lite-query` needs). The callable API, hot paths, and `stats()` shape are unchanged; the `24-signalbox` suite (staged since 1.3.0) now runs and passes. VersionMatrix gains an **identical-code guard** (SHA-256 of the engine source per baseline): a re-versioned publish with byte-identical `Signal.js` is marked `SKIP` structurally rather than flagged by noisy median variance. *Shipped (beta).*
|
|
961
|
-
- **
|
|
1044
|
+
- **1.5.0** -- the **API-surface minor**: two non-callable, allocation-light primitives `signalBox` / `computedBox` land alongside the callable `signal` / `computed` (same `ReactiveNode`, full interop, ~1.7x cheaper construction), and **`createRoot`** lands as the ownership escape hatch the owner tree was designed for (detached scope for lazily spawning long-lived nodes from inside a consumer effect -- the pattern `lite-query` needs). The callable API, hot paths, and `stats()` shape are unchanged; the `24-signalbox` suite (staged since 1.3.0) now runs and passes. VersionMatrix gains an **identical-code guard** (SHA-256 of the engine source per baseline): a re-versioned publish with byte-identical `Signal.js` is marked `SKIP` structurally rather than flagged by noisy median variance. *Shipped (beta).* **1.5.0-beta.2** adds the re-attach companions **`getOwner` / `runWithOwner`** (gen-stamped handles that degrade to rooted execution when the captured owner has been recycled; both async-gap hazards -- recycled-slot cascade death and corpse-adoption crash -- pinned in `test/28-run-with-owner.test.mjs`). **1.5.1** promotes the zero-GC gate from `futureVersions/zgc/` to `test/zgc/` (six scenarios + controls + injected-allocation self-test), wired into `test:zgc` / `test:all` / `verify` -- CI-wireable proof that the steady-state hot path allocates nothing.
|
|
1045
|
+
- **1.6.0-alpha** -- the **observability + lifecycle minor**. Two additions to the mutation-hook stream: op 6 (`flush-pass-start`, once per pass in `flushEffects`) and op 7 (`effect-enqueue`, in `markDownstream` when a dirty subscriber is enqueued) -- both branch-predicted-free when detached, allocation-free when attached, letting lite-devtools/profiler chart flush structure and per-burst enqueue counts without instrumentation. Plus the `flushPasses` counter on `stats()` (the 12th key) advancing only while a hook is attached. Adds **`createScope`** as the third ownership primitive alongside `createRoot` / `runWithOwner`: an adopting scope that returns one disposer for the whole subtree, exactly the per-item lifecycle a keyed-list or scene reconciler needs. Ships the two profiling harnesses `harness/burst-dag.mjs` and `harness/pull-stress.mjs` (see the Test harnesses section). The engine hot path is no longer byte-identical to 1.5 -- `markDownstream` and `flushEffects` picked up the new gate branches -- and the observable cost is a few percent on the cheap propagation shapes (KAIROS -7 -> -12%, DEEP CHAIN -14 -> -21% vs alien); the wide-aggregation wins are unchanged because the gate is round-off there. *Shipped (alpha).*
|
|
1046
|
+
- **Next** -- the pull-mode recursion depth limit (~5,000 chained computeds; `pull-stress.mjs` now pins the exact number on the current engine and will be the before/after baseline for the eventual iterative pull rewrite) remains the main outstanding architectural item.
|
|
962
1047
|
|
|
963
1048
|
> Note: the retracking rewrite that closes the dynamic-topology gap shipped in **1.1.4**, not a future release. The earlier roadmap that listed it under "v1.2" is superseded.
|
|
964
1049
|
|
package/Signal.d.ts
CHANGED
|
@@ -144,6 +144,16 @@ export interface RegistryStats {
|
|
|
144
144
|
* workload keeps this at 0. Reset only by {@link Registry.destroy}. Added in 1.4.0.
|
|
145
145
|
*/
|
|
146
146
|
poolGrowths: number;
|
|
147
|
+
/**
|
|
148
|
+
* Cumulative count of effect-flush drain passes. Advances once per pass, only
|
|
149
|
+
* while a mutation-hook listener is attached (gated by the same `mutationHook !==
|
|
150
|
+
* null` check that admits opcodes 6 and 7); frozen otherwise, so the steady-state
|
|
151
|
+
* write path is byte-identical to 1.5.0. Combined with `totalAllocations` and
|
|
152
|
+
* `poolGrowths`, lets devtools chart flush activity alongside allocation rate
|
|
153
|
+
* without the engine itself computing rates. Reset by {@link Registry.destroy}.
|
|
154
|
+
* Added in 1.6.0.
|
|
155
|
+
*/
|
|
156
|
+
flushPasses: number;
|
|
147
157
|
}
|
|
148
158
|
|
|
149
159
|
// --- Observer-lifecycle introspection (1.1.4) ---------------------------------
|
|
@@ -268,6 +278,66 @@ export interface Registry {
|
|
|
268
278
|
* effect (e.g. a query watcher). Returns whatever `fn` returns.
|
|
269
279
|
*/
|
|
270
280
|
createRoot<T>(fn: () => T): T;
|
|
281
|
+
/**
|
|
282
|
+
* Return the currently-active owner as an opaque, gen-stamped handle
|
|
283
|
+
* (`undefined` if called outside any effect/computed body). Companion to
|
|
284
|
+
* {@link runWithOwner}: capture the current lifecycle scope now, restore
|
|
285
|
+
* it later (typically across an async boundary). Introduced in 1.5.0-beta.2,
|
|
286
|
+
* carried forward unchanged into 1.6.
|
|
287
|
+
*
|
|
288
|
+
* The handle is a plain descriptor object (same shape as {@link describe}
|
|
289
|
+
* returns) stamped with an internal generation counter. It is safe to
|
|
290
|
+
* hold across async boundaries: if the captured owner is disposed and
|
|
291
|
+
* its pool slot is subsequently recycled by an unrelated effect/computed,
|
|
292
|
+
* the generation counter no longer matches and {@link runWithOwner}
|
|
293
|
+
* treats the handle as stale (degrades to rooted execution). This is the
|
|
294
|
+
* ABA guard already used by `describe` / `nodeId` / `forEachOwned`.
|
|
295
|
+
*
|
|
296
|
+
* The handle does NOT keep the owner alive -- it is a snapshot, not a
|
|
297
|
+
* reference. Node lifetime is controlled by the owner tree, not by
|
|
298
|
+
* outstanding handles.
|
|
299
|
+
*/
|
|
300
|
+
getOwner(): Owner;
|
|
301
|
+
/**
|
|
302
|
+
* Run `fn` with `ownerHandle` as the current lifecycle owner. Effects
|
|
303
|
+
* or computeds created directly in `fn` are adopted by that owner and
|
|
304
|
+
* cascade-dispose when the owner re-runs or is disposed. Introduced in
|
|
305
|
+
* 1.5.0-beta.2, carried forward unchanged into 1.6.
|
|
306
|
+
*
|
|
307
|
+
* Degradation semantics for handles that cannot be re-attached:
|
|
308
|
+
* - `null` / `undefined` -> rooted execution (createRoot semantics for
|
|
309
|
+
* ownership; created children survive, caller disposes them).
|
|
310
|
+
* - stale handle (owner disposed, slot recycled) -> rooted execution.
|
|
311
|
+
* Never adopts into the unrelated new resident of the recycled slot;
|
|
312
|
+
* never adopts into a corpse (a disposed owner whose slot is not yet
|
|
313
|
+
* recycled).
|
|
314
|
+
* - handle for a live signal (not an effect/computed) -> rooted
|
|
315
|
+
* execution (signals cannot own).
|
|
316
|
+
*
|
|
317
|
+
* Nulls the tracking observer for the duration of `fn` (the same pairing
|
|
318
|
+
* as {@link createRoot}): reads directly inside `fn` do NOT link into any
|
|
319
|
+
* enclosing observer. Inner effect/computed bodies still establish their
|
|
320
|
+
* own owner + observer scopes.
|
|
321
|
+
*
|
|
322
|
+
* Returns whatever `fn` returns.
|
|
323
|
+
*/
|
|
324
|
+
runWithOwner<T>(ownerHandle: Owner, fn: () => T): T;
|
|
325
|
+
/**
|
|
326
|
+
* Run `fn(dispose)` in a detached, untracked scope and return whatever `fn`
|
|
327
|
+
* returns (1.6.0). The single `dispose` argument cascade-disposes every effect
|
|
328
|
+
* and computed created inside `fn`. Lifecycle complement to {@link createRoot}:
|
|
329
|
+
* `createRoot` only *detaches* (caller must dispose each child by hand),
|
|
330
|
+
* `createScope` *adopts*, so one disposer tears down a subtree of unknown shape
|
|
331
|
+
* -- the per-item lifecycle a keyed-list or scene reconciler needs. Plain
|
|
332
|
+
* signals created directly in `fn` are NOT adopted (consistent with the 1.2.0
|
|
333
|
+
* ownership rule); computeds and effects are. The owner never re-runs, so
|
|
334
|
+
* direct-body reads in `fn` are untracked; reactive bindings belong in inner
|
|
335
|
+
* effect/computed bodies. A scope created inside a consumer effect SURVIVES
|
|
336
|
+
* that consumer's re-run -- the reconciler-critical detach property. The
|
|
337
|
+
* disposer is the same gen-guarded, ABA-safe handle `effect()` returns and
|
|
338
|
+
* resolves to the owner effect under `describe` / `nodeId` / `forEachOwned`.
|
|
339
|
+
*/
|
|
340
|
+
createScope<T>(fn: (dispose: () => void) => T): T;
|
|
271
341
|
/**
|
|
272
342
|
* Universal disposal for anything created by this registry: signals,
|
|
273
343
|
* computeds, boxes, or effect dispose handles. Cross-registry calls are
|
|
@@ -348,6 +418,20 @@ export function signalBox<T>(initial: T, opts?: SignalOptions<T>): SignalBox<T>;
|
|
|
348
418
|
export function computedBox<T>(fn: () => T, opts?: ComputedOptions<T>): ComputedBox<T>;
|
|
349
419
|
/** Run `fn` in a detached ownership scope (1.5.0), bound to the default registry. See {@link Registry.createRoot}. */
|
|
350
420
|
export function createRoot<T>(fn: () => T): T;
|
|
421
|
+
/**
|
|
422
|
+
* An owner handle -- an opaque descriptor returned by {@link getOwner},
|
|
423
|
+
* safe to hold across async boundaries. A stale, null, or non-tracker
|
|
424
|
+
* handle degrades cleanly in {@link runWithOwner} (rooted execution)
|
|
425
|
+
* rather than adopting into an unrelated recycled slot. See
|
|
426
|
+
* {@link Registry.getOwner} for the ABA-guard mechanics. 1.5.0-beta.2+.
|
|
427
|
+
*/
|
|
428
|
+
export type Owner = NodeDescriptor | undefined;
|
|
429
|
+
/** Capture the current owner as an opaque, gen-stamped handle (1.5.0-beta.2), bound to the default registry. See {@link Registry.getOwner}. */
|
|
430
|
+
export function getOwner(): Owner;
|
|
431
|
+
/** Run `fn` under a captured owner handle (1.5.0-beta.2), bound to the default registry. See {@link Registry.runWithOwner}. */
|
|
432
|
+
export function runWithOwner<T>(ownerHandle: Owner, fn: () => T): T;
|
|
433
|
+
/** Run `fn(dispose)` in a detached, adopting scope (1.6.0), bound to the default registry. See {@link Registry.createScope}. */
|
|
434
|
+
export function createScope<T>(fn: (dispose: () => void) => T): T;
|
|
351
435
|
/** Universal disposal -- see {@link Registry.dispose}. */
|
|
352
436
|
export function dispose(api: Disposable): void;
|
|
353
437
|
export function batch<T>(fn: () => T): T;
|
package/Signal.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @zakkster/lite-signal v1.
|
|
2
|
+
* @zakkster/lite-signal v1.6.0
|
|
3
3
|
* --------------------
|
|
4
4
|
* Hybrid Doubly-Linked-List Reactive Graph Engine -- decoupled (Signal1_3) base
|
|
5
5
|
* with the two 1.1.3 performance fixes ported in:
|
|
@@ -250,6 +250,8 @@ export function createRegistry(config) {
|
|
|
250
250
|
let statTotalAllocations = 0; // bumped on every createNode (pool pop OR fresh build)
|
|
251
251
|
let statTotalDisposals = 0; // bumped on every disposeNode
|
|
252
252
|
let statPoolGrowths = 0; // bumped when a node/link chunk pushes capacity past its ledger
|
|
253
|
+
let statFlushPasses = 0; // 1.6: bumped per flush pass, ONLY while a mutation-hook
|
|
254
|
+
// listener is attached (gated -> zero cost when detached).
|
|
253
255
|
|
|
254
256
|
const effectQueueA = [];
|
|
255
257
|
const effectQueueB = [];
|
|
@@ -314,12 +316,13 @@ export function createRegistry(config) {
|
|
|
314
316
|
*
|
|
315
317
|
* @private
|
|
316
318
|
*/
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
319
|
+
// --- Graph-mutation hook (1.2.1 keystone prototype) ---------------------
|
|
320
|
+
// Single nullable listener; every fire point is `if (mutationHook !== null)`
|
|
321
|
+
// -- branch-predicted free when absent, allocation-free when present
|
|
322
|
+
// (opcode + two int args). Enables push-based devtools (watchGraph) and the
|
|
323
|
+
// recompute profiler. Opcodes: 1 node-create, 2 node-dispose, 3 link-add,
|
|
324
|
+
// 4 link-remove, 5 recompute, 6 flush-pass-start (a=pass#, b=effects this pass),
|
|
325
|
+
// 7 effect-enqueue (a=node id). 6/7 added in 1.6 for burst/flush profiling.
|
|
323
326
|
let mutationHook = null;
|
|
324
327
|
function onGraphMutation(fn) {
|
|
325
328
|
if (fn !== null && typeof fn !== "function") throw new TypeError("onGraphMutation: listener must be a function or null");
|
|
@@ -743,6 +746,9 @@ export function createRegistry(config) {
|
|
|
743
746
|
if ((flags & (FLAG_QUEUED | FLAG_COMPUTING)) === 0) {
|
|
744
747
|
t.flags = flags | FLAG_QUEUED;
|
|
745
748
|
activeQueue[activeQueueLen++] = t;
|
|
749
|
+
// 1.6: op 7, effect enqueued. Gated; the ONE insertion inside the
|
|
750
|
+
// markDownstream inner loop -> gate-check KAIROS/MUX before shipping.
|
|
751
|
+
if (mutationHook !== null) mutationHook(7, t.id, 0);
|
|
746
752
|
}
|
|
747
753
|
} else {
|
|
748
754
|
// Intrusive push: t.nextMark holds the prior head
|
|
@@ -773,6 +779,9 @@ export function createRegistry(config) {
|
|
|
773
779
|
while (activeQueueLen > 0) {
|
|
774
780
|
if (++passes > maxFlushPasses) throw new Error("CycleError: flush passes exceeded");
|
|
775
781
|
const toRun = activeQueueLen | 0;
|
|
782
|
+
// 1.6 burst/flush instrumentation. Gated on the hook -> zero cost when no
|
|
783
|
+
// profiler is attached; statFlushPasses advances only while observed.
|
|
784
|
+
if (mutationHook !== null) { statFlushPasses = (statFlushPasses + 1) | 0; mutationHook(6, passes, toRun); }
|
|
776
785
|
const currentQueue = activeQueue;
|
|
777
786
|
|
|
778
787
|
isQueueA = !isQueueA;
|
|
@@ -1473,6 +1482,127 @@ export function createRegistry(config) {
|
|
|
1473
1482
|
}
|
|
1474
1483
|
}
|
|
1475
1484
|
|
|
1485
|
+
/**
|
|
1486
|
+
* Capture the currently-active owner as an opaque, gen-stamped handle
|
|
1487
|
+
* (`undefined` if called outside any effect/computed body). Companion to
|
|
1488
|
+
* `runWithOwner`: capture the lifecycle scope now, restore it later --
|
|
1489
|
+
* typically across an async boundary. Shipped in 1.5.0-beta.2, carried
|
|
1490
|
+
* forward unchanged into 1.6.
|
|
1491
|
+
*
|
|
1492
|
+
* The handle is a `describeNode` descriptor stamped with the pool slot's
|
|
1493
|
+
* generation counter. It is safe to hold across async boundaries: if the
|
|
1494
|
+
* captured owner is disposed and its slot is subsequently recycled by an
|
|
1495
|
+
* unrelated effect/computed, the gen no longer matches and `runWithOwner`
|
|
1496
|
+
* treats the handle as stale (degrades to rooted execution). Same ABA guard
|
|
1497
|
+
* used by `describe` / `nodeId` / `forEachOwned` / `ownerOf`.
|
|
1498
|
+
*
|
|
1499
|
+
* The handle does NOT keep the owner alive -- it is a snapshot, not a
|
|
1500
|
+
* reference. Node lifetime is controlled by the owner tree, not by
|
|
1501
|
+
* outstanding handles.
|
|
1502
|
+
*/
|
|
1503
|
+
function getOwner() {
|
|
1504
|
+
return currentOwner !== null ? describeNode(currentOwner) : undefined;
|
|
1505
|
+
}
|
|
1506
|
+
|
|
1507
|
+
/**
|
|
1508
|
+
* Run `fn` with `ownerHandle` as the current lifecycle owner. Effects
|
|
1509
|
+
* or computeds created directly in `fn` are adopted by that owner and
|
|
1510
|
+
* cascade-dispose when the owner re-runs or is disposed. Shipped in
|
|
1511
|
+
* 1.5.0-beta.2, carried forward unchanged into 1.6.
|
|
1512
|
+
*
|
|
1513
|
+
* Degradation semantics for handles that cannot be re-attached:
|
|
1514
|
+
* - `null` / `undefined` -> rooted execution (createRoot semantics for the
|
|
1515
|
+
* ownership axis; created children survive, caller disposes them).
|
|
1516
|
+
* - stale handle (owner disposed, slot recycled) -> rooted execution. Never
|
|
1517
|
+
* adopts into the unrelated new resident of the recycled slot; never
|
|
1518
|
+
* adopts into a corpse (a disposed owner whose slot is not yet recycled).
|
|
1519
|
+
* - handle for a live signal (not an effect/computed) -> rooted execution
|
|
1520
|
+
* (signals cannot own).
|
|
1521
|
+
*
|
|
1522
|
+
* Nulls the tracking observer for the duration of `fn` (the same pairing
|
|
1523
|
+
* as `createRoot`): reads directly inside `fn` do NOT link into any
|
|
1524
|
+
* enclosing observer. Inner effect/computed bodies still establish their
|
|
1525
|
+
* own owner + observer scopes.
|
|
1526
|
+
*
|
|
1527
|
+
* Returns whatever `fn` returns.
|
|
1528
|
+
*/
|
|
1529
|
+
function runWithOwner(ownerHandle, fn) {
|
|
1530
|
+
const node = liveNode(ownerHandle);
|
|
1531
|
+
const prevOwner = currentOwner;
|
|
1532
|
+
const prevObserver = currentObserver;
|
|
1533
|
+
const prevTracking = isTrackingDeps;
|
|
1534
|
+
currentOwner = (node !== undefined && (node.flags & (FLAG_COMPUTED | FLAG_EFFECT)) !== 0) ? node : null;
|
|
1535
|
+
currentObserver = null;
|
|
1536
|
+
isTrackingDeps = false;
|
|
1537
|
+
try {
|
|
1538
|
+
return fn();
|
|
1539
|
+
} finally {
|
|
1540
|
+
currentOwner = prevOwner;
|
|
1541
|
+
currentObserver = prevObserver;
|
|
1542
|
+
isTrackingDeps = prevTracking;
|
|
1543
|
+
}
|
|
1544
|
+
}
|
|
1545
|
+
|
|
1546
|
+
/**
|
|
1547
|
+
* Create a DISPOSABLE reactive scope: an owner that ADOPTS the effects and
|
|
1548
|
+
* computeds created inside `fn`, so a single returned `dispose` tears the
|
|
1549
|
+
* whole subtree down at once. Where `createRoot` only DETACHES (leaving the
|
|
1550
|
+
* caller to dispose each created node by hand -- "there is no owner to do it
|
|
1551
|
+
* automatically"), `createScope` hands back one disposer that cascade-disposes
|
|
1552
|
+
* everything `fn` built. This is the lifecycle primitive a keyed list / scene
|
|
1553
|
+
* reconciler needs for per-item scopes of unknown internal shape.
|
|
1554
|
+
*
|
|
1555
|
+
* `fn` receives `dispose` and runs ONCE in a detached, untracked context: no
|
|
1556
|
+
* ownership and no dependency leak from `fn`'s direct body into the enclosing
|
|
1557
|
+
* scope, and the scope owner itself never re-runs. Put reactive bindings in
|
|
1558
|
+
* inner effect / computed bodies inside `fn` -- those establish their own
|
|
1559
|
+
* tracking scopes AND are owned by this scope, so they update normally and are
|
|
1560
|
+
* cascade-disposed on `dispose()`. Reads in `fn`'s direct body are untracked.
|
|
1561
|
+
* Returns whatever `fn` returns.
|
|
1562
|
+
*
|
|
1563
|
+
* Plain signals created directly in `fn` are NOT adopted -- the engine never
|
|
1564
|
+
* owner-adopts signals (the lazy-alloc rule, 1.2.0) -- so dispose those
|
|
1565
|
+
* explicitly (the creator holds the handle) or let them fall out of reference.
|
|
1566
|
+
* Computeds and effects ARE adopted and cascade.
|
|
1567
|
+
*
|
|
1568
|
+
* Implementation: the scope owner is backed by a never-re-running effect node,
|
|
1569
|
+
* so it counts as one effect in stats() and its disposer is the same
|
|
1570
|
+
* gen-guarded handle effect() returns -- ABA-safety and introspection match
|
|
1571
|
+
* effects exactly. The API (`fn => dispose`) is the stable contract; a future
|
|
1572
|
+
* engine may swap in a lighter pure-owner node transparently.
|
|
1573
|
+
*
|
|
1574
|
+
* @template T
|
|
1575
|
+
* @param {(dispose: () => void) => T} fn
|
|
1576
|
+
* @returns {T}
|
|
1577
|
+
*/
|
|
1578
|
+
function createScope(fn) {
|
|
1579
|
+
let stop;
|
|
1580
|
+
let result;
|
|
1581
|
+
// Forward-referenced disposer: `stop` is assigned only after effect()
|
|
1582
|
+
// returns, but `fn` runs synchronously DURING effect(). Callers stash this
|
|
1583
|
+
// and invoke it later, by which point `stop` is set. (Disposing the scope
|
|
1584
|
+
// synchronously from inside `fn` is a no-op -- not a supported pattern.)
|
|
1585
|
+
const dispose = function dispose() { if (stop !== undefined) stop(); };
|
|
1586
|
+
// createRoot detaches owner+observer+tracking; inside it effect() creates a
|
|
1587
|
+
// ROOT owner effect (unowned -> survives the enclosing scope's re-runs).
|
|
1588
|
+
// untrack keeps `fn`'s direct reads from handing the owner any dependency,
|
|
1589
|
+
// so the owner runs exactly once; `fn`'s inner effects/computeds are owned
|
|
1590
|
+
// by it and cascade on dispose.
|
|
1591
|
+
createRoot(function () {
|
|
1592
|
+
stop = effect(function scopeOwner() {
|
|
1593
|
+
untrack(function () { result = fn(dispose); });
|
|
1594
|
+
});
|
|
1595
|
+
});
|
|
1596
|
+
// Stamp the wrapper so describe / nodeId / forEachOwned resolve it to the
|
|
1597
|
+
// owner effect, matching the first-class-handle contract effects gained in
|
|
1598
|
+
// 1.2.1. (`stop` carries the symbols once effect() has returned.)
|
|
1599
|
+
if (stop !== undefined && stop[NODE_PTR] !== undefined) {
|
|
1600
|
+
dispose[NODE_PTR] = stop[NODE_PTR];
|
|
1601
|
+
dispose[NODE_GEN] = stop[NODE_GEN];
|
|
1602
|
+
}
|
|
1603
|
+
return result;
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1476
1606
|
/**
|
|
1477
1607
|
* Register a function to run when the enclosing effect/computed re-runs or
|
|
1478
1608
|
* is disposed. Cascade order on disposal is inside-out: an effect's owned
|
|
@@ -1521,7 +1651,10 @@ export function createRegistry(config) {
|
|
|
1521
1651
|
// 1 - poolGrowths*initialCap/totalAllocations; avgLifetime ~ totalDisposals/rate.
|
|
1522
1652
|
totalAllocations: statTotalAllocations,
|
|
1523
1653
|
totalDisposals: statTotalDisposals,
|
|
1524
|
-
poolGrowths: statPoolGrowths
|
|
1654
|
+
poolGrowths: statPoolGrowths,
|
|
1655
|
+
// 1.6: flush-pass counter; advances only while a mutation-hook listener is
|
|
1656
|
+
// attached (frozen + zero-cost otherwise). Feeds devtools watchAllocations.
|
|
1657
|
+
flushPasses: statFlushPasses
|
|
1525
1658
|
};
|
|
1526
1659
|
}
|
|
1527
1660
|
|
|
@@ -1605,6 +1738,7 @@ export function createRegistry(config) {
|
|
|
1605
1738
|
statTotalAllocations = 0;
|
|
1606
1739
|
statTotalDisposals = 0;
|
|
1607
1740
|
statPoolGrowths = 0;
|
|
1741
|
+
statFlushPasses = 0;
|
|
1608
1742
|
|
|
1609
1743
|
for (let i = 0; i < flushErrorCount; i++) flushErrorBuffer[i] = null;
|
|
1610
1744
|
flushErrorCount = 0;
|
|
@@ -1697,7 +1831,7 @@ export function createRegistry(config) {
|
|
|
1697
1831
|
while (l !== null) { const nx = l.nextDep; fn(describeNode(l.source)); l = nx; }
|
|
1698
1832
|
}
|
|
1699
1833
|
|
|
1700
|
-
return {signal, computed, effect, signalBox, computedBox, dispose, batch, untrack, createRoot, onCleanup, stats, destroy, isTracking, hasObservers, observeObservers, forEachObserver, forEachSource, forEachOwned, ownerOf, nodeId, describe, onGraphMutation};
|
|
1834
|
+
return {signal, computed, effect, signalBox, computedBox, dispose, batch, untrack, createRoot, getOwner, runWithOwner, createScope, onCleanup, stats, destroy, isTracking, hasObservers, observeObservers, forEachObserver, forEachSource, forEachOwned, ownerOf, nodeId, describe, onGraphMutation};
|
|
1701
1835
|
}
|
|
1702
1836
|
|
|
1703
1837
|
// -----------------------------------------------------------------
|
|
@@ -1745,6 +1879,28 @@ export function createRoot(fn) {
|
|
|
1745
1879
|
return defaultRegistry.createRoot(fn);
|
|
1746
1880
|
}
|
|
1747
1881
|
|
|
1882
|
+
/**
|
|
1883
|
+
* Capture the currently-active owner as an opaque, gen-stamped handle
|
|
1884
|
+
* (undefined outside any effect/computed body). Companion to
|
|
1885
|
+
* {@link runWithOwner}; safe to hold across async boundaries via the
|
|
1886
|
+
* NODE_GEN ABA guard.
|
|
1887
|
+
*/
|
|
1888
|
+
export function getOwner() {
|
|
1889
|
+
return defaultRegistry.getOwner();
|
|
1890
|
+
}
|
|
1891
|
+
|
|
1892
|
+
/**
|
|
1893
|
+
* Run `fn` with `ownerHandle` as the current lifecycle owner. Stale, null,
|
|
1894
|
+
* undefined, or non-tracker handles degrade to rooted execution.
|
|
1895
|
+
*/
|
|
1896
|
+
export function runWithOwner(ownerHandle, fn) {
|
|
1897
|
+
return defaultRegistry.runWithOwner(ownerHandle, fn);
|
|
1898
|
+
}
|
|
1899
|
+
|
|
1900
|
+
export function createScope(fn) {
|
|
1901
|
+
return defaultRegistry.createScope(fn);
|
|
1902
|
+
}
|
|
1903
|
+
|
|
1748
1904
|
/**
|
|
1749
1905
|
* True iff a read RIGHT NOW would record a dependency on the default registry.
|
|
1750
1906
|
* See {@link createRegistry} for the per-registry version.
|
package/llms.txt
CHANGED
|
@@ -17,7 +17,9 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
|
|
|
17
17
|
- **Computed**: lazy memoized derivation. `computed(fn, { equals? })`. Cache hits return in O(deps) (version comparison only). Cache misses re-run the body and refresh `evalVersion`. Errors are cached via `FLAG_HAS_ERROR` and re-thrown on every read until a dep changes.
|
|
18
18
|
- **Effect**: side-effect runner. `effect(fn, { scheduler? })`. Runs immediately on creation, then on any tracked dep change. Returns a dispose function. Optional scheduler defers execution (e.g., to rAF, microtask, custom frame loop).
|
|
19
19
|
- **Box (1.5.0)**: non-callable, allocation-light variants. `signalBox(initial, { equals? })` returns `{ get, set, peek, update, subscribe }`; `computedBox(fn, { equals? })` returns `{ get, peek, subscribe }` (no set/update -- derived). Same `ReactiveNode` and zero-GC read/write path as the callable forms, full interop in one graph (a callable can read `box.get()` and vice versa). Construction is ~1.7x cheaper than the callable (an `Object.create(proto)` handle, not a closure). Built on a shared prototype from the start -- never `setPrototypeOf` (which would deopt the method-call ICs to megamorphic). Exported as registry methods and top-level helpers.
|
|
20
|
-
- **createRoot (1.5.0)**: `createRoot(fn)` runs `fn` in a detached ownership scope and returns `fn`'s value. Effects/computeds created directly in `fn` are NOT adopted by the enclosing owner, so they survive its re-runs/disposal (the caller owns their lifecycle). Both ownership and tracking are detached for `fn`'s direct body; inner effect/computed bodies still establish their own scopes. The escape hatch for lazily spawning a long-lived node from inside a consumer effect (e.g. `lite-query`'s query-watcher) -- without it, the consumer owns the watcher and cascade-disposes it on its next re-run. Mirrors Solid's `createRoot`.
|
|
20
|
+
- **createRoot (1.5.0)**: `createRoot(fn)` runs `fn` in a detached ownership scope and returns `fn`'s value. Effects/computeds created directly in `fn` are NOT adopted by the enclosing owner, so they survive its re-runs/disposal (the caller owns their lifecycle). Both ownership and tracking are detached for `fn`'s direct body; inner effect/computed bodies still establish their own scopes. The escape hatch for lazily spawning a long-lived node from inside a consumer effect (e.g. `lite-query`'s query-watcher) -- without it, the consumer owns the watcher and cascade-disposes it on its next re-run. Mirrors Solid's `createRoot`.
|
|
21
|
+
- **getOwner / runWithOwner (1.5.0-beta.2, carried into 1.6)**: the re-attach companion. `getOwner()` returns the current lifecycle owner as an opaque gen-stamped handle (`undefined` outside any effect/computed body); `runWithOwner(handle, fn)` runs `fn` with that owner reinstated so effects/computeds created directly in `fn` are adopted by it (and cascade-dispose when it re-runs). Nulls the tracking observer for `fn`'s direct body (same pairing as `createRoot`). Handles are **safe to hold across async boundaries**: they use the `describeNode` / `liveNode` ABA-guard machinery (`NODE_GEN` stamp checked against the pool slot's current gen), so stale handles -- owner disposed, slot recycled by an unrelated effect via the LIFO free list -- degrade to rooted execution rather than corrupting the graph. A raw-pointer implementation would (i) silently adopt continuations into the recycled slot's new resident (measured: continuation dies with a stranger on its next disposal), or (ii) crash the engine with `RangeError: Maximum call stack size exceeded` on a corpse handle (owner disposed, slot not yet recycled -- the disposal walk recurses without termination). Both hazards pinned in `test/28-run-with-owner.test.mjs`, empirically reproduced via `Publications/owner-hazard-repro.mjs`. Also exported as registry methods + top-level helpers.
|
|
22
|
+
- **createScope (1.6.0)**: `createScope(fn)` runs `fn(dispose)` in a detached, untracked scope and returns whatever `fn` returns, having handed `fn` a single `dispose` that cascade-disposes every effect and computed created inside `fn`. The lifecycle complement to `createRoot`: where `createRoot` only *detaches* (caller disposes each child by hand), `createScope` *adopts*, so one disposer tears down a subtree of unknown shape -- the per-item lifecycle a keyed-list or scene reconciler needs. Plain signals created directly in `fn` are NOT adopted (consistent with the 1.2.0 ownership rule); computeds and effects are. The scope owner is backed by a never-re-running effect node (counts as one effect in `stats()`), the pinned `signals + computeds + effects === activeNodes` invariant is untouched, and the disposer is the same gen-guarded ABA-safe handle `effect()` returns (`describe` / `nodeId` / `forEachOwned` resolve it to the owner). A scope created inside a consumer effect SURVIVES that consumer's re-run -- the reconciler-critical detach property.
|
|
21
23
|
- **dispose(api)**: universal disposal. Accepts a signal, computed, or effect dispose handle; idempotent; cross-registry calls are silent no-ops (per-registry `Symbol("node_ptr")` keys the node-identity slot on the returned API function, foreign signals fail the lookup and fall through). Passing an unrelated value is also safe; passing an arbitrary function invokes it (effect-handle contract).
|
|
22
24
|
- **Batch**: `batch(fn)` defers effect flush until the outermost batch closes. Nestable.
|
|
23
25
|
- **Untrack**: `untrack(fn)` reads without subscribing.
|
|
@@ -52,7 +54,94 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
|
|
|
52
54
|
|
|
53
55
|
## Version notes
|
|
54
56
|
|
|
55
|
-
- **1.
|
|
57
|
+
- **1.6.0-alpha.0** (current): the **observability-and-lifecycle minor**, shipping
|
|
58
|
+
on the `alpha` dist-tag while it settles. **Three** additions:
|
|
59
|
+
|
|
60
|
+
**1) `stats()` gains a twelfth key, `flushPasses`** -- advances once per
|
|
61
|
+
effect-flush drain pass. **2) Two new `onGraphMutation` opcodes for flush
|
|
62
|
+
profiling**: `6` flush pass `(passCount, effectsToRun)` at the top of each drain
|
|
63
|
+
pass, and `7` effect run in pass `(id, 0)` before each effect re-run inside a
|
|
64
|
+
pass. Both the `flushPasses` bump and the opcode dispatch sit behind the
|
|
65
|
+
existing `if (mutationHook !== null)` gate, so when no profiler is attached
|
|
66
|
+
they are inert: `flushPasses` is frozen, but the gate itself IS present -- one
|
|
67
|
+
branch-predicted `null` check per fire site (per pass in `flushEffects`, per
|
|
68
|
+
enqueued dirty subscriber in `markDownstream`'s inner loop). **The hot path
|
|
69
|
+
is no longer byte-identical to 1.5 for the first time since 1.2.2**; the
|
|
70
|
+
observable cost is a few percent on the cheapest propagation shapes (KAIROS
|
|
71
|
+
-7% -> -12% vs alien on the 1.6.0-alpha sweep, DEEP CHAIN -14% -> -21%) and
|
|
72
|
+
round-off on allocation-dominated shapes (SELECTIVE DAG +49%, DYNAMIC DAG
|
|
73
|
+
+43%, MUX +35%, SMALL SELECTIVE +29% -- unchanged from the 1.5.0-beta
|
|
74
|
+
sweep). When a profiler is actually attached, the observable becomes the
|
|
75
|
+
profiler's own cost and the gate itself disappears from the picture. This is
|
|
76
|
+
what lets lite-devtools 1.2 / lite-studio 1.2's `watchAllocations` chart
|
|
77
|
+
recompute/flush activity alongside the 1.4.0 allocation counters
|
|
78
|
+
(`totalAllocations` / `poolGrowths` / `totalDisposals`); only the flush
|
|
79
|
+
series requires 1.6.
|
|
80
|
+
|
|
81
|
+
**3) `createScope(fn)` -- the disposable-owner counterpart to `createRoot`.**
|
|
82
|
+
Runs `fn(dispose)` in a detached, untracked scope and returns whatever `fn`
|
|
83
|
+
returns, having handed `fn` a single `dispose` that **cascade-disposes every
|
|
84
|
+
effect and computed created inside `fn`**. `createRoot` only *detaches* (caller
|
|
85
|
+
disposes each child by hand -- correct for one known long-lived watcher);
|
|
86
|
+
`createScope` *adopts*, so one disposer tears down a subtree of unknown shape
|
|
87
|
+
-- the per-item lifecycle a keyed-list or scene reconciler needs, where the
|
|
88
|
+
item's reactive graph is the consumer's `mapFn` (not something the reconciler
|
|
89
|
+
can enumerate). Consistent with 1.2.0 ownership, **plain signals created
|
|
90
|
+
directly in `fn` are not adopted** (engine never owner-adopts signals);
|
|
91
|
+
computeds and effects are. The scope owner is backed by a never-re-running
|
|
92
|
+
effect node, so it counts as one effect in `stats()` and the pinned
|
|
93
|
+
`signals + computeds + effects === activeNodes` invariant is untouched; the
|
|
94
|
+
disposer is the same gen-guarded, ABA-safe handle `effect()` returns and
|
|
95
|
+
resolves to the owner under `describe` / `nodeId` / `forEachOwned`. A scope
|
|
96
|
+
created inside a consumer effect SURVIVES that consumer's re-run -- the
|
|
97
|
+
reconciler-critical detach property.
|
|
98
|
+
|
|
99
|
+
**`getOwner` / `runWithOwner` are also carried forward from 1.5.0-beta.2**
|
|
100
|
+
in this line -- unchanged, gen-stamped handle + `liveNode` ABA guard, still
|
|
101
|
+
degrading to rooted execution on stale/null/non-tracker handles. The two
|
|
102
|
+
hazards (recycled-slot cascade death, corpse-adoption crash) are pinned in
|
|
103
|
+
`test/28-run-with-owner.test.mjs` with allocation pressure applied so the
|
|
104
|
+
ABA guard is genuinely exercised. `Publications/owner-hazard-repro.mjs`
|
|
105
|
+
reports `VERDICT: SAFE` on the 1.6.0-alpha engine on both cases. The port
|
|
106
|
+
was verified via sha256 over the extracted function bodies of `pullComputed`,
|
|
107
|
+
`executeEffect`, `allocateLink`, `severTail`, `createNode`, `runCleanup`,
|
|
108
|
+
`disposeNode`, `createRoot`, `createScope`: all identical between pristine
|
|
109
|
+
1.6.0-alpha and the merged-with-getOwner engine. Only `markDownstream` and
|
|
110
|
+
`flushEffects` legitimately changed (for the new opcodes) and are
|
|
111
|
+
hash-tracked from this cycle instead.
|
|
112
|
+
|
|
113
|
+
Drop-in over 1.5.1-beta.1 modulo the small gate cost on the cheapest shapes.
|
|
114
|
+
Two root-level characterization harnesses ship in source (not in the
|
|
115
|
+
tarball): **`burst-dag.mjs`** (`npm run profile:burst`) reconstructs the
|
|
116
|
+
layered DAG burst shape and uses opcodes 5/6/7 + `stats().flushPasses` to
|
|
117
|
+
report flush passes, max recomputes per node, and per-burst us; also exports
|
|
118
|
+
`burstDagScenario` + `multiPassProbe`. **`pull-stress.mjs`** (`npm run
|
|
119
|
+
profile:pull`) is the pull-path companion: binary-searches the recursive-pull
|
|
120
|
+
depth limit (~5,000 named in the roadmap, pinned to a number per engine),
|
|
121
|
+
sweeps cold cost per level, confirms cached reads are O(1) via markEpoch;
|
|
122
|
+
exports `pullStressScenario` + `probeOverflow`. Both import only
|
|
123
|
+
`./Signal.js` + public `onGraphMutation`, run against any engine build.
|
|
124
|
+
**Tests:** 447 total (443 from 1.6-preview + the 4 createScope tests
|
|
125
|
+
+ 16 getOwner/runWithOwner tests already counted; the 447 aggregates the
|
|
126
|
+
full green suite on the merged engine), 436 pass, 0 fail, 1 skip (only the
|
|
127
|
+
architecturally-N/A SSR case in `17-reactivity`), 10 cancelled (the
|
|
128
|
+
`25-devtools-real-boot` cases needing devtools peer dep). `test/03-pool`
|
|
129
|
+
"stats() shape" pin bumped from 11-key 1.4 shape to 12-key 1.6 shape (adds
|
|
130
|
+
`flushPasses`). **Coverage:** `Signal.js` 100% statements / 96.96%
|
|
131
|
+
branches / 100% functions / 100% lines; `Watch.js` 100%. The branch drop vs
|
|
132
|
+
1.5.0 (97.35% -> 96.96%) is the `mutationHook !== null` gate on `flushPasses`
|
|
133
|
+
/ opcodes 6+7 -- the listener-attached branch is not exercised by the
|
|
134
|
+
default suite (which never attaches a hook).
|
|
135
|
+
|
|
136
|
+
- **1.5.1-beta.1** (was current before 1.6): the **zero-GC gate** minor.
|
|
137
|
+
`test/zgc/` promoted from `futureVersions/zgc/` and wired into
|
|
138
|
+
`npm run test:zgc` (chained by `test:all` and `verify`). No engine change vs
|
|
139
|
+
1.5.0-beta.2. On 1.6.0-alpha the gate runs unchanged and all seven scenarios
|
|
140
|
+
pass; the gate opcodes added in 1.6 do not perturb the zero-GC contract
|
|
141
|
+
because they are hook-gated (`if (mutationHook !== null)`) and the gate
|
|
142
|
+
scenarios never attach a mutation-hook listener.
|
|
143
|
+
|
|
144
|
+
- **1.5.0** (drop-in over 1.4.0): the **API-surface minor**. Two non-callable,
|
|
56
145
|
allocation-light primitives -- `signalBox(initial, opts?)` returning
|
|
57
146
|
`{ get, set, peek, update, subscribe }` and `computedBox(fn, opts?)` returning
|
|
58
147
|
`{ get, peek, subscribe }` -- land alongside the callable `signal` / `computed`,
|
|
@@ -76,7 +165,8 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
|
|
|
76
165
|
whatever `fn` returns. The owner/observer split (1.2.0) made `currentOwner` and
|
|
77
166
|
`currentObserver` distinct precisely so ownership could be detached without
|
|
78
167
|
affecting tracking; `createRoot` is the first of the two named primitives
|
|
79
|
-
(`runWithOwner`, the re-attach half,
|
|
168
|
+
(`runWithOwner`, the re-attach half, shipped in 1.5.0-beta.2 and is carried
|
|
169
|
+
forward into 1.6). The `24-signalbox`
|
|
80
170
|
suite (staged `{skip:true}` since 1.3.0) now runs and passes. **Tests:** 439
|
|
81
171
|
total, 438 pass, 0 fail, **1 skip** (only the architecturally-N/A SSR case in
|
|
82
172
|
`17-reactivity`; the 9 originally-staged signalBox tests are now active and
|
|
@@ -375,6 +465,10 @@ function effect(fn: () => void, opts?: { scheduler?: (run: () => void) => void }
|
|
|
375
465
|
function signalBox<T>(initial: T, opts?: { equals?: (a: T, b: T) => boolean }): SignalBox<T>; // 1.5.0
|
|
376
466
|
function computedBox<T>(fn: () => T, opts?: { equals?: (a: T, b: T) => boolean }): ComputedBox<T>; // 1.5.0
|
|
377
467
|
function createRoot<T>(fn: () => T): T; // 1.5.0 -- detached ownership scope; returns fn's value
|
|
468
|
+
type Owner = NodeDescriptor | undefined; // 1.5.0-beta.2 -- opaque, gen-stamped handle; safe across async gaps
|
|
469
|
+
function getOwner(): Owner; // 1.5.0-beta.2 -- undefined outside any effect/computed body
|
|
470
|
+
function runWithOwner<T>(ownerHandle: Owner, fn: () => T): T; // 1.5.0-beta.2 -- stale/null/signal-handle -> rooted execution
|
|
471
|
+
function createScope<T>(fn: (dispose: () => void) => T): T; // 1.6.0 -- adopting scope; single disposer tears down subtree
|
|
378
472
|
function dispose(api: Signal<any> | Computed<any> | SignalBox<any> | ComputedBox<any> | Dispose): void;
|
|
379
473
|
function batch<T>(fn: () => T): T;
|
|
380
474
|
function untrack<T>(fn: () => T): T;
|
|
@@ -517,49 +611,65 @@ None of these touch the reactive engine -- no `FLAG_WATCHER` on `ReactiveNode`,
|
|
|
517
611
|
|
|
518
612
|
The deliberate engineering for `watch`'s "0 per fire" is the hoisted `untrackedFire` closure with `currentNewValue` shared mutable state -- see source comment in `watch.js`. Inline arrow function inside the effect body would allocate per fire and break the zero-GC contract.
|
|
519
613
|
|
|
520
|
-
## Benchmark snapshot (Node 22, 2016-era Intel MacBook Pro, default eager, median across reps -- @1.
|
|
614
|
+
## Benchmark snapshot (Node 22, 2016-era Intel MacBook Pro, default eager, median across reps -- @1.6.0-alpha.0)
|
|
521
615
|
|
|
522
616
|
`benchmark.mjs` head-to-head vs alien-signals on app-shaped scenarios (time = median
|
|
523
617
|
execution; heap = average transient delta-heap per rep; lite-signal numbers are
|
|
524
|
-
@1.
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
618
|
+
@1.6.0-alpha.0, hot paths NOT byte-identical to 1.5 for the first time since 1.2.2 --
|
|
619
|
+
1.6 adds two hook-gated fires: op 6 in `flushEffects` (per pass), op 7 in
|
|
620
|
+
`markDownstream`'s inner loop (per enqueued dirty subscriber). Both are branch-
|
|
621
|
+
predicted-free when no profiler is attached; the residual cost is one predicted
|
|
622
|
+
`null` check per fire site. Third-party engine versions carried forward from the
|
|
623
|
+
1.5.0-beta sweep):
|
|
528
624
|
|
|
529
625
|
| Scenario | lite vs alien (time) | transient heap (lite / alien) |
|
|
530
626
|
| -------------------------------- | -------------------- | ----------------------------- |
|
|
531
|
-
| SELECTIVE DAG (set churn) | **+
|
|
532
|
-
| DYNAMIC DAG (FAN=6, read flips) | **+
|
|
533
|
-
| MUX (256 sigs -> sum -> effect) | **+
|
|
534
|
-
| SMALL SELECTIVE (~64x6) | **+29% faster** | 0.3 KB /
|
|
535
|
-
| LARGE WEB APP (~1000x12) |
|
|
627
|
+
| SELECTIVE DAG (set churn) | **+49% faster** | 1.6 MB / 29 MB |
|
|
628
|
+
| DYNAMIC DAG (FAN=6, read flips) | **+43% faster** | 4.9 MB / 27 MB |
|
|
629
|
+
| MUX (256 sigs -> sum -> effect) | **+35% faster** | 38 KB / 3.9 MB |
|
|
630
|
+
| SMALL SELECTIVE (~64x6) | **+29% faster** | 0.3 KB / 22.9 MB |
|
|
631
|
+
| LARGE WEB APP (~1000x12) | -3% (parity) | 0.3 KB / 41 KB |
|
|
536
632
|
| WIDE DENSE (~1000x5) | -6% (parity) | 0.3 KB / 11.6 MB |
|
|
537
|
-
|
|
|
538
|
-
|
|
|
539
|
-
| DEEP CHAIN (256-deep -> effect) | -
|
|
633
|
+
| BROADCAST (1 -> 1000 effects) | -10% | 73 KB / 21 KB |
|
|
634
|
+
| KAIROS (1 -> 1000 computeds) | -12% | 179 KB / 1.1 MB |
|
|
635
|
+
| DEEP CHAIN (256-deep -> effect) | -21% | 18 KB / 942 KB |
|
|
540
636
|
|
|
541
637
|
lite-signal's time wins are the allocation-heavy dynamic shapes (object pool allocates
|
|
542
638
|
near-nothing; alien churns the nursery), plus MUX fan-in aggregation -- the patterns
|
|
543
|
-
that dominate live UI under input churn.
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
639
|
+
that dominate live UI under input churn. **Speed wins vs alien: 4/9** (was 5/9 on
|
|
640
|
+
1.5.0-beta -- LARGE WEB APP flipped back to parity within host noise, +2% -> -3%).
|
|
641
|
+
The four wide-aggregation wins (SELECTIVE DAG, DYNAMIC DAG, MUX, SMALL SELECTIVE)
|
|
642
|
+
hold their prior magnitudes because the gate is round-off relative to per-iteration
|
|
643
|
+
retracking work. Losses widened on the cheapest propagation shapes where every branch
|
|
644
|
+
matters: BROADCAST (was -12%, now -10%), KAIROS (was -7%, now -12%), DEEP CHAIN (was
|
|
645
|
+
-14%, now -21%). The KAIROS and DEEP CHAIN widening is the observable gate cost --
|
|
646
|
+
one predicted `null` check per inner-loop iteration on shapes that iterate 1000-25000
|
|
647
|
+
times per rep. When a profiler is actually attached the observable becomes the
|
|
648
|
+
profiler's own cost. On allocation, lite wins 8/9 scenarios and is alone in the
|
|
649
|
+
zero-alloc band (~0.3 KB transient on the stable app shapes).
|
|
650
|
+
|
|
651
|
+
The cross-framework reactivity suite (5 frameworks) re-run on 1.6.0-alpha (default eager,
|
|
553
652
|
median-of-10): lite-signal is fastest on all five `dyn:*` rows -- `dyn: large web app`
|
|
554
|
-
|
|
555
|
-
simple component (+19%), dynamic component (+
|
|
556
|
-
slower and vue 15-
|
|
557
|
-
micro-rows
|
|
558
|
-
|
|
653
|
+
536ms (+11% vs alien-signals' 600ms), `dyn: wide dense` 903ms (+4% vs 939ms), plus
|
|
654
|
+
simple component (+19%), dynamic component (+13%), deep (+16%) -- with preact 6-19x
|
|
655
|
+
slower and vue 15-33x slower on the app-shaped graphs. On the `S: updateComputations`
|
|
656
|
+
micro-rows lite trades the lead with alien: **4/7 wins this sweep** (was 7/7 on
|
|
657
|
+
1.5.0-beta) -- the drop is consistent with the gate cost on 50-70ms rows that iterate
|
|
658
|
+
many thousands of times per measurement. Retracking verified correct by
|
|
559
659
|
`retracking.difftest.mjs` (20,000 direct + 10,000 batched writes, 0 disagreements vs
|
|
560
660
|
published 1.1.5). `prealloc: "lazy"` trades a little first-construction allocation on the
|
|
561
661
|
dynamic shapes for a smaller resident heap and faster cold start; steady state identical.
|
|
562
662
|
|
|
663
|
+
**Andrii Volynets js-reactivity-benchmark position: 4th of 15** with geomean
|
|
664
|
+
**73.1ms** (was 79.3 on 1.5.0-beta -- own-side improvement + Preact recovered from
|
|
665
|
+
its 1.14.2 regression). Ahead of Preact Signals (79.9) by ~9%. Behind alien-signals
|
|
666
|
+
(48.1), reflex (49.8), @reactively (58.3). **6 outright wins** (was 2 on
|
|
667
|
+
1.5.0-beta, 5 on 1.4.0): `broadPropagation`, `manyEffectsFromOneSource`,
|
|
668
|
+
`manySourcesIntoOneComputedEffect`, `manySourcesIntoOneComputedEffectWithDirect`,
|
|
669
|
+
`molBench`, and `32x8 - 4 sources - pull`. Top-3 count: 23/47. Head-to-head ratios:
|
|
670
|
+
vs @vue/reactivity 1.6x, vs Signia 2.0x, vs MobX 2.3x, vs @solidjs/signals 2.8x, vs
|
|
671
|
+
SolidJS 4.2x, vs Preact 1.09x. Raw log: `bench/AndriiVolynetsReactiveBench.log`.
|
|
672
|
+
|
|
563
673
|
Retained heap after forced GC: typically negative for all libs (V8 compacts).
|
|
564
674
|
The one exception: lite-signal shows ~+71 KB retained on KAIROS, which is the
|
|
565
675
|
pre-allocated pool holding the live 1002-node graph in steady state. This is
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zakkster/lite-signal",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.0-alpha",
|
|
4
4
|
"description": "Zero-GC reactive graph. Monomorphic object pool, versioned push-pull propagation, 32-bit modular versioning. Built for hot paths and long-running processes.",
|
|
5
5
|
"author": "Zahary Shinikchiev <shinikchiev@yahoo.com>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -32,10 +32,14 @@
|
|
|
32
32
|
"test:hardening": "npm --prefix test/ProfilerTests test",
|
|
33
33
|
"test:hardening:gc": "npm --prefix test/ProfilerTests run test:gc",
|
|
34
34
|
"test:harness": "npm --prefix harness/ProfilerTools test",
|
|
35
|
-
"test:
|
|
35
|
+
"test:zgc": "node --expose-gc --max-semi-space-size=4 --test 'test/zgc/*.test.mjs'",
|
|
36
|
+
"test:zgc:report": "node --expose-gc test/zgc/zero-gc-gate.mjs",
|
|
37
|
+
"test:all": "npm test && npm run test:hardening && npm run test:harness && npm run test:zgc",
|
|
36
38
|
"bench": "node --expose-gc bench/benchmark.mjs",
|
|
37
39
|
"bench-reactive": "node --expose-gc bench/benchmarkReactive.mjs",
|
|
38
|
-
"
|
|
40
|
+
"profile:burst": "node --expose-gc harness/burst-dag.mjs",
|
|
41
|
+
"profile:pull": "node --expose-gc harness/pull-stress.mjs",
|
|
42
|
+
"verify": "npm test && npm run test:zgc && npm run bench",
|
|
39
43
|
"gate": "node harness/VersionMatrix/pre-publish.mjs",
|
|
40
44
|
"prepublishOnly": "node harness/VersionMatrix/pre-publish.mjs"
|
|
41
45
|
},
|