@zakkster/lite-signal 1.7.0-alpha.4 → 1.7.0-alpha.6

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,118 @@ 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.7.0-alpha.6] -- 2026-08-20
8
+
9
+ Backports the **1.4.5 `createRegistry` input validation** (all four findings) onto
10
+ the 1.7.0-alpha.5 engine. Supersedes 1.7.0-alpha.5. 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.7.0-alpha.4] -- 2026-08-18
49
+
50
+ **Torture-suite and test parity with the shipped 1.4.4 canonical suite.** This is
51
+ a **verification-only** cut: `Signal.js` and `Signal.d.ts` are **UNCHANGED**
52
+ (shasum-identical to alpha.3). Nothing in the engine, the public surface, or the
53
+ runtime behaviour moved. Every number below was verified against the real 1.7.0
54
+ engine and pins its ACTUAL behaviour -- no assertion was softened, no budget
55
+ widened.
56
+
57
+ ### Added -- five torture scenarios ported to full 1.4.4 parity (17 -> 22)
58
+
59
+ `bench/torture/` now carries the complete **22-scenario superset (19 semantic +
60
+ 3 soak)**. The five ported scenarios all target primitives 1.7.0 already ships,
61
+ so they **run natively -- no SKIP**:
62
+
63
+ - `lifecycle-torture` -- `createRoot` detachment (detached children survive and
64
+ stay reactive, deps isolated) + `destroy` registry reset (stales every handle,
65
+ returns `stats().activeNodes` to 0). Both halves native.
66
+ - `owner-torture` -- `getOwner` / `runWithOwner` capture-restore via `createScope`:
67
+ live-owner adoption cascade-disposes, a STALE handle degrades to ROOTED, deps
68
+ stay isolated, plus a 300-seed capture/dispose/recycle/restore fuzz. Native.
69
+ - `error-torture` -- throwing effect bodies under flush: a single throw re-thrown
70
+ UNWRAPPED, 2+ aggregated into an `AggregateError` carrying EXACTLY those errors,
71
+ a survivor between two throwers still runs, and the error buffer drains flat
72
+ (`activeNodes`/`activeLinks` unchanged) over 4096 throw/clean cycles.
73
+ - `deep-chain-torture` -- `pullComputed` recursion fails CLOSED with a `RangeError`
74
+ beyond the stack budget (ramp 2000/2000/100000, depth never pinned) while the
75
+ iterative push path stays open; the registry that threw stays usable and the
76
+ re-throw is deterministic.
77
+ - `zerogc-torture` -- the zero-GC claim made falsifiable via `@zakkster/lite-gc-profiler`:
78
+ `measureAllocs`/`checkAllocs` at `maxBytesPerCall: 0` + `measureOps`/`checkNoGc`
79
+ at `maxMajor: 0` / `maxPauseMs: 2` + engine `stats()` deltas across steady and
80
+ create/dispose churn, with the `churn-box` signalBox path active on 1.7.0 and a
81
+ `ZEROGC_BREAK=1` self-test that must fail the gate.
82
+
83
+ `run.mjs` registers all five in the 1.4.4 order (owner after scope; error +
84
+ deep-chain after capacity; zerogc after dispose; lifecycle after introspect).
85
+ `node bench/torture/run.mjs --list` -> 22.
86
+
87
+ ### Added -- `test/30-throwing-equals.test.mjs`
88
+
89
+ Pins the behaviour of a user `equals` predicate that THROWS at all five engine
90
+ sites: the three callable sites (signal `set` pre-check, batch-revert check,
91
+ computed re-eval) and signalBox `boxSet`'s two (pre-check, revert). Includes the
92
+ CONTRAST anti-tautology test (a clean set-X-then-back suppresses the re-run,
93
+ proving the throw is the cause) plus the a-box / b-box cases.
94
+
95
+ ### Changed -- capacity section 9, tighter introspection, soak value-oracles
96
+
97
+ - `capacity-torture` gains section 9: the 16x link-grow ceiling (`maxLinks * 16`),
98
+ pinning `err.kind === "links"`, `err.capacity === maxLinks * 16`, growth
99
+ terminating AT the ceiling, and a fail-closed re-throw. Sections 1-8 untouched.
100
+ - `introspect-torture`'s `forEachOwned` assertion tightened from `>= 2` to
101
+ EXACTLY 2 owned children (deterministic count).
102
+ - The three soaks (`graph-fuzzer`, `scheduler-bench`, `torture-soak`) gained a
103
+ once-allocated `Int32Array` shadow value-oracle -- a rotating fixed window per
104
+ tick with zero per-tick allocation and a full sweep at teardown; a mismatch
105
+ exits 1 with seed + index. The reachable magic-constant JIT sink was replaced
106
+ with a module-scoped int32 sink read under an `if (ops > 0 && sink === 0)`
107
+ teardown guard.
108
+
109
+ ### Dev dependency
110
+
111
+ `@zakkster/lite-gc-profiler` (`^1.15.0`) added as a **dev-only** dependency for
112
+ `zerogc-torture`. `dependencies` stays empty; `package.json` `files[]` still
113
+ excludes `bench/`.
114
+
115
+ Verified green: torture **22/22** (20 execute + 2 later-version skips --
116
+ `cleanup-return-torture` 1.8.0, `dispose-torture` 1.9.0); unit **490 tests, 489
117
+ pass, 0 fail, 1 skip** (SSR N/A).
118
+
7
119
  ## [1.7.0-alpha.3] -- 2026-07-27
8
120
 
9
121
  Rolls up the post-`1.7.0-alpha.0` changes into the `alpha.3` tag. The
package/README.md CHANGED
@@ -841,7 +841,7 @@ npm run bench
841
841
 
842
842
  ## Testing strategy
843
843
 
844
- Four tiers, all reproducible. The full suite is **485 tests across 29 files**: 484 pass, 1 skipped (the architecturally-N/A SSR case in `17-reactivity` -- lite has no DOM layer), 0 failing. Plain `npm test` runs **477** of them; **8 are gated on `--expose-gc`** (3 in `04-zero-gc`, 4 in `09-conformance`, 1 in `11-adopted-reactive`) and need `npm run test:gc` or `npm run test:coverage`. Engine coverage under `c8` is **100% statements / 100% functions / 100% lines / 100% branches**; the two residual branch arms are provably unreachable defensive code carrying `/* c8 ignore */`, itemised at the end of this section.
844
+ Four tiers, all reproducible. The full suite is **498 tests across 30 files**: 497 pass, 1 skipped (the architecturally-N/A SSR case in `17-reactivity` -- lite has no DOM layer), 0 failing. Plain `npm test` runs **490** of them; **8 are gated on `--expose-gc`** (3 in `04-zero-gc`, 4 in `09-conformance`, 1 in `11-adopted-reactive`) and need `npm run test:gc` or `npm run test:coverage`. Engine coverage under `c8` is **100% statements / 100% functions / 100% lines / 100% branches**; the two residual branch arms are provably unreachable defensive code carrying `/* c8 ignore */`, itemised at the end of this section.
845
845
 
846
846
  ### Tier 1 -- Behavior (unit tests, fast)
847
847
 
@@ -875,13 +875,14 @@ Four tiers, all reproducible. The full suite is **485 tests across 29 files**: 4
875
875
  - **`27-create-root.test.mjs`** (7) -- `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. Includes the top-level-export binding case.
876
876
  - **`28-run-with-owner.test.mjs`** (16) -- `getOwner` / `runWithOwner` (1.7.0). 7 basic-shape 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). 3 degradation tests (`null` / `undefined` / a signal handle all fall through to rooted execution). 3 **hazard pins**, run with allocation pressure applied so the ABA guard is genuinely exercised: **recycled-slot cascade** (a stale handle must not adopt into the recycled slot's new resident), **corpse adoption** (adopting into a dead-but-unrecycled owner must not send the next disposal walk into unbounded recursion), and the two composed. Both hazards fail against a raw-pointer sketch and pass on the shipped gen-guarded implementation.
877
877
  - **`29-scope.test.mjs`** (4) -- `createScope` (1.6.0), the adopting counterpart to `createRoot`. 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; and `totalAllocations - totalDisposals === activeNodes` holds across the entire lifecycle.
878
+ - **`30-throwing-equals.test.mjs`** (9) -- a user `equals` predicate that THROWS, 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 -- not an atomic rollback the engine never provided), with a CONTRAST anti-tautology test proving a clean set-X-then-back suppresses the re-run so the throw is the demonstrated cause; a computed re-eval throw is cached as an error and re-thrown until a dep change re-evaluates cleanly. The box cases (`a-box`/`b-box`) confirm `boxSet` behaves identically to `read.set`.
878
879
 
879
880
  > **Known housekeeping:** `28-run-with-owner` and `29-scope` share the numeric prefix `28`. Both files are live and both run; one of them should be renumbered to `29-` on the next touch.
880
881
 
881
882
  ```bash
882
- npm test # 476 tests, 29 files, ~5s (8 gc-gated tests skipped)
883
- npm run test:gc # all 484 -- adds --expose-gc
884
- npm run test:coverage # all 484 under c8
883
+ npm test # 490 tests, 30 files, ~5s (8 gc-gated tests skipped)
884
+ npm run test:gc # all 498 (497 pass) -- adds --expose-gc
885
+ npm run test:coverage # all 498 under c8
885
886
  ```
886
887
 
887
888
  **Coverage (`c8`, engine files only):**
@@ -927,15 +928,16 @@ npm run bench
927
928
 
928
929
  ### Tier 4 -- Torture (correctness and resources under chaos)
929
930
 
930
- `bench/torture/` holds the complete **17-scenario superset (14 semantic + 3
931
- soak)** behind one runner (`run.mjs`), the forward-compatible set through 1.9.
931
+ `bench/torture/` holds the complete **22-scenario superset (19 semantic + 3
932
+ soak)** -- at full parity with the shipped 1.4.4 canonical suite -- behind one
933
+ runner (`run.mjs`), the forward-compatible set through 1.9.
932
934
  They are not perf benchmarks: the ops/sec figures reflect random workload
933
935
  composition, not engine throughput -- `bench/benchmark.mjs` remains the canonical
934
936
  perf harness. Every scenario feature-detects and **skips cleanly** below the
935
937
  engine version that introduces its feature, so on the 1.7.0 engine the runner
936
- executes **12 semantic** scenarios (including `flush-torture`) and reports a clean
937
- SKIP for the two later-version ones (`cleanup-return-torture` 1.8.0,
938
- `dispose-torture` 1.9.0).
938
+ executes **20 of the 22** (17 semantic + 3 soak, including `flush-torture` and the
939
+ four lifecycle scenarios that run natively) and reports a clean SKIP for the two
940
+ later-version ones (`cleanup-return-torture` 1.8.0, `dispose-torture` 1.9.0).
939
941
 
940
942
  ```bash
941
943
  npm run torture # everything
@@ -946,10 +948,11 @@ node bench/torture/run.mjs --list
946
948
 
947
949
  #### `semantic` -- deterministic, fast, asserts on **meaning**
948
950
 
949
- Run these on every commit. The nine untagged scenarios run on any 1.4.x+ engine;
950
- `box-torture` (1.5.0), `scope-torture` (1.6.0), and `flush-torture` (1.7.0) run
951
- here because their features exist; the two tagged `1.8.0+`/`1.9.0+` feature-detect
952
- and SKIP on this engine.
951
+ Run these on every commit. The untagged scenarios run on any 1.4.x+ engine;
952
+ `box-torture` (1.5.0), `lifecycle-torture` (1.5.0), `scope-torture` (1.6.0),
953
+ `owner-torture` (1.6.0), and `flush-torture` (1.7.0) run here because their
954
+ features exist; the two tagged `1.8.0+`/`1.9.0+` feature-detect and SKIP on this
955
+ engine.
953
956
 
954
957
  | scenario | pins |
955
958
  | -------- | ---- |
@@ -962,9 +965,14 @@ and SKIP on this engine.
962
965
  | `scheduler-storm` | deferred execution under 10,000 effects: gen-bound thunk ABA guard, `FLAG_QUEUED` coalescing, a throwing scheduler contained |
963
966
  | `box-torture` (1.5.0) | `signalBox`/`computedBox` interop: the oracle differential fuzz with every node realised as **either** a callable or a box |
964
967
  | `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 |
968
+ | `owner-torture` (1.6.0) | `getOwner`/`runWithOwner` capture-restore: live-owner adoption cascade-disposes, a STALE handle degrades to ROOTED, dep-isolation holds, + a 300-seed capture/dispose/recycle/restore fuzz |
965
969
  | `async-torture` | `watch`/`when`/`whenAsync` contracts + a 300-seed projection-guard storm |
966
- | `capacity-torture` | the fail-closed pool boundary: exact ceilings, re-throw-on-read, `grow` crossing the same boundary |
970
+ | `capacity-torture` | the fail-closed pool boundary: exact ceilings, re-throw-on-read, `grow` crossing the same boundary, and the `maxLinks * 16` grow ceiling terminating AT the wall |
971
+ | `error-torture` | throwing effect bodies under flush: a single throw re-thrown UNWRAPPED, 2+ into an `AggregateError` carrying EXACTLY those errors, a survivor still runs, buffer drains flat over 4096 throw/clean cycles |
972
+ | `deep-chain-torture` | `pullComputed` recursion fails CLOSED with a `RangeError` beyond the stack budget while the iterative push path stays open; the registry stays usable, the re-throw is deterministic |
967
973
  | `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 |
974
+ | `zerogc-torture` | the zero-GC claim made falsifiable via `@zakkster/lite-gc-profiler`: `measureAllocs`/`checkAllocs` at `maxBytesPerCall: 0` + `measureOps`/`checkNoGc` at `maxMajor: 0`/`maxPauseMs: 2` + engine `stats()` deltas across steady + churn, `churn-box` active, `ZEROGC_BREAK=1` self-test |
975
+ | `lifecycle-torture` (1.5.0) | `createRoot` detachment (children survive, deps isolated) + `destroy` registry reset (stales every handle, returns `stats().activeNodes` to 0) |
968
976
  | `cleanup-return-torture` (1.8.0+) | an effect's returned cleanup: timing, compose order, self-dispose guard -- SKIP on 1.7.0 |
969
977
  | `dispose-torture` (1.9.0+) | `Symbol.dispose` / `using` on lifecycle objects -- SKIP on 1.7.0 |
970
978
 
@@ -976,8 +984,10 @@ effect rewires, nested-batch + untrack reads, and microtask-scheduled async
976
984
  flushes -- for 5-10 seconds. What they assert, with a non-zero exit code on
977
985
  failure:
978
986
 
979
- - zero thrown exceptions during the run, and
980
- - after teardown, `activeNodes` / `activeLinks` return to the leaf-only baseline (the dispose path is sound under sustained churn).
987
+ - zero thrown exceptions during the run,
988
+ - after teardown, `activeNodes` / `activeLinks` return to the leaf-only baseline (the dispose path is sound under sustained churn),
989
+ - **value-correctness** via a once-allocated `Int32Array` shadow oracle -- a rotating fixed window checked per tick (zero per-tick allocation, a scalar cursor) plus a full sweep at teardown; a mismatch exits 1 with the seed and index, and
990
+ - the module-scoped int32 JIT sink advanced (an `if (ops > 0 && sink === 0)` teardown guard proves the work loops were not optimised away).
981
991
 
982
992
  ```bash
983
993
  node --expose-gc bench/torture/graph-fuzzer.mjs # 10s random-DAG fuzz, 1500 nodes
package/Signal.d.ts CHANGED
@@ -122,6 +122,16 @@ export interface RegistryStats {
122
122
  /** Node-pool capacity ledger. Doubles under the `"grow"` policy; under `"lazy"`
123
123
  * prealloc it may exceed the count of physically constructed nodes. */
124
124
  nodePoolCapacity: number;
125
+ /** TRUE node-pool population: the number of `ReactiveNode`s physically constructed
126
+ * (`nodePool.length`), distinct from the `nodePoolCapacity` ledger. Under
127
+ * `prealloc:"lazy"` (or a silently-flipped `prealloc` typo) this stays 0 until
128
+ * first demand while capacity reads the ledger -- so a mis-set `prealloc` is
129
+ * observable here rather than telemetry-blind. Added in the 1.4.5 backport. */
130
+ nodePoolPopulation: number;
131
+ /** TRUE link-pool population: the number of `ReactiveLink`s physically constructed
132
+ * (`linkPool.length`), distinct from the `linkPoolCapacity` ledger. Added in the
133
+ * 1.4.5 backport. */
134
+ linkPoolPopulation: number;
125
135
  /** Number of nodes currently allocated (signals + computeds + alive effects). */
126
136
  activeNodes: number;
127
137
  /**
package/Signal.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @zakkster/lite-signal v1.7.0-alpha.3
2
+ * @zakkster/lite-signal v1.7.0-alpha.6
3
3
  * --------------------
4
4
  * 1.7.0 -- flushStrategy: registry-level effect-delivery policy.
5
5
  *
@@ -237,10 +237,134 @@ export class CapacityError extends Error {
237
237
  * Error prefixed `"CycleError:"`.
238
238
  * @returns {Registry}
239
239
  */
240
+ /** The only config keys {@link createRegistry} recognizes. Anything else is
241
+ * rejected at construction with a did-you-mean hint (fail closed on an
242
+ * unverified state -- an unknown key is an error, never a silent ignore). */
243
+ const ALLOWED_KEYS = ["maxNodes", "maxLinks", "prealloc", "onCapacityExceeded", "maxFlushPasses", "flushStrategy"];
244
+
245
+ /** Ceiling on eager pool construction: `(maxNodes + maxLinks)` objects. A finite
246
+ * but absurd `maxNodes` (e.g. `1e9`, a plausible typo for `1e5`) that would
247
+ * otherwise OOM the process is refused BY NAME at construction rather than
248
+ * allocating forever. Only the `"eager"` path is bounded; `"lazy"` keeps its
249
+ * unbounded ledger. `1 << 24` == 16777216. */
250
+ const EAGER_CONSTRUCT_CEILING = 1 << 24;
251
+
252
+ /**
253
+ * Levenshtein edit distance between two short strings. Cold: called only on the
254
+ * constructor error path, over the known option names, so its per-call array
255
+ * allocation never touches any hot path.
256
+ * @param {string} a
257
+ * @param {string} b
258
+ * @returns {number}
259
+ */
260
+ function editDistance(a, b) {
261
+ const m = a.length;
262
+ const n = b.length;
263
+ const prev = new Array(n + 1);
264
+ const cur = new Array(n + 1);
265
+ for (let j = 0; j <= n; j++) prev[j] = j;
266
+ for (let i = 1; i <= m; i++) {
267
+ cur[0] = i;
268
+ for (let j = 1; j <= n; j++) {
269
+ const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;
270
+ let min = prev[j] + 1;
271
+ if (cur[j - 1] + 1 < min) min = cur[j - 1] + 1;
272
+ if (prev[j - 1] + cost < min) min = prev[j - 1] + cost;
273
+ cur[j] = min;
274
+ }
275
+ for (let j = 0; j <= n; j++) prev[j] = cur[j];
276
+ }
277
+ return prev[n];
278
+ }
279
+
280
+ /**
281
+ * The closest known config key to `key` within edit distance 2 (case-folded so
282
+ * `preAlloc`/`MAXNODES` resolve), or null when nothing is close. Cold path only.
283
+ * @param {string} key
284
+ * @returns {string|null}
285
+ */
286
+ function suggestKey(key) {
287
+ const lk = key.toLowerCase();
288
+ let best = null;
289
+ let bestD = 3;
290
+ for (let i = 0; i < ALLOWED_KEYS.length; i++) {
291
+ const d = editDistance(lk, ALLOWED_KEYS[i].toLowerCase());
292
+ if (d < bestD) { bestD = d; best = ALLOWED_KEYS[i]; }
293
+ }
294
+ return bestD <= 2 ? best : null;
295
+ }
296
+
297
+ /**
298
+ * Render a rejected value for an error message, e.g. `42 (number)`.
299
+ * Cold: this runs only on a throw path, never on any hot path. `String(symbol)`
300
+ * throws, so symbols are stringified defensively.
301
+ * @param {*} v
302
+ * @returns {string}
303
+ */
304
+ function received(v) {
305
+ return (typeof v === "symbol" ? v.toString() : String(v)) + " (" + typeof v + ")";
306
+ }
307
+
308
+ /**
309
+ * Validate that a numeric option is a finite integer >= 1. Cold: constructor
310
+ * error path only. Throws a {@link TypeError} prefixed `createRegistry: "<name>"`.
311
+ * @param {*} v
312
+ * @param {string} name
313
+ */
314
+ function requirePositiveInt(v, name) {
315
+ if (!Number.isInteger(v) || v < 1) {
316
+ throw new TypeError(
317
+ 'createRegistry: "' + name + '" must be a finite integer >= 1, received ' + received(v) + '.'
318
+ );
319
+ }
320
+ }
321
+
240
322
  export function createRegistry(config) {
241
323
  const NODE_PTR = Symbol("node_ptr");
242
324
  const NODE_GEN = Symbol("node_gen");
243
325
 
326
+ // --- 1.4.5 backport: createRegistry input validation (all cold, constructor-only).
327
+ // Config-shape gate: accept `undefined` or a non-null, non-array object; reject
328
+ // `null`, primitives and arrays BY NAME rather than dying later on `config.maxNodes`
329
+ // or an internal `nextFree` read (fail closed on an unverified state).
330
+ if (config !== undefined && (config === null || typeof config !== "object" || Array.isArray(config))) {
331
+ throw new TypeError(
332
+ 'createRegistry: "config" must be a plain object or undefined, received ' + received(config) + '.'
333
+ );
334
+ }
335
+ if (config !== undefined) {
336
+ // Per-option validation BY NAME -- a bad value throws `createRegistry: "<option>"`
337
+ // at construction, not a delayed internal TypeError on first use.
338
+ if (config.maxNodes !== undefined) requirePositiveInt(config.maxNodes, "maxNodes");
339
+ if (config.maxLinks !== undefined) requirePositiveInt(config.maxLinks, "maxLinks");
340
+ if (config.maxFlushPasses !== undefined) requirePositiveInt(config.maxFlushPasses, "maxFlushPasses");
341
+ if (config.prealloc !== undefined && config.prealloc !== "eager" && config.prealloc !== "lazy") {
342
+ throw new TypeError(
343
+ 'createRegistry: "prealloc" must be "eager" or "lazy", received ' + received(config.prealloc) + '.'
344
+ );
345
+ }
346
+ if (config.onCapacityExceeded !== undefined && config.onCapacityExceeded !== "throw" && config.onCapacityExceeded !== "grow") {
347
+ throw new TypeError(
348
+ 'createRegistry: "onCapacityExceeded" must be "throw" or "grow", received ' + received(config.onCapacityExceeded) + '.'
349
+ );
350
+ }
351
+ // Unknown-key rejection with a did-you-mean hint (`preAlloc` -> `prealloc`,
352
+ // `maxNods` -> `maxNodes`). Own enumerable keys only; cold path.
353
+ const badKeys = Object.keys(config);
354
+ for (let bi = 0; bi < badKeys.length; bi++) {
355
+ const bk = badKeys[bi];
356
+ if (ALLOWED_KEYS.indexOf(bk) === -1) {
357
+ const hint = suggestKey(bk);
358
+ throw new TypeError(
359
+ 'createRegistry: "' + bk + '" is not a recognized option' +
360
+ (hint !== null ? ' (did you mean "' + hint + '"?)' : '') +
361
+ '. Allowed: ' + ALLOWED_KEYS.join(", ") + '.'
362
+ );
363
+ }
364
+ }
365
+ }
366
+ // --- end 1.4.5 backport.
367
+
244
368
  let currentNodesCapacity = (config !== undefined && config.maxNodes !== undefined) ? config.maxNodes : 1024;
245
369
  let currentLinkCapacity = (config !== undefined && config.maxLinks !== undefined) ? config.maxLinks : currentNodesCapacity * 4;
246
370
  const policy = (config !== undefined && config.onCapacityExceeded !== undefined) ? config.onCapacityExceeded : "throw";
@@ -264,6 +388,20 @@ export function createRegistry(config) {
264
388
  // steady state is identical after warm-up, but the heap no longer carries
265
389
  // never-used live objects for every major GC to mark.
266
390
  const prealloc = (config !== undefined && config.prealloc !== undefined) ? config.prealloc : "eager";
391
+ // Eager-construction ceiling (cold): `"eager"` builds `(maxNodes + maxLinks)`
392
+ // objects up front; a finite-but-absurd capacity (e.g. `1e9`) would OOM the
393
+ // process with an uncatchable SIGABRT, not a throw. Refuse BY NAME before
394
+ // allocating. Named for the larger driver. `"lazy"` keeps its unbounded ledger.
395
+ if (prealloc === "eager" && (currentNodesCapacity + currentLinkCapacity) > EAGER_CONSTRUCT_CEILING) {
396
+ const driver = currentLinkCapacity > currentNodesCapacity ? "maxLinks" : "maxNodes";
397
+ throw new TypeError(
398
+ 'createRegistry: "' + driver + '" eager construction of ' +
399
+ (currentNodesCapacity + currentLinkCapacity) + ' objects (maxNodes ' +
400
+ currentNodesCapacity + ' + maxLinks ' + currentLinkCapacity + ') exceeds the ceiling of ' +
401
+ EAGER_CONSTRUCT_CEILING + '. Use prealloc:"lazy" for an unbounded on-demand ledger, ' +
402
+ 'or lower the capacity.'
403
+ );
404
+ }
267
405
  const nodePool = [];
268
406
  let freeNodeHead = null;
269
407
  const linkPool = [];
@@ -1801,6 +1939,12 @@ export function createRegistry(config) {
1801
1939
  pooledLinks: currentLinkCapacity - activeLinks,
1802
1940
  linkPoolCapacity: currentLinkCapacity,
1803
1941
  nodePoolCapacity: currentNodesCapacity,
1942
+ // 1.4.5 backport: TRUE pool population (nodePool.length / linkPool.length),
1943
+ // distinct from the *Capacity ledgers above. Under prealloc:"lazy" (or a
1944
+ // silently-flipped `prealloc` typo) population stays 0 while capacity reads
1945
+ // the ledger -- so a mis-set prealloc is now observable, not telemetry-blind.
1946
+ nodePoolPopulation: nodePool.length,
1947
+ linkPoolPopulation: linkPool.length,
1804
1948
  activeNodes,
1805
1949
  // 1.4: cumulative lifecycle counters (monotonic; reset by destroy()).
1806
1950
  // Derive: allocationRate = deltatotalAllocations/deltat; poolReuseRate =
package/llms.txt CHANGED
@@ -31,7 +31,7 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
31
31
  - **isTracking**: `isTracking()` returns true iff a read right now would record a dependency on this registry (for wrappers that lazily allocate signals).
32
32
  - **onCleanup**: registers teardown for the current computation; fires before each re-run and once on dispose. Works in effects and computeds.
33
33
  - **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.
34
- - **Registry**: `createRegistry({ maxNodes, maxLinks, prealloc, onCapacityExceeded, maxFlushPasses, flushStrategy })` 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. `flushStrategy` (1.7.0; `"eager"` default | `"sab"` | `"manual"`) chooses when effects deliver; every registry also exposes `r.flush()`.
34
+ - **Registry**: `createRegistry({ maxNodes, maxLinks, prealloc, onCapacityExceeded, maxFlushPasses, flushStrategy })` 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. `flushStrategy` (1.7.0; `"eager"` default | `"sab"` | `"manual"`) chooses when effects deliver; every registry also exposes `r.flush()`. **Config is validated at construction (1.7.0-alpha.6, 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**.
35
35
  - **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.
36
36
 
37
37
  ## Architecture invariants
@@ -59,17 +59,32 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
59
59
 
60
60
  ## Version notes
61
61
 
62
- - **1.7.0-alpha.3** (current): the **flush-strategy minor**. Two engine additions and
62
+ - **1.7.0-alpha.6** (current): backports the **1.4.5 `createRegistry` input validation** (all four findings) onto the 1.7.0-alpha.5 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.7.0-alpha.6]`.
63
+ - **1.7.0-alpha.4**: **torture-suite + test parity with the shipped 1.4.4
64
+ canonical suite** -- verification-only, the `Signal.js`/`Signal.d.ts` engine is
65
+ UNCHANGED (shasum-identical). Five scenarios were ported to bring `bench/torture/`
66
+ from 17 to **22** (19 semantic + 3 soak): `lifecycle-torture`, `owner-torture`,
67
+ `error-torture`, `deep-chain-torture`, `zerogc-torture` -- all four lifecycle
68
+ scenarios (`createRoot`, `createScope`, `getOwner`/`runWithOwner`, `destroy`) and
69
+ the flush scenario RUN NATIVELY on this engine, no SKIP; each was VERIFIED and
70
+ pins 1.7.0's actual behaviour, no assertion softened. `capacity-torture` gained a
71
+ section 9 pinning the 16x link-grow ceiling; `introspect-torture`'s `forEachOwned`
72
+ was tightened to assert EXACTLY 2 owned children; the three soaks (`graph-fuzzer`,
73
+ `scheduler-bench`, `torture-soak`) gained a once-allocated `Int32Array` shadow
74
+ value-oracle (zero per-tick allocation, full sweep at teardown) plus the int32 JIT
75
+ sink guard. A new `test/30-throwing-equals.test.mjs` pins all five engine `equals`
76
+ sites (3 callable + signalBox boxSet's 2). `@zakkster/lite-gc-profiler` is a
77
+ dev-only dependency for `zerogc-torture`; `files[]` still excludes `bench/`.
78
+ Verified green: torture **22/22** (20 execute + 2 later-version skips);
79
+ unit **490 tests, 489 pass, 0 fail, 1 skip** (SSR N/A).
80
+ - **1.7.0-alpha.3**: the **flush-strategy minor**. Two engine additions and
63
81
  one large tooling correction (all shipped in alpha.0, below); `alpha.3` rolls up
64
82
  the dangling-cursor crash fix (a one-line `disposeNode` cursor repair; the
65
83
  `freeLink` `-1` fallbacks it made dead were removed and branch coverage on
66
- `Signal.js` closed to **100%**), `flush-torture` now executing on this engine
67
- (so the runner runs **12 semantic** + 2 skip -- `cleanup-return` 1.8.0,
68
- `dispose` 1.9.0 -- of the 17-scenario suite), and the removal of a byte-identical
84
+ `Signal.js` closed to **100%**), `flush-torture` now executing on this engine,
85
+ and the removal of a byte-identical
69
86
  duplicate `test/28-scope.test.mjs` (the scope suite had been running twice; the
70
- correctly-numbered `29-scope.test.mjs` remains). Verified green: torture 17/17;
71
- unit **485 tests, 465 pass, 0 fail, 1 skip** (SSR N/A) -- 484 pass with the
72
- sibling `@zakkster/lite-devtools` the 19-test `test/25` rig needs.
87
+ correctly-numbered `29-scope.test.mjs` remains).
73
88
 
74
89
  **1) `flushStrategy` + `r.flush()`** -- per-registry control over *when* effects
75
90
  deliver (`"eager"` default | `"sab"` | `"manual"`), plus an explicit `flush()` on
@@ -780,7 +795,7 @@ function dumpOwnerTree(handle, depth = 0) {
780
795
  - `bench/benchmark.mjs` -- anti-DCE throughput harness (ops/s; results.txt).
781
796
  - `bench/mirror.mjs` + `bench/sweep.mjs` -- Andrii's canonical adapter verbatim, cross-framework rows diffing 1:1 against his log; aggregate output `rb.txt` (lite vs alien across 47 shapes, isolated-per-row).
782
797
  - `bench/dispose-recycle.mjs` -- 1.2.2 targeted microbench: create/dispose/recreate cycle (the free-list invariant audit target).
783
- - `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.7.0 engine and stays green from 1.4.x forward. `semantic` (deterministic, fast, asserts on MEANING; CI on every commit) -- the **12 that execute on 1.7.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 -- same graph + op sequence under eager/sab/manual reaching identical settled values -- plus per-strategy scheduling, re-entrant/empty `flush()`, and the `.subscribe()` contract under each); plus **2 that skip cleanly** as later-version features: `cleanup-return-torture` (1.8.0 effect-return cleanup), `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`.
798
+ - `bench/torture/` -- the complete **22-scenario superset (19 semantic + 3 soak)** at FULL PARITY with the shipped 1.4.4 canonical suite, 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.7.0 engine and stays green from 1.4.x forward. On the 1.7.0 engine **20 of the 22 execute** (17 semantic + 3 soak) and **2 skip cleanly** as later-version features. `semantic` (deterministic, fast, asserts on MEANING; CI on every commit) -- the **17 that execute on 1.7.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, `forEachOwned` pinned to EXACTLY 2 owned children), `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 -- live-owner adoption cascade-disposes, a STALE handle degrades to ROOTED, dep-isolation holds, plus a 300-seed capture/dispose/recycle/restore fuzz; native on 1.7.0), `async-torture` (watch / when / whenAsync contracts + a 300-seed projection-guard storm), `capacity-torture` (the fail-closed pool boundary + `CapacityError` + the 16x link-grow ceiling, growth terminating AT `maxLinks * 16` with a fail-closed re-throw), `error-torture` (throwing effect bodies under flush -- a single throw re-thrown UNWRAPPED, 2+ aggregated into an `AggregateError` carrying EXACTLY those errors, a survivor between two throwers still runs, and the error buffer drains flat over 4096 throw/clean cycles), `deep-chain-torture` (`pullComputed` recursion fails CLOSED with a RangeError beyond the stack budget while the iterative push path stays open; the registry that threw stays usable and the re-throw is deterministic), `flush-torture` (1.7.0: the three `flushStrategy` modes by cross-strategy differential -- same graph + op sequence under eager/sab/manual reaching identical settled values -- plus per-strategy scheduling, re-entrant/empty `flush()`, and the `.subscribe()` contract under each), `zerogc-torture` (the zero-GC claim made falsifiable via `@zakkster/lite-gc-profiler`: `measureAllocs`/`checkAllocs` at `maxBytesPerCall: 0` + `measureOps`/`checkNoGc` at `maxMajor: 0`/`maxPauseMs: 2` + engine `stats()` deltas across steady + create/dispose churn, with the `churn-box` signalBox path active on 1.7.0 and a `ZEROGC_BREAK=1` self-test that must fail the gate), `lifecycle-torture` (1.5.0 `createRoot` detachment -- detached children survive and stay reactive, deps isolated -- + 1.4.0 `destroy` registry reset that stales every handle and returns `stats().activeNodes` to 0; native on 1.7.0); plus **2 that skip cleanly** as later-version features: `cleanup-return-torture` (1.8.0 effect-return cleanup), `dispose-torture` (1.9.0 `Symbol.dispose`). `soak` (wall-clock bound, asserts on RESOURCES AND value-correctness via a once-allocated `Int32Array` shadow oracle -- a rotating fixed window per tick with zero per-tick allocation, a full sweep at teardown, mismatch -> exit 1 with seed+index; nightly): `graph-fuzzer`, `scheduler-bench`, `torture-soak` -- exit 0 iff zero errors AND post-teardown pool at or below its leaf-only floor AND every shadowed value 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`.
784
799
  - `bench/run-all.sh` + `bench/aggregate.mjs` -- cold-process-per-engine protocol + per-scenario aggregation.
785
800
  - `harness/run.mjs` -- dispatcher for the run-on-demand probes (smoke, field, dispose, churn, owner, creation, perf, burst, pull, toe, all).
786
801
  - `harness/smoke.mjs` -- 1.7 flushStrategy semantics (eager/sab/manual) + `flush()`; 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.7.0-alpha.4",
3
+ "version": "1.7.0-alpha.6",
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",