reflex-quant 1.3.1 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,66 +2,27 @@
2
2
 
3
3
  # ⚛ reflex-quant
4
4
 
5
- **A tiny, high-performance JavaScript signals library built for exact reactive semantics.**
5
+ **A small, contract-driven signals library for JavaScript and TypeScript.**
6
6
 
7
7
  [![npm](https://img.shields.io/npm/v/reflex-quant?color=cb3837&label=npm)](https://www.npmjs.com/package/reflex-quant)
8
8
  [![CI](https://github.com/volynetstyle/reflex-quant/actions/workflows/ci.yml/badge.svg)](https://github.com/volynetstyle/reflex-quant/actions/workflows/ci.yml)
9
- [![types](https://img.shields.io/badge/types-included-3178c6)](#api-at-a-glance)
10
- [![license](https://img.shields.io/npm/l/reflex-quant?color=blue)](LICENSE)
9
+ [![types](https://img.shields.io/badge/types-included-3178c6)](#api)
10
+ [![license](https://img.shields.io/npm/l/reflex-quant?color=blue)](https://github.com/volynetstyle/reflex-quant/blob/main/LICENSE)
11
11
 
12
- [**Website & live examples**](https://volynetstyle.github.io/reflex-quant/) ·
12
+ [Website & live examples](https://volynetstyle.github.io/reflex-quant/) ·
13
13
  [How it works](https://volynetstyle.github.io/reflex-quant/reactive-runtime-anatomy/) ·
14
14
  [Benchmarks](https://volynetstyle.github.io/reflex-quant/benchmarks/)
15
15
 
16
16
  </div>
17
17
 
18
- Reflex Quant is a framework-agnostic fine-grained reactivity library for JavaScript
19
- and TypeScript, with signals, computeds and effects in under 3 KB gzip. It combines
20
- exact dynamic dependency tracking, glitch-free propagation, stack-safe graph traversal
21
- and defined failure semantics. Its implementation was derived from a written
22
- reactive contract and validated through differential testing.
18
+ Reflex Quant provides signals, computed values and effects without a framework.
19
+ It tracks dependencies dynamically, propagates changes without glitches, and
20
+ defines how the graph behaves when callbacks fail. Its graph walks are
21
+ stack-safe, and unchanged computed values stop downstream propagation.
23
22
 
24
- In the [published JS Reactivity Benchmark snapshot](https://github.com/volynetstyle/js-reactivity-benchmark/blob/9a26a3bee200fe9610e19cc21e0b8e02730b5459/index.html)
25
- from November 10, 2026, Quant 1.1.2 ranked first on the family-balanced core
26
- score: 1.07× versus 1.20× for alien-signals 3.2.1. This is a result for that
27
- workload set, not a claim that Quant wins every benchmark. The separate
28
- [project CI suite](#performance) measures Quant 1.2.0.
29
-
30
- ```ts
31
- import { signal, computed, effect, read, set } from "reflex-quant";
32
-
33
- const count = signal(0);
34
- const doubled = computed(() => read(count) * 2);
35
-
36
- effect(() => console.log(`count=${read(count)} doubled=${read(doubled)}`));
37
- // count=0 doubled=0
38
-
39
- set(count, 1); // count=1 doubled=2
40
- set(count, 2); // count=2 doubled=4
41
- ```
42
-
43
- That covers most of it. You store values in **signals**, derive values with **computeds**, and react
44
- to changes with **effects**. Quant tracks what each one reads, so you never
45
- list dependencies by hand.
46
-
47
- ## Why quant?
48
-
49
- - 🤏 **Tiny.** About 2.9 KB min+gzip for the whole library, and no dependencies.
50
- - 🎯 **Exact.** Dependencies are whatever the last run actually read. Take a
51
- branch and the old dependencies drop away. Write a value that nothing
52
- currently reads and nothing reruns.
53
- - ⚡ **Fast.** Comparable to the fastest signal libraries on the
54
- [benchmarks](#performance), and reordering dependencies allocates nothing.
55
- - 🧱 **Stack-safe.** Updates travel through an explicit work stack instead of
56
- recursion, so a 100 000-deep chain of computeds updates without overflowing
57
- the call stack.
58
- - 🔬 **Proven, not guessed.** Every mechanism in the runtime is backed by a test
59
- that fails without it. Quant's invariants also found
60
- [two real bugs in Vue's reactivity](#correctness).
61
- - 🧩 **Framework-free.** Plain functions over plain values. You can use it in
62
- Node, the browser, workers, or behind any UI layer.
63
- - 🟦 **TypeScript-first.** Signals, computeds and effects are distinct types:
64
- the compiler won't let you `set` a computed.
23
+ Quant has no runtime dependencies. The production ESM build of version 1.3.2 is
24
+ 2,808 bytes gzip, including its banner. The package includes ESM, CommonJS and
25
+ TypeScript declarations, and supports Node.js 18+ and modern browsers.
65
26
 
66
27
  ## Install
67
28
 
@@ -69,564 +30,318 @@ list dependencies by hand.
69
30
  npm install reflex-quant
70
31
  ```
71
32
 
72
- ESM and CommonJS builds are included, along with type declarations. It needs Node.js 18+ or any modern browser.
73
-
74
- ---
75
-
76
- ## The 5-minute tour
77
-
78
- ### 1. Signals hold values
33
+ ## Quick start
79
34
 
80
35
  ```ts
81
- import { signal, read, set, update } from "reflex-quant";
82
-
83
- const name = signal("Ada");
84
-
85
- read(name); // "Ada"
86
- set(name, "Grace"); // replace
87
- update(name, (n) => n.toUpperCase()); // derive from current: "GRACE"
88
- ```
89
-
90
- ### 2. Computeds derive values, lazily and cached
91
-
92
- A computed doesn't run until something reads it. It reruns only when a value it
93
- read has changed.
36
+ import { signal, computed, effect, read, set, dispose } from "reflex-quant";
94
37
 
95
- ```ts
96
- const price = signal(4);
97
- const qty = signal(2);
38
+ const count = signal(0);
39
+ const doubled = computed(() => read(count) * 2);
98
40
 
99
- let runs = 0;
100
- const total = computed(() => {
101
- runs++;
102
- return read(price) * read(qty);
41
+ const logger = effect(() => {
42
+ console.log("count:", read(count), "doubled:", read(doubled));
103
43
  });
44
+ // count: 0 doubled: 0
104
45
 
105
- set(qty, 3);
106
- set(qty, 5); // runs === 0: nobody asked yet
46
+ set(count, 1); // count: 1 doubled: 2
47
+ set(count, 2); // count: 2 doubled: 4
107
48
 
108
- read(total); // 20, runs === 1
109
- read(total); // 20, runs === 1: cached
49
+ dispose(logger);
50
+ set(count, 3); // no log
110
51
  ```
111
52
 
112
- ### 3. Effects react to changes
53
+ A **signal** holds a writable value. A **computed** derives a cached value and
54
+ runs lazily when it is needed. An **effect** reacts to the values it reads.
55
+ Quant records the reads, so there are no dependency arrays to maintain.
113
56
 
114
- An effect runs once right away, then again whenever something it read changes.
115
- If it returns a function, quant calls that function before the next run and on
116
- dispose. This is the place to clean up timers, listeners and subscriptions.
117
-
118
- ```ts
119
- import { effect, dispose } from "reflex-quant";
120
-
121
- const room = signal("general");
122
-
123
- const chat = effect(() => {
124
- const r = read(room);
125
- console.log("join", r);
126
- return () => console.log("leave", r);
127
- });
128
- // join general
129
-
130
- set(room, "random");
131
- // leave general
132
- // join random
133
-
134
- dispose(chat);
135
- // leave random
136
- ```
57
+ ## Working with values
137
58
 
138
- ### 4. Dependencies follow your code
59
+ ### Dynamic dependencies
139
60
 
140
- Quant doesn't use dependency arrays. Each run records exactly what it read,
141
- so the dependencies change along with your `if` statements:
61
+ Each successful computation tracks the signals and computeds it actually read.
62
+ When a branch changes, dependencies from the previous branch are removed.
142
63
 
143
64
  ```ts
144
- const showFull = signal(false);
65
+ import { signal, computed, effect, read, set } from "reflex-quant";
66
+
67
+ const showLast = signal(false);
145
68
  const first = signal("Ada");
146
69
  const last = signal("Lovelace");
147
70
 
148
- const displayName = computed(() =>
149
- read(showFull) ? `${read(first)} ${read(last)}` : read(first),
71
+ const name = computed(() =>
72
+ read(showLast) ? read(first) + " " + read(last) : read(first),
150
73
  );
151
74
 
152
- effect(() => console.log(read(displayName))); // "Ada"
75
+ effect(() => console.log(read(name))); // Ada
153
76
 
154
- set(last, "Byron"); // (nothing: `last` isn't being read right now)
155
- set(showFull, true); // "Ada Byron"
156
- set(showFull, false); // "Ada"
157
- set(last, "King"); // (nothing again)
77
+ set(last, "Byron"); // no log: last is not a dependency yet
78
+ set(showLast, true); // Ada Byron
79
+ set(showLast, false); // Ada
80
+ set(last, "King"); // no log: the dependency was removed
158
81
  ```
159
82
 
160
- ### 5. No glitches, no duplicate runs
161
-
162
- When two computeds share a source, the effect still runs **once**, and it
163
- never sees a half-updated state:
164
-
165
- ```ts
166
- const first = signal("Ada");
167
- const last = signal("Lovelace");
168
- const upper = computed(() => read(first).toUpperCase());
169
- const initials = computed(() => read(first)[0] + read(last)[0]);
170
-
171
- effect(() => console.log(`${read(upper)} (${read(initials)})`));
172
- // ADA (AL)
173
-
174
- set(first, "Grace");
175
- // GRACE (GL) (one run, both values already fresh)
176
- ```
177
-
178
- ### 6. Unchanged results stop propagation
179
-
180
- If a computed recalculates and gets the same value, everything downstream stays
181
- put:
182
-
183
- ```ts
184
- const n = signal(1);
185
- const parity = computed(() => (read(n) % 2 === 0 ? "even" : "odd"));
186
-
187
- effect(() => console.log(read(parity))); // "odd"
188
-
189
- set(n, 3); // (nothing: still "odd")
190
- set(n, 4); // "even"
191
- ```
83
+ ### Equality and previous values
192
84
 
193
- Writing the same value to a signal is also a no-op (compared with `Object.is`).
85
+ Signals and computed results are compared with `Object.is`. Setting a signal to
86
+ the same value is a no-op. When a computed produces the same value as before,
87
+ its dependents do not rerun because of that computed.
194
88
 
195
- ### 7. Batch several writes into one update
89
+ For arrays and objects, replace the value rather than mutating it in place:
196
90
 
197
91
  ```ts
198
- import { batch } from "reflex-quant";
92
+ import { signal, update } from "reflex-quant";
199
93
 
200
- const x = signal(0);
201
- const y = signal(0);
202
- effect(() => console.log(`(${read(x)}, ${read(y)})`)); // (0, 0)
94
+ const todos = signal(["Read the contract"]);
203
95
 
204
- batch(() => {
205
- set(x, 10);
206
- set(y, 20);
207
- }); // (10, 20) (one run, not two)
96
+ update(todos, (list) => [...list, "Build something"]); // new array
208
97
  ```
209
98
 
210
- ### 8. Read without subscribing
211
-
212
- `peek` gives you an up-to-date value without making it a dependency.
213
- `untracked` does the same for a whole block of code.
99
+ A computed receives its last successfully committed value as `prev`. Before
100
+ the first successful run it receives the optional initial value, or `undefined`.
101
+ Returning `prev` lets you preserve object identity when a derived value is
102
+ equivalent:
214
103
 
215
104
  ```ts
216
- import { peek, untracked } from "reflex-quant";
105
+ import { signal, computed, effect, read, set } from "reflex-quant";
217
106
 
218
- const query = signal("cats");
219
- const page = signal(1);
107
+ type Cell = { col: number; row: number };
108
+ const mouse = signal({ x: 0, y: 0 });
220
109
 
221
- effect(() => console.log(`search "${read(query)}" page ${peek(page)}`));
222
- // search "cats" page 1
110
+ const cell = computed((prev: Cell | undefined) => {
111
+ const { x, y } = read(mouse);
112
+ const next = { col: Math.floor(x / 100), row: Math.floor(y / 100) };
113
+ return prev && prev.col === next.col && prev.row === next.row ? prev : next;
114
+ });
223
115
 
224
- set(page, 2); // (nothing: page was only peeked)
225
- set(query, "dogs"); // search "dogs" page 2
116
+ effect(() => console.log(read(cell))); // { col: 0, row: 0 }
117
+ set(mouse, { x: 10, y: 20 }); // no log: same cell
118
+ set(mouse, { x: 150, y: 20 }); // { col: 1, row: 0 }
226
119
  ```
227
120
 
228
- ---
121
+ Because computeds are lazy, `prev` advances once per successful computation,
122
+ not once per signal write. It is not a log of every intermediate value.
229
123
 
230
- ## Recipes
124
+ ### Effects and cleanup
231
125
 
232
- <details open>
233
- <summary><b>🛒 Shopping cart</b></summary>
126
+ An effect normally runs immediately. On a later change, Quant validates its
127
+ dependencies and reruns it when needed. The previous cleanup runs before the
128
+ rerun and on disposal.
234
129
 
235
130
  ```ts
236
- const items = signal([
237
- { name: "Coffee", price: 4, qty: 2 },
238
- { name: "Bagel", price: 3, qty: 1 },
239
- ]);
240
- const discount = signal(0);
241
-
242
- const subtotal = computed(() =>
243
- read(items).reduce((sum, i) => sum + i.price * i.qty, 0),
244
- );
245
- const total = computed(() => read(subtotal) * (1 - read(discount)));
246
-
247
- effect(() => console.log(`Total: $${read(total).toFixed(2)}`));
248
- // Total: $11.00
131
+ import { signal, effect, read, set, dispose } from "reflex-quant";
249
132
 
250
- update(items, (list) => [...list, { name: "Juice", price: 5, qty: 1 }]);
251
- // Total: $16.00
252
-
253
- set(discount, 0.1);
254
- // Total: $14.40
255
- ```
256
-
257
- </details>
258
-
259
- <details>
260
- <summary><b>✅ Todo list with a filter</b></summary>
133
+ const room = signal("general");
261
134
 
262
- ```ts
263
- const todos = signal([
264
- { text: "Write README", done: true },
265
- { text: "Ship 1.2.0", done: false },
266
- ]);
267
- const filter = signal<"all" | "open" | "done">("all");
268
-
269
- const visible = computed(() => {
270
- const f = read(filter);
271
- if (f === "all") return read(todos);
272
- return read(todos).filter((t) => t.done === (f === "done"));
135
+ const connection = effect(() => {
136
+ const current = read(room);
137
+ console.log("join", current);
138
+ return () => console.log("leave", current);
273
139
  });
274
- const left = computed(() => read(todos).filter((t) => !t.done).length);
275
-
276
- effect(() =>
277
- console.log(`${read(visible).map((t) => t.text).join(", ")} | ${read(left)} left`),
278
- );
279
- // Write README, Ship 1.2.0 | 1 left
280
-
281
- set(filter, "open");
282
- // Ship 1.2.0 | 1 left
283
-
284
- update(todos, (list) => list.map((t) => ({ ...t, done: true })));
285
- // | 0 left
286
- ```
287
-
288
- </details>
289
-
290
- <details>
291
- <summary><b>⏱ Debounced search</b> (with effect cleanup)</summary>
292
-
293
- ```ts
294
- const query = signal("");
140
+ // join general
295
141
 
296
- effect(() => {
297
- const q = read(query);
298
- const id = setTimeout(() => fetchResults(q), 300);
299
- return () => clearTimeout(id); // a new keystroke cancels the previous timer
300
- });
142
+ set(room, "random");
143
+ // leave general
144
+ // join random
301
145
 
302
- set(query, "r");
303
- set(query, "re");
304
- set(query, "reflex"); // only "reflex" is fetched
146
+ dispose(connection);
147
+ // leave random
305
148
  ```
306
149
 
307
- </details>
150
+ Effects are delivered synchronously. An effect created inside a batch or an
151
+ active delivery may have its first run deferred until that batch or delivery
152
+ drains. Reads are tracked only while the callback runs: read values before
153
+ scheduling a timer or promise if the effect should depend on them. The effect
154
+ callback may return a cleanup function synchronously.
308
155
 
309
- <details>
310
- <summary><b>🖱 Binding to the DOM</b> (no framework)</summary>
156
+ Disposal is terminal. Dispose effects when they are no longer needed; Quant does
157
+ not automatically own or dispose effects created by other effects. A disposed
158
+ computed never runs again, and its last committed value remains readable.
159
+ Disposing a node during its own run is safe: the run finishes before it
160
+ detaches. A computed that returns in that run commits its result; an effect
161
+ disposed during its run discards the cleanup returned by that run.
311
162
 
312
- ```ts
313
- const count = signal(0);
314
- const button = document.querySelector("button")!;
315
-
316
- button.addEventListener("click", () => update(count, (n) => n + 1));
317
-
318
- effect(() => {
319
- button.textContent = `Clicked ${read(count)} times`;
320
- });
321
- ```
163
+ ### Batch writes
322
164
 
323
- </details>
324
-
325
- <details>
326
- <summary><b>💾 Persisting to localStorage</b></summary>
165
+ `batch` defers effect delivery until the outermost batch ends. Writes commit
166
+ immediately, so reads and later writes inside the batch see the new values.
327
167
 
328
168
  ```ts
329
- const theme = signal(localStorage.getItem("theme") ?? "light");
169
+ import { signal, effect, read, set, batch } from "reflex-quant";
330
170
 
331
- effect(() => localStorage.setItem("theme", read(theme)));
171
+ const x = signal(0);
172
+ const y = signal(0);
173
+ effect(() => console.log(read(x), read(y))); // 0 0
332
174
 
333
- set(theme, "dark"); // saved
175
+ batch(() => {
176
+ set(x, 10);
177
+ console.log(read(x)); // 10
178
+ set(y, 20);
179
+ }); // 10 20, from the effect
334
180
  ```
335
181
 
336
- </details>
337
-
338
- <details>
339
- <summary><b>🎛 Custom equality</b> (skip updates that don't matter)</summary>
340
-
341
- A computed receives its previous value. If you return that same object,
342
- dependents treat the result as unchanged and don't rerun, so you don't need a
343
- separate comparator option:
344
-
345
- ```ts
346
- type Cell = { col: number; row: number };
347
- const mouse = signal({ x: 0, y: 0 });
348
-
349
- const cell = computed((prev: Cell | undefined) => {
350
- const { x, y } = read(mouse);
351
- const next = { col: Math.floor(x / 100), row: Math.floor(y / 100) };
352
- return prev && prev.col === next.col && prev.row === next.row ? prev : next;
353
- });
354
-
355
- effect(() => console.log(read(cell))); // { col: 0, row: 0 }
182
+ A batch is synchronous and is not a transaction: it does not roll writes back,
183
+ even if its callback throws. Its scope ends when the callback returns; work
184
+ after an `await` is outside that scope. A write from A to B and back to A still
185
+ commits two changes, so an effect depending directly on that signal can rerun.
356
186
 
357
- set(mouse, { x: 10, y: 20 }); // (nothing: same cell)
358
- set(mouse, { x: 150, y: 20 }); // { col: 1, row: 0 }
359
- ```
187
+ ### Read without tracking
360
188
 
361
- </details>
362
-
363
- ---
364
-
365
- ## API at a glance
366
-
367
- | Function | What it does |
368
- | ------------------------ | --------------------------------------------------------------------------------------------- |
369
- | `signal(value)` | Create a writable value. |
370
- | `computed(fn, initial?)` | Create a lazy, cached derived value. `fn(prev)` receives the last committed value. |
371
- | `effect(fn)` | Run `fn` now and again on every change it read. `fn` may return a cleanup function. Returns a handle. |
372
- | `read(x)` | Read a signal or computed and **subscribe** the current computation to it. `get(x)` is the same function (its 1.x name). |
373
- | `readSignal(s)` | `read` for a signal only, without the computed path: faster in loops that read many signals. |
374
- | `compute(c)` | `read` for a computed only (the same function, narrowed by type). |
375
- | `peek(x)` | Read the up-to-date value **without** subscribing. |
376
- | `set(s, value)` | Write a signal. Ignored if `Object.is(old, value)`. |
377
- | `update(s, fn)` | `set(s, fn(current))`. `fn` runs untracked. If it throws, nothing is written. |
378
- | `batch(fn)` | Run `fn`, then deliver all its writes as a single update. Returns `fn`'s result. |
379
- | `untracked(fn)` | Run `fn` without subscribing to anything it reads. |
380
- | `dispose(x)` | Stop an effect (running its cleanup) or detach a computed (its last committed value stays readable). |
381
- | `typeOf(x)` | `"signal"`, `"computed"` or `"effect"`, without evaluating anything. |
382
-
383
- > **Why `read(count)` and not `count()` or `count.value`?** Here the handle *is*
384
- > the reactive node. Quant allocates no wrapper object or getter closure, so
385
- > each signal costs one object.
386
- > Handles are opaque: their fields are internal and can differ between builds.
387
- > Access values through `read`, `readSignal`, `compute` or `peek`.
388
- >
389
- > **Why `readSignal`?** A signal never needs to be brought up to date; a
390
- > computed may have to run first. `read` serves both, so the computed path is
391
- > part of every read, and in loops that read many signals the engine pays for
392
- > it (`track.duplicate-64`, `stable.wide-8`). `readSignal` takes only a
393
- > `Signal` and has no computed path. Its type keeps computeds out; past the
394
- > types (plain JS or a cast), development builds throw, and production builds
395
- > would return a computed's last value without bringing it up to date.
396
-
397
- ## Good to know
398
-
399
- **Replace values, don't mutate them.** Quant compares values with `Object.is`.
400
- If you push into the same array, the array reference doesn't change, so nothing
401
- updates:
189
+ `peek` reads one signal or computed without subscribing the current computation.
190
+ `untracked` does the same for the synchronous reads in a callback.
402
191
 
403
192
  ```ts
404
- update(todos, (list) => { list.push("eggs"); return list; }); // ❌ no update
405
- update(todos, (list) => [...list, "eggs"]); // ✅ updates
406
- ```
193
+ import { signal, effect, read, peek, untracked, set } from "reflex-quant";
407
194
 
408
- **`prev` advances once per run, not once per write.** Computeds are lazy, so
409
- several writes made before anyone reads collapse into a single run:
195
+ const query = signal("cats");
196
+ const page = signal(1);
197
+ const locale = signal("en");
410
198
 
411
- ```ts
412
- const clicks = signal(0);
413
- const history = computed((prev) => [...prev, read(clicks)], [] as number[]);
199
+ effect(() => {
200
+ const currentQuery = read(query);
201
+ const currentPage = peek(page);
202
+ const currentLocale = untracked(() => read(locale));
203
+ console.log(currentQuery, currentPage, currentLocale);
204
+ });
205
+ // cats 1 en
414
206
 
415
- set(clicks, 1);
416
- set(clicks, 2);
417
- read(history); // [2] (1 was never observed)
207
+ set(page, 2); // no log
208
+ set(locale, "uk"); // no log
209
+ set(query, "dogs"); // dogs 2 uk
418
210
  ```
419
211
 
420
- If you need every write, append to the log in the code that does the writing,
421
- not in a computed.
422
-
423
- **Errors don't break the graph.** If a computed throws, `read` rethrows the error
424
- and the computed keeps its last good value as `prev`. Once its inputs are fixed,
425
- it recovers on the next read. If an effect throws during creation, it leaves
426
- nothing running.
427
-
428
- Two edges of error recovery are worth knowing. When a computed throws while an
429
- effect is checking whether it must rerun, that check stops there. The effect
430
- does not rerun until another change reaches it, even if a source the check
431
- never got to changes in the meantime; `read` still returns current values.
432
- And an effect whose first run throws can run once more before `effect()`
433
- throws, if that run triggered an update; side effects such as a request are
434
- not undone by the rollback.
435
-
436
- **Writes from inside a computation take effect afterwards.** If a callback
437
- writes a signal while a read is already checking its dependencies, that read
438
- may still answer from before the write. The next read sees it.
439
-
440
- The stack-safety guarantee covers Quant's graph walks: a chain of 100,000
441
- computeds is fine. It does not cover callbacks that call each other until
442
- the native JavaScript stack runs out. That is a resource failure of the
443
- host, and Quant promises nothing after a program catches it and goes on.
444
- An error a callback throws itself is an ordinary failure, handled as above.
445
-
446
- **Disposing from inside a run is safe.** A computed or effect may be
447
- disposed while it runs, by its own callback or by anything that callback
448
- calls. The run finishes, then the node detaches and never runs again. A
449
- computed's run that returns still commits its value, so the read that
450
- triggered it sees the new value and that value stays readable. If the run
451
- throws instead, the previous value stays. An effect disposed during its run
452
- drops the cleanup that run returns: disposal has already run the previous
453
- one, and nothing will run the new one.
454
-
455
- **Use the development build to catch cycles.** Bundlers that resolve the
456
- `development` export condition (Vite, webpack, and Node with
457
- `--conditions=development`) load a build that throws `Cycle detected` when a
458
- computed ends up reading itself. The production build skips this check and
459
- costs nothing extra.
460
-
461
- ## When to use something else
462
-
463
- Quant is deliberately a **core**: values, derivations, reactions. It doesn't
464
- include:
465
-
466
- - deep reactive objects or proxies (`store.user.name = …`),
467
- - async resources or suspense,
468
- - component lifecycles or ownership scopes (`effectScope` and similar),
469
- - a renderer.
470
-
471
- Each of these can be built on top of quant. None of them is included, because
472
- the [contract](CONTRACT.md) doesn't require them. If you need them out of the box, a
473
- full framework (Vue, Solid, Preact Signals, MobX) is a better fit.
474
-
475
- ---
212
+ ## API
213
+
214
+ | Function | Description |
215
+ | ------------------------ | --------------------------------------------------------------------------------------- |
216
+ | `signal(value)` | Create a writable signal. |
217
+ | `computed(fn, initial?)` | Create a lazy computed. `fn(prev)` receives the last committed value. |
218
+ | `effect(fn)` | Create an effect and return its handle. `fn` may return a cleanup. |
219
+ | `read(value)` | Read and track a signal or computed. `get` is an alias for the same function. |
220
+ | `readSignal(signal)` | Read and track a signal without the computed path. It accepts signals only. |
221
+ | `compute(computed)` | Read and track a computed; the same function as `read` with a narrower type. |
222
+ | `peek(value)` | Read an up-to-date value without tracking it. |
223
+ | `set(signal, value)` | Write a value, unless it is `Object.is`-equal to the current value. |
224
+ | `update(signal, fn)` | Write `fn(current)`. The callback runs untracked; if it throws, no value is written. |
225
+ | `batch(fn)` | Defer effect delivery through the synchronous callback. Return its result. |
226
+ | `untracked(fn)` | Run the synchronous callback without tracking its reads. Return its result. |
227
+ | `dispose(value)` | Stop an effect or detach a computed. |
228
+ | `typeOf(value)` | Identify a live handle as `"signal"`, `"computed"` or `"effect"` without evaluating it. |
229
+
230
+ The exported `Signal<T>`, `Computed<T>`, `Readable<T>` and `Effect` types keep
231
+ writable signals distinct from computed values. Handles are opaque; use the
232
+ functions above rather than accessing their fields. Use `typeOf` only with live
233
+ handles: a disposed computed can no longer be distinguished from a signal.
234
+
235
+ `readSignal` is a specialized entry point for signal-heavy paths. TypeScript
236
+ rejects a computed passed to it; the development build also checks this at
237
+ runtime. Use `read` or `compute` for computeds.
238
+
239
+ ## Errors and evaluation
240
+
241
+ A failing computed commits no value and, unless disposed, runs again on its
242
+ next demand; its previous successful value remains available as `prev`. If an
243
+ established effect fails, it can be reached again through its committed
244
+ dependencies and the dependencies read during the failed attempt. External side
245
+ effects are not rolled back.
246
+
247
+ If a computed throws while an effect is validating its dependencies, that
248
+ delivery stops before the effect's cleanup or rerun. The failure alone does
249
+ not schedule a retry. A later delivered invalidation can retry validation;
250
+ changes already coalesced into the failed delivery do not independently do so.
251
+
252
+ If `effect()` throws before returning a handle, it rolls back the new effect.
253
+ Already scheduled work in the same drain can still run before rollback, so any
254
+ side effects it performed remain. A first run deferred until after the handle
255
+ was returned is an established effect and follows the recovery rule above.
256
+ When a batch or drain encounters multiple errors, the first error is preserved
257
+ while required deferred deliveries are processed.
258
+
259
+ A write made during a computation or validation is a new change. A validation
260
+ already in progress can answer as of its start; subsequent work observes the
261
+ write. See the [contract](https://github.com/volynetstyle/reflex-quant/blob/main/CONTRACT.md)
262
+ for the precise failure and in-pass invalidation rules.
263
+
264
+ A computation must not demand a node whose execution or validation is already
265
+ in progress. This includes reactive cycles. The development build diagnoses
266
+ such demands; for example, enable it in Node with
267
+ `--conditions=development`. The production build does not provide the same
268
+ diagnostic.
269
+
270
+ Quant's stack-safety guarantee applies to its own graph walks. It does not
271
+ cover unbounded synchronous nesting of user callbacks that demand one another.
272
+
273
+ ## Scope
274
+
275
+ Quant is a reactive core. It does not include deep reactive proxies, async
276
+ resources, component lifecycles, ownership scopes or a renderer. Those can be
277
+ provided by an integration or framework when needed.
476
278
 
477
279
  ## Performance
478
280
 
281
+ The [benchmark page](https://volynetstyle.github.io/reflex-quant/benchmarks/)
282
+ contains per-scenario results from the project's CI suite, comparing Quant with
283
+ Reflex and alien-signals on the same runners. The
284
+ [performance history](https://github.com/volynetstyle/reflex-quant/blob/main/research/HISTORY.md)
285
+ records changes across runs.
286
+
479
287
  The broader [JS Reactivity Benchmark](https://volynetstyle.github.io/js-reactivity-benchmark/),
480
- maintained by Quant's author, compares 30 reactivity implementations. Its
288
+ maintained by Quant's author, compares a larger set of runtimes. Its
481
289
  [November 10, 2026 snapshot](https://github.com/volynetstyle/js-reactivity-benchmark/blob/9a26a3bee200fe9610e19cc21e0b8e02730b5459/index.html)
482
- ranked Quant 1.1.2 first with a **1.07×** family-balanced core score, versus
483
- **1.20×** for alien-signals 3.2.1. The score covers 33 shared core scenarios;
484
- stress and lifecycle capability tests are reported separately. Lower is better,
485
- and the scores are not the same as the pairwise time ratios below. No benchmark
486
- establishes a universally fastest library.
487
-
488
- The following is a separate, targeted snapshot of the newer Quant 1.2.0:
489
-
490
- Measured on CI against [Reflex](https://github.com/volynetstyle/Reflex) and
491
- [alien-signals](https://github.com/stackblitz/alien-signals), with all three
492
- runtimes on the same runner
493
- ([run 43479214912](https://github.com/volynetstyle/reflex-quant/actions/runs/43479214912), quant 1.2.0):
494
-
495
- - within 25 % of the faster of the two on **all 18** scenarios, and faster than both on **7** (plus a tie on
496
- `fan-out.effects-1000`, 0.998× the faster of the two);
497
- - geometric mean: **0.94×** the faster of the two per scenario, **0.92×** Reflex,
498
- **0.43×** alien-signals (lower is faster);
499
- - reorders allocate nothing. If a computation reads the same 256 sources in a
500
- rotated order on every pass, quant creates and removes **0** links per pass
501
- where alien-signals relinks 255 (`node bench/structure.mjs`), and takes 0.53×
502
- Reflex's time and 0.07× alien-signals' there;
503
- - Reflex is still faster on reversals, random permutations and sorts
504
- (`reorder.reverse-8` 1.13×, `value-sort.256x32` 1.19×, `long-reorder.256`
505
- 1.20×) and on the trivial read paths (`static.read-clean` 1.10×, the stable
506
- wide reads 1.13–1.17×); alien-signals is faster on `static.read-clean` (1.22×)
507
- and `lifecycle.mount-100` (1.10×).
508
-
509
- The suite is this project's own. Per-scenario numbers are on the
510
- [benchmarks page](https://volynetstyle.github.io/reflex-quant/benchmarks/), and the
511
- trajectory over CI runs is in [research/HISTORY.md](research/HISTORY.md).
512
-
513
- ## Correctness
514
-
515
- Quant is a research-driven library. Its design asks: what is the smallest known
516
- reactive runtime that satisfies a fixed contract? The contract is a set of semantic invariants and structural bounds in
517
- [CONTRACT.md](CONTRACT.md). It was extracted from the executable spec of
518
- [Reflex](https://github.com/volynetstyle/Reflex)
519
- (provenance in [research/REPORT.md](research/REPORT.md)). A mechanism is added
520
- only if dropping it would break the contract or the asymptotics. The ablations
521
- justify the mechanisms in this implementation; they do not prove a universal
522
- lower bound for every possible design.
523
-
524
- - **It found real bugs in Vue.** A port of quant's invariants to Vue 3.6 exposed
525
- two regressions in its Alien-derived reactivity core, both also reproducible
526
- in `alien-signals` 3.2.0. One was a lost update
527
- ([vuejs/core#16174](https://github.com/vuejs/core/issues/16174)). The other was
528
- generational-GC retention through removed links
529
- ([vuejs/core#16176](https://github.com/vuejs/core/issues/16176)). Both are
530
- now fixed upstream with permanent regression tests
531
- ([#16210](https://github.com/vuejs/core/pull/16210),
532
- [#16211](https://github.com/vuejs/core/pull/16211)).
533
- - **Differentially tested.** Quant gives the same answers as Reflex's executable
534
- spec, with three documented choices applied, on all 27 061 bounded and
535
- 18 660 recovery programs and on 100 000 generated ones. Graph integrity is
536
- checked after every operation.
537
- - **Nothing is optional.** Of the 67 ablations in `research/mutants.mjs`, 64
538
- make a test fail. The other 3 remove store orders kept as conventions
539
- (truthful transient state); the contract does not require them, and the
540
- [log](research/LOG.md) records why no test kills them. All 7 ablations of the
541
- development diagnostic fail a test of the development build.
542
- - Current Reflex is the same contract plus three failure-path choices. One of
543
- them drops an execution obligation that the contract (R2) says survives a
544
- failure.
545
-
546
- Read more: the [report](research/REPORT.md), the
547
- [design log](research/LOG.md) (one counterexample per mechanism), and the
548
- [`padawan`](https://github.com/volynetstyle/reflex-quant/tree/padawan) branch.
549
- That branch has the same semantics without the engineering (recursive push and pull,
550
- no counters), written as a guided tour, and it passes the same differential corpus.
551
-
552
- ## Under the hood
553
-
554
- The runtime has three layers:
555
-
556
- - **kernel**: the dependency machine (graph, tracking, propagation, validation);
557
- - **host**: effect lifecycle and delivery;
558
- - **surface**: the typed public API. It is a thin layer: no operation adds a field,
559
- a flag or a branch on a hot path ([research/LOG.md](research/LOG.md) item 26).
560
-
561
- The production build strips research instrumentation and development
562
- diagnostics. The illustrated
563
- [anatomy page](https://volynetstyle.github.io/reflex-quant/reactive-runtime-anatomy/)
564
- walks through each part.
565
-
566
- ```text
567
- src/ graph representation, kernel, host, public surface, instrumentation
568
- test/ differential (spec, contract spec, Reflex, quant), tracking,
569
- semantics, structural bounds; tools/ (QUANT_TOOLS=1)
570
- bench/ scenarios, adapters, build, timing (CI only), structure counters
571
- research/ evidence, design log, ablations, historical benchmark snapshots
572
- reference/ frozen Reflex implementation and provenance fixtures
573
- site/ the website (Astro)
574
- ```
575
-
576
- <details>
577
- <summary><b>Contributing: build, test and benchmark</b></summary>
578
-
579
- Development (including the site) uses Node.js 22.23.4 (see `.nvmrc`) or 24+
580
- and npm. The published library supports Node.js 18+. Run `npm ci` to install.
581
- The Reflex sources, spec harness and fixed production baseline live in
582
- `reference/reflex`, so you don't need a Reflex checkout.
290
+ ranked Quant 1.1.2 first on its family-balanced core score. This is a historical
291
+ result for that version and workload set, not a claim about every workload or
292
+ the current release.
293
+
294
+ ## Design and correctness
295
+
296
+ Quant is an experiment in deriving a minimal runtime from a written
297
+ [contract](https://github.com/volynetstyle/reflex-quant/blob/main/CONTRACT.md).
298
+ Core semantic and structural mechanisms are admitted only when their absence
299
+ violates an invariant or a declared structural bound; optimizations remain
300
+ possible within those obligations. The contract is Quant's own, with its
301
+ provenance recorded separately.
302
+
303
+ The test suite checks observable semantics, graph integrity and structural
304
+ bounds, including differential programs and failure recovery. Ablations test
305
+ what happens when mechanisms are removed from this implementation; they do not
306
+ prove that every possible implementation needs the same mechanisms.
307
+
308
+ The same invariants helped uncover a
309
+ [lost update](https://github.com/vuejs/core/issues/16174) and
310
+ [generational-GC retention](https://github.com/vuejs/core/issues/16176) in
311
+ Vue's reactivity implementation. For the evidence and limitations, see the
312
+ [research report](https://github.com/volynetstyle/reflex-quant/blob/main/research/REPORT.md),
313
+ [design log](https://github.com/volynetstyle/reflex-quant/blob/main/research/LOG.md)
314
+ and [architecture](https://github.com/volynetstyle/reflex-quant/blob/main/ARCHITECTURE.md).
315
+
316
+ ## Development
317
+
318
+ The repository uses Node.js 22.23.4 (see `.nvmrc`) or 24+ and npm. The
319
+ published library supports Node.js 18+. The Reflex reference sources and
320
+ fixtures are included in `reference/reflex`.
583
321
 
584
322
  ```sh
585
- npm run lint # lint production TypeScript
586
- npm run format:check # check production formatting
587
- npm run format # format production code and tool config
588
- npm run build && npm run check # standalone release and declarations
589
- npx vitest run --config vitest.config.ts # all tests, development build
590
- npm run test:production # the same suite, production build
591
- npx tsc -p tsconfig.json # typecheck src
592
- node research/mutants.mjs # ablation -> research/mutants.json
593
- node bench/build.mjs # bundles: quant, Reflex bf71877, alien-signals
594
- node bench/run.mjs --verify-only # same answers on all three runtimes
595
- node bench/structure.mjs # structural work per step
596
- node bench/run.mjs --rounds 9 # timing: run it on CI, not locally
597
- node bench/run.mjs --suite mechanisms --only '^push\.' # one mechanism: read write track push pull effect batch lifecycle
598
- node bench/run.mjs --suite scaling --only '^chain@' --out .cache/bench/s.json && node bench/scaling-report.mjs .cache/bench/s.json
599
- # growth with load: N = 16..4096, log-log slope per runtime
600
- node bench/cost/build.mjs && node bench/cost/run.mjs regime --rounds 0
601
- # cost-model probes (research/COST-MODEL.md); timing on CI
323
+ npm ci
324
+ npm run typecheck
325
+ npm run lint
326
+ npm run format:check
327
+ npm run build
328
+ npm run check
329
+ npm test
330
+ npm run test:production
602
331
  ```
603
332
 
604
- CI runs on Windows, macOS and Linux with Node 22.23.4 and 24. Each matrix job
605
- checks declarations, release artifacts, development and production tests, cost
606
- probe verification, and the site. Dependencies are installed from both lockfiles
607
- with `npm ci` (root and `site/`).
333
+ To verify the benchmark scenarios without collecting timings:
608
334
 
609
- `npm run check:bench` builds every cost probe and runs it in verification mode,
610
- including the independent leaf and decomposition cells, without collecting timings.
611
- `npm run check:bench -- --smoke` limits this to leaf and decomposition.
612
- `npm run check:site` builds the runtime and bench bundles, compares the site's
613
- visualizations with the runtime, builds Astro, and checks the generated internal
614
- page and asset URLs under the deployment base. Install site dependencies first
615
- with `npm ci --prefix site`.
616
-
617
- `.github/workflows/benchmark.yml` verifies all cost probes before any timing job
618
- starts, and it shares the verified bundles. Each timing job runs all three
619
- runtimes on one runner: compare ratios within a job, never times across jobs.
620
- Pages deployment uploads only a site that passed its checks. The Reflex
621
- benchmark baseline is fixed at commit `bf71877`; see
622
- `reference/reflex/README.md` for its provenance.
623
-
624
- Before proposing a change to the runtime, read [AGENTS.md](AGENTS.md) and
625
- [ARCHITECTURE.md](ARCHITECTURE.md). They describe the inclusion criterion
626
- a new mechanism has to meet.
335
+ ```sh
336
+ node bench/build.mjs
337
+ node bench/run.mjs --verify-only
338
+ ```
627
339
 
628
- </details>
340
+ See the [research guide](https://github.com/volynetstyle/reflex-quant/blob/main/research/README.md)
341
+ for ablations and further experiments. Before proposing a runtime change, read
342
+ [AGENTS.md](https://github.com/volynetstyle/reflex-quant/blob/main/AGENTS.md)
343
+ and [ARCHITECTURE.md](https://github.com/volynetstyle/reflex-quant/blob/main/ARCHITECTURE.md).
629
344
 
630
345
  ## License
631
346
 
632
- [MIT](LICENSE) © Andrii Volynets
347
+ [MIT](https://github.com/volynetstyle/reflex-quant/blob/main/LICENSE) © Andrii Volynets