@zakkster/lite-signal 1.6.0-preview.0 → 1.6.0-preview.2

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 CHANGED
@@ -64,8 +64,59 @@ pure-owner node transparently.
64
64
  Exported as a registry method and a top-level helper bound to the default registry,
65
65
  mirroring `createRoot`.
66
66
 
67
+ ### Added -- characterization harnesses (`burst-dag.mjs`, `pull-stress.mjs`)
68
+
69
+ Two root-level standalone harnesses that exercise the new 1.6.0 instrumentation
70
+ surface against the engine's two main hot paths. Both are engine-agnostic
71
+ (`./Signal.js` + public `onGraphMutation` only), both expose a CLI + module
72
+ exports, both stay out of `npm test` and the published tarball.
73
+
74
+ **`burst-dag.mjs`** (`npm run profile:burst`, also `node --expose-gc burst-dag.mjs
75
+ [--width=512 --layers=32 ...]`) reconstructs the published
76
+ `js-reactivity-benchmark` burst shape (sources -> width x layers, fanIn 8, burst
77
+ 16) and characterizes lite-signal's own flush behavior. The standalone path uses
78
+ the new `stats().flushPasses` counter as a cross-check against the opcode-6 pass
79
+ count -- by construction they must match when the hook is attached for exactly
80
+ one burst, which the harness asserts inline. Also exports `burstDagScenario`
81
+ (for plugging into a steady-state allocation gate) and `multiPassProbe` (a
82
+ controlled two-effect write-back that forces a `passes > 1` case so the opcode
83
+ dispatch can be smoke-tested on an engine where multi-pass actually occurs).
84
+
85
+ **`pull-stress.mjs`** (`npm run profile:pull`, also `node --expose-gc
86
+ pull-stress.mjs [--maxDepth=3584 --step=512 ...]`) is the pull-path companion:
87
+ characterizes how the recursive pull scales with chain depth and binary-searches
88
+ the exact overflow point. Three answers per run: (1) the exact deepest chain
89
+ that pulls successfully (the roadmap's "~5,000 chained computeds" pinned to a
90
+ number for the current engine), (2) per-level cold cost across a depth sweep
91
+ (should be roughly linear; superlinear flags a per-node bookkeeping cost
92
+ growing with depth), and (3) cached-read cost (should be O(1) regardless of
93
+ depth via the 1.1.4 `markEpoch` short-circuit). Structure pass at a safe fixed
94
+ depth confirms the opcode triple (0 flush passes, 0 effect runs, recomputes ==
95
+ depth) -- the pull path is doing nothing it shouldn't. Also exports
96
+ `pullStressScenario` for steady-state allocation gates and `probeOverflow`
97
+ for the binary search alone. Both `--kind=callable` and `--kind=box` are
98
+ supported and surface a real engine difference (box pulls overflow earlier
99
+ because `box.get()` adds a prototype-method frame per level, and cached box
100
+ reads are several times more expensive than cached callable reads).
101
+
102
+ Both files import only `./Signal.js`, so the same harness runs against any
103
+ engine build: point `Signal.js` at 1.5.x to compare without the counters
104
+ (`burst-dag` adapts -- only opcode 5 fires on that engine -- and `pull-stress`
105
+ works identically), or at a rejected candidate to re-verify on. The numbers
106
+ they produce are reproducible, comparable, and engine-version-aware.
107
+
67
108
  ### Verified
68
109
 
110
+ - **Full suite green** against the 1.6.0 engine: 443 tests, 442 pass, 0 fail,
111
+ 1 skip (only the architecturally-N/A SSR case in `17-reactivity`). +4
112
+ `createScope` tests in `test/28-scope_test.mjs`; the 1.5.0 box and createRoot
113
+ suites carry forward unchanged. **Coverage** (c8@11, Node 22): `Signal.js`
114
+ 100% statements / 96.96% branches / 100% functions / 100% lines; `Watch.js`
115
+ 100% across all four. The branch drop vs 1.5.0 (97.35% -> 96.96%) is the
116
+ zero-cost gate on `flushPasses` / opcode 6 / opcode 7 -- the
117
+ `if (mutationHook !== null)` mutation-hook-attached branch is not exercised
118
+ by the active test suite, which never attaches a hook; the inert path is
119
+ covered.
69
120
  - **`createScope` behavior** (4 tests, `node --expose-gc`): returns `fn`'s value and
70
121
  runs the owner exactly once even when `fn` reads signals in its direct body
71
122
  (untracked); inner effects/computeds track and update; `dispose()` cascade-disposes
@@ -271,7 +322,7 @@ as before (the reset keeps the arena warm); only the cumulative counts reset.
271
322
 
272
323
  ### Verified
273
324
 
274
- - **Full suite green** against the 1.4.0 engine: 430 tests, 420 pass, 0 fail,
325
+ - **Full suite green** against the 1.4.0 engine: 429 tests, 419 pass, 0 fail,
275
326
  10 skip (9 signalBox-staged-for-1.5.0 plus 1 architecturally-N/A SSR skip). The eager-default and the counter additions
276
327
  changed no existing test outcome.
277
328
  - **Counter correctness** confirmed directly: after building a signal ->
@@ -282,10 +333,10 @@ as before (the reset keeps the arena warm); only the cumulative counts reset.
282
333
  - **Zero-GC steady state holds**: the counters bump only on acquire / dispose /
283
334
  grow, none of which occur on the steady-state write path after warm-up. Writing
284
335
  through a built graph allocates nothing and moves no counter.
285
- - **`stats()` shape** is now the authoritative 11-key 1.4.x shape; the
286
- introspection-contract test is updated to expect the three counters present
287
- (the 1.2.x/1.3.0 test pinned their *absence*; that pin is correctly inverted
288
- for 1.4.0).
336
+ - **`stats()` shape** is now the authoritative 11-key 1.4.x shape, pinned by a
337
+ new shape-and-initial-zeros test in `03-pool` -- the first explicit pin for
338
+ the `stats()` surface (the 1.2.x / 1.3.0 entries described the absence of the
339
+ counters in prose; 1.4.0 codifies the new shape as a test assertion).
289
340
 
290
341
 
291
342
 
@@ -367,10 +418,10 @@ in 1.3.0.
367
418
 
368
419
  ### Verified
369
420
 
370
- - **Full suite green** against the 1.3.0 engine: 424 tests, 414 pass, 0 fail,
371
- 1 architecturally-N/A SSR skip (the `24-signalbox` suite is `{skip:true}` on
372
- 1.3.x -- those primitives land in 1.5.0). The eager-default flip changed no
373
- test outcome.
421
+ - **Full suite green** against the 1.3.0 engine: 423 tests, 413 pass, 0 fail,
422
+ 10 skip (9 `24-signalbox` tests `{skip:true}` on 1.3.x -- those primitives
423
+ land in 1.5.0 -- plus 1 architecturally-N/A SSR skip). The eager-default flip
424
+ changed no test outcome.
374
425
  - **Behavior-preservation difftest**: 20,000 direct + 10,000 batched writes
375
426
  against the published 1.1.5 reference, 0 disagreements. Pool growth, chunked
376
427
  refill, and the intrusive mark stack do not alter observable propagation.
@@ -380,8 +431,7 @@ in 1.3.0.
380
431
  scenarios.
381
432
  - **`stats()` shape unchanged from 1.2.x** (8 keys). The cumulative allocation
382
433
  counters (`totalAllocations` / `totalDisposals` / `poolGrowths`) remain
383
- reserved for 1.4.0 and are still absent here -- the introspection-contract
384
- test continues to pin their absence.
434
+ reserved for 1.4.0 and are still absent here.
385
435
 
386
436
 
387
437
 
package/README.md CHANGED
@@ -244,6 +244,7 @@ import {
244
244
  signalBox, computedBox, // 1.5.0 -- allocation-light, non-callable
245
245
  batch, untrack, onCleanup, isTracking,
246
246
  createRoot, // 1.5.0 -- detached ownership scope
247
+ createScope, // 1.6.0 -- detached, adopting scope (one disposer)
247
248
  // Registry / lifecycle
248
249
  createRegistry, setDefaultRegistry, dispose, destroy,
249
250
  stats, CapacityError,
@@ -358,6 +359,36 @@ Runs `fn` in a **detached ownership scope** and returns whatever `fn` returns. E
358
359
 
359
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. (The companion `runWithOwner`, for re-attaching to a captured owner, is named in the engine as the intended second half of this API and is not yet shipped.)
360
361
 
362
+ ### createScope (1.6.0)
363
+
364
+ ```ts
365
+ const items = signal([/* ... */]);
366
+ const itemDisposers = new Map();
367
+
368
+ // In a reconciler driver: each item gets its own per-item scope.
369
+ effect(() => {
370
+ for (const item of items()) {
371
+ if (!itemDisposers.has(item.id)) {
372
+ itemDisposers.set(item.id, createScope((dispose) => {
373
+ // The consumer's mapFn builds an arbitrary reactive subgraph here;
374
+ // every effect and computed it creates is owned by this scope.
375
+ effect(() => { /* render bindings */ });
376
+ return dispose;
377
+ }));
378
+ }
379
+ }
380
+ });
381
+
382
+ // Later, when an item leaves:
383
+ itemDisposers.get(removedId)(); // cascade-disposes the entire per-item subgraph
384
+ ```
385
+
386
+ Runs `fn(dispose)` in a **detached, adopting scope** and returns whatever `fn` returns. The single `dispose` argument handed to `fn` cascade-disposes every effect and computed created inside `fn` -- one disposer tears down a subtree of *unknown* shape. This is the lifecycle complement to `createRoot`: `createRoot` only *detaches* (the caller must dispose each child by hand, correct for one known long-lived watcher), while `createScope` *adopts*, which is what a per-item scope in a keyed-list or scene reconciler needs where the item's reactive graph is the consumer's `mapFn`, not something the reconciler can enumerate.
387
+
388
+ Like `createRoot`, both ownership and tracking are detached for the duration of `fn`'s direct body; inner effect/computed bodies still establish their own scopes. Consistent with the 1.2.0 ownership rule, **plain signals created directly in `fn` are not adopted** -- dispose those explicitly or let them fall out of reference; computeds and effects are adopted and cascade. A scope created inside a consumer effect SURVIVES that consumer's re-run -- the reconciler-critical detach property. The disposer is the same gen-guarded, ABA-safe handle `effect()` returns and resolves to its owner effect under `describe` / `nodeId` / `forEachOwned`. Double-dispose is an idempotent no-op.
389
+
390
+ Implementation note: the scope owner is backed by a never-re-running effect node, so it counts as one effect in `stats()` and the pinned `signals + computeds + effects === activeNodes` invariant is untouched. No new node kind, flag, or `stats()` key.
391
+
361
392
  ### isTracking
362
393
 
363
394
  ```ts
@@ -435,6 +466,8 @@ const unsub = onGraphMutation((opcode, intA, intB) => {
435
466
  case 3: devtools.onLinkAdd(intA, intB); break; // intA = source.id, intB = target.id
436
467
  case 4: devtools.onLinkRemove(intA, intB); break;
437
468
  case 5: devtools.onRecompute(intA); break; // before each effect re-run / computed re-eval
469
+ case 6: devtools.onFlushPass(intA, intB); break; // 1.6.0 -- (passCount, effectsToRun) at top of each drain pass
470
+ case 7: devtools.onEffectRunInPass(intA); break; // 1.6.0 -- (id, 0) before each effect re-run inside a pass
438
471
  }
439
472
  });
440
473
 
@@ -450,6 +483,10 @@ A registry-level (and top-level) debug hook for push-based tooling -- the connec
450
483
 
451
484
  **Listener contract: observe only -- never throw, never mutate the graph from inside.** The hook fires synchronously inside mutation points; mutating from the callback corrupts the in-flight operation. Wrap any downstream work that could touch the registry in a microtask.
452
485
 
486
+ **1.6.0 -- flush-profiling opcodes.** Opcodes `6` (flush pass) and `7` (effect run in pass) extend the surface to cover the flush dimension lite-devtools 1.2 / lite-studio 1.2 read through `watchAllocations`. The matching `stats().flushPasses` counter (the 12th `stats()` key) advances once per drain pass. Both the counter bump and the opcode dispatch sit behind the same `mutationHook !== null` gate, so when no listener is attached they are inert and `flushPasses` is frozen -- the flush loop is byte-identical to 1.5.0.
487
+
488
+ **Characterization harnesses (`burst-dag.mjs`, `pull-stress.mjs`).** Two root-level standalone harnesses that exercise the 1.6.0 instrumentation against the engine's two main hot paths. `burst-dag.mjs` (`npm run profile:burst`) reconstructs the layered DAG burst shape (sources -> width x layers, fanIn 8, burst 16) and uses opcodes 5/6/7 to characterize a single steady-state burst: flush passes, recomputes per node, effects enqueued vs short-circuited. Exports `burstDagScenario` for a steady-state allocation gate, and `multiPassProbe` for a controlled two-effect write-back that forces a `passes > 1` case so the opcode dispatch can be smoke-tested where multi-pass actually occurs. `pull-stress.mjs` (`npm run profile:pull`) is the pull-path companion: binary-searches the exact recursive-pull depth limit (the ~5,000-computed bound named in the roadmap, pinned to a number for the current engine), sweeps cold cost per level across depths to flag any superlinear bookkeeping, and confirms cached reads are O(1) regardless of depth (the 1.1.4 `markEpoch` short-circuit holds). Exports `pullStressScenario` for steady-state gates and `probeOverflow` for the bisection alone; supports both `--kind=callable` and `--kind=box`, which surface a real engine difference (box pulls overflow earlier because `box.get()` adds a prototype-method frame per level). Both import only `./Signal.js` + the public `onGraphMutation` hook, so the same files run against any engine build (point `Signal.js` at 1.5.x to compare without the counters). Neither is part of `npm test` or the published tarball -- they ship in source for reproducibility.
489
+
453
490
  ### onCleanup
454
491
 
455
492
  ```ts
@@ -531,7 +568,7 @@ Default sizing for a Twitch-extension-style budget:
531
568
  | Heavy dashboard (variable scale) | 2048 | 16384 | `"eager"` | `"grow"` |
532
569
  | Per-viewer sandbox / short-lived | 512 | 2048 | `"lazy"` | `"throw"` |
533
570
 
534
- `stats()` reports 11 keys: eight live gauges -- `signals`, `computeds`, `effects`, `activeNodes`, `activeLinks`, `pooledLinks`, `nodePoolCapacity`, `linkPoolCapacity` (the capacity keys are ledgers under `"lazy"`) -- plus three cumulative lifecycle counters added in **1.4.0**: `totalAllocations`, `totalDisposals`, and `poolGrowths` (monotonic over the registry's life, reset only by `destroy()`). Sample them over time to chart allocation rate, pool-reuse ratio, and graph churn; in a quiescent registry `totalAllocations - totalDisposals === activeNodes`. Drop it on screen for live observability.
571
+ `stats()` reports 12 keys: eight live gauges -- `signals`, `computeds`, `effects`, `activeNodes`, `activeLinks`, `pooledLinks`, `nodePoolCapacity`, `linkPoolCapacity` (the capacity keys are ledgers under `"lazy"`) -- plus three cumulative lifecycle counters added in **1.4.0**: `totalAllocations`, `totalDisposals`, `poolGrowths`, and a fourth counter added in **1.6.0**: `flushPasses` (advances once per effect-flush drain pass, gated behind the mutation-hook check so it stays frozen when no listener is attached -- zero cost in steady state). All four counters are monotonic over the registry's life and reset only by `destroy()`. Sample them over time to chart allocation rate, pool-reuse ratio, graph churn, and flush activity; in a quiescent registry `totalAllocations - totalDisposals === activeNodes`. Drop it on screen for live observability.
535
572
 
536
573
  </details>
537
574
 
@@ -695,7 +732,7 @@ These are the questions you'd ask in a code review, with the answers:
695
732
 
696
733
  ## Benchmarks
697
734
 
698
- 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 lite-signal **@1.3.0** (default `prealloc: "eager"`) vs alien-signals on the same `benchmark.mjs` loop -- the harness now reports **median execution time + transient heap** rather than ops/s. 1.3.0's hot paths are byte-identical to 1.2.2, so these track the 1.2.2 measurement; the deltas are run-to-run noise on this old host, not engine changes. **1.4.0 carries these forward unchanged** -- its only addition is three `stats()` counters that bump on acquire/dispose/grow, never on the steady-state read path, so throughput is identical (a fresh 1.4.0 bench run will be published when available). Full per-engine tables: [`results.txt`](./results.txt) (this propagation suite) and [`resultsReactive.txt`](./resultsReactive.txt) (the cross-framework reactivity suite).
735
+ 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 lite-signal **@1.3.0** (default `prealloc: "eager"`) vs alien-signals on the same `benchmark.mjs` loop -- the harness now reports **median execution time + transient heap** rather than ops/s. 1.3.0's hot paths are byte-identical to 1.2.2, so these track the 1.2.2 measurement; the deltas are run-to-run noise on this old host, not engine changes. **1.4.0, 1.5.0, and 1.6.0 carry these forward unchanged** -- 1.4.0 added three `stats()` counters on existing acquire/dispose/grow edges (never the steady-state read path); 1.5.0 added the box handle shape (allocation-light construction; the read/write hot path is the same pooled-node engine); 1.6.0 added `flushPasses` plus opcodes 6/7, all gated behind the existing `mutationHook !== null` check, so the flush loop is byte-identical to 1.5.0 when no listener is attached. Throughput is unchanged across all three additions (fresh 1.4.0 / 1.5.0 / 1.6.0 bench runs will be published when available). Full per-engine tables: [`results.txt`](./results.txt) (this propagation suite) and [`resultsReactive.txt`](./resultsReactive.txt) (the cross-framework reactivity suite).
699
736
 
700
737
  | Scenario | What it stresses | lite-signal | alien-signals | lite vs alien | transient heap (lite / alien) |
701
738
  | ---------- | -------------------------------- | ----------- | ------------- | ------------- | ----------------------------- |
@@ -763,7 +800,8 @@ Three tiers, all reproducible.
763
800
  - **`22-mutation-hook_test.mjs`** -- 1.2.1 `onGraphMutation` semantics (12 tests across 2 suites). Registration: unsubscribe returns a function; `null` argument clears and the unsub restores the prior listener; non-function/non-null throws `TypeError`; multiple registrations stack LIFO; registries are isolated (no cross-talk). Opcode emission: `1` node-create fires with `(id, flags)` for signal (32) / computed (1) / effect (2); `2` node-dispose fires for cascade-disposed owned children; `3` link-add fires with `(source.id, target.id)` on dependency record; `4` link-remove fires when a dep-set flip severs the tail; `5` recompute fires on initial eval AND re-eval; the hook fires synchronously inside the mutation (listener sees its own event before the caller returns); payload is always three plain numbers -- no objects, no closures.
764
801
  - **`23-owner-introspection_test.mjs`** -- 1.2.1 owner-tree introspection + effect-disposer regression (22 tests across 4 suites). `ownerOf`: undefined for top-level / garbage input / stale handle; returns the enclosing effect's descriptor for a child created inside an effect body. `forEachOwned`: no-op for handles with no owned children / garbage input / stale handle; iterates owned children as `{id, kind, value}` descriptors. Gen-guarded introspection (ABA fix): `nodeId` / `describe` / `hasObservers` return undefined / false for stale handles; `observeObservers` throws `TypeError`; `forEachObserver` / `forEachSource` are no-ops; descriptors returned by `describeNode` are themselves gen-stamped so a descriptor obtained pre-recycle correctly walks as a no-op post-recycle (the "descriptors are re-walkable handles" contract survives the guard). Plus the 1.2.1 effect-dispose-handle fix: passing the effect's disposer directly to `describe` / `nodeId` / `forEachSource` / `forEachOwned` / `ownerOf` / `hasObservers` works as a first-class introspection handle (pre-fix it was a bare closure and returned `undefined` for a *live* effect); after `fx()` dispose the same handle correctly goes stale on every entry point; the disposer's `NODE_GEN` mirrors the effect node's birthGen exactly.
765
802
  - **`24-signalbox_test.mjs`** -- the `signalBox` / `computedBox` allocation-light handle API, **activated in 1.5.0** (committed `{skip:true}` since 1.3.0, now running against the real implementation). 12 tests: box get/set/peek/update, `computedBox` derive + memoize, peek-does-not-track, subscribe fires-and-untracks, box<->callable interop both directions, batch coalescing (including set-then-revert net no-op), dispose with ABA-safety, the `equals` short-circuit, `computedBox.peek`, and the top-level helpers bound to the default registry.
766
- - **`27-create-root_test.mjs`** -- `createRoot` (1.5.0), the ownership escape hatch. A watcher spawned inside a consumer effect via `createRoot` survives the consumer's re-run (the exact `lite-query` lazy-watcher pattern); the contrast case confirms an *unwrapped* spawn is cascade-disposed; `createRoot` returns `fn`'s value, detaches tracking in `fn`'s direct body while inner effect bodies still track, and composes with box handles.
803
+ - **`27-create-root_test.mjs`** -- `createRoot` (1.5.0), the ownership escape hatch. A watcher spawned inside a consumer effect via `createRoot` survives the consumer's re-run (the exact `lite-query` lazy-watcher pattern); the contrast case confirms an *unwrapped* spawn is cascade-disposed; `createRoot` returns `fn`'s value, detaches tracking in `fn`'s direct body while inner effect bodies still track, and composes with box handles. 7 tests, including a top-level-export binding case that closes the otherwise-uncovered top-level `createRoot` path.
804
+ - **`28-scope_test.mjs`** -- `createScope` (1.6.0), the adopting counterpart to `createRoot`. 4 tests: the scope owner runs exactly once on creation; direct-body signal reads in `fn` are untracked while inner effect/computed bodies track normally; `dispose()` cascade-disposes the owned subtree (effects + computeds) while a directly-allocated signal correctly survives (the engine never owner-adopts signals); a scope created inside a consumer effect SURVIVES that consumer's re-run -- the reconciler-critical detach property; `dispose()` is idempotent; the disposer is introspection-stamped to its owner effect (`describe(dispose).kind === "effect"`); and `totalAllocations - totalDisposals === activeNodes` holds across the entire lifecycle.
767
805
  - **`25-devtools-real-boot_test.mjs`** -- Devtools/Studio contract (10 tests). Boots the actual `Devtools.js` against the 1.5.0 engine and exercises all 19 Devtools exports plus the 10 symbols Studio imports from Devtools. Pins the ghost contract: heavy introspection (graph walk, owner-tree, observer descriptors) adds **zero** nodes to the live graph. Catches the real-rig failure mode where importing the package by its own name from a repo whose `package.json` declares `name: "@zakkster/lite-signal"` resolves to the published build instead of the local engine.
768
806
  - **`26-free-list-invariant_test.mjs`** -- the 1.2.2 audit's cleanliness pins (3 invariant tests + 1 targeted coverage test). Asserts directly -- by inspecting freshly-allocated nodes through the documented `describe()` -> `NODE_PTR` introspection protocol -- that the `ReactiveNode` constructor and the fresh-pool-growth path initialize the ten fields the audit removed from `createNode` to identical values, so the deleted writes were defending against a state the engine cannot produce on a clean free list. The 4th test covers the swallow-on-self-dispose-then-throw branch in `pullComputed` (the path that lifted branch coverage from 98.07% to 98.43%).
769
807
 
@@ -1027,7 +1065,7 @@ The one remaining open item is a deliberate design choice (#179, below).
1027
1065
  The exact post-1.2 pass count is being re-run against the upstream suite;
1028
1066
  per-test results and the runner adapter live in `/conformance/`.
1029
1067
 
1030
- **177 of 178 tests pass **, placing lite-signal **in the second place of sixteen**
1068
+ **177 of 178 tests pass**, placing lite-signal **in the second place of sixteen**
1031
1069
  evaluated libraries -- just behind alien-signals (177).
1032
1070
 
1033
1071
  We publish both passing and failing tests, because honesty about behavior is
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,22 @@ 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
+ * Run `fn(dispose)` in a detached, untracked scope and return whatever `fn`
283
+ * returns (1.6.0). The single `dispose` argument cascade-disposes every effect
284
+ * and computed created inside `fn`. Lifecycle complement to {@link createRoot}:
285
+ * `createRoot` only *detaches* (caller must dispose each child by hand),
286
+ * `createScope` *adopts*, so one disposer tears down a subtree of unknown shape
287
+ * -- the per-item lifecycle a keyed-list or scene reconciler needs. Plain
288
+ * signals created directly in `fn` are NOT adopted (consistent with the 1.2.0
289
+ * ownership rule); computeds and effects are. The owner never re-runs, so
290
+ * direct-body reads in `fn` are untracked; reactive bindings belong in inner
291
+ * effect/computed bodies. A scope created inside a consumer effect SURVIVES
292
+ * that consumer's re-run -- the reconciler-critical detach property. The
293
+ * disposer is the same gen-guarded, ABA-safe handle `effect()` returns and
294
+ * resolves to the owner effect under `describe` / `nodeId` / `forEachOwned`.
295
+ */
296
+ createScope<T>(fn: (dispose: () => void) => T): T;
271
297
  /**
272
298
  * Universal disposal for anything created by this registry: signals,
273
299
  * computeds, boxes, or effect dispose handles. Cross-registry calls are
@@ -348,6 +374,8 @@ export function signalBox<T>(initial: T, opts?: SignalOptions<T>): SignalBox<T>;
348
374
  export function computedBox<T>(fn: () => T, opts?: ComputedOptions<T>): ComputedBox<T>;
349
375
  /** Run `fn` in a detached ownership scope (1.5.0), bound to the default registry. See {@link Registry.createRoot}. */
350
376
  export function createRoot<T>(fn: () => T): T;
377
+ /** Run `fn(dispose)` in a detached, adopting scope (1.6.0), bound to the default registry. See {@link Registry.createScope}. */
378
+ export function createScope<T>(fn: (dispose: () => void) => T): T;
351
379
  /** Universal disposal -- see {@link Registry.dispose}. */
352
380
  export function dispose(api: Disposable): void;
353
381
  export function batch<T>(fn: () => T): T;
package/llms.txt ADDED
@@ -0,0 +1,674 @@
1
+ # @zakkster/lite-signal
2
+
3
+ > Zero-GC reactive graph library. Object-pooled nodes and links, versioned
4
+ > push-pull propagation, 32-bit modular epoch counters. Synchronous flush, no
5
+ > microtask scheduler, no allocations in hot path after warm-up. ESM-only.
6
+ > ~3.2 KB min+gz, zero dependencies, MIT licensed.
7
+
8
+ The library exposes a small reactive primitives API (signal, computed, effect,
9
+ batch, untrack, onCleanup) backed by pre-allocated pools. Built for animation
10
+ loops, Twitch Extensions, game HUDs, and other contexts where GC pauses break
11
+ the frame budget. Effects flush synchronously in the same call stack as the
12
+ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
13
+
14
+ ## Core concepts
15
+
16
+ - **Signal**: root reactive cell. `signal(initial, { equals? })` returns a function. Call it to read (tracked), use `.peek()` to read without tracking, `.set(v)` to notify downstream, `.update(fn)` for read-modify-write, `.subscribe(fn)` for an effect-backed listener.
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
+ - **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
+ - **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`. The re-attach companion `runWithOwner` is named in the engine as the intended second half and is not yet shipped.
21
+ - **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
+ - **Batch**: `batch(fn)` defers effect flush until the outermost batch closes. Nestable.
23
+ - **Untrack**: `untrack(fn)` reads without subscribing.
24
+ - **isTracking**: `isTracking()` returns true iff a read right now would record a dependency on this registry (for wrappers that lazily allocate signals).
25
+ - **onCleanup**: registers teardown for the current computation; fires before each re-run and once on dispose. Works in effects and computeds.
26
+ - **Observer-lifecycle introspection** (1.1.4; top-level + per-registry): `hasObservers(handle)` returns true iff a signal/computed has >=1 live observer right now (O(1); a `peek` does not count). `observeObservers(handle, { onConnect?, onDisconnect? })` fires on the 0->1 and 1->0 observer transitions (after registration; transition-only) and returns an idempotent unobserve -- the auto-pause hook for tickers (lite-time/lite-raf start a source only while it's watched). `forEachObserver(handle, fn)` / `forEachSource(handle, fn)` walk the live graph in either direction, passing a `{ kind, value }` descriptor (`kind` is `"signal" | "computed" | "effect"`) -- for inspection (lite-devtools). The surface is gated by an internal counter: zero steady-state cost when nothing is observed. `hasObservers`/`forEach*` no-op on a non-handle; `observeObservers` throws `TypeError`. **Node identity (1.1.5):** `nodeId(handle)` returns the node's stable per-allocation id, `describe(handle)` returns the handle's own `{ id, kind, value }` descriptor, and `forEach*` descriptors now carry `id` too; a descriptor is **re-walkable** (pass it back into `forEachObserver`/`forEachSource`) -- the recursion primitive lite-devtools uses to walk the full DAG. **Owner-tree introspection (1.2.1):** `forEachOwned(handle, fn)` walks a node's owned children (lifetime-binding edges from the 1.2 owner tree -- invisible through dep/sub); `ownerOf(handle)` returns the owner's descriptor or `undefined` for top-level / stale handles. **Stale-handle guard (1.2.1):** the entire introspection surface plus `peek()`/`read()`/`set()` is now generation-checked. A handle held across the 1.2 owner-cascade auto-dispose used to resolve `NODE_PTR` ungated and silently report the recycled slot's NEW resident; 1.2.1 surfaces stale handles as `undefined` (or `TypeError`, for `observeObservers`) -- same ABA discipline `dispose()` always had. Descriptors are gen-stamped so the re-walkable contract survives the guard. **Push-based mutation hook (1.2.1):** `onGraphMutation(fn)` registers a single nullable listener invoked synchronously at every mutation point with three integers `(opcode, intA, intB)` -- opcodes `1` node-create / `2` node-dispose / `3` link-add / `4` link-remove / `5` recompute. Zero-cost gate when no listener is registered (one branch-predicted null check); allocation-free dispatch when registered. The connection point for push-based devtools/studio. Contract: observe only -- never throw, never mutate.
27
+ - **Registry**: `createRegistry({ maxNodes, maxLinks, prealloc, onCapacityExceeded, maxFlushPasses })` creates an isolated reactive world with its own pools. Useful for tests, plugins, multi-tenant sandboxes. Top-level helpers use a default registry created at module load. `prealloc` (1.3.0; `"eager"` default | `"lazy"`) chooses up-front vs on-demand pool construction; `onCapacityExceeded` (`"throw"` default | `"grow"`) chooses fail-fast vs chunked-incremental growth bounded by the 16x link ceiling.
28
+ - **CapacityError**: thrown when a fixed-size pool is exhausted under the `"throw"` policy, or when a `"grow"` policy hits the 16× starting-capacity ceiling on links.
29
+
30
+ ## Architecture invariants
31
+
32
+ - **Two object pools**: nodes (default 1024) and links (default 4×nodes). Singly-linked via `nextFree`, O(1) allocate/free.
33
+ - **Doubly-linked edge lists**: each link is in both a dep-list (on the target/observer) and a sub-list (on the source/dependency). O(1) unlink during cursor reconciliation.
34
+ - **Cursor reconciliation**: at the start of each computed/effect run, `activeObserverCurrentDep` points at the head of the existing dep list. As the body reads deps, matching links advance the cursor (zero alloc); non-matching links insert before the cursor and the displaced tail is severed at the end of the run.
35
+ - **Iterative mark phase**: `markDownstream` uses a pre-allocated `markStack` array for DFS -- no recursion, no call stack growth on wide fan-out.
36
+ - **Recursive computed pull**: `pullComputed` is call-stack recursive; deep chains beyond ~10,000 nodes will throw `RangeError`. Effects don't have this limit.
37
+ - **Double-buffered effect queue**: `effectQueueA` / `effectQueueB` alternate each flush pass -- effects *scheduled by* the current pass (cross-effect cascades) drain in the next pass. A **self-write** (an effect writing a signal it reads) is the exception: `markDownstream`'s `FLAG_COMPUTING` guard does **not** re-queue the writing effect, so a self-cycle runs exactly once -- while the write still propagates to the signal's other observers, and the effect stays responsive to later *external* writes (its `evalVersion` is bumped in the `executeEffect` finally). Mutual cross-effect write loops (A->B->A) are not self-cycles and trip `CycleError: flush passes exceeded` via `maxFlushPasses`.
38
+ - **maxFlushPasses ceiling**: default 100. Exceeding this throws `CycleError`. Prevents runaway effect loops.
39
+ - **32-bit modular versioning**: `globalVersion` and `node.version` are `(value + 1) | 0`, wrapping signed. Comparison via `((dep.version - evalVer) | 0) > 0` is wrap-safe and works in modular distance, not raw integer ordering. The engine never overflows.
40
+ - **Generation counter**: each node has a `gen` field incremented on dispose and destroy. Scheduler trampolines capture the current gen and no-op if it changes -- prevents stale callbacks from re-firing after dispose.
41
+ - **destroy()**: resets all pools, rebuilds free lists, bumps every node's gen, resets globalVersion to 1. Safe to call mid-flight (in-flight effects finish their current invocation, scheduled ones become no-ops).
42
+
43
+ ## Performance characteristics
44
+
45
+ - `signal.set(v)` -- O(downstream observers), zero alloc after warm-up.
46
+ - `signal.peek()` -- O(1), zero alloc.
47
+ - `computed()` cache hit -- O(deps), zero alloc.
48
+ - `computed()` cache miss -- O(deps + body), zero alloc if dep structure is stable.
49
+ - Effect re-run with stable dep order -- zero alloc.
50
+ - Stable read order: O(1) per dep via cursor reuse.
51
+ - Chaotic/randomized read order: 1.1.4 added version-stamped per-source reconciliation plus a `markEpoch` clean-read short-circuit on the pull, so the prior O(N)-per-dep degradation no longer dominates high-fan-in batched read-after-write -- the `dyn: large web app` and `dyn: wide dense` shapes that were the v1.1.x weakness are now the fastest of the five benchmarked frameworks (see resultsReactive.txt). Correctness verified by `retracking.difftest.mjs` (20,000 direct + 10,000 batched writes, 0 disagreements).
52
+
53
+ ## Version notes
54
+
55
+ - **1.6.0-preview** (current): the **observability-and-lifecycle minor**, shipping
56
+ on the `preview` dist-tag while it settles. Two additions, both on existing
57
+ hot-path-adjacent edges:
58
+
59
+ **1) `stats()` gains a twelfth key, `flushPasses`** -- advances once per
60
+ effect-flush drain pass. **2) Two new `onGraphMutation` opcodes for flush
61
+ profiling**: `6` flush pass `(passCount, effectsToRun)` at the top of each drain
62
+ pass, and `7` effect run in pass `(id, 0)` before each effect re-run inside a
63
+ pass. Both the `flushPasses` bump and the opcode dispatch sit behind the
64
+ existing `if (mutationHook !== null)` gate, so when no profiler is attached
65
+ they are inert: `flushPasses` is frozen and the flush loop is byte-identical
66
+ to 1.5.0. This is what lets lite-devtools 1.2 / lite-studio 1.2's
67
+ `watchAllocations` chart recompute/flush activity alongside the 1.4.0
68
+ allocation counters; only the flush series requires 1.6.
69
+
70
+ **3) `createScope(fn)` -- the disposable-owner counterpart to `createRoot`.**
71
+ Runs `fn(dispose)` in a detached, untracked scope and returns whatever `fn`
72
+ returns, having handed `fn` a single `dispose` that **cascade-disposes every
73
+ effect and computed created inside `fn`**. `createRoot` only *detaches* (caller
74
+ disposes each child by hand -- correct for one known long-lived watcher);
75
+ `createScope` *adopts*, so one disposer tears down a subtree of unknown shape
76
+ -- the per-item lifecycle a keyed-list or scene reconciler needs, where the
77
+ item's reactive graph is the consumer's `mapFn` (not something the reconciler
78
+ can enumerate). Consistent with 1.2.0 ownership, **plain signals created
79
+ directly in `fn` are not adopted** (engine never owner-adopts signals);
80
+ computeds and effects are. The scope owner is backed by a never-re-running
81
+ effect node, so it counts as one effect in `stats()` and the pinned
82
+ `signals + computeds + effects === activeNodes` invariant is untouched; the
83
+ disposer is the same gen-guarded, ABA-safe handle `effect()` returns and
84
+ resolves to the owner under `describe` / `nodeId` / `forEachOwned`. A scope
85
+ created inside a consumer effect SURVIVES that consumer's re-run -- the
86
+ reconciler-critical detach property.
87
+
88
+ **The callable API and hot paths are unchanged**; this is purely additive
89
+ instrumentation and a second ownership primitive. Drop-in over 1.5.0.
90
+ Two root-level characterization harnesses ship in source (not in the
91
+ tarball): **`burst-dag.mjs`** (`npm run profile:burst`) reconstructs the
92
+ layered DAG burst shape and uses opcodes 5/6/7 + `stats().flushPasses` to
93
+ report flush passes, max recomputes per node, and per-burst us; also exports
94
+ `burstDagScenario` + `multiPassProbe`. **`pull-stress.mjs`** (`npm run
95
+ profile:pull`) is the pull-path companion: binary-searches the recursive-pull
96
+ depth limit (~5,000 named in the roadmap, pinned to a number per engine),
97
+ sweeps cold cost per level, confirms cached reads are O(1) via markEpoch;
98
+ exports `pullStressScenario` + `probeOverflow`. Both import only
99
+ `./Signal.js` + public `onGraphMutation`, run against any engine build.
100
+ **Tests:** 443 total, 442 pass, 0 fail, 1 skip (only the architecturally-N/A
101
+ SSR case in `17-reactivity`); +4 `createScope` tests in `test/28-scope_test.mjs`
102
+ and the 1.4.0 pool tests carry the 11-key shape pin forward to the new 12-key
103
+ shape with `flushPasses`. **Coverage:** `Signal.js` 100% statements / 96.96%
104
+ branches / 100% functions / 100% lines; `Watch.js` 100%. The branch drop vs
105
+ 1.5.0 (97.35% -> 96.96%) is the `mutationHook !== null` gate on `flushPasses`
106
+ / opcodes 6+7 -- the listener-attached branch is not exercised by the
107
+ default suite (which never attaches a hook). Drop-in over 1.5.0.
108
+
109
+ - **1.5.0** (drop-in over 1.4.0): the **API-surface minor**. Two non-callable,
110
+ allocation-light primitives -- `signalBox(initial, opts?)` returning
111
+ `{ get, set, peek, update, subscribe }` and `computedBox(fn, opts?)` returning
112
+ `{ get, peek, subscribe }` -- land alongside the callable `signal` / `computed`,
113
+ plus **`createRoot(fn)`** as the ownership escape hatch. **The callable API, hot
114
+ paths, and `stats()` shape (11 keys) are unchanged from 1.4.0**; this is an
115
+ additive surface, not a second engine. Boxes wrap the same `ReactiveNode` and
116
+ interoperate freely with callables in one graph (verified both directions);
117
+ ownership, batching, glitch-freedom, and introspection apply uniformly, and box
118
+ nodes count in `stats().signals` / `computeds` exactly as callable nodes. Box
119
+ construction is ~1.7x cheaper than the callable (an `Object.create(proto)` handle
120
+ with two own props added in fixed order -- never `setPrototypeOf`, which would
121
+ transition the object to dictionary mode and blow the method-call ICs to
122
+ megamorphic); the read/write hot path stays zero-GC (200k box writes through a
123
+ 256-wide graph: 0 heap growth, 0 pool growths). `createRoot` runs `fn` with
124
+ `currentOwner` and `currentObserver` (and the tracking flag) nulled, so
125
+ effects/computeds created directly in `fn` are not adopted by the enclosing owner
126
+ and survive its re-runs/disposal -- the sanctioned opt-out for lazily spawning a
127
+ long-lived watcher from inside a consumer effect (`lite-query`'s pattern);
128
+ unwrapped, the consumer owns the watcher and cascade-disposes it. Inner
129
+ effect/computed bodies still establish their own scopes; `createRoot` returns
130
+ whatever `fn` returns. The owner/observer split (1.2.0) made `currentOwner` and
131
+ `currentObserver` distinct precisely so ownership could be detached without
132
+ affecting tracking; `createRoot` is the first of the two named primitives
133
+ (`runWithOwner`, the re-attach half, is not yet shipped). The `24-signalbox`
134
+ suite (staged `{skip:true}` since 1.3.0) now runs and passes. **Tests:** 439
135
+ total, 438 pass, 0 fail, **1 skip** (only the architecturally-N/A SSR case in
136
+ `17-reactivity`; the 9 originally-staged signalBox tests are now active and
137
+ the suite carries +3 box-coverage additions for a 12-test file, +7 `createRoot`
138
+ tests in `test/27-create-root_test.mjs`). **Coverage:** `Signal.js`
139
+ 100% statements / 97.35% branches / 100% functions / 100% lines; `Watch.js` 100%.
140
+ Drop-in over 1.4.0.
141
+
142
+ - **1.4.0** (drop-in over 1.3.0): the **observability minor**. `stats()` gains three
143
+ cumulative lifecycle counters -- `totalAllocations`, `totalDisposals`,
144
+ `poolGrowths` -- the surface reserved for 1.4.0 in the 1.2.x/1.3.0 notes, now
145
+ delivered. **The hot paths and public callable API are byte-identical to 1.3.0**;
146
+ the counters bump on existing acquire / dispose / pool-grow edges that already
147
+ ran, never on the steady-state read path, so throughput and zero-GC are
148
+ unchanged. The 1.3.0 eager pool default carries forward (`prealloc: "eager"`).
149
+ **`stats()` now returns 11 keys** (the 8 live gauges plus the 3 counters).
150
+ `totalAllocations` counts every node acquired (pool pop OR fresh build);
151
+ `totalDisposals` counts every node returned to the pool, with
152
+ `totalAllocations - totalDisposals === activeNodes` in a quiescent registry;
153
+ `poolGrowths` counts pool-growth chunks (node OR link crossing its ledger) --
154
+ nonzero after warm-up means the initial pool was undersized, 0 means an eager pool
155
+ was sized right. All three are monotonic and reset only by `destroy()`. They are
156
+ exact, not sampled: a consumer sampling `stats()` over time derives allocation
157
+ rate (delta totalAllocations / delta t), pool-reuse ratio
158
+ (1 - poolGrowths*initialCap/totalAllocations), and churn without the engine
159
+ computing rates -- the series lite-devtools 1.2 / lite-studio 1.2 plot. **Tests:**
160
+ 429 total, 419 pass, 0 fail, 10 skip (6 new counter tests in `test/03-pool_test.mjs`
161
+ cover the 11-key shape, the live invariant, poolGrowths firing on growth vs staying
162
+ 0 on a sized eager pool, and destroy() reset). **Coverage:** `Signal.js` 100%
163
+ statements / 98.26% branches / 100% functions / 100% lines; `Watch.js` 100%.
164
+ Drop-in over 1.3.0.
165
+
166
+ - **1.3.0** (drop-in over 1.2.2): the **pool minor**. Node and link pools become
167
+ growable and incrementally populated; the propagation mark phase moves to an
168
+ intrusive linked-list stack (a `nextMark` field); a small registry config surface
169
+ (`prealloc`, `onCapacityExceeded`, `maxFlushPasses`) is exposed. The hot paths and
170
+ public callable API are byte-identical to 1.2.2 -- everything here is
171
+ pool mechanics, construction-time behavior, and new opt-in config. Steady-state
172
+ zero-GC is unchanged: after warm-up the pools recycle exactly as before.
173
+ **`prealloc` (`"eager"` default | `"lazy"`):** `"eager"` constructs the full
174
+ `maxNodes` / `maxLinks` pools up front -- deterministic latency, zero allocation
175
+ inside any subsequent hot path (the 16ms / 120fps render-frame contract), at the
176
+ cost of a larger resident heap every major GC traces. `"lazy"` treats the
177
+ capacities as ledgers, constructs nodes/links on first demand, recycles through
178
+ the free lists thereafter -- smaller heap, faster cold start, lighter GC marking,
179
+ identical zero-GC steady state after warm-up. **Growable pools
180
+ (`onCapacityExceeded: "grow"`):** pools extend past their initial capacity via
181
+ chunked refill -- contiguous runs of up to 1024 links / 256 nodes per free-list
182
+ miss, not a single doubling burst, so any one growth pause stays bounded
183
+ (~chunk x ~0.5us). The growth path no longer length-extends the effect queues
184
+ or mark stack (which permanently converted them PACKED->HOLEY). Link growth is
185
+ bounded by the hard `maxLinks * 16` ceiling; `"throw"` (default, now backed by a
186
+ named `CapacityError`) preserves the 1.2.x fail-fast behavior.
187
+ **`maxFlushPasses`** (default 100) is now a public config -- the cycle-protection
188
+ ceiling that throws an `Error` prefixed `"CycleError:"`. **Intrusive mark stack:**
189
+ `markDownstream` walks an iterative DFS backed by a `nextMark` field on each node
190
+ instead of an external `markStack` array; behaviorally identical (same nodes, same
191
+ order, same glitch-free guarantee), and the write lands in the cache line already
192
+ hot from reading `markEpoch`. `nextMark` is the only node-shape change in 1.3.0.
193
+ **`stats()` shape unchanged** (8 keys: `signals`, `computeds`, `effects`,
194
+ `activeNodes`, `activeLinks`, `pooledLinks`, `nodePoolCapacity`,
195
+ `linkPoolCapacity`); the capacity keys are ledgers under `"lazy"`. Cumulative
196
+ allocation counters (`totalAllocations` / `totalDisposals` / `poolGrowths`) remain
197
+ reserved for 1.4.0 and are still absent. **Tests:** 423 total, 413 pass, 0 fail,
198
+ 10 skip (the 10 skips are 9 signalBox-staged-for-1.5.0 in
199
+ `test/24-signalbox_test.mjs` plus 1 architecturally-N/A SSR case in
200
+ `17-reactivity`); 4 new pool tests in `test/03-pool_test.mjs` cover the lazy
201
+ on-demand / never-allocated-destroy / grow-extends-ledger / link-ceiling paths.
202
+ **Coverage** (c8@11, Node 22): `Signal.js` 100% statements / 98.26% branches /
203
+ 100% functions / 100% lines; `Watch.js` 100% across all four. Behavior-
204
+ preservation difftest: 20,000 direct + 10,000 batched writes vs the published
205
+ 1.1.5 reference, 0 disagreements -- pool growth, chunked refill, and the intrusive
206
+ mark stack do not alter observable propagation. Drop-in over 1.2.2.
207
+
208
+ - **1.2.2**: `createNode` clean-free-list invariant audit. Removes
209
+ ten redundant field-writes that defended against a state the engine cannot
210
+ produce on a clean free-list: seven graph/batch fields (`headDep`, `tailDep`,
211
+ `headSub`, `tailSub`, `revertEpoch`, `preBatchValue`, `preBatchVersion`) and
212
+ three owner-tree fields (the non-adoption `firstOwned`, the adoption-path
213
+ `prevOwned`, and the else-branch `owner`). Both teardown paths
214
+ (`disposeNode` direct, `runCleanup` cascade) already null these fields, and
215
+ the `ReactiveNode` constructor initializes them to the same values on the
216
+ fresh-pool-growth path -- so the redundant writes in `createNode` were
217
+ defense against a state that cannot exist. **No public surface change, no
218
+ semantic change.** New `test/26-free-list-invariant_test.mjs` (3 invariant
219
+ tests + 1 targeted coverage test for the swallow-on-self-dispose-then-throw
220
+ branch in `pullComputed`) asserts the invariant directly by inspecting
221
+ freshly-allocated nodes via the documented `describe()` -> `NODE_PTR`
222
+ introspection protocol; new `test/25-devtools-real-boot_test.mjs` (10 tests)
223
+ boots the actual `Devtools.js` against the 1.2.2 engine and pins the 1.2.x
224
+ introspection contract for downstream tooling, including the 8-key
225
+ `stats()` shape (`signals`, `computeds`, `effects`, `activeNodes`,
226
+ `activeLinks`, `pooledLinks`, `nodePoolCapacity`, `linkPoolCapacity`).
227
+ 408 tests total: 398 pass, 10 skip, 0 fail (the 10 skips are 9
228
+ signalBox-staged-for-1.5.0 in `test/24-signalbox_test.mjs` plus 1
229
+ architecturally-N/A SSR case in `17-reactivity`). Coverage on `Signal.js`:
230
+ 100% statements / 98.43% branches / 100% functions / 100% lines; `Watch.js`
231
+ 100% across all four (c8@11, Node 22) -- a branch-coverage gain over the
232
+ 1.2.1 baseline (98.07%), from the targeted swallow-on-self-dispose-then-throw
233
+ test in `pullComputed`.
234
+ Version lineage:
235
+ this is the engine previously labeled `1.2.3` in dev -- renumbered to
236
+ `1.2.2` because the deletion is small, isolated, and intentionally
237
+ non-behavioral. Drop-in over 1.2.1. **Bench position** (third-party
238
+ [js-reactivity-benchmark](https://github.com/volynetstyle/js-reactivity-benchmark),
239
+ 15 frameworks, 47 tests): #4 by geomean (75.5) at 1.77x behind alien-signals
240
+ (1.00x), reflex (1.15x), @reactively (1.39x); now ahead of 5th-place Preact
241
+ Signals (79.2, lite ~5% ahead -- the gap widened from 1.2.x). The only
242
+ object-pooled zero-GC engine in the field. Ahead of @vue/reactivity (1.5x),
243
+ Signia (1.7x), MobX (2.3x), @solidjs/signals (2.7x), SolidJS (4.2x). Top-3 on
244
+ 21/47 tests; outright winner on `manyEffectsFromOneSource`,
245
+ `manySourcesIntoOneComputedEffect`, and
246
+ `manySourcesIntoOneComputedEffectWithDirect` (and edges the leader alien on a
247
+ fourth, the 1-source linear-chain pull). (The suite measures reactivity
248
+ libraries -- Vue reactivity core, MobX, Solid, Preact Signals -- not full UI
249
+ frameworks like React/Angular.)
250
+ In the community reactive suite (median-of-10), fastest of 5 frameworks
251
+ on the entire `dyn:*` family (the realistic large-DOM-framework shapes)
252
+ and the entire `S: updateComputations*` family. Behind on the
253
+ construction-cost path (`S: createComputations*`, `cellx`, `createDataSignals`).
254
+
255
+ - **1.2.1**: correctness-and-introspection patch. Drop-in over 1.2.0;
256
+ no public surface removed. **Stale-handle introspection (ABA fix):** the v1.2.0
257
+ owner tree made the engine recycle pool slots autonomously on owner re-run, so
258
+ holding a stale handle stopped being a user error and became a routine
259
+ occurrence. Pre-1.2.1, `nodeId`/`describe`/`forEachObserver`/`forEachSource`/
260
+ `hasObservers`/`observeObservers`/`peek()` would resolve `NODE_PTR` ungated
261
+ and happily report the recycled slot's NEW resident through an old handle
262
+ (wrong id, wrong value, wrong edges). All six entry points + `peek()` + `read()`
263
+ + `set()` now resolve through a generation check (the same ABA discipline
264
+ `dispose()` already had); stale handles read as `undefined` (or throw the
265
+ documented `TypeError`, for `observeObservers`). `describe()` descriptors are
266
+ gen-stamped alongside `NODE_PTR`, so the "descriptors are re-walkable handles"
267
+ contract survives the guard: a fresh descriptor walks, one held across a
268
+ recycle correctly goes stale. **Added -- `onGraphMutation(fn)`:** registry-level
269
+ (and top-level) graph-mutation hook for push-based tooling. Single nullable
270
+ listener; every fire point is `if (mutationHook !== null) mutationHook(opcode, intA, intB)`
271
+ -- zero-cost gate when absent, allocation-free dispatch when present. Opcodes:
272
+ `1` node-create `(id, flags)`, `2` node-dispose `(id, flags)` (cascades
273
+ included), `3` link-add `(source.id, target.id)`, `4` link-remove `(source.id, target.id)`,
274
+ `5` recompute `(id, 0)` before each effect re-run / computed re-eval.
275
+ Contract: observe only -- never throw, never mutate the graph from inside.
276
+ This is the connection point lite-devtools 1.1 / lite-studio 1.1 use to go
277
+ push-based. **Added -- `forEachOwned(handle, fn)` / `ownerOf(handle)`:** owner-
278
+ tree introspection. `forEachOwned` iterates a node's owned children as
279
+ re-walkable descriptors; `ownerOf` returns the owner's descriptor or
280
+ `undefined` (top-level or stale). Same descriptor conventions as
281
+ `forEachObserver`/`forEachSource`; garbage input is a no-op/`undefined`.
282
+ Also: `Object.is` hoisted to a module-level const (one IC entry instead of
283
+ per-call lookup in `signal()`/`computed()`). 404 tests, **100% line / 98.07%
284
+ branch coverage** on `Signal.js` + `Watch.js`. New
285
+ `test/21-perf-pins.test.mjs` (6 tests -- construction-shape + ABA-guard pins),
286
+ `test/22-mutation-hook.test.mjs` (12 tests -- `onGraphMutation` registration,
287
+ the 5 opcodes, payload shape, registry isolation), and
288
+ `test/23-owner-introspection.test.mjs` (14 tests -- `forEachOwned`, `ownerOf`,
289
+ and gen-guarded behaviour across the introspection surface). Differential
290
+ fuzz vs the published 1.1.5: 0 disagreements over 30,000 writes.
291
+
292
+ - **1.2.0**: structural refactor (three named layers: graph topology /
293
+ ownership / propagation) plus four additive features built on top. Drop-in over
294
+ 1.1.5; no public surface removed. **Owner tree:** an effect or computed that
295
+ creates nested observers (effect/computed) now owns them -- when the owner
296
+ re-runs or is disposed, the engine cascade-disposes those observers before
297
+ the new run. Plain signals are deliberately NOT owner-adopted so lazy-
298
+ allocation wrappers (lite-store keys, lite-form fields) continue to survive
299
+ re-runs of the computed that allocated them. **Pre-batch revert:** inside a
300
+ `batch(...)`, set X then set X back (under the signal's `equals`) reverts the
301
+ version bump -- downstream effects/computeds do not fire. **AggregateError on
302
+ multi-throw:** two or more effects throwing in the same flush pass aggregate to
303
+ `AggregateError` at the trigger; single-throw is unchanged. **Scheduler thunk
304
+ caching:** the scheduler closure is cached on the node and gen-bound, so async
305
+ schedules that fire post-dispose against a recycled slot are guaranteed no-ops
306
+ (ABA safe). Internal split: `currentObserver` and `currentOwner` are now
307
+ distinct pointers (today they move together, no behavioural change). **Perf:**
308
+ shared `peek` (one closure per registry instead of per primitive) shaves
309
+ 10-14% off signal/computed creation on the `S:create*` micros, no hot-path or
310
+ behavioural change. 363 tests, 100% line / 98.62% branch coverage on
311
+ `Signal.js` + `Watch.js`. Differential fuzz vs the published 1.1.5: 0
312
+ disagreements over 30,000 writes. New `test/19-v12-additions.test.mjs`
313
+ (24 tests) and `test/20-axis-stress.test.mjs` (23 tests -- eight orthogonal
314
+ engine-invariant axes plus permanent conformance pins). **Conformance fixes
315
+ in 1.2.0**: #141 (dispose during execution then continue: no re-run), and
316
+ #238 / #241 / #243 (cleanup ordering on cascade: inner-before-outer,
317
+ deepest-first, and the inner-only-re-run regression). #141 was a latent
318
+ crash present in 1.1.5 too; the v1.2 owner tree exercised it more
319
+ aggressively. Fix is two-fold -- nullify the tracking cursor in `disposeNode`
320
+ when the disposed node is the active observer (plus a `gen`-snapshot guard
321
+ in `executeEffect`/`pullComputed`); and swap `runCleanup` to cascade
322
+ children first, then own.
323
+
324
+ - **1.1.5**: additive release in service of `@zakkster/lite-devtools` -- stable
325
+ node identity on the introspection surface. `nodeId(handle)` -> the node's stable
326
+ per-allocation id (the dedupe key for graph walks); `describe(handle)` -> the handle's
327
+ own `{ id, kind, value }` descriptor, **re-walkable** (pass it back into
328
+ `forEachObserver`/`forEachSource` to walk the full DAG); `forEach*` descriptors now carry
329
+ `id`. One SMI write at allocation, node shape kept monomorphic -- **zero steady-state
330
+ cost**. Drop-in over 1.1.4, no breaking changes. New `test/18-identity_test.mjs` (5 tests); plus `14-lifecycle-teardown`, `16-alien-parity`, and the `17-reactivity` behavioral suite.
331
+
332
+ - **1.1.4**: combined release -- a retracking rewrite plus an observer-lifecycle
333
+ introspection surface. Drop-in over 1.1.3. **Retracking:** version-stamped O(1)
334
+ reconciliation + a `markEpoch` clean-read short-circuit replace the cursor strategy's
335
+ O(N)-per-dep degradation under chaotic high-fan-in batched read-after-write; stable read
336
+ order is unchanged (still O(1), still zero-alloc). The two documented v1.1.x losses flipped
337
+ to wins and are now fastest of five frameworks -- `dyn: large web app` 6194ms->571ms, `dyn:
338
+ wide dense` 5115ms->912ms (verified by `retracking.difftest.mjs`: 20k direct + 10k batched, 0
339
+ disagreements; no regressions elsewhere). **Introspection:** `hasObservers`,
340
+ `observeObservers`, `forEachObserver`, `forEachSource` (top-level + per-registry), gated by
341
+ an internal counter so zero steady-state cost when unused. New `test/13-introspection_test.mjs`
342
+ (10 tests). Internally staged as 1.1.4 + 1.1.5; ships as a single 1.1.4.
343
+
344
+ - **1.1.3**: adds `isTracking()` (top-level + per-registry). Returns true iff a
345
+ read right now would record a dependency (`isTrackingDeps && currentObserver !== null`).
346
+ False inside `untrack`, `subscribe` callbacks, `onCleanup` bodies, `watch` /
347
+ `when` callbacks, and outside any observer. ~1-2 ns. For wrapper libraries
348
+ (lite-store, lite-query, lite-form) that allocate reactive primitives lazily
349
+ on property reads. Per-registry: wrappers operating against a non-default
350
+ registry must call THAT registry's `isTracking()`, not the top-level one.
351
+ No behavior or engine changes.
352
+
353
+
354
+ - **1.1.2**: hot-path micro-optimizations, no behavior/API change.
355
+ Inlined cursor fast-path in `signal`/`computed` reads (stable-order reads skip
356
+ the `allocateLink` call); zero-allocation creation path (`opts` read defensively
357
+ instead of defaulting to `{}`); single-closure `subscribe`. Owner-tree
358
+ conformance items #209/#210 are wired but skipped pending the v1.2 ownership
359
+ hybrid.
360
+
361
+ ## When to use
362
+
363
+ - Animation loops, game HUDs, scoreboards, telemetry overlays.
364
+ - Twitch Extensions (1 MB bundle / 3 s cold start budget).
365
+ - Long-running browser sessions (millions of writes per session).
366
+ - Multi-tenant SDKs where each tenant needs an isolated reactive world.
367
+ - Any context where a GC pause breaks the frame budget.
368
+
369
+ ## When NOT to use
370
+
371
+ - Server-side rendering -- no SSR story.
372
+ - Graph *construction* is allocation-heavy (per-node closures): on create-many micro-benchmarks `alien-signals` builds faster. Real apps build once and update forever -- lite-signal leads every dynamic-topology (`dyn:*`) row and trades the lead with alien within a few percent on the sub-60ms `S: updateComputations` micro-rows (noise-dominated). (The former "chaotic read order" caveat was closed in 1.1.4.)
373
+ - If you want time-travel or serialization -- build those on top. (Graph-inspection devtools are now buildable on the 1.1.4 introspection surface; see lite-devtools.)
374
+
375
+ ## API summary
376
+
377
+ ```ts
378
+ // Default registry helpers
379
+ function signal<T>(initial: T, opts?: { equals?: (a: T, b: T) => boolean }): Signal<T>;
380
+ function computed<T>(fn: () => T, opts?: { equals?: (a: T, b: T) => boolean }): Computed<T>;
381
+ function effect(fn: () => void, opts?: { scheduler?: (run: () => void) => void }): Dispose;
382
+ function signalBox<T>(initial: T, opts?: { equals?: (a: T, b: T) => boolean }): SignalBox<T>; // 1.5.0
383
+ function computedBox<T>(fn: () => T, opts?: { equals?: (a: T, b: T) => boolean }): ComputedBox<T>; // 1.5.0
384
+ function createRoot<T>(fn: () => T): T; // 1.5.0 -- detached ownership scope; returns fn's value
385
+ function dispose(api: Signal<any> | Computed<any> | SignalBox<any> | ComputedBox<any> | Dispose): void;
386
+ function batch<T>(fn: () => T): T;
387
+ function untrack<T>(fn: () => T): T;
388
+ function isTracking(): boolean;
389
+ function hasObservers(handle: Signal<any> | Computed<any>): boolean;
390
+ function observeObservers(
391
+ handle: Signal<any> | Computed<any>,
392
+ hooks?: { onConnect?: () => void; onDisconnect?: () => void }
393
+ ): () => void; // returns idempotent unobserve
394
+ function forEachObserver(handle: Signal<any> | Computed<any>, fn: (d: NodeDescriptor) => void): void;
395
+ function forEachSource(handle: Signal<any> | Computed<any>, fn: (d: NodeDescriptor) => void): void;
396
+ function forEachOwned(handle: Signal<any> | Computed<any>, fn: (d: NodeDescriptor) => void): void; // 1.2.1
397
+ function ownerOf(handle: Signal<any> | Computed<any>): NodeDescriptor | undefined; // 1.2.1
398
+ function nodeId(handle: Signal<any> | Computed<any>): number | undefined; // 1.1.5
399
+ function describe(handle: Signal<any> | Computed<any>): NodeDescriptor | undefined; // 1.1.5
400
+ function onGraphMutation( // 1.2.1
401
+ fn: ((opcode: 1|2|3|4|5, intA: number, intB: number) => void) | null
402
+ ): () => void; // unsub restores prior listener
403
+ function onCleanup(fn: () => void): void;
404
+ function stats(): RegistryStats;
405
+
406
+ // Registry construction
407
+ function createRegistry(config?: RegistryConfig): Registry;
408
+ function setDefaultRegistry(r: Registry): void;
409
+
410
+ interface Signal<T> {
411
+ (): T; // tracked read
412
+ peek(): T; // untracked read
413
+ set(value: T): void;
414
+ update(fn: (prev: T) => T): void;
415
+ subscribe(fn: (value: T) => void): Dispose;
416
+ }
417
+
418
+ interface Computed<T> {
419
+ (): T; // tracked read
420
+ peek(): T; // untracked read
421
+ subscribe(fn: (value: T) => void): Dispose;
422
+ }
423
+
424
+ interface SignalBox<T> { // 1.5.0 -- non-callable, allocation-light
425
+ get(): T; // tracked read
426
+ set(value: T): void;
427
+ peek(): T; // untracked read
428
+ update(fn: (prev: T) => T): void;
429
+ subscribe(fn: (value: T) => void): Dispose;
430
+ }
431
+
432
+ interface ComputedBox<T> { // 1.5.0
433
+ get(): T; // tracked read
434
+ peek(): T; // untracked read
435
+ subscribe(fn: (value: T) => void): Dispose;
436
+ }
437
+
438
+ type Dispose = () => void;
439
+
440
+ interface NodeDescriptor { // yielded by forEachObserver / forEachSource / describe
441
+ id: number; // stable per-allocation id (1.1.5); dedupe + re-walk key
442
+ kind: "signal" | "computed" | "effect";
443
+ value: unknown; // node's current value
444
+ }
445
+
446
+ interface RegistryConfig {
447
+ maxNodes?: number; // default 1024 (ledger under "lazy")
448
+ maxLinks?: number; // default maxNodes * 4 (ledger under "lazy")
449
+ prealloc?: "eager" | "lazy"; // default "eager" (1.3.0): up-front vs on-demand pool construction
450
+ maxFlushPasses?: number; // default 100
451
+ onCapacityExceeded?: "throw" | "grow"; // default "throw"; "grow" = chunked refill, ledger doubles, 16x link ceiling
452
+ }
453
+
454
+ interface RegistryStats { // 11 keys as of 1.4.0
455
+ signals: number;
456
+ computeds: number;
457
+ effects: number;
458
+ activeLinks: number;
459
+ pooledLinks: number;
460
+ linkPoolCapacity: number; // ledger; doubles under "grow"
461
+ nodePoolCapacity: number; // ledger; doubles under "grow"
462
+ activeNodes: number; // live gauge
463
+ totalAllocations: number; // 1.4.0: cumulative node acquires; reset by destroy()
464
+ totalDisposals: number; // 1.4.0: cumulative node disposals; totalAllocations - totalDisposals === activeNodes
465
+ poolGrowths: number; // 1.4.0: cumulative pool-growth chunks; 0 if eager pool sized right
466
+ }
467
+
468
+ class CapacityError extends Error {
469
+ kind: "nodes" | "links";
470
+ capacity: number;
471
+ }
472
+ ```
473
+
474
+ ## Watchers (added in v1.1)
475
+
476
+ Three composable watcher primitives, all built from `effect` + `untrack`. Tree-shakeable.
477
+
478
+ ### watch(source, callback, options?)
479
+
480
+ Fires callback on every change of the projected source value.
481
+
482
+ - **Signature**: `watch<T>(source: () => T, callback: (newValue: T, oldValue: T | undefined, stop: () => void) => void, options?: { immediate?: boolean }): () => void`
483
+ - **Returns**: dispose function. Idempotent. Safe to call synchronously inside the callback.
484
+ - **options.immediate**: when `true`, callback fires once on registration with `oldValue = undefined`. Default `false`.
485
+ - **Equality guard**: uses `Object.is(newValue, oldValue)` internally to avoid firing when the projected value is unchanged across dep mutations. Critical for raw getter sources like `() => health() <= 0` -- many dep changes can produce the same boolean. Wrapping the source in `computed()` would achieve the same via the computed's own equality check.
486
+ - **UNINITIALIZED sentinel**: uses `Symbol("watch.uninitialized")` instead of `undefined` to detect first-run. This means `signal(undefined)` is correctly distinguished from "watcher hasn't fired yet".
487
+ - **Callback reads are untracked**: the callback can read other signals without registering them as dependencies.
488
+ - **Stop in callback**: third callback argument is a stop handle. Safe to call at any point including synchronously during the immediate fire (the `wantsStopEarly` flag defers dispose until after the effect is registered).
489
+ - **Allocation profile**: 3 closures at registration (stop, effect body, hoisted untrack body). **Zero allocations per fire** -- the untrack body is hoisted with `currentNewValue` as shared mutable state. Hot-path safe at 120fps.
490
+
491
+ ### when(predicate, callback)
492
+
493
+ Fires callback exactly once when predicate first returns truthy, then auto-disposes.
494
+
495
+ - **Signature**: `when(predicate: () => unknown, callback: () => void): () => void`
496
+ - **Returns**: dispose function. Useful for cancelling before predicate fires; idempotent; no-op after callback has fired.
497
+ - **Synchronous fire**: if predicate is already truthy at registration, callback fires synchronously and watcher disposes immediately (same `wantsStopEarly` pattern as `watch`).
498
+ - **One-shot guarantee**: internal `fired` flag protects against double-fire even if dispose timing lets one more evaluation through.
499
+ - **Callback reads are untracked.**
500
+ - **Truthy/falsy semantics**: standard JS truthy check. `0`, `""`, `null`, `undefined`, `false`, `NaN` do not trigger; everything else does.
501
+ - **Allocation profile**: 2 closures at registration (stop, effect body). **Zero allocations per check** -- `untrack(callback)` passes the user's callback directly without wrapping. Hot-path safe at 120fps.
502
+
503
+ ### whenAsync(predicate)
504
+
505
+ Promise variant of `when`.
506
+
507
+ - **Signature**: `whenAsync(predicate: () => unknown): Promise<void>`
508
+ - **Returns**: Promise that resolves when predicate first becomes truthy.
509
+ - **Implementation**: `return new Promise((resolve) => when(predicate, resolve))`.
510
+ - **Foot-gun**: promise never rejects. If predicate never becomes truthy, promise never settles. Use `Promise.race` for timeout: `Promise.race([whenAsync(p), timeoutPromise])`.
511
+ - **! HOT-PATH WARNING**: `new Promise(...)` is a heap allocation. Each call allocates 1 Promise + 1 executor closure + Promise infrastructure (resolve fn, microtask state) + 2 closures from internal `when` call. This is unavoidable -- Promises require heap allocation by spec. **Do NOT call per frame.** Use for high-level orchestration (boot sequences, scene transitions, awaiting user input). For 60/120fps logic, use `when(predicate, callback)` directly -- it's zero-GC.
512
+
513
+ ### Architecture note
514
+
515
+ None of these touch the reactive engine -- no `FLAG_WATCHER` on `ReactiveNode`, no extension to the object pool, no new internal primitive. They compose entirely from public API. This is the test that the core engine is structurally complete: when a higher-level pattern can be built without extending the engine, the engine has enough.
516
+
517
+ ### Allocation profile summary
518
+
519
+ | Primitive | At registration | Per fire / check |
520
+ |---|---|---|
521
+ | `watch` | 3 closures | 0 |
522
+ | `when` | 2 closures | 0 |
523
+ | `whenAsync` | 1 Promise + executor + Promise internals + 2 closures (from `when`) | 0 |
524
+
525
+ 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.
526
+
527
+ ## Benchmark snapshot (Node 22, 2016-era Intel MacBook Pro, default eager, median across reps -- @1.3.0)
528
+
529
+ `benchmark.mjs` head-to-head vs alien-signals on app-shaped scenarios (time = median
530
+ execution; heap = average transient delta-heap per rep; lite-signal numbers are
531
+ @1.3.0, hot paths byte-identical to 1.2.2):
532
+
533
+ | Scenario | lite vs alien (time) | transient heap (lite / alien) |
534
+ | -------------------------------- | -------------------- | ----------------------------- |
535
+ | SELECTIVE DAG (set churn) | **+48% faster** | 1.5 MB / 37 MB |
536
+ | DYNAMIC DAG (FAN=6, read flips) | **+43% faster** | 5.1 MB / 24 MB |
537
+ | MUX (256 sigs -> sum -> effect) | **+38% faster** | 38 KB / 3.9 MB |
538
+ | SMALL SELECTIVE (~64x6) | **+29% faster** | 0.3 KB / 23.9 MB |
539
+ | KAIROS (1 -> 1000 computeds) | -1% (parity) | 178 KB / 1.1 MB |
540
+ | LARGE WEB APP (~1000x12) | -4% (parity) | 0.3 KB / 41 KB |
541
+ | WIDE DENSE (~1000x5) | -4% (parity) | 0.3 KB / 11.6 MB |
542
+ | BROADCAST (1 -> 1000 effects) | -10% | 72 KB / 21 KB |
543
+ | DEEP CHAIN (256-deep -> effect) | -18% | 18 KB / 905 KB |
544
+
545
+ lite-signal's time wins are the allocation-heavy dynamic shapes (object pool allocates
546
+ near-nothing; alien churns the nursery), plus MUX fan-in aggregation -- the patterns
547
+ that dominate live UI under input churn. Parity on the cheap stable wide shapes (within
548
+ run-to-run noise on this old host). Two losses: BROADCAST (pure fan-out, no retracking
549
+ for the pool to amortize) and DEEP CHAIN (alien's flatter representation wins when the
550
+ propagation path is long rather than wide). On allocation, lite wins 8/9 scenarios and
551
+ is alone in the zero-alloc band (~0.3 KB transient on the stable app shapes). NOTE: the
552
+ BROADCAST and KAIROS results are now parity-or-behind on 1.3.0's isolated harness;
553
+ earlier ops/s snapshots that showed lite ahead on those were measured under a different
554
+ (multi-engine, shared-heap) protocol.
555
+
556
+ The cross-framework reactivity suite (5 frameworks) re-run on 1.3.0 (default eager,
557
+ median-of-10): lite-signal is fastest on all five `dyn:*` rows -- `dyn: large web app`
558
+ 544ms (+7% vs alien-signals' 586ms), `dyn: wide dense` 902ms (+3% vs 926ms), plus
559
+ simple component (+17%), dynamic component (+15%), deep (+14%) -- with preact 6-19x
560
+ slower and vue 15-32x slower on the app-shaped graphs. On the sub-60ms
561
+ `S: updateComputations` micro-rows lite and alien trade the lead within a few percent
562
+ (lite ahead on 3/7), noise-dominated on this host. Retracking verified correct by
563
+ `retracking.difftest.mjs` (20,000 direct + 10,000 batched writes, 0 disagreements vs
564
+ published 1.1.5). `prealloc: "lazy"` trades a little first-construction allocation on the
565
+ dynamic shapes for a smaller resident heap and faster cold start; steady state identical.
566
+
567
+ Retained heap after forced GC: typically negative for all libs (V8 compacts).
568
+ The one exception: lite-signal shows ~+71 KB retained on KAIROS, which is the
569
+ pre-allocated pool holding the live 1002-node graph in steady state. This is
570
+ the design: the pool IS the working memory. Not a leak.
571
+
572
+ ## Common idioms
573
+
574
+ ```js
575
+ // Glitch-free diamond
576
+ const a = signal(1);
577
+ const b = computed(() => a() + 1);
578
+ const c = computed(() => a() * 2);
579
+ const d = computed(() => b() + c()); // re-evaluates exactly once per a.set
580
+
581
+ // Conditional subscription (b only tracked when flag is true)
582
+ const flag = signal(true);
583
+ const a = signal(1);
584
+ const b = signal(2);
585
+ const sum = computed(() => flag() ? a() + b() : a());
586
+
587
+ // Scheduler integration (rAF batching)
588
+ let queued = false;
589
+ effect(() => render(state()), {
590
+ scheduler: run => {
591
+ if (queued) return;
592
+ queued = true;
593
+ requestAnimationFrame(() => { queued = false; run(); });
594
+ }
595
+ });
596
+
597
+ // Sandboxed plugin
598
+ const sandbox = createRegistry({ maxNodes: 256, onCapacityExceeded: "throw" });
599
+ plugin(sandbox.signal, sandbox.computed, sandbox.effect);
600
+ // later:
601
+ sandbox.destroy(); // entire reactive world reset
602
+
603
+ // 1.2.1: push-based devtools via onGraphMutation
604
+ // Single listener; opcodes 1=create, 2=dispose, 3=link-add, 4=link-remove, 5=recompute.
605
+ // Allocation-free dispatch with just three integers.
606
+ const unsubscribe = onGraphMutation((opcode, intA, intB) => {
607
+ switch (opcode) {
608
+ case 1: devtools.onNodeCreate(intA, intB); break; // intA=id, intB=flags
609
+ case 2: devtools.onNodeDispose(intA); break;
610
+ case 3: devtools.onLinkAdd(intA, intB); break; // intA=source.id, intB=target.id
611
+ case 4: devtools.onLinkRemove(intA, intB); break;
612
+ case 5: devtools.onRecompute(intA); break;
613
+ }
614
+ });
615
+ // Stop listening -- restores prior listener (or null), engine returns to zero-cost state.
616
+ unsubscribe();
617
+
618
+ // 1.2.1: walk the owner tree (cascade-disposal domains)
619
+ // forEachOwned + ownerOf complement forEachObserver + forEachSource:
620
+ // the dep/sub edges show DATA FLOW; the owner edges show LIFETIME BINDING.
621
+ function dumpOwnerTree(handle, depth = 0) {
622
+ const d = describe(handle);
623
+ if (!d) return;
624
+ console.log(" ".repeat(depth * 2), d.kind, d.id);
625
+ forEachOwned(d, (child) => dumpOwnerTree(child, depth + 1));
626
+ }
627
+ ```
628
+
629
+ ## File layout
630
+
631
+ - `Signal.js` -- full implementation, single file.
632
+ - `Signal.d.ts` -- TypeScript declarations for all public API.
633
+ - `test/01-core_test.mjs` -- signal/computed/effect basics, equality, untrack.
634
+ - `test/02-topology_test.mjs` -- diamonds, chains, fan-out/in, cycle detection.
635
+ - `test/03-pool_test.mjs` -- capacity errors, grow policy, pool reuse.
636
+ - `test/04-zero-gc_test.mjs` -- heap retention (run with --expose-gc).
637
+ - `test/05-scheduler_test.mjs` -- scheduler races, dispose, gen counter, version wrap.
638
+ - `test/06-nested-objects_test.mjs` -- nested-object & reference-identity behaviours.
639
+ - `test/07-dispose_test.mjs` -- universal disposal: registry.dispose(api).
640
+ - `test/08-watch_test.mjs` -- new watch reactivity tests.
641
+ - `test/09-conformance_test.mjs` -- johnsoncodehk/reactive-framework-test-suite conformance fixes tests.
642
+ - `test/10-is-tracking_test.mjs` -- `isTracking()` across observer bodies, untracked windows, and outside any observer.
643
+ - `test/11-adopted-reactive_test.mjs` -- engine-agnostic edge cases adopted from the wider ecosystem (alien-signals link-integrity #226-228, equality-predicate corners, `update()`/`peek()`/`subscribe` contracts).
644
+ - `test/12-coverage_test.mjs` -- targeted public-surface + hot-path branch coverage (top-level routing, clean-read short-circuit, tail severance, scheduler ABA); owner-tree block capability-gated.
645
+ - `test/13-introspection_test.mjs` -- observer-lifecycle surface: `hasObservers`, `observeObservers` auto-pause, `forEach*` enumeration (10 tests).
646
+ - `test/14-lifecycle-teardown_test.mjs` -- effect-teardown guards: stopped effect doesn't re-subscribe to a signal read later in the same run, self-dispose leaves no orphan link, throwing setup leaves no live subscription (4 tests).
647
+ - `test/15-owner-lazy-alloc_test.mjs` -- owner-adoption contract for the 1.2.0 owner tree (lazy signals never adopted; observers still auto-disposed); capability-gated, skipped on 1.1.x (4 tests).
648
+ - `test/16-alien-parity_test.mjs` -- differential guards vs alien-signals@3.2.0 fixed-bug classes: cleanup reads create no deps, inner write doesn't block computed-chain propagation, dynamic dep-set correct under dirty-check (3 tests).
649
+ - `test/17-reactivity_test.mjs` -- behavioral suite over universal signal-system bug classes (subscription lifecycle, cleanup ordering, stale-dep tracking, batching, equality, nested invalidation, memory, sync async-boundary, scheduler/loops, + differential-review additions); SSR is N/A (~30 tests).
650
+ - `test/18-identity_test.mjs` -- node identity (1.1.5): `nodeId`/`describe`, descriptor `id`, re-walkable descriptors, non-perturbing (5 tests).
651
+ - `test/19-v12-additions_test.mjs` -- 1.2.0 surface coverage: shared-peek, owner-adoption rule, pre-batch revert (24 tests).
652
+ - `test/20-axis-stress_test.mjs` -- eight orthogonal stress axes (batch-under-exception, connect/disconnect re-entrancy, untrack vs owner cascade, etc.) (23 tests).
653
+ - `test/21-perf-pins_test.mjs` -- 1.2.1 construction-shape + ABA-guard pins (6 tests).
654
+ - `test/22-mutation-hook_test.mjs` -- 1.2.1 `onGraphMutation` registration + opcode emission (12 tests).
655
+ - `test/23-owner-introspection_test.mjs` -- `ownerOf`, `forEachOwned`, gen-guarded introspection (14 tests).
656
+ - `test/24-signalbox_test.mjs` -- staged for 1.5.0; all tests `{skip: true}` on 1.2.x.
657
+ - `test/25-devtools-real-boot_test.mjs` -- 1.2.2: real `Devtools.js` boot against the engine, ghost-contract pin, `stats()` shape pin (10 tests).
658
+ - `test/26-free-list-invariant_test.mjs` -- 1.2.2: the audit's clean-free-list invariant, asserted by inspecting freshly-allocated nodes (4 tests).
659
+ - `bench/benchmark.mjs` -- anti-DCE throughput harness (ops/s; results.txt).
660
+ - `bench/benchmarkReactive.mjs` -- cross-framework reactivity suite vs alien-signals, preact, vue-reactivity, solid (resultsReactive.txt).
661
+ - `bench/dispose-recycle.mjs` -- 1.2.2 targeted microbench: create/dispose/recreate cycle (the free-list invariant audit target).
662
+ - `bench/torture/` -- crash-detection soaks: `graph-fuzzer`, `scheduler-bench`, `torture-soak`. Exit 0 iff zero errors AND post-teardown pool clean.
663
+ - `bench/run-all.sh` + `bench/aggregate.mjs` -- cold-process-per-engine protocol + per-scenario aggregation.
664
+ - `demo/index.html` -- interactive visualization of the reactive graph.
665
+
666
+ ## Install
667
+
668
+ ```bash
669
+ npm install @zakkster/lite-signal
670
+ ```
671
+
672
+ ## License
673
+
674
+ MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zakkster/lite-signal",
3
- "version": "1.6.0-preview.0",
3
+ "version": "1.6.0-preview.2",
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",
@@ -31,6 +31,8 @@
31
31
  "test:coverage": "c8 node --test --test-reporter=spec",
32
32
  "bench": "node --expose-gc bench/benchmark.mjs",
33
33
  "bench-reactive": "node --expose-gc bench/benchmarkReactive.mjs",
34
+ "profile:burst": "node --expose-gc burst-dag.mjs",
35
+ "profile:pull": "node --expose-gc pull-stress.mjs",
34
36
  "verify": "npm test && npm run bench"
35
37
  },
36
38
  "keywords": [