@zakkster/lite-signal 1.5.0-beta.1 → 1.5.0-beta.3

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,126 @@ 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.5.0] -- 2026-06-XX
7
+ ## [1.5.0-beta.2] -- 2026-07-XX
8
+
9
+ The re-attach companion to `createRoot`: **`getOwner`** and **`runWithOwner`**
10
+ ship on the same additive-surface story as 1.5.0. **No engine change.** The
11
+ hot-path function bodies (`pullComputed`, `markDownstream`, `executeEffect`,
12
+ `flushEffects`, `allocateLink`, `severTail`, `createNode`, `runCleanup`,
13
+ `disposeNode`) are **verified byte-identical to 1.5.0-beta.1** via sha256 over
14
+ their extracted bodies. The new primitives are ~20 lines of user-API code plus
15
+ two top-level bindings; every read of `currentOwner` still happens at the same
16
+ sites (creation, effect body save/restore, cleanup), and the propagation path
17
+ remains owner-free per the `markDownstream` invariant comment. Drop-in over
18
+ 1.5.0-beta.1.
19
+
20
+ ### Added -- `getOwner()` and `runWithOwner(ownerHandle, fn)`
21
+
22
+ `getOwner()` returns an **opaque, gen-stamped handle** for the current
23
+ lifecycle owner (or `undefined` outside any effect/computed body).
24
+ `runWithOwner(handle, fn)` runs `fn` with that handle re-installed as the
25
+ current owner: effects and computeds created directly in `fn` are adopted
26
+ by that owner and cascade-dispose when it re-runs or is disposed. Nulls
27
+ the tracking observer for the duration of `fn` (Solid semantics, matching
28
+ `createRoot`'s pairing) so accidental cross-async edges cannot form.
29
+
30
+ The handles use the same `describeNode` / `liveNode` ABA-guard machinery
31
+ that `describe` / `nodeId` / `forEachOwned` / `ownerOf` have used since
32
+ 1.2.1: a returned descriptor carries an internal `NODE_GEN` stamp, and
33
+ `runWithOwner` resolves via `liveNode()` which checks that the stamp
34
+ still matches the pool slot's current gen. Stale, null, undefined, or
35
+ non-tracker handles all **degrade to rooted execution** -- `currentOwner`
36
+ set to `null`, `fn` runs, created children survive without adoption, and
37
+ the caller is responsible for their disposal (the same contract as
38
+ `createRoot`).
39
+
40
+ ### Fixed -- the two hazards the gen guard exists to prevent
41
+
42
+ The design was originally sketched with raw node pointers -- `getOwner()
43
+ { return currentOwner; }` and `runWithOwner(node, fn) { const p =
44
+ currentOwner; currentOwner = node; ... }`. That shape is broken in this
45
+ engine because nodes are pooled and the LIFO free list recycles a
46
+ disposed owner's slot into whatever effect/computed is allocated next.
47
+ Two failure modes were empirically reproduced against a 1.5.0-beta
48
+ engine patched with the raw-pointer alternative
49
+ (`Publications/owner-hazard-repro.mjs`):
50
+
51
+ - **Recycled-slot cascade death.** Owner A captured; A disposed; effect B
52
+ allocated (LIFO -> same slot); `runWithOwner(captured)` silently
53
+ adopts the continuation into B; B's re-run cascade-disposes it.
54
+ Measured on the unsafe engine: continuation ran 1 time before
55
+ stranger disposal, 1 time after (should have been 2, then 3).
56
+ - **Corpse adoption = engine crash.** Same capture, slot NOT yet
57
+ recycled; `runWithOwner(captured, () => effect(...))` splices a child
58
+ into a disposed owner's `firstOwned` list; the next disposal walk
59
+ recurses without termination. Measured: `RangeError: Maximum call
60
+ stack size exceeded` at `runCleanup` / `disposeNode`. Not a leak, a
61
+ crash.
62
+
63
+ Both hazards are pinned in `test/28-run-with-owner.test.mjs` and both
64
+ fail on the raw-pointer sketch; both pass on the shipped
65
+ `describeNode` / `liveNode` implementation. The safe implementation
66
+ degrades both hazards to rooted execution (the continuation runs and
67
+ survives independently of any stranger's lifecycle -- the only honest
68
+ semantics for "the scope you captured no longer exists").
69
+
70
+ ### Added -- `test/28-run-with-owner.test.mjs`
71
+
72
+ **16 tests**, structured to catch the failure modes above rather than
73
+ just the microtask happy path:
74
+
75
+ - Basic shape (7 tests): `getOwner()` returns undefined outside any
76
+ effect/computed and a descriptor inside; `runWithOwner` adopts a
77
+ nested effect into the captured owner, nulls the tracking observer
78
+ for reads directly in `fn`, returns whatever `fn` returns, restores
79
+ previous owner/observer/tracking on return AND on throw, and nests
80
+ correctly (inner switches, outer unwinds).
81
+ - Degradation (3 tests): `null` / `undefined` / a signal handle all
82
+ degrade to rooted execution and the created effect works normally
83
+ (fires on updates, disposable).
84
+ - Hazard pins (3 tests, plus a composed test): the recycled-slot cascade
85
+ and the corpse-adoption case, each with allocation pressure applied
86
+ BEFORE `runWithOwner` (a stranger effect is created to force slot
87
+ recycling), so the ABA guard is genuinely exercised. A follow-up
88
+ composed test asserts the continuation survives both the stranger's
89
+ re-runs and its disposal.
90
+
91
+ Full test suite on 1.5.0-beta.2: **455 total** (439 pre-existing +
92
+ 16 new), 444 pass, 0 fail, 1 skip (SSR N/A), 10 cancelled (the
93
+ `25-devtools-real-boot` cases that need `@zakkster/lite-devtools`
94
+ installed as a peer -- pre-existing, unrelated).
95
+
96
+ ### Added -- `Publications/owner-hazard-repro.mjs`
97
+
98
+ A standalone reproducer for the two hazards, callable against any engine
99
+ (`node owner-hazard-repro.mjs <path-to-Signal.js>`). Prints
100
+ `VERDICT: SAFE` on the shipping implementation, `VERDICT: CORRUPTED` +
101
+ a stack overflow on the raw-pointer sketch. Kept in `Publications/`
102
+ alongside the other reproducers rather than under `test/` so it can
103
+ travel to other engines (a candidate 1.6, or a rejected candidate you
104
+ want to confirm) without dragging the whole test tree along.
105
+
106
+ ### Verified -- no hot-path change vs 1.5.0-beta.1
107
+
108
+ sha256 over the extracted function bodies of `pullComputed`,
109
+ `markDownstream`, `executeEffect`, `flushEffects`, `allocateLink`,
110
+ `severTail`, `createNode`, `runCleanup`, and `disposeNode` matches
111
+ 1.5.0-beta.1 byte-for-byte. `currentOwner` is written by exactly the
112
+ sites that wrote it before (creation adoption, effect-body save/restore,
113
+ cleanup), plus the two new user-API primitives. Propagation
114
+ (`markDownstream`) remains owner-free per its documented invariant.
115
+
116
+ ### Not shipped
117
+
118
+ - Watch.js needs no changes -- `watch` / `when` / `whenAsync` create
119
+ effects through the normal path and inherit correct adoption under
120
+ `runWithOwner` automatically. Verified against the safe engine.
121
+ - `runWithOwner` deliberately does NOT accept a callable `signal`
122
+ handle as an "owner" (signals cannot own). It falls through to
123
+ rooted execution instead, matching the shape of every other
124
+ handle-taking introspection API.
125
+
126
+ ## [1.5.0-beta.1] -- 2026-06-XX
8
127
 
9
128
  The API-surface minor: two new **non-callable, allocation-light** reactive
10
129
  primitives, `signalBox` and `computedBox`, land alongside the existing callable
package/README.md CHANGED
@@ -245,6 +245,7 @@ import {
245
245
  signalBox, computedBox, // 1.5.0 -- allocation-light, non-callable
246
246
  batch, untrack, onCleanup, isTracking,
247
247
  createRoot, // 1.5.0 -- detached ownership scope
248
+ getOwner, runWithOwner, // 1.5.0-beta.2 -- capture + restore ownership across async gaps
248
249
  // Registry / lifecycle
249
250
  createRegistry, setDefaultRegistry, dispose, destroy,
250
251
  stats, CapacityError,
@@ -357,7 +358,31 @@ dispose();
357
358
 
358
359
  Runs `fn` in a **detached ownership scope** and returns whatever `fn` returns. Effects and computeds created directly inside `fn` are not adopted by the enclosing owner, so they survive the enclosing effect's re-runs and disposal -- there is no parent to auto-dispose them, so the caller is responsible (typically `fn` returns a disposer or the created handle). Both ownership *and* tracking are detached for the duration of `fn`'s direct body; inner effect/computed bodies still establish their own scopes as usual. Mirrors Solid's `createRoot` on the lifecycle axis.
359
360
 
360
- The problem it solves: lazily spawning a *long-lived* node from *inside* a consumer effect is otherwise a footgun -- the spawned node is adopted by the consumer, so the consumer's next re-run cascade-disposes it. That is the ownership model working as designed (owned children dispose with their parent); `createRoot` is the sanctioned opt-out. Any consumer that creates a watcher/subscription inside a reactive scope and expects it to outlive that scope wraps the spawn in `createRoot(() => effect(...))` -- `lite-query`'s query-watcher being the first in the ecosystem. (The companion `runWithOwner`, for re-attaching to a captured owner, is named in the engine as the intended second half of this API and is not yet shipped.)
361
+ The problem it solves: lazily spawning a *long-lived* node from *inside* a consumer effect is otherwise a footgun -- the spawned node is adopted by the consumer, so the consumer's next re-run cascade-disposes it. That is the ownership model working as designed (owned children dispose with their parent); `createRoot` is the sanctioned opt-out. Any consumer that creates a watcher/subscription inside a reactive scope and expects it to outlive that scope wraps the spawn in `createRoot(() => effect(...))` -- `lite-query`'s query-watcher being the first in the ecosystem. The companion primitives `getOwner` / `runWithOwner` -- for capturing the current owner and restoring it across an async boundary -- ship in **1.5.0-beta.2**; see the next section.
362
+
363
+ ### getOwner / runWithOwner (1.5.0-beta.2)
364
+
365
+ The re-attach half of the ownership escape hatch. `createRoot` detaches; `getOwner` + `runWithOwner` **capture and restore**. Together they give you the Solid-shaped ownership API for the async pattern that comes up whenever you have to leave a synchronous reactive scope, do work, and come back:
366
+
367
+ ```javascript
368
+ import { effect, getOwner, runWithOwner, signal } from '@zakkster/lite-signal';
369
+
370
+ const s = signal(0);
371
+ effect(() => {
372
+ const owner = getOwner(); // opaque, gen-stamped handle
373
+ fetch('/data').then(res => res.json()).then(data => {
374
+ runWithOwner(owner, () => { // re-enter the captured scope
375
+ effect(() => { console.log(s(), data); });
376
+ });
377
+ });
378
+ });
379
+ ```
380
+
381
+ `getOwner()` returns the current owner as an **opaque, gen-stamped handle** (or `undefined` outside any effect/computed body). `runWithOwner(handle, fn)` runs `fn` with the captured lifecycle scope reinstated: effects and computeds created directly in `fn` are adopted by that owner and cascade-dispose when it re-runs or is disposed. Reads directly in `fn` do not link -- tracking is detached the same way `createRoot` detaches it, so accidental cross-async edges cannot form. Compose with an inner effect if you want tracking under the restored owner.
382
+
383
+ **Handles are safe to hold across async boundaries.** This is where a raw-pointer implementation would corrupt the graph: node objects are pooled and the LIFO free list recycles a disposed owner's slot into whatever effect/computed is allocated next. A stale raw pointer would silently adopt continuations into that stranger. Instead, `getOwner` returns a `describeNode` handle stamped with the pool slot's generation; `runWithOwner` resolves via `liveNode()`, and if the gen has moved (slot recycled) or the handle refers to a signal (not a tracker), it degrades to **rooted execution** -- the continuation runs, stays alive, and is simply not owned by anyone. That is the only honest semantics for "the scope you captured no longer exists": the alternative was a silent cascade-dispose by an unrelated stranger, or, if the slot was disposed but not yet recycled, a `RangeError: Maximum call stack size exceeded` inside the cleanup recursion. Both hazards are pinned in `test/28-run-with-owner.test.mjs` and empirically demonstrated in `Publications/owner-hazard-repro.mjs`.
384
+
385
+ The handles do **not** keep owners alive -- they are snapshots, not references. Node lifetime is controlled by the owner tree, not by outstanding handles.
361
386
 
362
387
  ### isTracking
363
388
 
@@ -765,6 +790,7 @@ Three tiers, all reproducible.
765
790
  - **`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.
766
791
  - **`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.
767
792
  - **`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.
793
+ - **`28-run-with-owner.test.mjs`** -- `getOwner` / `runWithOwner` (1.5.0-beta.2), the re-attach companion. 16 tests, structured in three groups: basic shape (7 tests: undefined outside, effect/computed inside, restore-on-return, throw-safety, nesting), degradation (3 tests: null / undefined / signal-handle all fall through to rooted execution), and the three **hazard pins** that a raw-pointer implementation fails: (i) recycled-slot cascade -- capture, dispose owner, allocate an effect that reuses the pool slot, `runWithOwner(captured)` must not adopt into the recycled slot's new resident; (ii) corpse adoption -- capture, dispose owner but not-yet-recycled, `runWithOwner(captured, () => effect(...))` must not crash with `RangeError` in the cleanup recursion; (iii) composed -- both together, continuation must survive stranger re-runs AND disposal. All three fail against the naive `getOwner() { return currentOwner; }` shape (empirically verified against a 1.5.0-beta engine patched with the raw-pointer alternative -- `Publications/owner-hazard-repro.mjs`); all three pass with the `describeNode` gen-stamped handle + `liveNode` ABA guard that ships.
768
794
  - **`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.
769
795
  - **`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%).
770
796
 
@@ -957,8 +983,8 @@ The cross-framework reactivity suite agrees independently, re-run on **1.5.0-bet
957
983
  - **1.2.0** -- the **ownership hybrid**: an owner tree so nested effects/computeds auto-dispose with their parent (closes conformance #209 / #210, matching Solid's `createRoot` ergonomics). Plus three additive features built on the same internal split: pre-batch revert (`batch(() => { a.set(99); a.set(10); })` doesn't re-fire), multi-throw `AggregateError`, and scheduler-thunk caching with an ABA gen guard. *Shipped.*
958
984
  - **1.3.0** -- the **pool minor**: node and link pools become growable and incrementally populated. New `prealloc` config (`"eager"` default | `"lazy"`) chooses up-front vs on-demand construction; `onCapacityExceeded: "grow"` extends pools via chunked refill (runs of up to 1024 links / 256 nodes, ledger doubles) bounded by the 16x link ceiling; `maxFlushPasses` is now a public config. Internally the propagation mark phase moved to an intrusive linked-list stack (a `nextMark` field) -- the only node-shape change. The hot paths and public callable API are byte-identical to 1.2.2; steady-state zero-GC is unchanged. *Shipped.*
959
985
  - **1.4.0** -- the **observability minor**: `stats()` gains three cumulative lifecycle counters (`totalAllocations`, `totalDisposals`, `poolGrowths`), the surface reserved for it in the 1.2.x/1.3.0 notes. Monotonic over the registry's life, reset by `destroy()`, bumped on the existing acquire/dispose/grow edges -- no hot-path change, no public callable API change. This is what lite-devtools / lite-studio read to chart allocation rate, pool-reuse ratio, and graph churn. Also adds the `harness/VersionMatrix/` regression gate (cold-process, same-host, two baselines) as a `prepublish` step, so a release that regresses `frame.avg` on the four reference workloads (reactive-graph-mix, deep-chain, broadcast-fanout, dynamic-dep-churn) fails the publish. Drop-in over 1.3.0. *Shipped.*
960
- - **1.5.0** -- the **API-surface minor**: two non-callable, allocation-light primitives `signalBox` / `computedBox` land alongside the callable `signal` / `computed` (same `ReactiveNode`, full interop, ~1.7x cheaper construction), and **`createRoot`** lands as the ownership escape hatch the owner tree was designed for (detached scope for lazily spawning long-lived nodes from inside a consumer effect -- the pattern `lite-query` needs). The callable API, hot paths, and `stats()` shape are unchanged; the `24-signalbox` suite (staged since 1.3.0) now runs and passes. VersionMatrix gains an **identical-code guard** (SHA-256 of the engine source per baseline): a re-versioned publish with byte-identical `Signal.js` is marked `SKIP` structurally rather than flagged by noisy median variance. *Shipped (beta).*
961
- - **Next** -- `runWithOwner` (the re-attach companion to `createRoot`); the pull-mode recursion depth limit (~5,000 chained computeds) remains the main outstanding architectural item.
986
+ - **1.5.0** -- the **API-surface minor**: two non-callable, allocation-light primitives `signalBox` / `computedBox` land alongside the callable `signal` / `computed` (same `ReactiveNode`, full interop, ~1.7x cheaper construction), and **`createRoot`** lands as the ownership escape hatch the owner tree was designed for (detached scope for lazily spawning long-lived nodes from inside a consumer effect -- the pattern `lite-query` needs). The callable API, hot paths, and `stats()` shape are unchanged; the `24-signalbox` suite (staged since 1.3.0) now runs and passes. VersionMatrix gains an **identical-code guard** (SHA-256 of the engine source per baseline): a re-versioned publish with byte-identical `Signal.js` is marked `SKIP` structurally rather than flagged by noisy median variance. *Shipped (beta).* **1.5.0-beta.2** adds the re-attach companions **`getOwner` / `runWithOwner`** (gen-stamped handles that degrade to rooted execution when the captured owner has been recycled -- the raw-pointer alternative would silently adopt continuations into the recycled slot's new resident, or crash the engine with unbounded cleanup recursion on a corpse handle; both hazards pinned in `test/28-run-with-owner.test.mjs`). Hot paths remain byte-identical to 1.5.0-beta.1 -- verified via sha256 over extracted function bodies (`pullComputed`, `markDownstream`, `executeEffect`, `flushEffects`, `allocateLink`, `severTail`, `createNode`, `runCleanup`, `disposeNode`).
987
+ - **Next** -- the pull-mode recursion depth limit (~5,000 chained computeds) remains the main outstanding architectural item. Watching lite-query's real-world adoption of `createRoot` + `runWithOwner` for what the next escape hatch needs to be.
962
988
 
963
989
  > Note: the retracking rewrite that closes the dynamic-topology gap shipped in **1.1.4**, not a future release. The earlier roadmap that listed it under "v1.2" is superseded.
964
990
 
package/Signal.d.ts CHANGED
@@ -268,6 +268,49 @@ export interface Registry {
268
268
  * effect (e.g. a query watcher). Returns whatever `fn` returns.
269
269
  */
270
270
  createRoot<T>(fn: () => T): T;
271
+ /**
272
+ * Return the currently-active owner as an opaque, gen-stamped handle
273
+ * (`undefined` if called outside any effect/computed body). Companion to
274
+ * {@link runWithOwner}: capture the current lifecycle scope now, restore
275
+ * it later (typically across an async boundary). Introduced in 1.5.0-beta.2.
276
+ *
277
+ * The handle is a plain descriptor object (same shape as {@link describe}
278
+ * returns) stamped with an internal generation counter. It is safe to
279
+ * hold across async boundaries: if the captured owner is disposed and
280
+ * its pool slot is subsequently recycled by an unrelated effect/computed,
281
+ * the generation counter no longer matches and {@link runWithOwner}
282
+ * treats the handle as stale (degrades to rooted execution). This is the
283
+ * ABA guard already used by `describe` / `nodeId` / `forEachOwned`.
284
+ *
285
+ * The handle does NOT keep the owner alive -- it is a snapshot, not a
286
+ * reference. Node lifetime is controlled by the owner tree, not by
287
+ * outstanding handles.
288
+ */
289
+ getOwner(): Owner;
290
+ /**
291
+ * Run `fn` with `ownerHandle` as the current lifecycle owner. Effects
292
+ * or computeds created directly in `fn` are adopted by that owner and
293
+ * cascade-dispose when the owner re-runs or is disposed. Introduced in
294
+ * 1.5.0-beta.2.
295
+ *
296
+ * Degradation semantics for handles that cannot be re-attached:
297
+ * - `null` / `undefined` -> rooted execution (createRoot semantics for
298
+ * ownership; created children survive, caller disposes them).
299
+ * - stale handle (owner disposed, slot recycled) -> rooted execution.
300
+ * Never adopts into the unrelated new resident of the recycled slot;
301
+ * never adopts into a corpse (a disposed owner whose slot is not yet
302
+ * recycled).
303
+ * - handle for a live signal (not an effect/computed) -> rooted
304
+ * execution (signals cannot own).
305
+ *
306
+ * Nulls the tracking observer for the duration of `fn` (the same pairing
307
+ * as {@link createRoot}): reads directly inside `fn` do NOT link into any
308
+ * enclosing observer. Inner effect/computed bodies still establish their
309
+ * own owner + observer scopes.
310
+ *
311
+ * Returns whatever `fn` returns.
312
+ */
313
+ runWithOwner<T>(ownerHandle: Owner, fn: () => T): T;
271
314
  /**
272
315
  * Universal disposal for anything created by this registry: signals,
273
316
  * computeds, boxes, or effect dispose handles. Cross-registry calls are
@@ -348,6 +391,18 @@ export function signalBox<T>(initial: T, opts?: SignalOptions<T>): SignalBox<T>;
348
391
  export function computedBox<T>(fn: () => T, opts?: ComputedOptions<T>): ComputedBox<T>;
349
392
  /** Run `fn` in a detached ownership scope (1.5.0), bound to the default registry. See {@link Registry.createRoot}. */
350
393
  export function createRoot<T>(fn: () => T): T;
394
+ /**
395
+ * An owner handle -- an opaque descriptor returned by {@link getOwner},
396
+ * safe to hold across async boundaries. A stale, null, or non-tracker
397
+ * handle degrades cleanly in {@link runWithOwner} (rooted execution)
398
+ * rather than adopting into an unrelated recycled slot. See
399
+ * {@link Registry.getOwner} for the ABA-guard mechanics. 1.5.0-beta.2+.
400
+ */
401
+ export type Owner = NodeDescriptor | undefined;
402
+ /** Capture the current owner as an opaque, gen-stamped handle (1.5.0-beta.2), bound to the default registry. See {@link Registry.getOwner}. */
403
+ export function getOwner(): Owner;
404
+ /** Run `fn` under a captured owner handle (1.5.0-beta.2), bound to the default registry. See {@link Registry.runWithOwner}. */
405
+ export function runWithOwner<T>(ownerHandle: Owner, fn: () => T): T;
351
406
  /** Universal disposal -- see {@link Registry.dispose}. */
352
407
  export function dispose(api: Disposable): void;
353
408
  export function batch<T>(fn: () => T): T;
package/Signal.js CHANGED
@@ -1457,6 +1457,25 @@ export function createRegistry(config) {
1457
1457
  * Mirrors Solid's `createRoot` for the lifecycle axis. Returns whatever
1458
1458
  * `fn` returns (typically a disposer or the created handle).
1459
1459
  */
1460
+ function getOwner() {
1461
+ return currentOwner !== null ? describeNode(currentOwner) : undefined;
1462
+ }
1463
+ function runWithOwner(ownerHandle, fn) {
1464
+ const node = liveNode(ownerHandle);
1465
+ const prevOwner = currentOwner;
1466
+ const prevObserver = currentObserver;
1467
+ const prevTracking = isTrackingDeps;
1468
+ currentOwner = (node !== undefined && (node.flags & (FLAG_COMPUTED | FLAG_EFFECT)) !== 0) ? node : null;
1469
+ currentObserver = null;
1470
+ isTrackingDeps = false;
1471
+ try {
1472
+ return fn();
1473
+ } finally {
1474
+ currentOwner = prevOwner;
1475
+ currentObserver = prevObserver;
1476
+ isTrackingDeps = prevTracking;
1477
+ }
1478
+ }
1460
1479
  function createRoot(fn) {
1461
1480
  const prevOwner = currentOwner;
1462
1481
  const prevObserver = currentObserver;
@@ -1697,7 +1716,7 @@ export function createRegistry(config) {
1697
1716
  while (l !== null) { const nx = l.nextDep; fn(describeNode(l.source)); l = nx; }
1698
1717
  }
1699
1718
 
1700
- return {signal, computed, effect, signalBox, computedBox, dispose, batch, untrack, createRoot, onCleanup, stats, destroy, isTracking, hasObservers, observeObservers, forEachObserver, forEachSource, forEachOwned, ownerOf, nodeId, describe, onGraphMutation};
1719
+ return {getOwner, runWithOwner, signal, computed, effect, signalBox, computedBox, dispose, batch, untrack, createRoot, onCleanup, stats, destroy, isTracking, hasObservers, observeObservers, forEachObserver, forEachSource, forEachOwned, ownerOf, nodeId, describe, onGraphMutation};
1701
1720
  }
1702
1721
 
1703
1722
  // -----------------------------------------------------------------
@@ -1745,6 +1764,29 @@ export function createRoot(fn) {
1745
1764
  return defaultRegistry.createRoot(fn);
1746
1765
  }
1747
1766
 
1767
+ /**
1768
+ * Return the currently-active owner as an opaque, gen-stamped handle
1769
+ * (undefined if outside any effect/computed body). Pass to
1770
+ * {@link runWithOwner} to re-enter the captured lifecycle scope. The handle
1771
+ * is safe to hold across async boundaries: it goes STALE when the captured
1772
+ * owner is disposed and the pool slot is recycled, and stale handles
1773
+ * degrade to rooted execution rather than adopting into a stranger.
1774
+ */
1775
+ export function getOwner() {
1776
+ return defaultRegistry.getOwner();
1777
+ }
1778
+
1779
+ /**
1780
+ * Run `fn` with `ownerHandle` as the lifecycle owner: effects/computeds
1781
+ * created directly in `fn` are adopted by that owner. A null/undefined/stale
1782
+ * handle degrades to rooted execution (created children survive; the caller
1783
+ * disposes them). Nulls the tracking observer for the duration of `fn`.
1784
+ * See {@link Registry.runWithOwner}.
1785
+ */
1786
+ export function runWithOwner(ownerHandle, fn) {
1787
+ return defaultRegistry.runWithOwner(ownerHandle, fn);
1788
+ }
1789
+
1748
1790
  /**
1749
1791
  * True iff a read RIGHT NOW would record a dependency on the default registry.
1750
1792
  * See {@link createRegistry} for the per-registry version.
package/llms.txt CHANGED
@@ -17,7 +17,8 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
17
17
  - **Computed**: lazy memoized derivation. `computed(fn, { equals? })`. Cache hits return in O(deps) (version comparison only). Cache misses re-run the body and refresh `evalVersion`. Errors are cached via `FLAG_HAS_ERROR` and re-thrown on every read until a dep changes.
18
18
  - **Effect**: side-effect runner. `effect(fn, { scheduler? })`. Runs immediately on creation, then on any tracked dep change. Returns a dispose function. Optional scheduler defers execution (e.g., to rAF, microtask, custom frame loop).
19
19
  - **Box (1.5.0)**: non-callable, allocation-light variants. `signalBox(initial, { equals? })` returns `{ get, set, peek, update, subscribe }`; `computedBox(fn, { equals? })` returns `{ get, peek, subscribe }` (no set/update -- derived). Same `ReactiveNode` and zero-GC read/write path as the callable forms, full interop in one graph (a callable can read `box.get()` and vice versa). Construction is ~1.7x cheaper than the callable (an `Object.create(proto)` handle, not a closure). Built on a shared prototype from the start -- never `setPrototypeOf` (which would deopt the method-call ICs to megamorphic). Exported as registry methods and top-level helpers.
20
- - **createRoot (1.5.0)**: `createRoot(fn)` runs `fn` in a detached ownership scope and returns `fn`'s value. Effects/computeds created directly in `fn` are NOT adopted by the enclosing owner, so they survive its re-runs/disposal (the caller owns their lifecycle). Both ownership and tracking are detached for `fn`'s direct body; inner effect/computed bodies still establish their own scopes. The escape hatch for lazily spawning a long-lived node from inside a consumer effect (e.g. `lite-query`'s query-watcher) -- without it, the consumer owns the watcher and cascade-disposes it on its next re-run. Mirrors Solid's `createRoot`. The re-attach companion `runWithOwner` is named in the engine as the intended second half and is not yet shipped.
20
+ - **createRoot (1.5.0)**: `createRoot(fn)` runs `fn` in a detached ownership scope and returns `fn`'s value. Effects/computeds created directly in `fn` are NOT adopted by the enclosing owner, so they survive its re-runs/disposal (the caller owns their lifecycle). Both ownership and tracking are detached for `fn`'s direct body; inner effect/computed bodies still establish their own scopes. The escape hatch for lazily spawning a long-lived node from inside a consumer effect (e.g. `lite-query`'s query-watcher) -- without it, the consumer owns the watcher and cascade-disposes it on its next re-run. Mirrors Solid's `createRoot`.
21
+ - **getOwner / runWithOwner (1.5.0-beta.2)**: the re-attach companion. `getOwner()` returns the current lifecycle owner as an opaque gen-stamped handle (`undefined` outside any effect/computed body); `runWithOwner(handle, fn)` runs `fn` with that owner reinstated so effects/computeds created directly in `fn` are adopted by it (and cascade-dispose when it re-runs). Nulls the tracking observer for `fn`'s direct body (same pairing as `createRoot`). Handles are **safe to hold across async boundaries**: they use the `describeNode` / `liveNode` ABA-guard machinery (`NODE_GEN` stamp checked against the pool slot's current gen), so stale handles -- owner disposed, slot recycled by an unrelated effect via the LIFO free list -- degrade to rooted execution rather than corrupting the graph. A raw-pointer implementation would (i) silently adopt continuations into the recycled slot's new resident (measured: continuation dies with a stranger on its next disposal), or (ii) crash the engine with `RangeError: Maximum call stack size exceeded` on a corpse handle (owner disposed, slot not yet recycled -- the disposal walk recurses without termination). Both hazards pinned in `test/28-run-with-owner.test.mjs`, empirically reproduced via `Publications/owner-hazard-repro.mjs`. Also exported as registry methods + top-level helpers.
21
22
  - **dispose(api)**: universal disposal. Accepts a signal, computed, or effect dispose handle; idempotent; cross-registry calls are silent no-ops (per-registry `Symbol("node_ptr")` keys the node-identity slot on the returned API function, foreign signals fail the lookup and fall through). Passing an unrelated value is also safe; passing an arbitrary function invokes it (effect-handle contract).
22
23
  - **Batch**: `batch(fn)` defers effect flush until the outermost batch closes. Nestable.
23
24
  - **Untrack**: `untrack(fn)` reads without subscribing.
@@ -52,7 +53,62 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
52
53
 
53
54
  ## Version notes
54
55
 
55
- - **1.5.0-beta** (current): the **API-surface minor**. Two non-callable,
56
+ - **1.5.0-beta.2** (current): the re-attach companion to `createRoot`.
57
+ **`getOwner()`** and **`runWithOwner(ownerHandle, fn)`** land as registry
58
+ methods + top-level bindings. **No engine change** from 1.5.0-beta.1 -- the
59
+ hot-path function bodies (`pullComputed`, `markDownstream`, `executeEffect`,
60
+ `flushEffects`, `allocateLink`, `severTail`, `createNode`, `runCleanup`,
61
+ `disposeNode`) are byte-identical (sha256-verified over extracted bodies).
62
+ The two new primitives are ~20 lines of user-API code + two top-level
63
+ bindings; `currentOwner` is read/written at the same sites as before
64
+ (creation adoption, effect-body save/restore, cleanup) plus the two new
65
+ wrappers. Drop-in over 1.5.0-beta.1.
66
+
67
+ **Handles are gen-stamped, not raw pointers.** `getOwner()` returns a
68
+ `describeNode` handle stamped with the pool slot's `NODE_GEN`;
69
+ `runWithOwner` resolves via `liveNode()` (the same ABA-guard machinery
70
+ `describe` / `nodeId` / `forEachOwned` / `ownerOf` have used since 1.2.1).
71
+ Stale, null, undefined, or non-tracker (signal) handles all degrade to
72
+ **rooted execution**: `currentOwner` set to `null`, `fn` runs, created
73
+ children survive without adoption, caller disposes them (same contract
74
+ as `createRoot`). This matters because node objects are pooled and the
75
+ LIFO free list recycles a disposed owner's slot into the next
76
+ effect/computed allocated. A raw-pointer alternative
77
+ (`getOwner() { return currentOwner; }`) fails two hazards, both pinned
78
+ in `test/28-run-with-owner.test.mjs` and empirically reproduced by
79
+ `Publications/owner-hazard-repro.mjs`:
80
+ (i) **Recycled-slot cascade death** -- owner A captured; A disposed;
81
+ stranger B allocated (LIFO -> A's slot); `runWithOwner(captured)`
82
+ silently adopts continuation into B; B's next re-run
83
+ cascade-disposes it. Measured on the unsafe engine: continuation
84
+ ran 1 time before stranger disposal, 1 time after (should be 2
85
+ then 3).
86
+ (ii) **Corpse adoption = engine crash** -- capture; A disposed; slot
87
+ NOT yet recycled; `runWithOwner(captured, () => effect(...))`
88
+ splices a child into a disposed owner's `firstOwned`; next
89
+ disposal walk recurses without termination.
90
+ `RangeError: Maximum call stack size exceeded` at `runCleanup` /
91
+ `disposeNode`. Not a leak; a crash.
92
+ Both hazards degrade to rooted execution on the shipped implementation.
93
+
94
+ **Semantics.** `runWithOwner` nulls the tracking observer + tracking flag
95
+ for the duration of `fn` (same pairing `createRoot` uses). Reads directly
96
+ in `fn` do not link to any enclosing observer; if the caller wants
97
+ tracking under the restored owner, they nest an inner effect/computed in
98
+ `fn` which establishes its own scope. Returns whatever `fn` returns.
99
+ Restores previous owner/observer/tracking triplet on return AND on
100
+ throw. Signal handles are rejected (`runWithOwner(signalHandle, fn)` ->
101
+ rooted execution) because signals cannot own -- the `flags & (FLAG_COMPUTED
102
+ | FLAG_EFFECT)` check gates adoption. `getOwner()` returns `undefined`
103
+ (not `null`) outside any effect/computed body to match the shape of the
104
+ other handle-taking APIs. **Tests:** 455 total (439 pre-existing + 16
105
+ new), 444 pass, 0 fail, 1 skip (SSR N/A), 10 cancelled (`25-devtools-
106
+ real-boot` cases needing the devtools peer dep -- pre-existing).
107
+ **Watch.js needs no changes**: `watch` / `when` / `whenAsync` create
108
+ effects through the normal path and inherit correct adoption under
109
+ `runWithOwner` automatically.
110
+
111
+ - **1.5.0-beta.1** (was "current" before beta.2): the **API-surface minor**. Two non-callable,
56
112
  allocation-light primitives -- `signalBox(initial, opts?)` returning
57
113
  `{ get, set, peek, update, subscribe }` and `computedBox(fn, opts?)` returning
58
114
  `{ get, peek, subscribe }` -- land alongside the callable `signal` / `computed`,
@@ -375,6 +431,9 @@ function effect(fn: () => void, opts?: { scheduler?: (run: () => void) => void }
375
431
  function signalBox<T>(initial: T, opts?: { equals?: (a: T, b: T) => boolean }): SignalBox<T>; // 1.5.0
376
432
  function computedBox<T>(fn: () => T, opts?: { equals?: (a: T, b: T) => boolean }): ComputedBox<T>; // 1.5.0
377
433
  function createRoot<T>(fn: () => T): T; // 1.5.0 -- detached ownership scope; returns fn's value
434
+ type Owner = NodeDescriptor | undefined; // 1.5.0-beta.2 -- opaque, gen-stamped handle; safe across async gaps
435
+ function getOwner(): Owner; // 1.5.0-beta.2 -- undefined outside any effect/computed body
436
+ function runWithOwner<T>(ownerHandle: Owner, fn: () => T): T; // 1.5.0-beta.2 -- stale/null/signal-handle -> rooted execution
378
437
  function dispose(api: Signal<any> | Computed<any> | SignalBox<any> | ComputedBox<any> | Dispose): void;
379
438
  function batch<T>(fn: () => T): T;
380
439
  function untrack<T>(fn: () => T): T;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zakkster/lite-signal",
3
- "version": "1.5.0-beta.1",
3
+ "version": "1.5.0-beta.3",
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",