@zakkster/lite-signal 1.3.0-rc.1 → 1.4.0-beta.0

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
@@ -4,7 +4,86 @@ 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.3.0] -- 2026-06-XX
7
+ ## [1.4.0] -- 2026-06-XX
8
+
9
+ The observability minor: `stats()` gains **three cumulative lifecycle counters**
10
+ (`totalAllocations`, `totalDisposals`, `poolGrowths`) -- the surface reserved for
11
+ 1.4.0 in the 1.2.x and 1.3.0 notes, now delivered. This is what lite-devtools /
12
+ lite-studio read to chart allocation rate, pool-reuse ratio, and graph churn over
13
+ time. Drop-in over 1.3.0 -- no hot-path change, no public callable API change; the
14
+ counters are bumped on existing lifecycle edges (acquire / dispose / grow) that
15
+ already ran, so steady-state throughput and zero-GC are unchanged. The eager pool
16
+ default introduced in 1.3.0 carries forward (`prealloc: "eager"`).
17
+
18
+ ### Added -- cumulative lifecycle counters on `stats()`
19
+
20
+ `stats()` now returns **11 keys**: the 8 from 1.2.x/1.3.0 plus three monotonic
21
+ counters. They are cumulative over the registry's life and reset only by
22
+ `destroy()`.
23
+
24
+ - **`totalAllocations`** -- incremented on every node acquire, whether the node
25
+ is popped from the free list or freshly constructed during a pool-growth chunk.
26
+ This is the true number of nodes the registry has ever handed out, not the
27
+ current live count (`activeNodes` remains the live gauge).
28
+ - **`totalDisposals`** -- incremented on every `disposeNode`, i.e. every node
29
+ returned to the pool. `totalAllocations - totalDisposals` tracks the live set
30
+ and should equal `activeNodes` in a quiescent registry.
31
+ - **`poolGrowths`** -- incremented whenever a node *or* link refill chunk pushes
32
+ capacity past its current ledger (`maxNodes` / `maxLinks`). A nonzero value
33
+ after warm-up means the initial pool was undersized for the workload and the
34
+ registry grew at runtime -- the signal a tool uses to recommend a larger
35
+ `maxNodes` / `maxLinks`, or that confirms an eager pool was sized correctly
36
+ (stays 0).
37
+
38
+ The counters are exact, not sampled: they sit on the same `createNode` /
39
+ `disposeNode` / chunk-refill edges the engine already executes, so reading them
40
+ costs nothing and they cannot drift from the real lifecycle.
41
+
42
+ ### Why these three, and what they enable
43
+
44
+ The point is *derivable* observability without the engine itself computing rates.
45
+ A consumer sampling `stats()` over time gets, with no extra engine work:
46
+
47
+ - **allocation rate** = delta `totalAllocations` / delta t (graph build pressure),
48
+ - **pool-reuse ratio** = `1 - poolGrowths * initialCapacity / totalAllocations`
49
+ (how much work the pool absorbed vs. how much forced growth),
50
+ - **approximate average lifetime** ~ `totalDisposals` / allocation rate (churn).
51
+
52
+ These are exactly the series lite-devtools 1.2 / lite-studio 1.2 plot. The engine
53
+ stays a measurement *source*, not a metrics framework -- consistent with the
54
+ zero-overhead-in-steady-state contract.
55
+
56
+ ### Changed -- `destroy()` resets the counters
57
+
58
+ `destroy()` (the in-place arena reset) now also zeroes the three counters along
59
+ with the rest of registry state, so a reused registry reports lifecycle numbers
60
+ for its current epoch only. Grown pool *capacity* is retained across `destroy()`
61
+ as before (the reset keeps the arena warm); only the cumulative counts reset.
62
+
63
+ ### Verified
64
+
65
+ - **Full suite green** against the 1.4.0 engine: 430 tests, 420 pass, 0 fail,
66
+ 10 skip. The 10 skips are the 9 `{skip:true}` `signalBox` tests in `24-signalbox`
67
+ (staged for 1.5.0) plus 1 architecturally-N/A SSR case in `17-reactivity`. The
68
+ eager-default and the counter additions changed no existing test outcome; 6 new
69
+ counter tests in `03-pool` cover the new surface.
70
+ - **Coverage** (c8@11, Node 22): `Signal.js` 100% statements / 98.26% branches /
71
+ 100% functions / 100% lines; `Watch.js` 100% across all four. The three counter
72
+ bumps sit on already-covered acquire / dispose / grow edges.
73
+ - **Counter correctness** confirmed directly: after building a signal ->
74
+ computed -> effect graph, `totalAllocations` equals the node count and
75
+ `totalDisposals` tracks effect/computed teardown; forcing a pool past its
76
+ ledger under `onCapacityExceeded: "grow"` increments `poolGrowths`; an
77
+ eager pool sized to cover its graph keeps `poolGrowths` at 0.
78
+ - **Zero-GC steady state holds**: the counters bump only on acquire / dispose /
79
+ grow, none of which occur on the steady-state write path after warm-up. Writing
80
+ through a built graph allocates nothing and moves no counter.
81
+ - **`stats()` shape** is now the authoritative 11-key 1.4.x shape; the
82
+ introspection-contract test is updated to expect the three counters present
83
+ (the 1.2.x/1.3.0 test pinned their *absence*; that pin is correctly inverted
84
+ for 1.4.0).
85
+
86
+
8
87
 
9
88
  The pool minor: the node and link pools become **growable and incrementally
10
89
  populated**, the propagation mark phase moves to an **intrusive linked-list
@@ -83,16 +162,8 @@ in 1.3.0.
83
162
  ### Verified
84
163
 
85
164
  - **Full suite green** against the 1.3.0 engine: 424 tests, 414 pass, 0 fail,
86
- 10 skip. The 10 skips are the 9 `{skip:true}` `signalBox` tests in
87
- `24-signalbox` (those primitives land in 1.5.0) plus 1 architecturally-N/A
88
- SSR case in `17-reactivity`. The eager-default flip changed no test outcome.
89
- Four new tests in `03-pool` cover the 1.3.0 paths: lazy on-demand construction
90
- reaching the same steady state as eager, a never-allocated lazy registry
91
- surviving `destroy()`, `"grow"` extending both pool ledgers, and the
92
- `maxLinks * 16` link ceiling.
93
- - **Coverage** (c8@11, Node 22): `Signal.js` 100% statements / 98.26% branches /
94
- 100% functions / 100% lines; `Watch.js` 100% across all four. The lazy-pool
95
- `destroy()` paths added in 1.3.0 are covered by the new `03-pool` tests.
165
+ 10 skip (9 signalBox-staged-for-1.5.0 in `24-signalbox` plus 1 architecturally-N/A
166
+ SSR case in `17-reactivity`). The eager-default flip changed no test outcome.
96
167
  - **Behavior-preservation difftest**: 20,000 direct + 10,000 batched writes
97
168
  against the published 1.1.5 reference, 0 disagreements. Pool growth, chunked
98
169
  refill, and the intrusive mark stack do not alter observable propagation.
package/README.md CHANGED
@@ -494,7 +494,7 @@ Default sizing for a Twitch-extension-style budget:
494
494
  | Heavy dashboard (variable scale) | 2048 | 16384 | `"eager"` | `"grow"` |
495
495
  | Per-viewer sandbox / short-lived | 512 | 2048 | `"lazy"` | `"throw"` |
496
496
 
497
- `stats()` reports `signals`, `computeds`, `effects`, `activeNodes`, `activeLinks`, `pooledLinks`, `nodePoolCapacity`, `linkPoolCapacity` (8 keys; the capacity keys are ledgers under `"lazy"`). Drop it on screen for live observability.
497
+ `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.
498
498
 
499
499
  </details>
500
500
 
@@ -658,7 +658,7 @@ These are the questions you'd ask in a code review, with the answers:
658
658
 
659
659
  ## Benchmarks
660
660
 
661
- 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.
661
+ 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).
662
662
 
663
663
  | Scenario | What it stresses | lite-signal | alien-signals | lite vs alien | transient heap (lite / alien) |
664
664
  | ---------- | -------------------------------- | ----------- | ------------- | ------------- | ----------------------------- |
@@ -705,7 +705,7 @@ Three tiers, all reproducible.
705
705
 
706
706
  - **`01-core_test.mjs`** -- signal/computed/effect basics, equality semantics, NaN/+/-0, subscribe/peek/update, untrack, batch, cleanup ordering, first-run error recovery, nested object reference-identity gotchas.
707
707
  - **`02-topology_test.mjs`** -- diamond glitch-freedom, 256-deep and 1024-deep computed chains, wide fan-out (1000 effects from one signal), dynamic dependency switching, conditional fan-out, nested effects, cycle detection (`CycleError`).
708
- - **`03-pool_test.mjs`** -- `CapacityError` under both `"throw"` and `"grow"` policies, the 16× link ceiling, stable pool reuse across thousands of create/dispose cycles, registry isolation, and (1.3.0) the lazy-prealloc paths: on-demand construction reaching the same steady state as eager, a never-allocated lazy registry surviving `destroy()`, and `"grow"` extending both pool ledgers past their initial capacity.
708
+ - **`03-pool_test.mjs`** -- `CapacityError` under both `"throw"` and `"grow"` policies, the 16× link ceiling, stable pool reuse across thousands of create/dispose cycles, registry isolation, (1.3.0) the lazy-prealloc paths: on-demand construction reaching the same steady state as eager, a never-allocated lazy registry surviving `destroy()`, and `"grow"` extending both pool ledgers past their initial capacity, and (1.4.0) the `stats()` lifecycle counters: the 11-key shape, `totalAllocations` / `totalDisposals` tracking the `activeNodes` live invariant, `poolGrowths` firing on growth and staying 0 on a correctly-sized eager pool, and `destroy()` resetting all three.
709
709
  - **`05-scheduler_test.mjs`** -- scheduler-deferred effects, dispose-during-schedule races, microtask integration, 32-bit version wrap (simulated), `setDefaultRegistry`, `onCleanup` inside computeds.
710
710
  - **`06-nested-objects_test.mjs`** -- array mutation patterns (push/splice/spread), deep nested paths, Map/Set/Date inside signals, custom structural equality, computed memoisation cutoffs over object slices, signal-of-signals composition, high-frequency object updates, batched immutable updates.
711
711
  - **`07-dispose_test.mjs`** -- unified `dispose(api)` across signals, computeds and effect handles, idempotency, cross-registry isolation (per-registry Symbol prevents pool corruption), foreign-value safety, top-level helper routing, 500-cycle balanced churn leaving pool and stats stable.
@@ -726,7 +726,7 @@ Three tiers, all reproducible.
726
726
  - **`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.
727
727
  - **`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.
728
728
  - **`24-signalbox_test.mjs`** -- staged for v1.5.0; all 9 tests `{skip: true}` on 1.3.x. The `signalBox` / `computedBox` allocation-light handle API lands in 1.5.0; the suite is committed early so the surface is pinned and the skips are visible in the test count (the 10 skips on 1.3.0 are these 9 plus 1 architecturally-N/A SSR case in `17-reactivity`).
729
- - **`25-devtools-real-boot_test.mjs`** -- Devtools/Studio contract (10 tests). Boots the actual `Devtools.js` against the 1.3.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.
729
+ - **`25-devtools-real-boot_test.mjs`** -- Devtools/Studio contract (10 tests). Boots the actual `Devtools.js` against the 1.4.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.
730
730
  - **`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%).
731
731
 
732
732
  ```bash
@@ -825,7 +825,7 @@ In stable environments (game engines, particle systems, visualizers), `lite-sign
825
825
  > not engine changes. lite remains the only zero-alloc library on every stable scenario
826
826
  > (see [`results.txt`](./results.txt)).
827
827
 
828
- The cross-framework reactivity suite agrees independently, re-run on **1.3.0** (default eager, median-of-10, isolated): lite-signal is the **fastest of five frameworks on all five `dyn` rows** -- `dyn: large web app` **544ms** (+7% vs alien-signals' 586ms) and `dyn: wide dense` **902ms** (+3% vs 926ms), plus simple component (+17%), dynamic component (+15%), and deep (+14%) -- with preact 6-19× slower and vue 15-32× slower on the app-shaped graphs (see the `run_*.txt` logs). On the tiny `S: updateComputations` micro-rows lite and alien trade the lead within a few percent (lite ahead on 3 of 7); these sub-60ms kernels are dominated by run-to-run noise on this old host. 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).
828
+ The cross-framework reactivity suite agrees independently, re-run on **1.3.0** (default eager, median-of-10, isolated): lite-signal is the **fastest of five frameworks on all five `dyn` rows** -- `dyn: large web app` **544ms** (+7% vs alien-signals' 586ms) and `dyn: wide dense` **902ms** (+3% vs 926ms), plus simple component (+17%), dynamic component (+15%), and deep (+14%) -- with preact 6-19× slower and vue 15-32× slower on the app-shaped graphs (see [`resultsReactive.txt`](./resultsReactive.txt)). On the tiny `S: updateComputations` micro-rows lite and alien trade the lead within a few percent (lite ahead on 3 of 7); these sub-60ms kernels are dominated by run-to-run noise on this old host. 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).
829
829
 
830
830
  **The Takeaway:** as of 1.1.4 you no longer have to choose, and 1.3.0 holds the line -- the engine still ranks **4th of 15** on the official js-reactivity-benchmark (the only zero-GC library in the field). `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. It runs at parity with alien-signals on cheap stable shapes. The one shape where alien's flatter representation still leads is the 256-deep computed pipeline (DEEP CHAIN, -18% on the 1.3.0 isolated run).
831
831
 
@@ -833,7 +833,8 @@ The cross-framework reactivity suite agrees independently, re-run on **1.3.0** (
833
833
  - **1.1.5** -- additions in service of `lite-devtools` (node identity/traversability on the introspection walkers, for full auto-discovered graph rendering). *Shipped.*
834
834
  - **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.*
835
835
  - **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.*
836
- - **1.4** -- next engine work. The pull-mode recursion depth limit (~5,000 chained computeds) is the main outstanding architectural item; cumulative allocation counters (`totalAllocations` / `totalDisposals` / `poolGrowths`) are reserved for the `stats()` surface here.
836
+ - **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. Drop-in over 1.3.0. *Shipped (beta).*
837
+ - **1.5** -- the `signalBox` / `computedBox` allocation-light handle API (staged in `test/24-signalbox`). The pull-mode recursion depth limit (~5,000 chained computeds) remains the main outstanding architectural item.
837
838
 
838
839
  > 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.
839
840
 
package/Signal.d.ts CHANGED
@@ -92,6 +92,26 @@ export interface RegistryStats {
92
92
  nodePoolCapacity: number;
93
93
  /** Number of nodes currently allocated (signals + computeds + alive effects). */
94
94
  activeNodes: number;
95
+ /**
96
+ * Cumulative count of every node acquired over the registry's life -- whether
97
+ * popped from the free list or freshly constructed during a pool-growth chunk.
98
+ * Monotonic; reset only by {@link Registry.destroy}. The true total ever handed
99
+ * out, not the live count (`activeNodes` is the live gauge). Added in 1.4.0.
100
+ */
101
+ totalAllocations: number;
102
+ /**
103
+ * Cumulative count of every node returned to the pool (`disposeNode`). Monotonic;
104
+ * reset only by {@link Registry.destroy}. In a quiescent registry
105
+ * `totalAllocations - totalDisposals === activeNodes`. Added in 1.4.0.
106
+ */
107
+ totalDisposals: number;
108
+ /**
109
+ * Cumulative count of pool-growth chunks -- incremented whenever a node *or* link
110
+ * refill pushes capacity past its current ledger. Nonzero after warm-up means the
111
+ * initial pool was undersized and grew at runtime; an eager pool sized for its
112
+ * workload keeps this at 0. Reset only by {@link Registry.destroy}. Added in 1.4.0.
113
+ */
114
+ poolGrowths: number;
95
115
  }
96
116
 
97
117
  // --- Observer-lifecycle introspection (1.1.4) ---------------------------------
package/Signal.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @zakkster/lite-signal v1.3.0
2
+ * @zakkster/lite-signal v1.4.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:
@@ -201,6 +201,7 @@ export class CapacityError extends Error {
201
201
  * miss, not a single doubling burst -- so any one growth pause stays
202
202
  * bounded; the capacity ledger still doubles (`stats()` semantics
203
203
  * unchanged). Link growth is bounded by a hard ceiling of `maxLinks * 16`.
204
+ * Each chunk increments `stats().poolGrowths`.
204
205
  * @param {number} [config.maxFlushPasses=100] Cycle-protection: max effect-queue
205
206
  * drain passes before throwing an
206
207
  * Error prefixed `"CycleError:"`.
@@ -240,6 +241,13 @@ export function createRegistry(config) {
240
241
  let statSignals = 0;
241
242
  let statComputeds = 0;
242
243
  let statEffects = 0;
244
+ // 1.4: cumulative lifecycle counters for churn-rate observability (lite-devtools
245
+ // / lite-studio derive allocationRate, poolReuseRate, avg node lifetime from these).
246
+ // Monotonic across the registry's life; reset only by destroy(). Three integer
247
+ // bumps at existing chokepoints -- no new node fields, no hot-path cost.
248
+ let statTotalAllocations = 0; // bumped on every createNode (pool pop OR fresh build)
249
+ let statTotalDisposals = 0; // bumped on every disposeNode
250
+ let statPoolGrowths = 0; // bumped when a node/link chunk pushes capacity past its ledger
243
251
 
244
252
  const effectQueueA = [];
245
253
  const effectQueueB = [];
@@ -259,35 +267,20 @@ export function createRegistry(config) {
259
267
  let nodeSeq = 1 | 0;
260
268
  let lifecycleCount = 0 | 0;
261
269
  const lifecycleMap = new WeakMap();
262
-
263
270
  function fireConnect(node) {
264
271
  const e = lifecycleMap.get(node);
265
272
  if (e === undefined || e.onConnect === undefined) return;
266
273
  const po = currentObserver, pt = isTrackingDeps;
267
- currentObserver = null;
268
- isTrackingDeps = false;
269
- try {
270
- e.onConnect();
271
- } finally {
272
- currentObserver = po;
273
- isTrackingDeps = pt;
274
- }
274
+ currentObserver = null; isTrackingDeps = false;
275
+ try { e.onConnect(); } finally { currentObserver = po; isTrackingDeps = pt; }
275
276
  }
276
-
277
277
  function fireDisconnect(node) {
278
278
  const e = lifecycleMap.get(node);
279
279
  if (e === undefined || e.onDisconnect === undefined) return;
280
280
  const po = currentObserver, pt = isTrackingDeps;
281
- currentObserver = null;
282
- isTrackingDeps = false;
283
- try {
284
- e.onDisconnect();
285
- } finally {
286
- currentObserver = po;
287
- isTrackingDeps = pt;
288
- }
281
+ currentObserver = null; isTrackingDeps = false;
282
+ try { e.onDisconnect(); } finally { currentObserver = po; isTrackingDeps = pt; }
289
283
  }
290
-
291
284
  let isFlushing = false;
292
285
 
293
286
  const flushErrorBuffer = [];
@@ -319,21 +312,18 @@ export function createRegistry(config) {
319
312
  *
320
313
  * @private
321
314
  */
322
- // --- Graph-mutation hook (1.2.1 keystone prototype) ---------------------
323
- // Single nullable listener; every fire point is `if (mutationHook !== null)`
324
- // -- branch-predicted free when absent, allocation-free when present
325
- // (opcode + two int args). Enables push-based devtools (watchGraph) and the
326
- // recompute profiler. Opcodes: 1 node-create, 2 node-dispose, 3 link-add,
327
- // 4 link-remove, 5 recompute.
315
+ // --- Graph-mutation hook (1.2.1 keystone prototype) ---------------------
316
+ // Single nullable listener; every fire point is `if (mutationHook !== null)`
317
+ // -- branch-predicted free when absent, allocation-free when present
318
+ // (opcode + two int args). Enables push-based devtools (watchGraph) and the
319
+ // recompute profiler. Opcodes: 1 node-create, 2 node-dispose, 3 link-add,
320
+ // 4 link-remove, 5 recompute.
328
321
  let mutationHook = null;
329
-
330
322
  function onGraphMutation(fn) {
331
323
  if (fn !== null && typeof fn !== "function") throw new TypeError("onGraphMutation: listener must be a function or null");
332
324
  const prev = mutationHook;
333
325
  mutationHook = fn;
334
- return () => {
335
- if (mutationHook === fn) mutationHook = prev;
336
- };
326
+ return () => { if (mutationHook === fn) mutationHook = prev; };
337
327
  }
338
328
 
339
329
  function allocateLink(source, target) {
@@ -391,6 +381,7 @@ export function createRegistry(config) {
391
381
  let doubled = currentLinkCapacity;
392
382
  while (doubled < linkPool.length) doubled *= 2;
393
383
  currentLinkCapacity = doubled > maxLinkLimit ? maxLinkLimit : doubled;
384
+ statPoolGrowths++; // 1.4: link capacity ledger crossed
394
385
  }
395
386
  } else {
396
387
  link = freeLinkHead;
@@ -565,6 +556,7 @@ export function createRegistry(config) {
565
556
  node.nextFree = freeNodeHead;
566
557
  freeNodeHead = node;
567
558
  activeNodes = (activeNodes - 1) | 0;
559
+ statTotalDisposals++; // 1.4: every node returned to the pool
568
560
  }
569
561
 
570
562
  /**
@@ -599,6 +591,7 @@ export function createRegistry(config) {
599
591
  let doubled = currentNodesCapacity;
600
592
  while (doubled < nodePool.length) doubled *= 2;
601
593
  currentNodesCapacity = doubled;
594
+ statPoolGrowths++; // 1.4: capacity ledger crossed
602
595
  }
603
596
  } else {
604
597
  node = freeNodeHead;
@@ -606,6 +599,7 @@ export function createRegistry(config) {
606
599
  node.nextFree = null;
607
600
  }
608
601
  activeNodes = (activeNodes + 1) | 0;
602
+ statTotalAllocations++; // 1.4: every node acquired (pool pop or fresh build)
609
603
 
610
604
  // 1.2.3: Clean free-list invariant (Andrii's recommendation).
611
605
  //
@@ -625,8 +619,7 @@ export function createRegistry(config) {
625
619
  node.version = 0;
626
620
  node.evalVersion = 0;
627
621
  node.markEpoch = 0;
628
- node.id = nodeSeq;
629
- nodeSeq = (nodeSeq + 1) | 0; // fresh identity per allocation (ported from 1.1.5)
622
+ node.id = nodeSeq; nodeSeq = (nodeSeq + 1) | 0; // fresh identity per allocation (ported from 1.1.5)
630
623
 
631
624
  // Wire into Owner Context (lifecycle, not tracking -- keyed off currentOwner).
632
625
  // ONLY observers (computed/effect) are adopted: a re-running owner disposes
@@ -1000,10 +993,7 @@ export function createRegistry(config) {
1000
993
  // closures: set() is the hot write path (a closure over `node` beats the
1001
994
  // this[NODE_PTR] load and keeps `const {set} = signal()` working), and peek()'s
1002
995
  // body is too cheap to absorb the node recovery.
1003
- function sharedUpdate(fn) {
1004
- return this.set(fn(this[NODE_PTR].value));
1005
- }
1006
-
996
+ function sharedUpdate(fn) { return this.set(fn(this[NODE_PTR].value)); }
1007
997
  function sharedSubscribe(fn) {
1008
998
  const read = this;
1009
999
  return effect(() => {
@@ -1017,7 +1007,6 @@ export function createRegistry(config) {
1017
1007
  }
1018
1008
  });
1019
1009
  }
1020
-
1021
1010
  // Shared peeks (one per registry, not per primitive). Save one closure
1022
1011
  // allocation per signal/computed creation versus the previous per-instance
1023
1012
  // arrows. Method-invoked, so `this` is the read function and this[NODE_PTR]
@@ -1028,7 +1017,6 @@ export function createRegistry(config) {
1028
1017
  if (this[NODE_GEN] !== node.gen) return undefined; // stale handle: slot recycled (ABA guard, matches read())
1029
1018
  return node.value;
1030
1019
  }
1031
-
1032
1020
  function sharedComputedPeek() {
1033
1021
  const node = this[NODE_PTR];
1034
1022
  if (this[NODE_GEN] !== node.gen) return undefined;
@@ -1314,6 +1302,15 @@ export function createRegistry(config) {
1314
1302
  /**
1315
1303
  * Snapshot of registry counters. Useful for diagnostics and tests --
1316
1304
  * e.g. asserting that `activeNodes` returns to a baseline after teardown.
1305
+ *
1306
+ * Returns 11 keys: eight live gauges (`signals`, `computeds`, `effects`,
1307
+ * `activeNodes`, `activeLinks`, `pooledLinks`, `nodePoolCapacity`,
1308
+ * `linkPoolCapacity`) plus three cumulative lifecycle counters added in 1.4.0
1309
+ * (`totalAllocations`, `totalDisposals`, `poolGrowths`). The counters are
1310
+ * monotonic over the registry's life and reset only by {@link destroy}; sample
1311
+ * them over time to derive allocation rate, pool-reuse ratio, and graph churn
1312
+ * without the engine computing rates itself. In a quiescent registry
1313
+ * `totalAllocations - totalDisposals === activeNodes`.
1317
1314
  * @returns {RegistryStats}
1318
1315
  */
1319
1316
  function stats() {
@@ -1325,7 +1322,13 @@ export function createRegistry(config) {
1325
1322
  pooledLinks: currentLinkCapacity - activeLinks,
1326
1323
  linkPoolCapacity: currentLinkCapacity,
1327
1324
  nodePoolCapacity: currentNodesCapacity,
1328
- activeNodes
1325
+ activeNodes,
1326
+ // 1.4: cumulative lifecycle counters (monotonic; reset by destroy()).
1327
+ // Derive: allocationRate = deltatotalAllocations/deltat; poolReuseRate =
1328
+ // 1 - poolGrowths*initialCap/totalAllocations; avgLifetime ~ totalDisposals/rate.
1329
+ totalAllocations: statTotalAllocations,
1330
+ totalDisposals: statTotalDisposals,
1331
+ poolGrowths: statPoolGrowths
1329
1332
  };
1330
1333
  }
1331
1334
 
@@ -1406,6 +1409,9 @@ export function createRegistry(config) {
1406
1409
  statSignals = 0;
1407
1410
  statComputeds = 0;
1408
1411
  statEffects = 0;
1412
+ statTotalAllocations = 0;
1413
+ statTotalDisposals = 0;
1414
+ statPoolGrowths = 0;
1409
1415
 
1410
1416
  for (let i = 0; i < flushErrorCount; i++) flushErrorBuffer[i] = null;
1411
1417
  flushErrorCount = 0;
@@ -1416,7 +1422,6 @@ export function createRegistry(config) {
1416
1422
  const node = liveNode(handle);
1417
1423
  return node !== undefined && node.headSub !== null;
1418
1424
  }
1419
-
1420
1425
  function observeObservers(handle, opts) {
1421
1426
  const node = liveNode(handle);
1422
1427
  if (node === undefined) throw new TypeError("observeObservers: argument is not a reactive handle");
@@ -1437,7 +1442,6 @@ export function createRegistry(config) {
1437
1442
  if (lifecycleMap.delete(node)) lifecycleCount = (lifecycleCount - 1) | 0;
1438
1443
  };
1439
1444
  }
1440
-
1441
1445
  function describeNode(node) {
1442
1446
  const fl = node.flags;
1443
1447
  const kind = (fl & FLAG_EFFECT) !== 0 ? "effect" : (fl & FLAG_COMPUTED) !== 0 ? "computed" : "signal";
@@ -1451,7 +1455,6 @@ export function createRegistry(config) {
1451
1455
  d[NODE_GEN] = node.gen; // descriptors are re-walkable handles; stamp gen so the ABA guard holds for them too
1452
1456
  return d;
1453
1457
  }
1454
-
1455
1458
  // Gen-guarded handle resolution (1.2.1): with the v1.2 owner tree, the
1456
1459
  // ENGINE recycles slots autonomously (owner re-run cascade-disposes owned
1457
1460
  // children), so stale handles are a normal occurrence -- introspecting the
@@ -1465,28 +1468,20 @@ export function createRegistry(config) {
1465
1468
  if (handle[NODE_GEN] !== node.gen) return undefined; // stale: slot recycled
1466
1469
  return node;
1467
1470
  }
1468
-
1469
1471
  function nodeId(handle) {
1470
1472
  const node = liveNode(handle);
1471
1473
  return node !== undefined ? node.id : undefined;
1472
1474
  }
1473
-
1474
1475
  function describe(handle) {
1475
1476
  const node = liveNode(handle);
1476
1477
  return node !== undefined ? describeNode(node) : undefined;
1477
1478
  }
1478
-
1479
1479
  function forEachObserver(handle, fn) {
1480
1480
  const node = liveNode(handle);
1481
1481
  if (node === undefined) return;
1482
1482
  let l = node.headSub;
1483
- while (l !== null) {
1484
- const nx = l.nextSub;
1485
- fn(describeNode(l.target));
1486
- l = nx;
1487
- }
1483
+ while (l !== null) { const nx = l.nextSub; fn(describeNode(l.target)); l = nx; }
1488
1484
  }
1489
-
1490
1485
  /** Iterate this node's OWNED children (v1.2 owner tree). Additive 1.3 API
1491
1486
  * prototype: lets devtools/studio walk + render the ownership hierarchy
1492
1487
  * (cascade-disposal domains), which is invisible through dep/sub edges. */
@@ -1494,52 +1489,22 @@ export function createRegistry(config) {
1494
1489
  const node = liveNode(handle);
1495
1490
  if (node === undefined) return;
1496
1491
  let c = node.firstOwned;
1497
- while (c !== null) {
1498
- const nx = c.nextOwned;
1499
- fn(describeNode(c));
1500
- c = nx;
1501
- }
1492
+ while (c !== null) { const nx = c.nextOwned; fn(describeNode(c)); c = nx; }
1502
1493
  }
1503
-
1504
1494
  /** Descriptor of this node's owner, or undefined (top-level / stale handle). */
1505
1495
  function ownerOf(handle) {
1506
1496
  const node = liveNode(handle);
1507
1497
  if (node === undefined || node.owner === null) return undefined;
1508
1498
  return describeNode(node.owner);
1509
1499
  }
1510
-
1511
1500
  function forEachSource(handle, fn) {
1512
1501
  const node = liveNode(handle);
1513
1502
  if (node === undefined) return;
1514
1503
  let l = node.headDep;
1515
- while (l !== null) {
1516
- const nx = l.nextDep;
1517
- fn(describeNode(l.source));
1518
- l = nx;
1519
- }
1504
+ while (l !== null) { const nx = l.nextDep; fn(describeNode(l.source)); l = nx; }
1520
1505
  }
1521
1506
 
1522
- return {
1523
- signal,
1524
- computed,
1525
- effect,
1526
- dispose,
1527
- batch,
1528
- untrack,
1529
- onCleanup,
1530
- stats,
1531
- destroy,
1532
- isTracking,
1533
- hasObservers,
1534
- observeObservers,
1535
- forEachObserver,
1536
- forEachSource,
1537
- forEachOwned,
1538
- ownerOf,
1539
- nodeId,
1540
- describe,
1541
- onGraphMutation
1542
- };
1507
+ return {signal, computed, effect, dispose, batch, untrack, onCleanup, stats, destroy, isTracking, hasObservers, observeObservers, forEachObserver, forEachSource, forEachOwned, ownerOf, nodeId, describe, onGraphMutation};
1543
1508
  }
1544
1509
 
1545
1510
  // -----------------------------------------------------------------
@@ -1599,35 +1564,27 @@ export function destroy() {
1599
1564
  export function hasObservers(handle) {
1600
1565
  return defaultRegistry.hasObservers(handle);
1601
1566
  }
1602
-
1603
1567
  export function observeObservers(handle, opts) {
1604
1568
  return defaultRegistry.observeObservers(handle, opts);
1605
1569
  }
1606
-
1607
1570
  export function forEachObserver(handle, fn) {
1608
1571
  return defaultRegistry.forEachObserver(handle, fn);
1609
1572
  }
1610
-
1611
1573
  export function forEachSource(handle, fn) {
1612
1574
  return defaultRegistry.forEachSource(handle, fn);
1613
1575
  }
1614
-
1615
1576
  export function onGraphMutation(fn) {
1616
1577
  return defaultRegistry.onGraphMutation(fn);
1617
1578
  }
1618
-
1619
1579
  export function forEachOwned(handle, fn) {
1620
1580
  return defaultRegistry.forEachOwned(handle, fn);
1621
1581
  }
1622
-
1623
1582
  export function ownerOf(handle) {
1624
1583
  return defaultRegistry.ownerOf(handle);
1625
1584
  }
1626
-
1627
1585
  export function nodeId(handle) {
1628
1586
  return defaultRegistry.nodeId(handle);
1629
1587
  }
1630
-
1631
1588
  export function describe(handle) {
1632
1589
  return defaultRegistry.describe(handle);
1633
1590
  }
package/llms.txt CHANGED
@@ -50,10 +50,35 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
50
50
 
51
51
  ## Version notes
52
52
 
53
- - **1.3.0** (current): the **pool minor**. Node and link pools become growable
54
- and incrementally populated; the propagation mark phase moves to an intrusive
55
- linked-list stack; a small registry config surface is exposed. **The hot paths
56
- and public callable API are byte-identical to 1.2.2** -- everything here is
53
+ - **1.4.0-beta** (current): the **observability minor**. `stats()` gains three
54
+ cumulative lifecycle counters -- `totalAllocations`, `totalDisposals`,
55
+ `poolGrowths` -- the surface reserved for 1.4.0 in the 1.2.x/1.3.0 notes, now
56
+ delivered. **The hot paths and public callable API are byte-identical to 1.3.0**;
57
+ the counters bump on existing acquire / dispose / pool-grow edges that already
58
+ ran, never on the steady-state read path, so throughput and zero-GC are
59
+ unchanged. The 1.3.0 eager pool default carries forward (`prealloc: "eager"`).
60
+ **`stats()` now returns 11 keys** (the 8 live gauges plus the 3 counters).
61
+ `totalAllocations` counts every node acquired (pool pop OR fresh build);
62
+ `totalDisposals` counts every node returned to the pool, with
63
+ `totalAllocations - totalDisposals === activeNodes` in a quiescent registry;
64
+ `poolGrowths` counts pool-growth chunks (node OR link crossing its ledger) --
65
+ nonzero after warm-up means the initial pool was undersized, 0 means an eager pool
66
+ was sized right. All three are monotonic and reset only by `destroy()`. They are
67
+ exact, not sampled: a consumer sampling `stats()` over time derives allocation
68
+ rate (delta totalAllocations / delta t), pool-reuse ratio
69
+ (1 - poolGrowths*initialCap/totalAllocations), and churn without the engine
70
+ computing rates -- the series lite-devtools 1.2 / lite-studio 1.2 plot. **Tests:**
71
+ 430 total, 420 pass, 0 fail, 10 skip (6 new counter tests in `test/03-pool_test.mjs`
72
+ cover the 11-key shape, the live invariant, poolGrowths firing on growth vs staying
73
+ 0 on a sized eager pool, and destroy() reset). **Coverage:** `Signal.js` 100%
74
+ statements / 98.26% branches / 100% functions / 100% lines; `Watch.js` 100%.
75
+ Drop-in over 1.3.0.
76
+
77
+ - **1.3.0** (drop-in over 1.2.2): the **pool minor**. Node and link pools become
78
+ growable and incrementally populated; the propagation mark phase moves to an
79
+ intrusive linked-list stack (a `nextMark` field); a small registry config surface
80
+ (`prealloc`, `onCapacityExceeded`, `maxFlushPasses`) is exposed. The hot paths and
81
+ public callable API are byte-identical to 1.2.2 -- everything here is
57
82
  pool mechanics, construction-time behavior, and new opt-in config. Steady-state
58
83
  zero-GC is unchanged: after warm-up the pools recycle exactly as before.
59
84
  **`prealloc` (`"eager"` default | `"lazy"`):** `"eager"` constructs the full
@@ -320,15 +345,18 @@ interface RegistryConfig {
320
345
  onCapacityExceeded?: "throw" | "grow"; // default "throw"; "grow" = chunked refill, ledger doubles, 16x link ceiling
321
346
  }
322
347
 
323
- interface RegistryStats {
348
+ interface RegistryStats { // 11 keys as of 1.4.0
324
349
  signals: number;
325
350
  computeds: number;
326
351
  effects: number;
327
352
  activeLinks: number;
328
353
  pooledLinks: number;
329
- linkPoolCapacity: number;
330
- nodePoolCapacity: number;
331
- activeNodes: number;
354
+ linkPoolCapacity: number; // ledger; doubles under "grow"
355
+ nodePoolCapacity: number; // ledger; doubles under "grow"
356
+ activeNodes: number; // live gauge
357
+ totalAllocations: number; // 1.4.0: cumulative node acquires; reset by destroy()
358
+ totalDisposals: number; // 1.4.0: cumulative node disposals; totalAllocations - totalDisposals === activeNodes
359
+ poolGrowths: number; // 1.4.0: cumulative pool-growth chunks; 0 if eager pool sized right
332
360
  }
333
361
 
334
362
  class CapacityError extends Error {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zakkster/lite-signal",
3
- "version": "1.3.0-rc.1",
3
+ "version": "1.4.0-beta.0",
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",