Disposing nodes
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.
const a = createSourceNode(1);
const b = createSourceNode(2);
const useA = createSourceNode(true);
const sum = createDerivedNode(
(callingNode) => readSource(callingNode, a) + readSource(callingNode, b),
);
const doubled = createDerivedNode(
(callingNode) => readDerived(callingNode, sum) * 2,
);
const chosen = createDerivedNode((callingNode) =>
readSource(callingNode, useA)
? readSource(callingNode, a)
: readSource(callingNode, b),
);
const doubledRetain = retainDerivedNode(doubled);
retainDerivedNode(chosen);
// sum is 3, doubled is 6, and chosen is 1
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.
The cleanup queue and the scheduler
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.
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.
Disposing by age
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.
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.
Suppose the scheduler drains the queue once per update after releaseRetain(doubledRetain). Each update writes to unrelated nodes, and the scheduler uses minAge = 2.
- The first
disposeOlderThanUpdates(2)keepsdoubled, which is 0 updates old, and returns 1. - After one more update, the second keeps it at 1 update old and returns 1.
- After another, the third disposes
doubled.sumloses 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.
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.
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.
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.
Updates dispose the unneeded nodes they mark
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.
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.
Scheduling cleanup
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.
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.
This scheduler uses the idle deadline as its disposal budget.
function drainInIdleTime(deadline: IdleDeadline) {
disposeOlderThanUpdates(2, deadline);
}
scheduler.schedule = () => requestIdleCallback(drainInIdleTime);
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.
To dispose everything at the end of each call into pico-js:
scheduler.schedule = disposeAll;
To dispose in chunks, with the time budget of each idle callback:
function disposeInIdleTime(deadline: IdleDeadline) {
while (deadline.timeRemaining() > 0) {
if (!disposeNext()) {
return;
}
}
requestIdleCallback(disposeInIdleTime);
}
scheduler.schedule = () => requestIdleCallback(disposeInIdleTime);
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:
scheduler.schedule = () => {};
Disposal functions
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:
disposeAll()disposes every node on the cleanup queue that is still unneeded, and every node that this leaves unneeded.disposeNext()disposes one node, the one most recently added to the cleanup queue, and returns whether the cleanup queue still has entries.disposeOlderThanUpdates(minAge)disposes the nodes that became unneeded at leastminAgeupdates ago and are still unneeded, and keeps the rest on the cleanup queue. An update is awriteSourceor a batch commit, with no batch open and no flush running; awriteSourceto 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 ofdisposeOlderThanUpdateswith 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, asdisposeAlldoes. It returns the number of entries still on the cleanup queue, and when that is not 0, pico-js callsscheduleagain at the end of the next outermost operation.disposeOlderThanUpdates(minAge, budget)takes anIdleDeadlineor aperformance.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 whateverminAgeis. 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 ofdisposeOlderThanUpdatesafter 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 ofdisposeNext,disposeAll, ortakeUnneededin between can make it treat every entry as queued at the current update, which also only delays disposal. WithminAge0, it disposes every unneeded node queued before the call, and the nodes that this leaves unneeded. pico-js counts updates on everywriteSourceoutside a batch that reaches marking and on each batch commit, one increment each, whether or not an app callsdisposeOlderThanUpdates.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 todisposeIfUnneededand that is never queued again stays cached.disposeIfUnneeded(node)disposesnodeif it is unneeded and not already disposed, puts the nodes that this leaves unneeded on the cleanup queue, and returns whether it disposednode.
Call each of them outside write batches, computations, and change callbacks, as disposeNext and disposeAll.
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:
const MIN_AGE = 2;
function disposeOldInIdleTime() {
disposeOlderThanUpdates(MIN_AGE);
}
scheduler.schedule = () => requestIdleCallback(disposeOldInIdleTime);
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:
const MAX_AGE_MS = 5000;
const takenAt = new Map<DerivedNode<unknown>, number>();
// `schedule` is called again whenever a take has emptied the cleanup queue and
// it refills, so the flag keeps one idle callback pending.
let pending = false;
function requestDrain() {
if (!pending) {
pending = true;
requestIdleCallback(drainInIdleTime);
}
}
function drainInIdleTime() {
pending = false;
const now = performance.now();
for (const node of takeUnneeded()) {
takenAt.set(node, now);
}
for (const [node, time] of takenAt) {
if (now - time >= MAX_AGE_MS) {
disposeIfUnneeded(node);
takenAt.delete(node);
}
}
// The queue now holds only the nodes that these disposals left unneeded.
for (let left = takeUnneeded(); left.length > 0; left = takeUnneeded()) {
for (const node of left) {
disposeIfUnneeded(node);
takenAt.delete(node);
}
}
if (takenAt.size > 0) {
requestDrain();
}
}
scheduler.schedule = requestDrain;
Disposal contracts
- Run cleanup outside write batches, computations, and change callbacks.
- A custom scheduler must not throw, and once called it must keep calling
disposeNextuntil it returnsfalse, calldisposeAll, or calldisposeOlderThanUpdatesonce. If it stops early, the remaining unneeded nodes stay cached until something callsdisposeNext,disposeAll, ordisposeOlderThanUpdatesagain, and pico-js does not callscheduleagain until the cleanup queue has been emptied and refilled, or adisposeOlderThanUpdatesleaves entries. Ifschedulethrows, the error comes out of the call into pico-js that called it, after that call has done its work.writeSource,endWriteBatch, andreleaseRetainhave flushed.retainDerivedNodeandreadDerivedOutsideComputationhave computed the node but return no retain or value, so a retain made that way can never be released. pico-js then does not callscheduleagain until the cleanup queue has been emptied and refilled.