@isograph/pico 0.0.0-main-5f205c00
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/LICENSE-MIT +7 -0
- package/README.md +152 -0
- package/dist/index.cjs +1154 -0
- package/dist/index.d.cts +176 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +176 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +1139 -0
- package/dist/index.mjs.map +1 -0
- package/docs/contracts.md +45 -0
- package/docs/correctness.md +233 -0
- package/docs/design.md +97 -0
- package/docs/disposing-nodes.md +171 -0
- package/docs/lifetimes.md +25 -0
- package/docs/performance.md +85 -0
- package/package.json +49 -0
- package/src/batch/batch.ts +133 -0
- package/src/batch/flush.ts +30 -0
- package/src/batch/notifications.ts +39 -0
- package/src/disposal/age-drain.ts +124 -0
- package/src/disposal/cleanup.ts +171 -0
- package/src/disposal/older-than-updates.ts +132 -0
- package/src/disposal/schedule.ts +78 -0
- package/src/disposal/take.ts +52 -0
- package/src/disposal/update-counter.ts +9 -0
- package/src/graph/edges.ts +167 -0
- package/src/graph/marking.ts +310 -0
- package/src/graph/nodes.ts +196 -0
- package/src/graph/read.ts +150 -0
- package/src/graph/recompute.ts +127 -0
- package/src/graph/refresh.ts +232 -0
- package/src/index.ts +18 -0
- package/src/retention/retain.ts +133 -0
- package/src/state.ts +39 -0
package/docs/design.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
---
|
|
2
|
+
slug: /design
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
# pico-js design
|
|
6
|
+
|
|
7
|
+
Each derived node keeps edges to the sources and derived nodes its computation read on its last run. Writing to a source marks its dependents. A later read refreshes only the nodes it needs. For a node with a change callback, pico-js also checks the value at the end of the update so it can notify the caller.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
const a = createSourceNode(1);
|
|
11
|
+
const b = createSourceNode(2);
|
|
12
|
+
const useA = createSourceNode(true);
|
|
13
|
+
|
|
14
|
+
const sum = createDerivedNode(
|
|
15
|
+
(callingNode) => readSource(callingNode, a) + readSource(callingNode, b),
|
|
16
|
+
);
|
|
17
|
+
const doubled = createDerivedNode(
|
|
18
|
+
(callingNode) => readDerived(callingNode, sum) * 2,
|
|
19
|
+
);
|
|
20
|
+
const chosen = createDerivedNode((callingNode) =>
|
|
21
|
+
readSource(callingNode, useA)
|
|
22
|
+
? readSource(callingNode, a)
|
|
23
|
+
: readSource(callingNode, b),
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
const doubledRetain = retainDerivedNode(doubled);
|
|
27
|
+
retainDerivedNode(chosen);
|
|
28
|
+
// sum is 3, doubled is 6, and chosen is 1
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Each example starts from this state unless it says otherwise.
|
|
32
|
+
|
|
33
|
+
## Invalidate upward
|
|
34
|
+
|
|
35
|
+
In this example both retains have no callback, so `writeSource(a, 10)` marks nodes without running a computation. It marks `sum` and `chosen` `DIRTY` because they read `a` directly. It marks `doubled` `MAYBE_DIRTY` because that node reads `sum`, whose new value is still unknown. A write to `b` would mark `sum` and `doubled` but leave `chosen` alone.
|
|
36
|
+
|
|
37
|
+
Once a write has marked a path, a second write can usually stop at the first already-marked reader. For example, if you write to `a` and then to `b` before reading anything, the second write finds `sum` already `DIRTY`. The exception involves readers first reached through a node with a callback, described [below](#marking-past-a-node-on-the-flush-queue).
|
|
38
|
+
|
|
39
|
+
## Lazily recompute
|
|
40
|
+
|
|
41
|
+
A read of a `CLEAN` node returns its cached value. Other reads may need to recompute the node or verify its dependencies. The flush uses the same rules when it refreshes nodes with callbacks.
|
|
42
|
+
|
|
43
|
+
A read of a `DIRTY` node recomputes it. `readDerivedOutsideComputation(chosen)` after `writeSource(a, 10)` runs the computation of `chosen`, which returns 10 and makes `chosen` `CLEAN`.
|
|
44
|
+
|
|
45
|
+
A read of a `MAYBE_DIRTY` node first brings its derived dependencies up to date, one at a time in the order the node read them. This check is called verification. It stops at the first derived dependency that changed, and then recomputes the node. A derived dependency changed if its recompute returned a value not `===` to its previous value. If none changed, the node becomes `CLEAN` without running. `readDerivedOutsideComputation(doubled)` after `writeSource(a, 10)` brings `sum` up to date first. `sum` is `DIRTY`, so it recomputes to 12. Its value changed, so `doubled` recomputes to 24.
|
|
46
|
+
|
|
47
|
+
Suppose `a` is 10 and `b` is 2. Both `sum` (12) and `doubled` (24) are `CLEAN`. Writing 11 to `a` and 1 to `b` marks `sum` as `DIRTY` and `doubled` as `MAYBE_DIRTY`. Reading `doubled` recomputes `sum`, which still returns 12. Verification then marks `doubled` as `CLEAN` without running its computation. The unchanged result cuts off propagation.
|
|
48
|
+
|
|
49
|
+
## Nodes with callbacks
|
|
50
|
+
|
|
51
|
+
A node with a callback has at least one retain with an `onChange` function. When marking first reaches such a node and takes it out of `CLEAN`, pico-js queues it for the flush. A second walk marks its dependents `MAYBE_DIRTY` so later reads will verify them, but leaves callbacks reached only through that walk off the queue. At the end of the update, the flush refreshes each queued node. If one needs the value of another queued node, the read refreshes that dependency first.
|
|
52
|
+
|
|
53
|
+
Retain `doubled` with a callback, `retainDerivedNode(doubled, (value) => console.log(value))`. `writeSource(a, 10)` marks `sum` `DIRTY`, and when marking reaches `doubled` it makes `doubled` `MAYBE_DIRTY` and puts it on the flush queue. The flush recomputes `sum` to 12 and `doubled` to 24, and the callback logs 24.
|
|
54
|
+
|
|
55
|
+
Now give `sum` a callback and leave `doubled` lazy. Writing the original value, `writeSource(a, 1)`, still queues `sum` because Pico treats every source write as an update. The flush recomputes `sum` to 3. Its result stayed equal, so reading `doubled` can reuse the cached 6.
|
|
56
|
+
|
|
57
|
+
### Marking past a node on the flush queue
|
|
58
|
+
|
|
59
|
+
Suppose both `sum` and `doubled` have callbacks. A write to `a` marks `sum` dirty and queues it. A second walk marks `doubled` `MAYBE_DIRTY` and sets its `MARKED_BEYOND` bit. This records that the write reached `doubled` through a queued callback node. A direct read of `doubled` will check its input, but the flush can wait for `sum`'s result before deciding whether to queue `doubled`.
|
|
60
|
+
|
|
61
|
+
- If `sum` changes, `markDependentsOfChangedDerivedNode` upgrades its direct reader `doubled` to `DIRTY`, clears the bit, and queues it for refresh.
|
|
62
|
+
- If `sum` keeps its value and no other input of `doubled` changed, the flush can leave `doubled` alone. Its next read verifies `sum` and reuses its cache.
|
|
63
|
+
- If another write reaches `doubled` through a path without a queued callback node, that write clears the bit and queues `doubled` itself. Its value can change independently of `sum`.
|
|
64
|
+
|
|
65
|
+
During refresh, a computation can read a callback node before the flush reaches its queue entry. That read refreshes the node immediately and records any change for notification. When the queue reaches the same node later, it is already `CLEAN`.
|
|
66
|
+
|
|
67
|
+
### Skipping repeated walks past a node
|
|
68
|
+
|
|
69
|
+
Suppose three components independently read the same price band, a derived node with a callback. Their edges appear in the band’s reader list in order R1, R2, R3. A price change within the same band leaves all three readers marked `MAYBE_DIRTY`, with the boundary at R1. Reading R1 verifies its cached value and makes it `CLEAN`. Its edge is already at the head, so the boundary advances to R2. The next marking pass checks R1, stops before R2, and moves the boundary back to R1. A further write with no intervening reads can skip all three edges.
|
|
70
|
+
|
|
71
|
+
A node on the flush queue that keeps its value still costs the walk past it. A projection that keeps its value on most writes and has N dependents with callbacks would have all N dependents visited on every such write, although after the first walk none of them is `CLEAN`. Each derived node therefore keeps a `firstKnownMarkedDependentEdge` boundary pointer into its list of dependents, which prepends new and moved edges at `firstDependent`. Every edge from `firstKnownMarkedDependentEdge` to the end of the list has a dependent that is not `CLEAN`. Every derived dependency of a `CLEAN` node is `CLEAN`, so no node above those dependents is `CLEAN` either. When the walk that sets `MARKED_BEYOND` visits a node, it walks only the prefix of edges before `firstKnownMarkedDependentEdge` and advances `firstKnownMarkedDependentEdge` to `firstDependent`, skipping the node when `firstDependent === firstKnownMarkedDependentEdge`.
|
|
72
|
+
|
|
73
|
+
A dependent becomes `CLEAN` only when its computation returns, after it read the node through `readDerived`, or when verification makes it `CLEAN`, after verification visited the dependent's edge to the node. A dependent joins the node's dependents only through `readDerived`. Every edge whose dependent may become `CLEAN` is placed strictly before `firstKnownMarkedDependentEdge`:
|
|
74
|
+
|
|
75
|
+
- `addEdgeToDerivedDependents` prepends every new or moved edge at `firstDependent`, strictly before `firstKnownMarkedDependentEdge`.
|
|
76
|
+
- `readDerived` calls `moveEdgeBeforeKnownMarkedDependents` on a reused edge when `firstKnownMarkedDependentEdge` is not `undefined`, moving the edge to `firstDependent` and advancing `firstKnownMarkedDependentEdge` if the edge was the boundary.
|
|
77
|
+
- `verifyDerivedDependencies` calls `moveEdgeBeforeKnownMarkedDependents` on each edge it visits when `dependency.firstKnownMarkedDependentEdge` is not `undefined`.
|
|
78
|
+
|
|
79
|
+
`removeEdgeFromDerivedDependents` advances `firstKnownMarkedDependentEdge` to `edge.nextDependentEdge` when unlinking the boundary edge itself, `markDependentsOfChangedDerivedNode` resets `firstKnownMarkedDependentEdge` to `undefined` so dependents recomputing after a value change skip `moveEdgeBeforeKnownMarkedDependents`, and disposal resets `firstKnownMarkedDependentEdge` to `undefined`. A derived node keeps its 12 fields, with `firstKnownMarkedDependentEdge` alongside `firstDependent` and no tail pointer.
|
|
80
|
+
|
|
81
|
+
Because only dependents that became `CLEAN` since the last beyond walk sit before `firstKnownMarkedDependentEdge`, if k of N dependents rerun or verify between two writes that leave the node unchanged, the second write walks only those k edges instead of all N. A move before `firstKnownMarkedDependentEdge` made inside a computation stays in effect until the computation returns, because the walk that advances `firstKnownMarkedDependentEdge` to `firstDependent` starts only from a write or a release, and neither runs inside a computation. [Correctness](./correctness.md) proves that the engine gives no stale read with `firstKnownMarkedDependentEdge`.
|
|
82
|
+
|
|
83
|
+
### When callbacks run
|
|
84
|
+
|
|
85
|
+
Callbacks run last, for every node on the flush queue whose value changed, and only after the flush has refreshed every node on the flush queue. They never run at the moment the value of a node on the flush queue changes. Retain `doubled` with a callback, as in "Nodes with callbacks", and retain `sum` with the callback `() => console.log(readDerivedOutsideComputation(doubled))`. `writeSource(a, 10)` puts `sum` on the flush queue and marks `doubled` `MAYBE_DIRTY` with `MARKED_BEYOND`, without putting `doubled` on the flush queue. The flush recomputes `sum` to 12, and only then marks `doubled` `DIRTY` and appends it to the flush queue behind `sum`. The flush refreshes `doubled` to 24 before it calls any callback, and the callback of `sum` then logs 24. By the time the first callback runs, both nodes hold their final values for this update.
|
|
86
|
+
|
|
87
|
+
## Dynamic dependencies
|
|
88
|
+
|
|
89
|
+
A computation can take a different branch on each run. After `writeSource(useA, false)`, the next read of `chosen` replaces its dependency on `a` with a dependency on `b`. Writes to `b` then invalidate `chosen`. Writes to `a` leave it alone.
|
|
90
|
+
|
|
91
|
+
## Batches
|
|
92
|
+
|
|
93
|
+
A batch stages one value per source. At commit Pico stores each value and marks its readers, then refreshes the affected nodes with callbacks. If `sum` has a callback, a batch that sets `a` to 10 and `b` to 20 recomputes `sum` once and delivers 30 to its callback. With only a plain retain, `sum` stays dirty until a read needs its value.
|
|
94
|
+
|
|
95
|
+
## Other documents
|
|
96
|
+
|
|
97
|
+
[Disposing nodes](./disposing-nodes.md) describes when pico-js disposes a cached node, [performance](./performance.md) describes the data structures and techniques that make the algorithm fast, and [correctness](./correctness.md) proves that no computation, top-level read, or change callback receives a stale value.
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
---
|
|
2
|
+
slug: /disposal
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
# Disposing nodes
|
|
6
|
+
|
|
7
|
+
A derived node becomes eligible for disposal when it has no retains and no dependents. The examples start with the graph below and continue from the preceding example unless stated otherwise.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
const a = createSourceNode(1);
|
|
11
|
+
const b = createSourceNode(2);
|
|
12
|
+
const useA = createSourceNode(true);
|
|
13
|
+
|
|
14
|
+
const sum = createDerivedNode(
|
|
15
|
+
(callingNode) => readSource(callingNode, a) + readSource(callingNode, b),
|
|
16
|
+
);
|
|
17
|
+
const doubled = createDerivedNode(
|
|
18
|
+
(callingNode) => readDerived(callingNode, sum) * 2,
|
|
19
|
+
);
|
|
20
|
+
const chosen = createDerivedNode((callingNode) =>
|
|
21
|
+
readSource(callingNode, useA)
|
|
22
|
+
? readSource(callingNode, a)
|
|
23
|
+
: readSource(callingNode, b),
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
const doubledRetain = retainDerivedNode(doubled);
|
|
27
|
+
retainDerivedNode(chosen);
|
|
28
|
+
// sum is 3, doubled is 6, and chosen is 1
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
A node is needed while it has a retain or a dependent, which is a node that read it on its latest run. A node with neither is unneeded. Disposing a node removes its edges, drops its cached value, and makes it `UNCOMPUTED`, which means it has no cached value, so the next read or retain computes it again. A dependency that loses its last dependent this way and has no retain becomes unneeded in turn. A recompute that stops reading a derived node has the same effect on that node, which joins the cleanup queue if it then has no dependent and no retain.
|
|
32
|
+
|
|
33
|
+
## The cleanup queue and the scheduler
|
|
34
|
+
|
|
35
|
+
After `releaseRetain(doubledRetain)`, `doubled` has no retains or dependents. It goes on the cleanup queue with its cached value and edges intact. A top-level read of an unneeded node also adds a queue entry, even if the node already has one. If something reads or retains `doubled` before disposal and its inputs are unchanged, it still returns 6 without recomputing.
|
|
36
|
+
|
|
37
|
+
A scheduler decides when the nodes on the cleanup queue are disposed. The default scheduler uses the two-update age rule described below. A custom scheduler chooses when to drain the queue. If the caller follows the contracts, pico-js never calls `scheduler.schedule` inside a batch, a computation, or a change callback, so no node is disposed while an operation that might still read it is running. A `readDerivedOutsideComputation` inside a computation that runs outside a flush breaks the contract and can call `scheduler.schedule` there, and the README states those results. Each disposal first checks that the node is still unneeded, so if `doubled` is retained again before the scheduler reaches it, the disposal skips it. When the scheduler disposes `doubled`, `sum` loses its last dependent and has no retain, so it joins the cleanup queue and is disposed next. `chosen` stays, because it has a retain.
|
|
38
|
+
|
|
39
|
+
## Disposing by age
|
|
40
|
+
|
|
41
|
+
`disposeAll` and `disposeNext` dispose `doubled` at the first drain after its release, even if `doubled` is retained again one update later. `disposeOlderThanUpdates(minAge)` waits instead. An update is a `writeSource` or a batch commit, and pico-js counts them. A call of `disposeOlderThanUpdates` is a drain. It disposes the node of each entry that is at least `minAge` updates old, if the node is still unneeded, and keeps the younger entries. A node can have several entries, and only the newest one counts: if `doubled` is released, retained, and released again, its age starts at the second release. Entries of a node that is needed at the drain, or already disposed, are dropped, because a release queues the node again when it becomes unneeded.
|
|
42
|
+
|
|
43
|
+
Each drain records the queue position of its boundary with the current update count, so the entries queued since the previous drain carry the count of this drain. An entry is at least `minAge` updates old when the count has grown by `minAge` since then. Drains without an update in between age nothing. When a drain leaves entries, pico-js calls `schedule` again at the end of the next outermost operation, so a scheduler drains once per call of `schedule` and never runs while the app is idle. An update that ends between an entry's enqueue and the next drain does not count for it, so its age can be short by those updates, which only delays its disposal.
|
|
44
|
+
|
|
45
|
+
Suppose the scheduler drains the queue once per update after `releaseRetain(doubledRetain)`. Each update writes to unrelated nodes, and the scheduler uses `minAge = 2`.
|
|
46
|
+
|
|
47
|
+
- The first `disposeOlderThanUpdates(2)` keeps `doubled`, which is 0 updates old, and returns 1.
|
|
48
|
+
- After one more update, the second keeps it at 1 update old and returns 1.
|
|
49
|
+
- After another, the third disposes `doubled`. `sum` loses its last dependent, so the same drain disposes it too, and the call returns 0. The age rule applies to the entries that releases, unlinks, and top-level reads queue; a node that a drain's own disposals leave unneeded is disposed in that drain, if it is still unneeded.
|
|
50
|
+
|
|
51
|
+
The entries queued between two drains lie next to each other in the queue, because entries are only appended. `disposeOlderThanUpdates` puts an `UNCOMPUTED` marker node at its last boundary. Every disposal skips an `UNCOMPUTED` node, so the marker stays until a `disposeNext`, `disposeAll`, or `takeUnneeded` removes it together with every entry above it. A drain that does not find the marker at its last boundary treats every entry as queued at the current update, so an entry is disposed later than `minAge` updates after a mixed call, never earlier.
|
|
52
|
+
|
|
53
|
+
A drain can take a budget, an `IdleDeadline` or a timestamp. It always makes its first disposal, then stops when the budget runs out. The old entries it did not reach stay queued with their ages, and the entries its disposals queued and its cascade did not reach stay queued with cascade status, in a first segment that the next drain finds old enough at every `minAge`. The default scheduler passes its idle period, or 5 ms in a `setTimeout` task, and asks for one more callback only when a drain ran out of budget with old entries left. The scan that starts a drain is not budgeted, because it must see every newer entry before it can judge an older one.
|
|
54
|
+
|
|
55
|
+
`takeUnneeded()` hands the queued nodes that are still unneeded to the caller and empties the queue, and `disposeIfUnneeded(node)` disposes one of them if it is still unneeded. With these two, a scheduler keeps its own record of when each node became unneeded, as in the custom scheduler example below. pico-js keeps no entry for a taken node. If the node is retained or read by another node while the caller holds it, `disposeIfUnneeded` returns `false` for it, and the release that makes it unneeded again queues it again.
|
|
56
|
+
|
|
57
|
+
## Updates dispose the unneeded nodes they mark
|
|
58
|
+
|
|
59
|
+
Marking takes a node out of `CLEAN` and leaves its cached value invalid or doubtful. If nobody needs that node, keeping it only means that later updates walk it. Marking therefore lists a node that it takes out of `CLEAN` while the node has no dependents and no retain, and the update disposes each listed node that is still unneeded and not `CLEAN`, and each dependency that this leaves unneeded and not `CLEAN`. A dependency that is `CLEAN` still has a current value, so it goes on the cleanup queue. When the update put nodes with callbacks on the flush queue, the flush does this after it brings them up to date and before it calls callbacks, and otherwise the update does it at its end. Inside a batch, both happen at the end of the batch. An unneeded node that was already `DIRTY` or `MAYBE_DIRTY` was not taken out of `CLEAN` by this update, so it waits on the cleanup queue.
|
|
60
|
+
|
|
61
|
+
Starting from the state after the release, and before the scheduler disposes `doubled`, suppose `writeSource(a, 10)` runs. Marking makes `sum` `DIRTY` and `doubled` `MAYBE_DIRTY`, and lists `doubled`, which has no dependents and no retain. The update disposes `doubled`, and then `sum`, which is `DIRTY` and has no dependents left. `chosen` is retained and stays `DIRTY`.
|
|
62
|
+
|
|
63
|
+
## Scheduling cleanup
|
|
64
|
+
|
|
65
|
+
The default scheduler calls `disposeOlderThanUpdates(2)` during an idle callback if the host provides `requestIdleCallback`. Otherwise it schedules a timer with a 5 ms work budget. If a drain runs out of time while eligible nodes remain, the default scheduler requests another callback.
|
|
66
|
+
|
|
67
|
+
Cleanup is controlled by `scheduler`, an object with a `schedule` function field that you can assign. pico-js calls `scheduler.schedule()` with no arguments at the end of the first call into pico-js that completes after the cleanup queue went from empty to non-empty, or after a `disposeOlderThanUpdates` that left entries on it. That call is a `writeSource`, `retainDerivedNode`, `releaseRetain`, or `readDerivedOutsideComputation` made outside a batch and outside a change callback, or the `endWriteBatch` that closes the batch. A `writeSource` to a source that has no dependents, or that no computation has read since the source was created or last written, returns without calling `schedule`, and the next of these calls calls it. Adding a node to a non-empty cleanup queue does not cause another call to `schedule`.
|
|
68
|
+
|
|
69
|
+
This scheduler uses the idle deadline as its disposal budget.
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
function drainInIdleTime(deadline: IdleDeadline) {
|
|
73
|
+
disposeOlderThanUpdates(2, deadline);
|
|
74
|
+
}
|
|
75
|
+
scheduler.schedule = () => requestIdleCallback(drainInIdleTime);
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
It differs from the default in one case: when a drain runs out of time with old nodes left, the default asks for another idle callback at once, and this one waits for the next call into pico-js.
|
|
79
|
+
|
|
80
|
+
To dispose everything at the end of each call into pico-js:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
scheduler.schedule = disposeAll;
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
To dispose in chunks, with the time budget of each idle callback:
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
function disposeInIdleTime(deadline: IdleDeadline) {
|
|
90
|
+
while (deadline.timeRemaining() > 0) {
|
|
91
|
+
if (!disposeNext()) {
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
requestIdleCallback(disposeInIdleTime);
|
|
96
|
+
}
|
|
97
|
+
scheduler.schedule = () => requestIdleCallback(disposeInIdleTime);
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
To dispose only when you choose, make `schedule` do nothing and call `disposeAll()` yourself, outside a write batch, a computation, and a change callback, for example when your app is idle. The contract then requires you to call `disposeAll()`, or to drain `disposeNext()`, later. Until you do, unneeded nodes stay cached, except that an update still disposes the unneeded nodes it marks:
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
scheduler.schedule = () => {};
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## Disposal functions
|
|
107
|
+
|
|
108
|
+
`disposeNext` and `disposeAll` dispose a node as soon as the scheduler runs, so a node that becomes unneeded and is used again one update later, for example a screen that an app leaves and comes back to, is disposed in between and computed again. Each of these strategies is a separate export, and a bundle that does not import one does not contain its code:
|
|
109
|
+
|
|
110
|
+
- `disposeAll()` disposes every node on the cleanup queue that is still unneeded, and every node that this leaves unneeded.
|
|
111
|
+
- `disposeNext()` disposes one node, the one most recently added to the cleanup queue, and returns whether the cleanup queue still has entries.
|
|
112
|
+
- `disposeOlderThanUpdates(minAge)` disposes the nodes that became unneeded at least `minAge` updates ago and are still unneeded, and keeps the rest on the cleanup queue. An update is a `writeSource` or a batch commit, with no batch open and no flush running; a `writeSource` to a source that has no dependents, or that no computation has read since its last write, returns before that and is not an update. A call of `disposeOlderThanUpdates` with no update since the previous call ages nothing, so idle periods alone never free a node. A node's age starts when it last became unneeded, or at its last top-level read while unneeded, so a node that is needed again in between starts over. The age rule applies to the entries that releases, unlinks, and top-level reads queue. The nodes that its own disposals leave unneeded, and those that disposing them leaves unneeded in turn, it disposes in the same call, as `disposeAll` does. It returns the number of entries still on the cleanup queue, and when that is not 0, pico-js calls `schedule` again at the end of the next outermost operation. `disposeOlderThanUpdates(minAge, budget)` takes an `IdleDeadline` or a `performance.now()` timestamp as its budget, and stops disposing when the budget runs out, but not before its first disposal. It keeps the rest queued: the old entries with their ages, and the entries that its own disposals queued with cascade status, which the next call disposes whatever `minAge` is. The scan of the whole queue that starts each call is the one part that the budget does not limit. An entry queued by a release, an unlink, or a top-level read counts its age from the first call of `disposeOlderThanUpdates` after it was queued, so its age can be short by the number of updates between its enqueue and that call, and the entry is never freed early. A call of `disposeNext`, `disposeAll`, or `takeUnneeded` in between can make it treat every entry as queued at the current update, which also only delays disposal. With `minAge` 0, it disposes every unneeded node queued before the call, and the nodes that this leaves unneeded. pico-js counts updates on every `writeSource` outside a batch that reaches marking and on each batch commit, one increment each, whether or not an app calls `disposeOlderThanUpdates`.
|
|
113
|
+
- `takeUnneeded()` empties the cleanup queue and returns its nodes that are still unneeded, oldest first, once per entry. pico-js then holds no entry for a taken node, and queues it again only when it is needed and becomes unneeded again, or on a top-level read while it is unneeded. A taken node that the caller never passes to `disposeIfUnneeded` and that is never queued again stays cached.
|
|
114
|
+
- `disposeIfUnneeded(node)` disposes `node` if it is unneeded and not already disposed, puts the nodes that this leaves unneeded on the cleanup queue, and returns whether it disposed `node`.
|
|
115
|
+
|
|
116
|
+
Call each of them outside write batches, computations, and change callbacks, as `disposeNext` and `disposeAll`.
|
|
117
|
+
|
|
118
|
+
`disposeOlderThanUpdates` can leave entries on the cleanup queue, and they can only age on a later update. When it leaves entries, pico-js calls `schedule` again at the end of the next outermost operation, that is, the next `writeSource`, `endWriteBatch`, `retainDerivedNode`, `releaseRetain`, or `readDerivedOutsideComputation` made outside a batch and outside a change callback. A scheduler that uses it therefore drains once per call of `schedule` and never asks for idle time on its own. It drains at most once more per burst of activity than the updates require, and never while the app is idle:
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
const MIN_AGE = 2;
|
|
122
|
+
function disposeOldInIdleTime() {
|
|
123
|
+
disposeOlderThanUpdates(MIN_AGE);
|
|
124
|
+
}
|
|
125
|
+
scheduler.schedule = () => requestIdleCallback(disposeOldInIdleTime);
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
A scheduler can keep its own record of the unneeded nodes with `takeUnneeded` and `disposeIfUnneeded`, for example to age them by wall-clock time, which pico-js itself does not read. This one is opt-in: it records in a `Map` the time at which it took each node, disposes a node 5 s after it took it last, and in the same idle callback disposes the nodes that those disposals leave unneeded, since nothing else runs during the callback. Taking a node again resets its time, and a node that is needed when its turn comes is forgotten, because pico-js queues it again when it becomes unneeded:
|
|
129
|
+
|
|
130
|
+
```ts
|
|
131
|
+
const MAX_AGE_MS = 5000;
|
|
132
|
+
const takenAt = new Map<DerivedNode<unknown>, number>();
|
|
133
|
+
// `schedule` is called again whenever a take has emptied the cleanup queue and
|
|
134
|
+
// it refills, so the flag keeps one idle callback pending.
|
|
135
|
+
let pending = false;
|
|
136
|
+
function requestDrain() {
|
|
137
|
+
if (!pending) {
|
|
138
|
+
pending = true;
|
|
139
|
+
requestIdleCallback(drainInIdleTime);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
function drainInIdleTime() {
|
|
143
|
+
pending = false;
|
|
144
|
+
const now = performance.now();
|
|
145
|
+
for (const node of takeUnneeded()) {
|
|
146
|
+
takenAt.set(node, now);
|
|
147
|
+
}
|
|
148
|
+
for (const [node, time] of takenAt) {
|
|
149
|
+
if (now - time >= MAX_AGE_MS) {
|
|
150
|
+
disposeIfUnneeded(node);
|
|
151
|
+
takenAt.delete(node);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
// The queue now holds only the nodes that these disposals left unneeded.
|
|
155
|
+
for (let left = takeUnneeded(); left.length > 0; left = takeUnneeded()) {
|
|
156
|
+
for (const node of left) {
|
|
157
|
+
disposeIfUnneeded(node);
|
|
158
|
+
takenAt.delete(node);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (takenAt.size > 0) {
|
|
162
|
+
requestDrain();
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
scheduler.schedule = requestDrain;
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
## Disposal contracts
|
|
169
|
+
|
|
170
|
+
- Run cleanup outside write batches, computations, and change callbacks.
|
|
171
|
+
- A custom scheduler must not throw, and once called it must keep calling `disposeNext` until it returns `false`, call `disposeAll`, or call `disposeOlderThanUpdates` once. If it stops early, the remaining unneeded nodes stay cached until something calls `disposeNext`, `disposeAll`, or `disposeOlderThanUpdates` again, and pico-js does not call `schedule` again until the cleanup queue has been emptied and refilled, or a `disposeOlderThanUpdates` leaves entries. If `schedule` throws, the error comes out of the call into pico-js that called it, after that call has done its work. `writeSource`, `endWriteBatch`, and `releaseRetain` have flushed. `retainDerivedNode` and `readDerivedOutsideComputation` have computed the node but return no retain or value, so a retain made that way can never be released. pico-js then does not call `schedule` again until the cleanup queue has been emptied and refilled.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
---
|
|
2
|
+
slug: /lifetimes
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
# Node lifetimes and SSR
|
|
6
|
+
|
|
7
|
+
## Retaining and releasing nodes
|
|
8
|
+
|
|
9
|
+
A retain keeps a node and its dependencies cached. `retainDerivedNode` brings the node up to date before returning the retain. A React component can retain the values it displays on mount and release them on unmount. When a node has no remaining retains or dependents, pico-js can reclaim its cached result.
|
|
10
|
+
|
|
11
|
+
Keep the retain handle for as long as the subscriber needs the node. Release that same handle when the subscriber goes away. Multiple components can retain the same node independently. Releasing one component’s retain leaves the other components subscribed.
|
|
12
|
+
|
|
13
|
+
## Disposal and garbage collection
|
|
14
|
+
|
|
15
|
+
Pico disposal drops a derived node’s cached value and removes its dependency edges. A caller that still holds the node can read it again. The next read computes a fresh value. JavaScript’s garbage collector reclaims the object itself once nothing references it. If an application keeps nodes in a lookup map, it must also drop those entries or the map when it no longer needs them.
|
|
16
|
+
|
|
17
|
+
The default cleanup scheduler gives recently abandoned results time to be reused, for example when two routes display the same record. The [disposal guide](./disposing-nodes.md) describes the queue, age threshold, and scheduler API.
|
|
18
|
+
|
|
19
|
+
## Server requests
|
|
20
|
+
|
|
21
|
+
A source holds its own value, and a derived node holds its own cached result. For request-specific data, create the nodes and any lookup maps per request. Reusing a module-level node for the current user would let requests overwrite one another’s data.
|
|
22
|
+
|
|
23
|
+
Requests that load the same copy of pico-js share its open batch and cleanup scheduler. Close each batch before yielding to another request. Otherwise a write from that request can join the pending writes, and an attempt to open another batch throws. Configure the scheduler once for the server.
|
|
24
|
+
|
|
25
|
+
For example, a request handler can create a source for that request’s viewer and pass its derived nodes to the renderer. After rendering, the handler releases any retains it created and drops references to the request’s store. The next request creates its own sources and derived nodes.
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
---
|
|
2
|
+
slug: /performance
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
# Performance
|
|
6
|
+
|
|
7
|
+
The examples below use `sum`, `doubled`, and `chosen` to show how pico-js stores dependencies and avoids repeated work. Unless an example gives a new starting state, it continues from the preceding one. The [design document](./design.md) describes the update algorithm.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
const a = createSourceNode(1);
|
|
11
|
+
const b = createSourceNode(2);
|
|
12
|
+
const useA = createSourceNode(true);
|
|
13
|
+
|
|
14
|
+
const sum = createDerivedNode(
|
|
15
|
+
(callingNode) => readSource(callingNode, a) + readSource(callingNode, b),
|
|
16
|
+
);
|
|
17
|
+
const doubled = createDerivedNode(
|
|
18
|
+
(callingNode) => readDerived(callingNode, sum) * 2,
|
|
19
|
+
);
|
|
20
|
+
const chosen = createDerivedNode((callingNode) =>
|
|
21
|
+
readSource(callingNode, useA)
|
|
22
|
+
? readSource(callingNode, a)
|
|
23
|
+
: readSource(callingNode, b),
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
const doubledRetain = retainDerivedNode(doubled);
|
|
27
|
+
retainDerivedNode(chosen);
|
|
28
|
+
// sum is 3, doubled is 6, and chosen is 1
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Benchmark results
|
|
32
|
+
|
|
33
|
+
On the Isograph application model, Pico was significantly faster than Alien Signals on 11 of 21 completed workloads and significantly slower on one. Against Preact Signals Core it was significantly faster on 12, with the other nine differences inconclusive. The table shows median event times for the application cases and elapsed time for the sparse-read graph benchmark.
|
|
34
|
+
|
|
35
|
+
| Workload | Pico | Alien Signals | Preact Signals Core |
|
|
36
|
+
| --------------------------------------------------------------------------- | -------: | ------------: | ------------------: |
|
|
37
|
+
| Navigate to a screen with 30% unchanged records | 15.53 ms | 17.15 ms | 19.51 ms |
|
|
38
|
+
| Update a rarely changing field with 1,000 readers and independent rerenders | 2.33 µs | 21.89 µs | 18.26 µs |
|
|
39
|
+
| Read 10 leaves out of 10,000 after a write | 775.1 µs | 813.4 µs | 69.67 µs |
|
|
40
|
+
|
|
41
|
+
These runs used the Pico engine at `26644a430`, Alien Signals 3.2.1, Preact Signals Core 1.14.5, and Node 24.12.0. The [full comparison](https://github.com/isographlabs/isograph/pull/1027#issuecomment-7286974637) includes per-scenario descriptions, p95 latency, work counts, and paired confidence intervals.
|
|
42
|
+
|
|
43
|
+
## Edge lists
|
|
44
|
+
|
|
45
|
+
Each dependency edge belongs to two lists. The dependent stores its source edges and derived edges in separate singly linked lists, in read order. Recomputing walks each list from the front and removes any unused suffix. The dependency stores a doubly linked list of its dependents, so pico-js can unlink any edge in constant time. The edge itself contains both sets of links. For example, the edge from `sum` to `a` belongs to both the source list of `sum` and the dependents list of `a`. Marking walks dependents. Verification walks derived dependencies.
|
|
46
|
+
|
|
47
|
+
## Positional edge reuse
|
|
48
|
+
|
|
49
|
+
A recompute reuses the edges of the previous run by position. The n-th source read takes the n-th source edge, the n-th derived read takes the n-th derived edge, and an edge moves only when its read is of a different node. Once the edges of the previous run are used up, a read adds an edge, unless it reads the same node as the previous read of its kind. Edges beyond the last read are removed. When `sum` recomputes and reads `a` and then `b` again, both edges stay and no edge is allocated. After `writeSource(useA, false)` and a read of `chosen`, its first source edge stays and its second moves from the dependents of `a` to the dependents of `b`.
|
|
50
|
+
|
|
51
|
+
A `DIRTY` node that is still needed keeps its edges until it recomputes, so its recompute reuses them instead of unlinking and relinking them. An update disposes an unneeded `DIRTY` node (see [disposing nodes](./disposing-nodes.md)).
|
|
52
|
+
|
|
53
|
+
## The source's record
|
|
54
|
+
|
|
55
|
+
After `writeSource(a, 10)` walks its dependents, `a` records that every node that read it is already `DIRTY`. A computation that reads `a` clears the record. Until then, `writeSource(a, 11)` only stores the value and walks nothing, which saves the walk over the dependents of a source that is written repeatedly without being read in between.
|
|
56
|
+
|
|
57
|
+
## Passing `callingNode`
|
|
58
|
+
|
|
59
|
+
A computation passes its `callingNode` to `readSource` and `readDerived`. Nested computations can therefore record dependencies without saving and restoring a global current node. The public types prevent a caller from passing a source or a derived-node handle in place of a `CallingNode`.
|
|
60
|
+
|
|
61
|
+
One experimental engine build kept the current computation in a global. On a write followed by a read of a retained three-node chain, its timing was within noise of the explicit `callingNode` API. On a write that made one node reread 1,000 derived nodes, the global version took 4.7% longer. It took 1.4% to 8.2% longer in three of 22 application scenarios. The other differences were within noise.
|
|
62
|
+
|
|
63
|
+
A separate experimental wrapper also uses a closure for each read and dispatches on the node kind. In the original wrapper benchmark, the three-node and 1,000-dependency cases took 1.34 and 1.91 times as long as direct calls, respectively. Across 59 cases, `batch(fn)` took 3% to 27% longer than explicit batch calls in eight, mostly repeated write batches and effect churn. It was faster in three. The remaining differences were within noise.
|
|
64
|
+
|
|
65
|
+
## Explicit stacks
|
|
66
|
+
|
|
67
|
+
Marking, disposal, and the descent of verification through lazy `MAYBE_DIRTY` nodes walk the graph with explicit stacks, so a long chain of such nodes does not overflow the call stack. A chain of nodes that compute for the first time, or that are all `DIRTY`, recurses through the computations, and uses the call stack. Verification through `MAYBE_DIRTY` nodes with callbacks uses the call stack too, because `verifyDerivedDependencies` pulls a dependency with a callback, and that pull verifies the dependency in a call of its own. The [contracts](./contracts.md) give the chain lengths at which each of these overflowed. A stack is allocated only when it is needed. Marking allocates one when a walk through lazy nodes branches, and allocates `beyondCallbackStack` when a queued callback node has reader edges to mark before its known-marked boundary. Verification allocates one when it descends into a node with several dependents. Disposal allocates one when a disposed node leaves a dependency that is not `CLEAN` unneeded.
|
|
68
|
+
|
|
69
|
+
## Allocation
|
|
70
|
+
|
|
71
|
+
An update that puts no node with a callback on the flush queue allocates no flush queue, and a batch commit allocates its flush queue on the first callback node it marks. An empty batch or a batch that writes one source needs no map. A batch that writes several sources stores the additional pending values in a map. The list of unneeded nodes is one module-level array that every update reuses. pico-js writes its entries by index and keeps a count of the entries in use. Clearing the list sets each entry in use to `undefined` and the count to 0, as the list of changed nodes does, so the array is never truncated, and a later update writes into the slots it already has.
|
|
72
|
+
|
|
73
|
+
## Object shape and equality
|
|
74
|
+
|
|
75
|
+
Pico uses separate source and derived edge helpers so each access to `firstDependent` sees only one kind of node. V8 can then specialize that access when its receivers share a hidden class. The representation of `.value` matters even when the helper only reads links. Derived nodes start with `value: undefined`. On Node 24.12, derived nodes that later held an integer, a double, a string, or an object all shared a hidden class. Sources start with the supplied value. In the same test, sources created with integers before the first double had a different hidden class from sources created afterward. [V8 describes how field representations affect hidden classes.](https://v8.dev/blog/react-cliff)
|
|
76
|
+
|
|
77
|
+
New edges prepend at `firstDependent`, so neither node needs a tail pointer: a source node has 3 fields, and a derived node keeps its 12 fields with `firstKnownMarkedDependentEdge`. Equality is `===` only, with no comparison function to call.
|
|
78
|
+
|
|
79
|
+
## State constants
|
|
80
|
+
|
|
81
|
+
The runtime imports named states and bit masks from `src/state.ts`. Both package builds inline their numeric values, so a check such as `node.status === CLEAN` compiles to `node.status === 3`.
|
|
82
|
+
|
|
83
|
+
## Runtime checks
|
|
84
|
+
|
|
85
|
+
Starting a batch checks whether one is already open. Callers enforce the restrictions on reads, writes, and computations described in the [contracts](./contracts.md).
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@isograph/pico",
|
|
3
|
+
"version": "0.0.0-main-5f205c00",
|
|
4
|
+
"description": "A graph of source nodes and derived nodes, recomputed on read when an input changed.",
|
|
5
|
+
"publishConfig": {
|
|
6
|
+
"access": "public"
|
|
7
|
+
},
|
|
8
|
+
"files": [
|
|
9
|
+
"LICENSE-MIT",
|
|
10
|
+
"dist",
|
|
11
|
+
"docs",
|
|
12
|
+
"src"
|
|
13
|
+
],
|
|
14
|
+
"main": "./dist/index.cjs",
|
|
15
|
+
"types": "./dist/index.d.cts",
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"dependencies": {},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"typescript": "5.6.3",
|
|
20
|
+
"vitest": "^2.1.2"
|
|
21
|
+
},
|
|
22
|
+
"repository": {
|
|
23
|
+
"type": "git",
|
|
24
|
+
"url": "git+https://github.com/isographlabs/isograph.git",
|
|
25
|
+
"directory": "libs/pico-js"
|
|
26
|
+
},
|
|
27
|
+
"sideEffects": false,
|
|
28
|
+
"module": "./dist/index.mjs",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"module-sync": "./dist/index.mjs",
|
|
32
|
+
"module": "./dist/index.mjs",
|
|
33
|
+
"node": "./dist/index.cjs",
|
|
34
|
+
"default": "./dist/index.mjs"
|
|
35
|
+
},
|
|
36
|
+
"./package.json": "./package.json"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"compile-libs": "tsdown",
|
|
40
|
+
"watch-libs": "tsdown --watch",
|
|
41
|
+
"test": "vitest run",
|
|
42
|
+
"test-watch": "vitest watch",
|
|
43
|
+
"test:random": "vitest run --config vitest.random.config.ts",
|
|
44
|
+
"test:exhaustive": "vitest run --config vitest.exhaustive.config.ts",
|
|
45
|
+
"coverage": "vitest run --coverage",
|
|
46
|
+
"tsc": "tsc -b",
|
|
47
|
+
"tsc-force": "tsc --build --clean && tsc --build --force"
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { FLUSH_IDLE } from '../state';
|
|
2
|
+
import {
|
|
3
|
+
markedUnneededCount,
|
|
4
|
+
markDependentsOfWrittenSource,
|
|
5
|
+
storeSourceValueAndFindDependentsToMark,
|
|
6
|
+
} from '../graph/marking';
|
|
7
|
+
import type {
|
|
8
|
+
MutableDerivedNode,
|
|
9
|
+
MutableSourceNode,
|
|
10
|
+
SourceNode,
|
|
11
|
+
} from '../graph/nodes';
|
|
12
|
+
import { disposeMarkedUnneededNodes } from '../disposal/cleanup';
|
|
13
|
+
import { refreshQueuedNodesAndNotifyCallbacks, flushState } from './flush';
|
|
14
|
+
import { scheduleCleanupIfRequested } from '../disposal/schedule';
|
|
15
|
+
import { incrementUpdateCount } from '../disposal/update-counter';
|
|
16
|
+
|
|
17
|
+
/** Stage a write in the open batch, or publish it immediately when no batch is open. */
|
|
18
|
+
export function writeSource<TValue>(
|
|
19
|
+
source: SourceNode<TValue>,
|
|
20
|
+
value: TValue,
|
|
21
|
+
): void {
|
|
22
|
+
if (firstPendingSource !== CLOSED_BATCH) {
|
|
23
|
+
// Each entry keeps the value paired with its source at this call. The
|
|
24
|
+
// batch erases the value type because different sources can share a batch.
|
|
25
|
+
const pending = source as MutableSourceNode<unknown>;
|
|
26
|
+
if (firstPendingSource === pending) {
|
|
27
|
+
firstPendingValue = value;
|
|
28
|
+
} else if (firstPendingSource === undefined) {
|
|
29
|
+
firstPendingSource = pending;
|
|
30
|
+
firstPendingValue = value;
|
|
31
|
+
} else {
|
|
32
|
+
(otherWrites ??= new Map()).set(pending, value);
|
|
33
|
+
}
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
const firstDependentToMark = storeSourceValueAndFindDependentsToMark(
|
|
37
|
+
source as MutableSourceNode<TValue>,
|
|
38
|
+
value,
|
|
39
|
+
);
|
|
40
|
+
if (firstDependentToMark === undefined) return;
|
|
41
|
+
flushQueuedNodesOrDisposeMarkedNodes(
|
|
42
|
+
markDependentsOfWrittenSource(undefined, firstDependentToMark),
|
|
43
|
+
);
|
|
44
|
+
countUpdateAndScheduleCleanupIfIdle();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// CLOSED_BATCH means no batch is open. undefined means the open batch has no writes.
|
|
48
|
+
const CLOSED_BATCH = Symbol('closed batch');
|
|
49
|
+
|
|
50
|
+
let firstPendingSource:
|
|
51
|
+
| MutableSourceNode<unknown>
|
|
52
|
+
| undefined
|
|
53
|
+
| typeof CLOSED_BATCH = CLOSED_BATCH;
|
|
54
|
+
|
|
55
|
+
let firstPendingValue: unknown;
|
|
56
|
+
|
|
57
|
+
let otherWrites: Map<MutableSourceNode<unknown>, unknown> | undefined;
|
|
58
|
+
|
|
59
|
+
export function flushQueuedNodesOrDisposeMarkedNodes(
|
|
60
|
+
queue: Array<MutableDerivedNode<unknown>> | undefined,
|
|
61
|
+
): void {
|
|
62
|
+
if (queue !== undefined) {
|
|
63
|
+
refreshQueuedNodesAndNotifyCallbacks(queue);
|
|
64
|
+
} else if (markedUnneededCount > 0) {
|
|
65
|
+
disposeMarkedUnneededNodes();
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function countUpdateAndScheduleCleanupIfIdle(): void {
|
|
70
|
+
if (flushState === FLUSH_IDLE) {
|
|
71
|
+
incrementUpdateCount();
|
|
72
|
+
scheduleCleanupIfRequested();
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Open one synchronous write batch. Callers must not nest batches or read or retain nodes inside one. */
|
|
77
|
+
export function startWriteBatch(): void {
|
|
78
|
+
if (firstPendingSource !== CLOSED_BATCH)
|
|
79
|
+
throw new Error('A write batch is already open.');
|
|
80
|
+
firstPendingSource = undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Publish the last write to each source, refresh the graph, then notify subscribers. */
|
|
84
|
+
export function endWriteBatch(): void {
|
|
85
|
+
const source = firstPendingSource;
|
|
86
|
+
if (source === CLOSED_BATCH) return;
|
|
87
|
+
firstPendingSource = CLOSED_BATCH;
|
|
88
|
+
let queue: Array<MutableDerivedNode<unknown>> | undefined;
|
|
89
|
+
if (source !== undefined) {
|
|
90
|
+
const firstDependentToMark = storeSourceValueAndFindDependentsToMark(
|
|
91
|
+
source,
|
|
92
|
+
firstPendingValue,
|
|
93
|
+
);
|
|
94
|
+
firstPendingValue = undefined;
|
|
95
|
+
if (firstDependentToMark !== undefined)
|
|
96
|
+
queue = markDependentsOfWrittenSource(undefined, firstDependentToMark);
|
|
97
|
+
if (otherWrites !== undefined) {
|
|
98
|
+
for (const [other, value] of otherWrites) {
|
|
99
|
+
const edge = storeSourceValueAndFindDependentsToMark(other, value);
|
|
100
|
+
if (edge !== undefined)
|
|
101
|
+
queue = markDependentsOfWrittenSource(queue, edge);
|
|
102
|
+
}
|
|
103
|
+
otherWrites = undefined;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
flushQueuedNodesOrDisposeMarkedNodes(queue);
|
|
107
|
+
countUpdateAndScheduleCleanupIfIdle();
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* An outermost operation is a call to `writeSource`, `endWriteBatch`,
|
|
112
|
+
* `retainDerivedNode`, `releaseRetain`, or `readDerivedOutsideComputation` made with no
|
|
113
|
+
* batch open and no flush running, or the `endWriteBatch` that commits the writes.
|
|
114
|
+
*
|
|
115
|
+
* Internal invariant: a top-level read never runs inside a computation or a
|
|
116
|
+
* batch body (its contract), so a top-level read inside an `onChange` is the
|
|
117
|
+
* only nesting of operations outside a batch, and the flush state covers it.
|
|
118
|
+
*/
|
|
119
|
+
export function scheduleCleanupIfOutsideBatchAndFlush(): void {
|
|
120
|
+
if (firstPendingSource === CLOSED_BATCH && flushState === FLUSH_IDLE) {
|
|
121
|
+
scheduleCleanupIfRequested();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Top-level reads are forbidden in batch bodies. An onChange callback can
|
|
127
|
+
* still read during a flush.
|
|
128
|
+
*/
|
|
129
|
+
export function scheduleCleanupIfNotFlushing(): void {
|
|
130
|
+
if (flushState === FLUSH_IDLE) {
|
|
131
|
+
scheduleCleanupIfRequested();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { disposeMarkedUnneededNodes } from '../disposal/cleanup';
|
|
2
|
+
import { markedUnneededCount } from '../graph/marking';
|
|
3
|
+
import type { MutableDerivedNode } from '../graph/nodes';
|
|
4
|
+
import { refreshNodesInFlushQueue } from '../graph/refresh';
|
|
5
|
+
import { FLUSH_IDLE, FLUSH_RUNNING } from '../state';
|
|
6
|
+
import { notifyRetainsOfChangedNodes } from './notifications';
|
|
7
|
+
|
|
8
|
+
type FlushState = typeof FLUSH_IDLE | typeof FLUSH_RUNNING;
|
|
9
|
+
|
|
10
|
+
export let flushState: FlushState = FLUSH_IDLE;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Guarantee: every `onChange` runs after the flush has refreshed every node
|
|
14
|
+
* on the flush queue, in the order of each node's first recompute that
|
|
15
|
+
* changed its value.
|
|
16
|
+
*
|
|
17
|
+
* Internal invariant: an `onChange` writes nothing, so it puts no node on the
|
|
18
|
+
* flush queue and no node on the marked-unneeded list.
|
|
19
|
+
*/
|
|
20
|
+
export function refreshQueuedNodesAndNotifyCallbacks(
|
|
21
|
+
flushQueue: Array<MutableDerivedNode<unknown>>,
|
|
22
|
+
): void {
|
|
23
|
+
flushState = FLUSH_RUNNING;
|
|
24
|
+
refreshNodesInFlushQueue(flushQueue);
|
|
25
|
+
if (markedUnneededCount > 0) {
|
|
26
|
+
disposeMarkedUnneededNodes();
|
|
27
|
+
}
|
|
28
|
+
notifyRetainsOfChangedNodes();
|
|
29
|
+
flushState = FLUSH_IDLE;
|
|
30
|
+
}
|