@zakkster/lite-signal 1.8.0-alpha.5 → 1.8.0-alpha.7

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,6 +4,90 @@ 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.8.0-alpha.7] -- 2026-08-20
8
+
9
+ Backports the **1.4.5 `createRegistry` input validation** (all four findings) onto
10
+ the 1.8.0-alpha.6 engine. Supersedes 1.8.0-alpha.6. Only `createRegistry`'s *cold*
11
+ construction path changed -- the hot paths are byte-identical and the zero-GC gates
12
+ (`bench/torture/run.mjs` 22/22) are unchanged. If you had a typo in your registry
13
+ config, you will now hear about it.
14
+
15
+ ### Added -- createRegistry validates its config (fail closed)
16
+
17
+ - **Bounded eager construction.** `prealloc:"eager"` with a non-finite or absurd
18
+ capacity (`maxNodes:Infinity`, `maxNodes:1e9`) previously ran an unbounded
19
+ construction loop and killed the process with an **uncatchable SIGABRT**. It now
20
+ throws a `TypeError` **by name**, before allocating, gated on `(maxNodes+maxLinks)`
21
+ against a ceiling of `1<<24` (16,777,216) objects. `prealloc:"lazy"` keeps its
22
+ unbounded on-demand ledger, untouched.
23
+ - **Per-option validation by name.** `maxNodes` / `maxLinks` / `maxFlushPasses` must
24
+ be finite integers `>= 1`; `prealloc` must be exactly `"eager"` | `"lazy"`;
25
+ `onCapacityExceeded` must be exactly `"throw"` | `"grow"`. Each bad value throws a
26
+ `TypeError` prefixed `createRegistry: "<option>"` at construction -- not a delayed
27
+ internal `nextFree` TypeError on first use.
28
+ - **Config-shape gate.** A non-object, `null`, or array `config` throws
29
+ `createRegistry: "config"` rather than dying later.
30
+ - **Unknown-key rejection with did-you-mean.** An unrecognized key throws with a
31
+ Levenshtein suggestion (`maxNods` -> `maxNodes`, `preAlloc` -> `prealloc`) instead
32
+ of being silently ignored.
33
+ - **`flushStrategy` stays a first-class option.** It is a recognized key (its own native value-guard is unchanged); only misspelled *keys* are rejected.
34
+ - **`stats()` gains `nodePoolPopulation` / `linkPoolPopulation`** -- the TRUE count
35
+ of physically constructed nodes/links, distinct from the `*Capacity` ledgers. A
36
+ silently mis-set `prealloc` is now observable (population 0 under lazy) instead of
37
+ telemetry-blind. **The one observable API change: `stats()` grows to 14 keys,
38
+ purely additive** -- no existing key changed; only an exact key-*count* assertion
39
+ is affected (updated in `test/03-pool.test.mjs`).
40
+
41
+ ### Tests
42
+
43
+ New `test/*-config-validation.test.mjs` adds the full config matrix, the did-you-mean
44
+ cases, the eager ceiling, the population contract, and the three OOM rows as isolated
45
+ child-process cases proving the fixed engine throws + exits 0 under a 256 MB cap where
46
+ the unvalidated engine died.
47
+
48
+ ## [1.8.0-alpha.5] -- 2026-08-18
49
+
50
+ Brings the `bench/torture/` suite and the throwing-`equals` unit test to **full
51
+ parity with the shipped 1.4.4 canon**. This is a **verification-only** cut: the
52
+ engine (`Signal.js` + `Signal.d.ts`) is **UNCHANGED, byte-identical** to
53
+ `alpha.4` -- every ported scenario was run against the 1.8.0 engine and pins its
54
+ **actual** behaviour; no assertion was softened and no budget widened.
55
+
56
+ ### Added -- torture parity (17 -> 22 scenarios)
57
+
58
+ - Registered the already-present-and-passing `owner-torture` (`getOwner` /
59
+ `runWithOwner` capture-restore + ABA degradation, a 1.6.0 primitive).
60
+ - Ported four scenarios that all run **natively** on the 1.8.0 engine:
61
+ `lifecycle-torture` (`createRoot` detachment + `destroy` registry reset),
62
+ `error-torture` (throwing effect bodies: per-effect buffering, exact-order
63
+ `AggregateError`, buffer drain over 4096 cycles), `deep-chain-torture`
64
+ (`pullComputed` recursion fail-closed with a `RangeError` vs the heap-iterative
65
+ push path), and `zerogc-torture` (the falsifiable zero-GC gate via
66
+ `measureAllocs` / `measureOps` + `stats()` counters, with the `ZEROGC_BREAK`
67
+ self-test). None needed pinning to a divergent behaviour.
68
+ - `capacity-torture` gained section 9: the **16x grow-link ceiling** (multiplier
69
+ confirmed against `Signal.js:285`), fail-closed with a `links` `CapacityError`.
70
+ - The three soaks (`graph-fuzzer`, `scheduler-bench`, `torture-soak`) gained an
71
+ **Int32Array value-oracle** (a fixed shadow window over the writable signals,
72
+ allocated once, zero per-tick allocation, full sweep at teardown).
73
+ - New `test/30-throwing-equals.test.mjs` pins all **five** `equals()` invocation
74
+ sites -- 3 callable (signal set pre-check, batch revert, computed re-eval) plus
75
+ the 2 `signalBox` `boxSet` sites (pre-check, revert).
76
+
77
+ The `cleanup-return`, `owner`, `flush`, `scope` and `createRoot`-based scenarios
78
+ all run natively on this engine. On the 1.8.0 engine the runner now executes
79
+ **18 semantic** scenarios and cleanly SKIPS the one remaining later-version
80
+ scenario (`dispose-torture` 1.9.0); the suite total is **22 (19 semantic + 3
81
+ soak)**.
82
+
83
+ ### Verified -- full suite green on the 1.8.0 engine (Node 22, `--expose-gc`)
84
+
85
+ - **Torture:** 22/22 (`torture:semantic` 19/19 -- 18 executed, 1 clean skip
86
+ `dispose` 1.9.0; `torture:soak` 3/3, value-oracle matched).
87
+ - **Unit (plain `npm test`):** 499 tests, 498 pass, 0 fail, 1 skip (the
88
+ architectural SSR N/A in `17-reactivity`).
89
+ - **Unit (`npm run test:gc`):** 507 tests, 506 pass, 0 fail, 1 skip.
90
+
7
91
  ## [1.8.0-alpha.4] -- 2026-07-27
8
92
 
9
93
  Rolls up the post-`1.8.0-preview` changes into the `alpha.4` tag. The
package/README.md CHANGED
@@ -809,7 +809,10 @@ npm run bench
809
809
 
810
810
  ## Testing strategy
811
811
 
812
- Three tiers, all reproducible.
812
+ Four tiers, all reproducible. The full suite is **507 tests across 31 files**:
813
+ 506 pass, 1 skipped (the architecturally-N/A SSR case in `17-reactivity` -- lite
814
+ has no DOM layer), 0 failing. Plain `npm test` runs **499** of them; the rest are
815
+ gated on `--expose-gc` and need `npm run test:gc` or `npm run test:coverage`.
813
816
 
814
817
  ### Tier 1 -- Behavior (unit tests, fast)
815
818
 
@@ -840,6 +843,9 @@ Three tiers, all reproducible.
840
843
  - **`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.
841
844
  - **`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.
842
845
  - **`29-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.
846
+ - **`28-run-with-owner.test.mjs`** -- `getOwner` / `runWithOwner` (1.7.0; 16 tests). Capture inside an effect and inside a computed, `undefined` outside any body, adoption, tracking-observer nulling, return-value pass-through, state restoration on return *and* on throw, nested restore; three degradation tests (`null` / `undefined` / a signal handle fall through to rooted execution); and three ABA hazard pins run under allocation pressure (recycled-slot cascade, corpse adoption, and the two composed).
847
+ - **`30-throwing-equals.test.mjs`** -- a user `equals` predicate that THROWS (9 tests), pinned at all **five** engine sites it is called from: the three callable sites (signal `set` pre-check, batch-revert check, computed re-eval) and `signalBox` `boxSet`'s two (pre-check, revert). A pre-check throw propagates the ORIGINAL error unwrapped and leaves the handle unmutated with no downstream firing; a batch-revert throw is PINNED to the engine's actual behaviour (net value written, version left bumped, downstream fires), with a CONTRAST anti-tautology test proving a clean set-X-then-back suppresses the re-run; a computed re-eval throw is cached and re-thrown until a dep change re-evaluates cleanly. The `a-box`/`b-box` cases confirm `boxSet` behaves identically to `read.set`.
848
+ - **`33-cleanup-return.test.mjs`** -- the 1.8.0 effect-cleanup-return contract: an effect body may `return` a cleanup that fires before each re-run and once on dispose, composes after any `onCleanup` from the same body in call order, is ignored for non-function returns, and is excluded for computeds (a returned function stays the VALUE).
843
849
  - **`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.
844
850
  - **`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%).
845
851
 
@@ -872,13 +878,13 @@ npm run bench
872
878
 
873
879
  ### Tier 4 -- Torture (correctness and resources under chaos)
874
880
 
875
- `bench/torture/` holds the complete **17-scenario superset (14 semantic + 3
881
+ `bench/torture/` holds the complete **22-scenario superset (19 semantic + 3
876
882
  soak)** behind one runner (`run.mjs`), the forward-compatible set through 1.9.
877
883
  They are not perf benchmarks: the ops/sec figures reflect random workload
878
884
  composition, not engine throughput -- `bench/benchmark.mjs` remains the canonical
879
885
  perf harness. Every scenario feature-detects and **skips cleanly** below the
880
886
  engine version that introduces its feature, so on the 1.8.0 engine the runner
881
- executes **13 semantic** scenarios (including `cleanup-return-torture`) and
887
+ executes **18 semantic** scenarios (including `cleanup-return-torture`) and
882
888
  reports a clean SKIP for the one remaining later-version scenario
883
889
  (`dispose-torture` 1.9.0).
884
890
 
@@ -891,8 +897,9 @@ node bench/torture/run.mjs --list
891
897
 
892
898
  #### `semantic` -- deterministic, fast, asserts on **meaning**
893
899
 
894
- Run these on every commit. The nine untagged scenarios run on any 1.4.x+ engine;
895
- `box-torture` (1.5.0), `scope-torture` (1.6.0), `flush-torture` (1.7.0), and
900
+ Run these on every commit. Most scenarios run on any 1.4.x+ engine; `box-torture`
901
+ and `lifecycle-torture` (1.5.0), `scope-torture` / `owner-torture` /
902
+ `introspect-torture` (1.6.0), `flush-torture` (1.7.0), and
896
903
  `cleanup-return-torture` (1.8.0) run here because their features exist; the one
897
904
  tagged `1.9.0+` scenario feature-detects and SKIPs on this engine.
898
905
 
@@ -907,10 +914,15 @@ tagged `1.9.0+` scenario feature-detects and SKIPs on this engine.
907
914
  | `scheduler-storm` | deferred execution under 10,000 effects: gen-bound thunk ABA guard, `FLAG_QUEUED` coalescing, a throwing scheduler contained |
908
915
  | `box-torture` (1.5.0) | `signalBox`/`computedBox` interop: the oracle differential fuzz with every node realised as **either** a callable or a box |
909
916
  | `scope-torture` (1.6.0) | `createScope` adoption contract, the disposal-crash repro + a 300-seed fuzz, `runWithOwner` re-attachment into a scope, pool balance over 200 rounds |
917
+ | `owner-torture` (1.6.0) | `getOwner`/`runWithOwner` capture-restore + ABA degradation under allocation pressure |
910
918
  | `async-torture` | `watch`/`when`/`whenAsync` contracts + a 300-seed projection-guard storm |
911
- | `capacity-torture` | the fail-closed pool boundary: exact ceilings, re-throw-on-read, `grow` crossing the same boundary |
919
+ | `capacity-torture` | the fail-closed pool boundary: exact ceilings, re-throw-on-read, `grow` crossing the same boundary, and the 16x grow-link ceiling (section 9) |
920
+ | `error-torture` | throwing effect bodies: single throw re-thrown unwrapped, 2+ aggregate into an exact-order `AggregateError`, survivor still runs, buffer drains over 4096 cycles with `activeNodes`/`activeLinks` flat |
921
+ | `deep-chain-torture` | `pullComputed` recursion fail-closed (a `RangeError` at some depth <= the ceiling; registry stays usable, deterministic re-throw) vs the heap-iterative push cascade that completes |
912
922
  | `flush-torture` (1.7.0) | the three `flushStrategy` modes by cross-strategy differential (same graph + op sequence under eager/sab/manual settling to identical values), per-strategy scheduling, re-entrant/empty `flush()`, and the `.subscribe()` contract under each |
913
923
  | `cleanup-return-torture` (1.8.0) | an effect's returned cleanup: timing at re-run/dispose, compose order (appended after `onCleanup` from the same body), the self-dispose guard, and the computed exclusion -- 400 seeds |
924
+ | `zerogc-torture` | the falsifiable zero-GC gate: retained bytes (`measureAllocs`/`checkAllocs`, `maxBytesPerCall: 0`), major/pause window (`measureOps`/`checkNoGc`, `maxMajor: 0`), and `stats()` counters across steady + churn scenarios; `ZEROGC_BREAK=1` self-test |
925
+ | `lifecycle-torture` (1.5.0) | `createRoot` detachment (children survive, deps isolated) + `destroy` full registry reset (handles stale, pool baseline restored) |
914
926
  | `dispose-torture` (1.9.0+) | `Symbol.dispose` / `using` on lifecycle objects -- SKIP on 1.8.0 |
915
927
 
916
928
  #### `soak` -- wall-clock bound, asserts on **resources**
@@ -922,7 +934,8 @@ flushes -- for 5-10 seconds. What they assert, with a non-zero exit code on
922
934
  failure:
923
935
 
924
936
  - zero thrown exceptions during the run, and
925
- - after teardown, `activeNodes` / `activeLinks` return to the leaf-only baseline (the dispose path is sound under sustained churn).
937
+ - after teardown, `activeNodes` / `activeLinks` return to the leaf-only baseline (the dispose path is sound under sustained churn), and
938
+ - an Int32Array value-oracle (a fixed shadow window over the writable signals, allocated once, zero per-tick allocation, swept in full at teardown) matched every read -- a wrong value fails the run, not just a crash.
926
939
 
927
940
  ```bash
928
941
  node --expose-gc bench/torture/graph-fuzzer.mjs # 10s random-DAG fuzz, 1500 nodes
package/Signal.d.ts CHANGED
@@ -136,6 +136,16 @@ export interface RegistryStats {
136
136
  /** Node-pool capacity ledger. Doubles under the `"grow"` policy; under `"lazy"`
137
137
  * prealloc it may exceed the count of physically constructed nodes. */
138
138
  nodePoolCapacity: number;
139
+ /** TRUE node-pool population: the number of `ReactiveNode`s physically constructed
140
+ * (`nodePool.length`), distinct from the `nodePoolCapacity` ledger. Under
141
+ * `prealloc:"lazy"` (or a silently-flipped `prealloc` typo) this stays 0 until
142
+ * first demand while capacity reads the ledger -- so a mis-set `prealloc` is
143
+ * observable here rather than telemetry-blind. Added in the 1.4.5 backport. */
144
+ nodePoolPopulation: number;
145
+ /** TRUE link-pool population: the number of `ReactiveLink`s physically constructed
146
+ * (`linkPool.length`), distinct from the `linkPoolCapacity` ledger. Added in the
147
+ * 1.4.5 backport. */
148
+ linkPoolPopulation: number;
139
149
  /** Number of nodes currently allocated (signals + computeds + alive effects). */
140
150
  activeNodes: number;
141
151
  /**
package/Signal.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @zakkster/lite-signal v1.8.0-alpha.4
2
+ * @zakkster/lite-signal v1.8.0-alpha.7
3
3
  * Copyright (c) Zahary Shinikchiev <shinikchiev@yahoo.com>
4
4
  * MIT License
5
5
  * --------------------
@@ -274,10 +274,134 @@ export class CapacityError extends Error {
274
274
  * Error prefixed `"CycleError:"`.
275
275
  * @returns {Registry}
276
276
  */
277
+ /** The only config keys {@link createRegistry} recognizes. Anything else is
278
+ * rejected at construction with a did-you-mean hint (fail closed on an
279
+ * unverified state -- an unknown key is an error, never a silent ignore). */
280
+ const ALLOWED_KEYS = ["maxNodes", "maxLinks", "prealloc", "onCapacityExceeded", "maxFlushPasses", "flushStrategy"];
281
+
282
+ /** Ceiling on eager pool construction: `(maxNodes + maxLinks)` objects. A finite
283
+ * but absurd `maxNodes` (e.g. `1e9`, a plausible typo for `1e5`) that would
284
+ * otherwise OOM the process is refused BY NAME at construction rather than
285
+ * allocating forever. Only the `"eager"` path is bounded; `"lazy"` keeps its
286
+ * unbounded ledger. `1 << 24` == 16777216. */
287
+ const EAGER_CONSTRUCT_CEILING = 1 << 24;
288
+
289
+ /**
290
+ * Levenshtein edit distance between two short strings. Cold: called only on the
291
+ * constructor error path, over the known option names, so its per-call array
292
+ * allocation never touches any hot path.
293
+ * @param {string} a
294
+ * @param {string} b
295
+ * @returns {number}
296
+ */
297
+ function editDistance(a, b) {
298
+ const m = a.length;
299
+ const n = b.length;
300
+ const prev = new Array(n + 1);
301
+ const cur = new Array(n + 1);
302
+ for (let j = 0; j <= n; j++) prev[j] = j;
303
+ for (let i = 1; i <= m; i++) {
304
+ cur[0] = i;
305
+ for (let j = 1; j <= n; j++) {
306
+ const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;
307
+ let min = prev[j] + 1;
308
+ if (cur[j - 1] + 1 < min) min = cur[j - 1] + 1;
309
+ if (prev[j - 1] + cost < min) min = prev[j - 1] + cost;
310
+ cur[j] = min;
311
+ }
312
+ for (let j = 0; j <= n; j++) prev[j] = cur[j];
313
+ }
314
+ return prev[n];
315
+ }
316
+
317
+ /**
318
+ * The closest known config key to `key` within edit distance 2 (case-folded so
319
+ * `preAlloc`/`MAXNODES` resolve), or null when nothing is close. Cold path only.
320
+ * @param {string} key
321
+ * @returns {string|null}
322
+ */
323
+ function suggestKey(key) {
324
+ const lk = key.toLowerCase();
325
+ let best = null;
326
+ let bestD = 3;
327
+ for (let i = 0; i < ALLOWED_KEYS.length; i++) {
328
+ const d = editDistance(lk, ALLOWED_KEYS[i].toLowerCase());
329
+ if (d < bestD) { bestD = d; best = ALLOWED_KEYS[i]; }
330
+ }
331
+ return bestD <= 2 ? best : null;
332
+ }
333
+
334
+ /**
335
+ * Render a rejected value for an error message, e.g. `42 (number)`.
336
+ * Cold: this runs only on a throw path, never on any hot path. `String(symbol)`
337
+ * throws, so symbols are stringified defensively.
338
+ * @param {*} v
339
+ * @returns {string}
340
+ */
341
+ function received(v) {
342
+ return (typeof v === "symbol" ? v.toString() : String(v)) + " (" + typeof v + ")";
343
+ }
344
+
345
+ /**
346
+ * Validate that a numeric option is a finite integer >= 1. Cold: constructor
347
+ * error path only. Throws a {@link TypeError} prefixed `createRegistry: "<name>"`.
348
+ * @param {*} v
349
+ * @param {string} name
350
+ */
351
+ function requirePositiveInt(v, name) {
352
+ if (!Number.isInteger(v) || v < 1) {
353
+ throw new TypeError(
354
+ 'createRegistry: "' + name + '" must be a finite integer >= 1, received ' + received(v) + '.'
355
+ );
356
+ }
357
+ }
358
+
277
359
  export function createRegistry(config) {
278
360
  const NODE_PTR = Symbol("node_ptr");
279
361
  const NODE_GEN = Symbol("node_gen");
280
362
 
363
+ // --- 1.4.5 backport: createRegistry input validation (all cold, constructor-only).
364
+ // Config-shape gate: accept `undefined` or a non-null, non-array object; reject
365
+ // `null`, primitives and arrays BY NAME rather than dying later on `config.maxNodes`
366
+ // or an internal `nextFree` read (fail closed on an unverified state).
367
+ if (config !== undefined && (config === null || typeof config !== "object" || Array.isArray(config))) {
368
+ throw new TypeError(
369
+ 'createRegistry: "config" must be a plain object or undefined, received ' + received(config) + '.'
370
+ );
371
+ }
372
+ if (config !== undefined) {
373
+ // Per-option validation BY NAME -- a bad value throws `createRegistry: "<option>"`
374
+ // at construction, not a delayed internal TypeError on first use.
375
+ if (config.maxNodes !== undefined) requirePositiveInt(config.maxNodes, "maxNodes");
376
+ if (config.maxLinks !== undefined) requirePositiveInt(config.maxLinks, "maxLinks");
377
+ if (config.maxFlushPasses !== undefined) requirePositiveInt(config.maxFlushPasses, "maxFlushPasses");
378
+ if (config.prealloc !== undefined && config.prealloc !== "eager" && config.prealloc !== "lazy") {
379
+ throw new TypeError(
380
+ 'createRegistry: "prealloc" must be "eager" or "lazy", received ' + received(config.prealloc) + '.'
381
+ );
382
+ }
383
+ if (config.onCapacityExceeded !== undefined && config.onCapacityExceeded !== "throw" && config.onCapacityExceeded !== "grow") {
384
+ throw new TypeError(
385
+ 'createRegistry: "onCapacityExceeded" must be "throw" or "grow", received ' + received(config.onCapacityExceeded) + '.'
386
+ );
387
+ }
388
+ // Unknown-key rejection with a did-you-mean hint (`preAlloc` -> `prealloc`,
389
+ // `maxNods` -> `maxNodes`). Own enumerable keys only; cold path.
390
+ const badKeys = Object.keys(config);
391
+ for (let bi = 0; bi < badKeys.length; bi++) {
392
+ const bk = badKeys[bi];
393
+ if (ALLOWED_KEYS.indexOf(bk) === -1) {
394
+ const hint = suggestKey(bk);
395
+ throw new TypeError(
396
+ 'createRegistry: "' + bk + '" is not a recognized option' +
397
+ (hint !== null ? ' (did you mean "' + hint + '"?)' : '') +
398
+ '. Allowed: ' + ALLOWED_KEYS.join(", ") + '.'
399
+ );
400
+ }
401
+ }
402
+ }
403
+ // --- end 1.4.5 backport.
404
+
281
405
  let currentNodesCapacity = (config !== undefined && config.maxNodes !== undefined) ? config.maxNodes : 1024;
282
406
  let currentLinkCapacity = (config !== undefined && config.maxLinks !== undefined) ? config.maxLinks : currentNodesCapacity * 4;
283
407
  const policy = (config !== undefined && config.onCapacityExceeded !== undefined) ? config.onCapacityExceeded : "throw";
@@ -301,6 +425,20 @@ export function createRegistry(config) {
301
425
  // steady state is identical after warm-up, but the heap no longer carries
302
426
  // never-used live objects for every major GC to mark.
303
427
  const prealloc = (config !== undefined && config.prealloc !== undefined) ? config.prealloc : "eager";
428
+ // Eager-construction ceiling (cold): `"eager"` builds `(maxNodes + maxLinks)`
429
+ // objects up front; a finite-but-absurd capacity (e.g. `1e9`) would OOM the
430
+ // process with an uncatchable SIGABRT, not a throw. Refuse BY NAME before
431
+ // allocating. Named for the larger driver. `"lazy"` keeps its unbounded ledger.
432
+ if (prealloc === "eager" && (currentNodesCapacity + currentLinkCapacity) > EAGER_CONSTRUCT_CEILING) {
433
+ const driver = currentLinkCapacity > currentNodesCapacity ? "maxLinks" : "maxNodes";
434
+ throw new TypeError(
435
+ 'createRegistry: "' + driver + '" eager construction of ' +
436
+ (currentNodesCapacity + currentLinkCapacity) + ' objects (maxNodes ' +
437
+ currentNodesCapacity + ' + maxLinks ' + currentLinkCapacity + ') exceeds the ceiling of ' +
438
+ EAGER_CONSTRUCT_CEILING + '. Use prealloc:"lazy" for an unbounded on-demand ledger, ' +
439
+ 'or lower the capacity.'
440
+ );
441
+ }
304
442
  const nodePool = [];
305
443
  let freeNodeHead = null;
306
444
  const linkPool = [];
@@ -1858,6 +1996,12 @@ export function createRegistry(config) {
1858
1996
  pooledLinks: currentLinkCapacity - activeLinks,
1859
1997
  linkPoolCapacity: currentLinkCapacity,
1860
1998
  nodePoolCapacity: currentNodesCapacity,
1999
+ // 1.4.5 backport: TRUE pool population (nodePool.length / linkPool.length),
2000
+ // distinct from the *Capacity ledgers above. Under prealloc:"lazy" (or a
2001
+ // silently-flipped `prealloc` typo) population stays 0 while capacity reads
2002
+ // the ledger -- so a mis-set prealloc is now observable, not telemetry-blind.
2003
+ nodePoolPopulation: nodePool.length,
2004
+ linkPoolPopulation: linkPool.length,
1861
2005
  activeNodes,
1862
2006
  // 1.4: cumulative lifecycle counters (monotonic; reset by destroy()).
1863
2007
  // Derive: allocationRate = deltatotalAllocations/deltat; poolReuseRate =
package/llms.txt CHANGED
@@ -25,7 +25,7 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
25
25
  - **onCleanup**: registers teardown for the current computation; fires before each re-run and once on dispose. Works in effects and computeds.
26
26
  - **Returned cleanup (1.8.0)**: an EFFECT body may `return` a cleanup function (Solid/Vue/Reflex-compatible). Runs at the same points as onCleanup (before each re-run, once on dispose) and is APPENDED after any onCleanup registered in the same body, so the two styles compose in call order. Non-function returns are ignored; a self-disposed body registers nothing (gen-guarded). COMPUTEDS ARE EXCLUDED: a computed returning a function keeps treating it as the VALUE. Cost: one `typeof` per effect run, off the mark/pull path; `executeEffect` is the only body whose sha256 changed 1.7.0 -> 1.8.0.
27
27
  - **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.
28
- - **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
+ - **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. **Config is validated at construction (1.8.0-alpha.7, backported from 1.4.5):** every option is checked BY NAME (the six recognized keys include `flushStrategy`), a bad shape or unknown key throws a `TypeError` prefixed `createRegistry: "<name>"` with a did-you-mean hint, and an absurd eager capacity (`maxNodes:Infinity`/`1e9`) is refused before it can OOM the process. `stats()` gains `nodePoolPopulation` / `linkPoolPopulation` (true constructed-object counts, distinct from the `*Capacity` ledgers) -> **14 keys**.
29
29
  - **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.
30
30
 
31
31
  ## Architecture invariants
@@ -53,7 +53,8 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
53
53
 
54
54
  ## Version notes
55
55
 
56
- - **1.8.0-alpha.4** (current): the **effect-cleanup-return minor**. An EFFECT body
56
+ - **1.8.0-alpha.7** (current): backports the **1.4.5 `createRegistry` input validation** (all four findings) onto the 1.8.0-alpha.6 engine. Only `createRegistry`'s *cold* path moved; hot paths stay byte-identical and `bench/torture/run.mjs` is unchanged at 22/22. Bad config now throws a named `TypeError` (unknown keys get a did-you-mean); an absurd eager capacity is refused before it can OOM the process; `stats()` grows to 14 keys (adds `nodePoolPopulation`/`linkPoolPopulation`, purely additive). New `test/*-config-validation.test.mjs` (matrix + ceiling + population + OOM child processes). See CHANGELOG `[1.8.0-alpha.7]`.
57
+ - **1.8.0-alpha.4**: the **effect-cleanup-return minor**. An EFFECT body
57
58
  may now `return` a cleanup function (Solid/Vue/Reflex-compatible), run at the same
58
59
  points as imperative `onCleanup` -- before each re-run and once on dispose -- and
59
60
  APPENDED after any `onCleanup` from the same body, so both compose in call order.
@@ -65,10 +66,22 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
65
66
  composes with the cleanup-return path; the dead `freeLink` `-1` arms removed) and
66
67
  closes `Signal.js` to **100%** statements/branches/functions/lines. Torture: the
67
68
  `cleanup-return-torture` scenario now **executes** (400 seeds: timing, compose
68
- order, self-dispose guard, computed exclusion), so the 17-scenario runner runs
69
- **13 semantic** + 1 skip (`dispose` 1.9.0). Verified green: torture 17/17; unit
70
- **492 tests, 472 pass, 0 fail, 1 skip** (SSR N/A) -- 491 pass with the sibling
71
- `@zakkster/lite-devtools` the 19-test `test/25` rig needs. Drop-in over 1.7.0.
69
+ order, self-dispose guard, computed exclusion). `alpha.5` brings the bench/torture
70
+ suite to **full parity with the shipped 1.4.4 canon** -- verification-only, engine
71
+ UNCHANGED (`Signal.js` byte-identical): registers the already-present-and-passing
72
+ `owner-torture` and ports four scenarios that run NATIVELY on the 1.8.0 engine
73
+ (`lifecycle-torture` createRoot detachment + destroy reset; `error-torture`
74
+ throwing-effect buffering + AggregateError + buffer drain; `deep-chain-torture`
75
+ pullComputed fail-closed RangeError vs the iterative push path; `zerogc-torture`
76
+ the falsifiable zero-GC gate). So the runner is now **22 scenarios (19 semantic +
77
+ 3 soak)**, of which **18 semantic EXECUTE on the 1.8.0 engine** -- only
78
+ `dispose-torture` (1.9.0 `Symbol.dispose`) still self-skips. `capacity-torture`
79
+ gained section 9 (the 16x grow-link ceiling); the three soaks gained an
80
+ Int32Array value-oracle. New `test/30-throwing-equals.test.mjs` pins all five
81
+ `equals()` invocation sites (3 callable + 2 signalBox boxSet). Verified green:
82
+ torture 22/22; unit (plain `npm test`) **499 tests, 498 pass, 0 fail, 1 skip**
83
+ (the 1 skip is SSR N/A); `npm run test:gc` **507 tests, 506 pass, 0 fail, 1 skip**.
84
+ Drop-in over 1.7.0.
72
85
 
73
86
  - **1.7.0**: the **flush-strategy minor**. `createRegistry({flushStrategy})` gives
74
87
  per-registry control over *when* effects deliver (`"eager"` default | `"sab"` |
@@ -716,7 +729,7 @@ function dumpOwnerTree(handle, depth = 0) {
716
729
  - `bench/benchmark.mjs` -- anti-DCE throughput harness (ops/s; results.txt).
717
730
  - `bench/benchmarkReactive.mjs` -- cross-framework reactivity suite vs alien-signals, preact, vue-reactivity, solid (resultsReactive.txt).
718
731
  - `bench/dispose-recycle.mjs` -- 1.2.2 targeted microbench: create/dispose/recreate cycle (the free-list invariant audit target).
719
- - `bench/torture/` -- the complete **17-scenario superset (14 semantic + 3 soak)** behind one runner (`run.mjs`), two groups, forward-compatible through 1.9. Every scenario feature-detects and SKIPS cleanly below the engine version that introduces its feature, so the whole set is safe on the 1.8.0 engine and stays green from 1.4.x forward. `semantic` (deterministic, fast, asserts on MEANING; CI on every commit) -- the **13 that execute on 1.8.0**: `oracle-fuzzer` (every computed vs an independent uncached reference, 400 seeds x 120 ops), `glitch-hunter` (glitch freedom + exact wakeups), `work-accounting` (minimum body-execution counts over 10 topologies), `op-accounting` (structural work from the `onGraphMutation` opcode lane, not wall-clock), `introspect-torture` (1.6.0: read-only introspection surface -- `describe`/`nodeId`/`hasObservers`/`isTracking`/`forEach*`/`ownerOf`/`observeObservers` -- walk-agreement + the ABA gen-stamp guard), `concurrent-storm` (8 reentrancy / flush-ordering contracts), `scheduler-storm` (gen-bound thunk ABA guard, FLAG_QUEUED coalescing, throwing-scheduler containment), `box-torture` (1.5.0: signalBox/computedBox interop -- the oracle differential fuzz with every node realised as callable OR box), `scope-torture` (1.6.0: `createScope` adoption + disposal-crash fuzz + `runWithOwner` re-attachment), `async-torture` (watch / when / whenAsync contracts + a 300-seed projection-guard storm), `capacity-torture` (the fail-closed pool boundary), `flush-torture` (1.7.0: the three `flushStrategy` modes by cross-strategy differential + per-strategy scheduling + `.subscribe()`), `cleanup-return-torture` (1.8.0: an effect's returned cleanup -- timing at re-run/dispose, compose order appended after `onCleanup`, self-dispose guard, computed exclusion; 400 seeds); plus **1 that skips cleanly** as a later-version feature: `dispose-torture` (1.9.0 `Symbol.dispose`). `soak` (wall-clock bound, asserts on RESOURCES; nightly): `graph-fuzzer`, `scheduler-bench`, `torture-soak` -- exit 0 iff zero errors AND post-teardown pool at or below its leaf-only floor AND the JIT sink advanced. Runner spawns each scenario as a child process (several assert on global pool accounting) and passes `--expose-gc` unconditionally. Scripts: `npm run torture`, `torture:semantic`, `torture:soak`.
732
+ - `bench/torture/` -- the complete **22-scenario superset (19 semantic + 3 soak)** behind one runner (`run.mjs`), two groups, forward-compatible through 1.9. Every scenario feature-detects and SKIPS cleanly below the engine version that introduces its feature, so the whole set is safe on the 1.8.0 engine and stays green from 1.4.x forward. `semantic` (deterministic, fast, asserts on MEANING; CI on every commit) -- the **18 that execute on 1.8.0**: `oracle-fuzzer` (every computed vs an independent uncached reference, 400 seeds x 120 ops), `glitch-hunter` (glitch freedom + exact wakeups), `work-accounting` (minimum body-execution counts over 10 topologies), `op-accounting` (structural work from the `onGraphMutation` opcode lane, not wall-clock), `introspect-torture` (1.6.0: read-only introspection surface -- `describe`/`nodeId`/`hasObservers`/`isTracking`/`forEach*`/`ownerOf`/`observeObservers` -- walk-agreement + the ABA gen-stamp guard), `concurrent-storm` (8 reentrancy / flush-ordering contracts), `scheduler-storm` (gen-bound thunk ABA guard, FLAG_QUEUED coalescing, throwing-scheduler containment), `box-torture` (1.5.0: signalBox/computedBox interop -- the oracle differential fuzz with every node realised as callable OR box), `scope-torture` (1.6.0: `createScope` adoption + disposal-crash fuzz + `runWithOwner` re-attachment), `owner-torture` (1.6.0: `getOwner`/`runWithOwner` capture-restore + ABA degradation), `async-torture` (watch / when / whenAsync contracts + a 300-seed projection-guard storm), `capacity-torture` (the fail-closed pool boundary + `CapacityError` + the 16x grow-link ceiling), `error-torture` (throwing effect bodies: per-effect buffering, exact-order `AggregateError`, buffer drain over 4096 cycles), `deep-chain-torture` (`pullComputed` recursion fail-closed with a `RangeError` vs the heap-iterative push path), `flush-torture` (1.7.0: the three `flushStrategy` modes by cross-strategy differential + per-strategy scheduling + `.subscribe()`), `cleanup-return-torture` (1.8.0: an effect's returned cleanup -- timing at re-run/dispose, compose order appended after `onCleanup`, self-dispose guard, computed exclusion; 400 seeds), `zerogc-torture` (the falsifiable zero-GC gate: `measureAllocs`/`measureOps` + `stats()` counters, `ZEROGC_BREAK` self-test), `lifecycle-torture` (`createRoot` detachment + `destroy` registry reset); plus **1 that skips cleanly** as a later-version feature: `dispose-torture` (1.9.0 `Symbol.dispose`). `soak` (wall-clock bound, asserts on RESOURCES; nightly): `graph-fuzzer`, `scheduler-bench`, `torture-soak` -- each now carries an Int32Array value-oracle (a fixed shadow window over the writable signals, allocated once, zero per-tick alloc, full sweep at teardown) so a wrong value fails the run, not just a crash; exit 0 iff zero errors AND post-teardown pool at or below its leaf-only floor AND the value-oracle matched AND the JIT sink advanced. Runner spawns each scenario as a child process (several assert on global pool accounting) and passes `--expose-gc` unconditionally. Scripts: `npm run torture`, `torture:semantic`, `torture:soak`.
720
733
  - `bench/run-all.sh` + `bench/aggregate.mjs` -- cold-process-per-engine protocol + per-scenario aggregation.
721
734
  - `harness/run.mjs` -- dispatcher for the run-on-demand probes (smoke, field, dispose, churn, owner, creation, perf, burst, pull, toe, all).
722
735
  - `harness/smoke.mjs` -- 1.7 flushStrategy semantics (eager/sab/manual) + `flush()`, and the 1.8 effect-cleanup-return contract (fires before re-run + on dispose, composes with onCleanup in call order, non-function returns ignored, computed-returning-a-function still yields the VALUE). ASSERTS, so it fails loudly on a regression. First in `harness:all` and `verify`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zakkster/lite-signal",
3
- "version": "1.8.0-alpha.5",
3
+ "version": "1.8.0-alpha.7",
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",
@@ -86,6 +86,7 @@
86
86
  "sideEffects": false,
87
87
  "devDependencies": {
88
88
  "@zakkster/lite-devtools": "^1.2.0",
89
+ "@zakkster/lite-gc-profiler": "^1.15.0",
89
90
  "@zakkster/lite-profiler": "^1.1.0",
90
91
  "@zakkster/lite-profiler-signal": "^1.2.0",
91
92
  "@zakkster/lite-signal": "^1.3.0 || >=1.4.0-beta.0 || >=1.6.0-preview.0",