Skip to main content

pico-js correctness

Under the correctness contracts, every computation, top-level read, and change callback receives current values. In a flush, each registered onChange runs once if its node changed value, after all queued nodes have been refreshed. The proof below follows the functions in src/.

Contract and terms​

Computations are synchronous and pure. A computation reads nodes only through readSource or readDerived with its own callingNode. The graph is acyclic. Batch bodies may write sources or release retains. Change callbacks may call only readDerivedOutsideComputation. Computations and callbacks return normally.

  • X -> Y means that X's dependency list holds an edge to Y, so X read Y in its last run.
  • Below and above follow edges: Y is below X if there is a path X -> ... -> Y.
  • A node with a callback is a node with a retain that has an onChange (callbackState === HAS_CALLBACK), as in the README. Every other node is lazy.
  • A node is unrefreshed if it has a callback, is on the flush queue of the running flush, and has not been refreshed since it was put there.
  • A step is one engine function call that runs to completion with no computation of another node inside it. The invariants below hold between steps. Inside a running computation of node N, they hold with N counted as not CLEAN.

Claim I states that a read cannot return the cached value of a CLEAN node while any node below it remains unrefreshed.

Paths that return a derived value or let a computation continue without recomputing​

  1. readDerived calls getCurrentDerivedValue before linking or reusing the caller's edge. The input is current by the time the reader records it.
  2. getCurrentDerivedValue of a CLEAN node returns node.value.
  3. For a MAYBE_DIRTY node, getCurrentDerivedValue verifies the derived inputs. If verification returns CLEAN, the cached value is current. Otherwise this read continues on path 4.
  4. A read reruns a DIRTY computation. If the node has a callback and a flush is refreshing nodes, the read refreshes the node just as the queue would. Otherwise it uses recomputeValueAndMarkDependents.
  5. verifyDerivedDependencies checks each derived input. It skips a CLEAN input and recomputes a DIRTY one. A linked input cannot be disposed while the reader holds the edge, so the remaining case is MAYBE_DIRTY. The verifier descends iteratively for a lazy input. It refreshes an input with a callback before continuing with the reader. After refreshing the input it checks whether any direct input marked the reader DIRTY. It recomputes a dirty intermediate reader and returns DIRTY for a dirty requested node. Reaching the end of the input list makes the reader CLEAN.
  6. The flush skips a queued node if an earlier refresh already made it CLEAN, or if the node is MAYBE_DIRTY and verifying its inputs shows it can reuse its value.
  7. A rerun propagates a change only if the returned value differs from the previous value under ===. This rule applies during both an ordinary read and a flush.
  8. refreshQueuedNodesAndNotifyCallbacks in batch/flush.ts calls refreshNodesInFlushQueue in graph/refresh.ts. The refresh loop visits entries in insertion order, including entries appended during refresh. It recomputes each node that path 6 did not skip.
  9. readDerivedOutsideComputation (read.ts) and retainDerivedNode (retain.ts) call getCurrentDerivedValue and return or keep its value.
  10. The flush clears the active refresh queue before notifyRetainsOfChangedNodes runs. A read in an onChange uses path 9. A dirty read uses recomputeValueAndMarkDependents.
  11. First computes and recomputes nested inside any of the above: computeInitialDerivedValue and rerunComputationAndUpdateDependencies run a computation whose reads are path 1.
  12. The walk that sets MARKED_BEYOND, markReadersBeyondQueuedCallbacks (marking.ts), which walks only edges before firstKnownMarkedDependentEdge. It returns no value, but it decides which nodes stay CLEAN, so claim I depends on that boundary being correct.

A read returns a cached value only from a clean node or a node verification just made clean. A flush may also skip such a node. To prove I for those paths, it suffices to show that a clean node has no unrefreshed input below it.

Invariants​

C: CLEAN is closed downward​

Every derived dependency of a CLEAN node is CLEAN. Equivalently, every node above a node that is not CLEAN is not CLEAN.

An unrefreshed node cannot be CLEAN. By C, no node above an unrefreshed node can be CLEAN either. This proves I between steps.

C also covers source dependencies. A write to a source marks every reader of the source (markDependentsOfWrittenSource), so a CLEAN node has no source dependency written since it last ran.

BS: firstKnownMarkedDependentEdge bounds the non-CLEAN suffix of dependents​

For every derived node D, D.firstKnownMarkedDependentEdge is either undefined or an edge currently in D's dependents list, and every edge from D.firstKnownMarkedDependentEdge to the end of D's dependents list has a dependent whose status is not CLEAN. With C, none of the nodes above those dependents is CLEAN, so stopping the walk that sets MARKED_BEYOND at D.firstKnownMarkedDependentEdge (and skipping D when D.firstDependent === D.firstKnownMarkedDependentEdge) marks nothing less.

W: a move before firstKnownMarkedDependentEdge inside a computation stays in effect​

An edge placed strictly before D.firstKnownMarkedDependentEdge inside a computation of node N stays strictly before D.firstKnownMarkedDependentEdge at least until N becomes CLEAN. The walk that sets MARKED_BEYOND is the only code that moves firstKnownMarkedDependentEdge backward to firstDependent, and that walk starts only from a write (writeSource through markDependentsOfWrittenSource) or from a release (clearCallbackStateIfNoCallbackRetainsRemain through markTransitiveDependentsMaybeDirty). The contract excludes both inside a computation, and inside the getCurrentDerivedValue that a computation's read makes, because a computation does not write or release, and nested computations are computations too.

L: a lazy node that is not CLEAN has no CLEAN dependent​

This is the lazy case of C. The proof states it separately because the comments in the code rely on it (the DIRTY case of markTransitiveDependentsMaybeDirty, and recomputeValueAndMarkDependents).

M: the dependents of a lazy node that is DIRTY, or MAYBE_DIRTY without MARKED_BEYOND, are in one of those states​

Every dependent of a lazy node that is DIRTY, or MAYBE_DIRTY without MARKED_BEYOND, is itself DIRTY, or MAYBE_DIRTY without MARKED_BEYOND. Every node with a callback in one of those two states is on the flush queue for the current update, and the flush has not refreshed it since marking put it there, because a refresh leaves a node CLEAN (F).

M is needed only for the proof about callbacks, and for the claim that a MAYBE_DIRTY node with MARKED_BEYOND holds a current value once no node below it is unrefreshed.

F: what a pull leaves behind​

After getCurrentDerivedValue(n) returns, n is CLEAN. A clean read returns immediately. An initial computation or a rerun stores a current value and sets CLEAN. Verification either marks the requested node CLEAN or returns DIRTY to its caller. On a regular pull, the caller runs recomputeValueAndMarkDependents. During the refresh phase of a flush, a read of a callback node uses the same refresh as a queue entry, which records a changed value for notification. Both paths leave the node clean. An acyclic computation cannot read itself while it is running.

Proof of C​

C holds for the empty graph. Every operation that changes a status, an edge, or a flag keeps it.

Status changes to CLEAN​

Three stores set a node CLEAN: in computeInitialDerivedValue, in rerunComputationAndUpdateDependencies, and in verifyDerivedDependencies when the node's edges are exhausted.

  • rerunComputationAndUpdateDependencies sets lastSourceDependency and lastDerivedDependency to undefined before it runs the computation, so every derived edge that the node keeps after unlinkUnreadDependencies was moved or reused by a readDerived of this run, and unlinkUnreadDependencies drops the rest. That readDerived pulled the dependency, so by F the dependency was CLEAN when read. It is still CLEAN when the computation returns. A later read in the same computation can change statuses only by marking, and marking starts at a node that is recomputed or refreshed. Such a node is not CLEAN. If it were below an earlier dependency D, C applied to D, which was CLEAN, would have failed before this step. So no marking reaches D.
  • computeInitialDerivedValue does not reset either cursor and does not call unlinkUnreadDependencies. An UNCOMPUTED node N enters computeInitialDerivedValue with no edges and with both cursors undefined. createDerivedNode creates it so, and disposal (disposeNode and disposeMarkedUnneededNodes in cleanup.ts) unlinks every edge and resets both cursors before it sets UNCOMPUTED. No other code makes a node UNCOMPUTED. While the computation of N runs, only readSource and readDerived called with N as callingNode write N's dependency lists or N's cursors. The computation reads only through those two functions with the callingNode it receives, and does not keep it (the contract of createDerivedNode). A nested computation writes the lists of its own node. removeEdgeFromSourceDependents, removeEdgeFromDerivedDependents, addEdgeToSourceDependents, addEdgeToDerivedDependents, and moveEdgeBeforeKnownMarkedDependents write lists of dependents and never nextDependencyEdge. No disposal of N runs inside a computation: disposeNext, disposeAll, disposeOlderThanUpdates, and disposeIfUnneeded run outside computations (their contract), and disposeMarkedUnneededNodes runs only from writeSource, endWriteBatch, and releaseRetain (through flushQueuedNodesOrDisposeMarkedNodes in batch/batch.ts), none of which a computation calls. By induction over N's reads, each cursor is undefined while its list is empty and otherwise points at the tail of its list, and every edge in the list was appended in this run. At a read, the cursor is undefined and the list is empty, so next is firstSourceDependency or firstDerivedDependency, which is undefined; or the cursor is the tail, so next is its nextDependencyEdge, which is undefined. The read therefore never takes the reuse branch. It either finds the cursor's edge already on the same dependency and changes nothing, or appends a new edge whose nextDependencyEdge is undefined and moves the cursor to it. When the computation returns, each cursor is undefined with its list empty, or is the tail of its list, so unlinkUnreadDependencies would unlink nothing and store nothing new. No computation throws, so every computeInitialDerivedValue returns, every edge N keeps was linked by a readDerived of this run, and the argument of the first bullet holds for N.
  • verifyDerivedDependencies: an input was already CLEAN, verified CLEAN, or recomputed. The argument of the first bullet shows that earlier inputs stay CLEAN. If refreshing any input marked the node DIRTY, the verifier reruns an intermediate node or returns DIRTY for its caller to rerun the requested node.

Status changes away from CLEAN​

  • markDependentsOfWrittenSource for a write. Its first loop sets each CLEAN reader of the source DIRTY. markTransitiveDependentsMaybeDirty walks from a lazy one through lazy nodes, sets every CLEAN node it meets MAYBE_DIRTY without MARKED_BEYOND, and goes on through the lazy ones. A one with a callback goes on the flush queue and, when firstDependent !== undefined and firstDependent !== firstKnownMarkedDependentEdge, on beyondCallbackStack, and the walk that sets MARKED_BEYOND walks edges before firstKnownMarkedDependentEdge, sets every CLEAN node it meets MAYBE_DIRTY with MARKED_BEYOND, and goes on through it. Each walk stops only at a node that is not CLEAN, above which nothing is CLEAN by C before the step, or at firstKnownMarkedDependentEdge, at and after which nothing is CLEAN by BS and C. After the step, every node above a node that the step took out of CLEAN is not CLEAN.
  • markDependentsOfChangedDerivedNode after the refresh of a node P with a callback changed its value. P was not CLEAN before its refresh, so by C no dependent of P was CLEAN then. During P's computation only nodes below P run, so no dependent of P becomes CLEAN. So under the contract markDependentsOfChangedDerivedNode finds no CLEAN node, and its CLEAN case does nothing. Its other branches change MAYBE_DIRTY to DIRTY or clear MARKED_BEYOND, which does not change whether a node is CLEAN.
  • markMaybeDirtyDependentsDirty changes only MAYBE_DIRTY to DIRTY.
  • clearCallbackStateIfNoCallbackRetainsRemain (retain.ts) runs markTransitiveDependentsMaybeDirty from the node, and its walk through lazy nodes marks the node's dependents as the walk of a write does.
  • Disposal sets UNCOMPUTED only on a node with no dependents.

Edge changes​

  • Only readDerived links a derived edge or moves one to another dependency, from the running node, which is not CLEAN, to a node that getCurrentDerivedValue just made CLEAN (F). C constrains only the dependencies of CLEAN nodes, so an edge from a node that is not CLEAN cannot break it, and the running node becomes CLEAN only under the rules above.
  • unlinkUnreadDependencies, unlinkRemainingDerivedDependencies, and disposal remove edges. Removing an edge cannot break C.

Proof of BS​

The walk that sets MARKED_BEYOND records stop = marked.firstKnownMarkedDependentEdge, skips the node if marked.firstDependent === stop, and otherwise sets marked.firstKnownMarkedDependentEdge = marked.firstDependent and in the same loop visits every edge from firstDependent up to stop and sets every CLEAN dependent among them to MAYBE_DIRTY. Every edge at or after stop already had a non-CLEAN dependent by BS before the loop, so after the loop every edge from marked.firstKnownMarkedDependentEdge to the end has a non-CLEAN dependent. BS can break only if a dependent whose edge is at or after firstKnownMarkedDependentEdge becomes CLEAN, a CLEAN dependent is linked at or after firstKnownMarkedDependentEdge, or firstKnownMarkedDependentEdge stops pointing to an edge in the list.

  • addEdgeToDerivedDependents prepends every new or moved edge at dependency.firstDependent, strictly before firstKnownMarkedDependentEdge, so no newly linked edge enters [firstKnownMarkedDependentEdge, undefined).
  • removeEdgeFromDerivedDependents advances dependency.firstKnownMarkedDependentEdge = edge.nextDependentEdge whenever edge === dependency.firstKnownMarkedDependentEdge, so firstKnownMarkedDependentEdge always stays in the list or becomes undefined, and the suffix only shrinks.
  • moveEdgeBeforeKnownMarkedDependents(edge) runs only when dependency.firstKnownMarkedDependentEdge !== undefined. If edge === dependency.firstKnownMarkedDependentEdge, it advances dependency.firstKnownMarkedDependentEdge = edge.nextDependentEdge first; if edge.previousDependentEdge !== undefined, it moves edge to dependency.firstDependent. In every position (head or non-head, before, at, or after firstKnownMarkedDependentEdge), edge ends strictly before dependency.firstKnownMarkedDependentEdge and the suffix [firstKnownMarkedDependentEdge, undefined) contains only edges from the previous suffix.
  • A dependent becomes CLEAN by computeInitialDerivedValue or rerunComputationAndUpdateDependencies, which read each kept derived dependency through readDerived (see the proof of C). A new or moved edge was prepended by addEdgeToDerivedDependents, a reused edge had moveEdgeBeforeKnownMarkedDependents called when firstKnownMarkedDependentEdge !== undefined, and an adjacent duplicate read kept the edge already placed before firstKnownMarkedDependentEdge earlier in the same run. By W, every kept edge stays strictly before firstKnownMarkedDependentEdge until the store of CLEAN. Or the dependent becomes CLEAN by verifyDerivedDependencies, which calls moveEdgeBeforeKnownMarkedDependents(edge) whenever dependency.firstKnownMarkedDependentEdge !== undefined on every edge it visits before setting the node CLEAN. verifyDerivedDependencies runs no walk that moves firstKnownMarkedDependentEdge back, so every edge stays strictly before firstKnownMarkedDependentEdge.
  • markDependentsOfChangedDerivedNode resets node.firstKnownMarkedDependentEdge = undefined, which makes the suffix empty. Disposal (disposeNode) sets node.firstKnownMarkedDependentEdge = undefined on a node with no dependents.

Proof of M​

M breaks only if a lazy node becomes DIRTY, or MAYBE_DIRTY without MARKED_BEYOND, while a dependent is MAYBE_DIRTY with MARKED_BEYOND, or if a node with a callback enters one of those two states without going on the flush queue.

  • The first loops of markDependentsOfWrittenSource and markDependentsOfChangedDerivedNode, and the walk through lazy nodes of markTransitiveDependentsMaybeDirty, which markDependentsOfChangedDerivedNode runs too, set CLEAN to DIRTY or to MAYBE_DIRTY without MARKED_BEYOND, or clear MARKED_BEYOND. In each case they go on through a lazy node to its dependents and put a one with a callback on the flush queue. A walk stops at a node that is already DIRTY, or MAYBE_DIRTY without MARKED_BEYOND, whose dependents are in one of those states by M.
  • markMaybeDirtyDependentsDirty sets a node DIRTY. Take the first time this breaks M: it is called for the dependents of a lazy node K whose recompute changed its value (in recomputeValueAndMarkDependents), and one dependent J is MAYBE_DIRTY with MARKED_BEYOND. K's value changed, so a dependency of K changed since K last ran. If that dependency is a source, the write made K DIRTY. If it is a node with a callback whose refresh in the flush changed its value, its markDependentsOfChangedDerivedNode made K DIRTY, or MAYBE_DIRTY without MARKED_BEYOND. If it is a lazy node, or a node with a callback that a pull outside the flush recomputed through recomputeValueAndMarkDependents, its markMaybeDirtyDependentsDirty set K DIRTY, and by the choice of the first break that left M intact. So K was DIRTY, or MAYBE_DIRTY without MARKED_BEYOND, and by M its dependent J was in one of those states, not MAYBE_DIRTY with MARKED_BEYOND. The break cannot happen.
  • The walk that sets MARKED_BEYOND sets it only on a CLEAN node, and by C every node below a CLEAN node is CLEAN.

Proof of I for each path​

By C, I holds between steps. For each path:

  • Path 1, new edge: the value comes from getCurrentDerivedValue. By F the node is CLEAN, and by C nothing unrefreshed is below it.
  • Path 1, edge reused by position or moved: the same, because readDerived pulls before it looks at the edge.
  • Path 2: by C.
  • Path 3: verifyDerivedDependencies set the node CLEAN under the rule proved for verifyDerivedDependencies in the proof of C, so C holds for it.
  • On path 4, a flush refreshes a dirty callback node as soon as a reader needs its value. Its computation reads through path 1.
  • Path 5 reaches only inputs already computed and still linked to their reader. It reads a cached value under C, verifies a possibly dirty input, or reruns a dirty one as in path 4.
  • Path 6 can skip a clean node by C. Every enqueue site requires a callback, and its retain keeps the node computed. Computations cannot release retains, and the flush finishes the refresh loop before delivering callbacks.
  • Path 7: the value is the result of a rerun whose reads are path 1.
  • Path 8: each refresh is path 4 or 6. The order of the walk does not matter for I, because a pull of an unrefreshed node refreshes it at once.
  • Path 9: outside a flush no node is unrefreshed. retainDerivedNode runs outside flushes (contract). readDerivedOutsideComputation inside a flush runs only from an onChange, which is path 10.
  • Path 10: when notifyRetainsOfChangedNodes runs, the walk has reached flushQueue.length, so every entry was refreshed or skipped, and no node is unrefreshed. An onChange read can recompute lazy nodes (path 4, lazy branch), whose recomputeValueAndMarkDependents calls only markMaybeDirtyDependentsDirty, which puts nothing on a flush queue. An onChange writes nothing (contract). So no node joins a flush queue while callbacks run.
  • Path 11: each read of a nested computation is path 1, with the running node counted as not CLEAN. A computation runs only on a node that is DIRTY or UNCOMPUTED. computeInitialDerivedValue runs on an UNCOMPUTED node, and a rerun begins only after the node status or verifyDerivedDependencies establishes that the node is DIRTY. The node keeps that status until computeInitialDerivedValue or rerunComputationAndUpdateDependencies sets it CLEAN. A nested refresh's markDependentsOfChangedDerivedNode can reach the running node N through N's edge from its previous run, and both loops of markDependentsOfChangedDerivedNode leave a DIRTY or UNCOMPUTED node as it is, so that marking changes nothing on N. N's value is current, because each value it read was current when read and, by the argument for rerunComputationAndUpdateDependencies in the proof of C, did not change afterwards.
  • Path 12: proved under C and BS.

Change callbacks​

Each onChange runs after the flush has refreshed every node on the flush queue​

refreshQueuedNodesAndNotifyCallbacks drains the growing queue before it calls notifyRetainsOfChangedNodes. The loop reads the current queue length on every iteration, so it visits entries appended during refresh. Path 10 shows that nothing is appended while callbacks run. The contracts exclude nested flushes.

Each onChange runs exactly when its node's value changed in the update​

  • The refresh calls recordChangedNode only when the rerun returns a value different from the previous one under ===.
  • Each node with a callback is refreshed with a change at most once per flush. After its refresh it is CLEAN, so by C every node below it is CLEAN. A change in a flush starts only at a node that is not CLEAN, because no write happens during a flush, so nothing below it changes again, nothing marks it again, and no second recompute of it runs. The flush therefore records each changed node at most once. The value that notifyRetainsOfChangedNodes passes is therefore the value of that one changed recompute.
  • No change is missed. A node with a callback whose value changes in the update has a dependency that changed. Following changed dependencies down reaches a written source or a node with a callback whose refresh changed its value. Both mark with a walk through lazy nodes, and by M that walk reaches the node with a callback and puts it on the flush queue, or the node is a direct reader of the written source and goes on the flush queue in the first loop of markDependentsOfWrittenSource. The queue loop and a nested read of a dirty callback node both record the change before returning. After the refresh walk, a node with a callback that is not CLEAN is MAYBE_DIRTY with MARKED_BEYOND. A lazy node below it that is DIRTY, or MAYBE_DIRTY without MARKED_BEYOND, would put it in one of those states by M, so no such node is below it, and its value is current, and an onChange read of it verifies it CLEAN with no recompute that changes it.
  • The first compute of a node calls no onChange, because computeInitialDerivedValue records nothing, and a node gets a callback only after retainDerivedNode pulled it.

The ascent of verifyDerivedDependencies finds the right edge​

verifyDerivedDependencies pushes an edge on savedReaderEdges only when the dependency has more than one dependent at descent time. On ascent, it checks whether savedReaderEdges is non-empty and its top edge's dependency is the current nodeBeingVerified; if so, it pops that edge, and otherwise it takes nodeBeingVerified.firstDependent.

This finds the exact descent edge into nodeBeingVerified because three properties hold throughout the descent:

  1. No node on the descent path gains a dependent before ascent passes it. A node gains a dependent only through readDerived during a computation. The computations that run during descent are pulls and recomputes of nodes below the last node of the path. Each derived dependency that a path node read before its edge to the next path node was verified unchanged, and no source that the path node read was written since it last ran, because a write makes each reader of the source DIRTY, and every path node is MAYBE_DIRTY. Because computations are pure, a path node's computation, run now, would reach the next path node and through the path every node below it; a read of a path node by a node below the path would therefore make a cycle, which the contract excludes.
  2. No edge on the descent path is unlinked before ascent passes it. An edge u -> v on the descent path is removed only by readDerived or unlinkUnreadDependencies of u, or by disposal of u. No disposal runs during verifyDerivedDependencies, and u is MAYBE_DIRTY and does not recompute until ascent reaches u.
  3. Every node appears at most once on the descent path, because the graph has no cycles.

A node v on the descent path can still lose another dependent B during descent: a DIRTY node B that read v on its previous run can be pulled by a node below v if B switches branches and drops v while the lower node switches branches and reads B (an acyclic topology inversion). In that case v had more than one dependent when descent entered it (so its descent edge was pushed onto savedReaderEdges) and only one dependent when ascent reaches it. By induction over the descent path and (3), the top of savedReaderEdges has dependency === nodeBeingVerified if and only if descent pushed an edge for that node. When descent pushed an edge for that node, ascent pops it even if other dependents of that node were unlinked during descent. When descent did not push an edge for that node, the node had a single dependent at descent time, gained none by (1), and kept its descent edge by (2), so nodeBeingVerified.firstDependent is that edge.

Disposal strategies​

disposeOlderThanUpdates (older-than-updates.ts), through disposeEligibleCleanupEntries (age-drain.ts), and takeUnneeded and disposeIfUnneeded (take.ts) read and change the cleanup queue of cleanup.ts. disposeAll and disposeNext read no state of theirs. disposeOlderThanUpdates also reads updateCount (update-counter.ts), which writeSource and endWriteBatch increment. Q is the invariant of cleanup.ts that each node that is not UNCOMPUTED and is unneeded is on the cleanup queue or on the marked-unneeded list of the running write, except a node that readDerived has brought up to date and not yet linked. With takeUnneeded, Q also allows a node that a caller has taken and that has not become needed since.

Q​

Every path that makes a node unneeded while it is not UNCOMPUTED queues it: releaseRetain (retain.ts), readDerivedOutsideComputation and the reuse branch of readDerived (read.ts), unlinkRemainingDerivedDependencies (recompute.ts), disposeNode for each dependency it leaves unneeded, and disposeMarkedUnneededNodes, which disposes each such node or queues it if it is CLEAN (cleanup.ts). The strategies keep Q:

  • disposeEligibleCleanupEntries drops an entry only if its node is needed, is UNCOMPUTED, or has a newer entry that the same call keeps or disposes. It disposes only nodes that are unneeded, which makes them UNCOMPUTED. Disposing a node removes only edges, so it never makes another node needed and never changes another node's status; every node the call kept for disposal is therefore still unneeded when its turn comes. Every dependency a disposal leaves unneeded is queued by disposeNode, and the cascade of the same call disposes it if it is still unneeded and not UNCOMPUTED, or drops its entry if it is needed again or already disposed. So when the call returns, every node that it left unneeded is UNCOMPUTED, and no entry above the marker remains from the call. With a budget, a drain that runs out of time disposes fewer nodes: every old entry it kept and did not dispose stays queued, and every entry its disposals queued that the cascade did not reach stays queued, at the front. Their nodes are unneeded and on the queue, so Q holds.
  • takeUnneeded drops the entries of needed and UNCOMPUTED nodes, and hands the others to the caller, which the extended Q allows.
  • disposeIfUnneeded disposes only an unneeded node, as disposeNode does in disposeNext.

A dropped entry of a needed node is safe because Q asks nothing of a needed node, and the path that makes it unneeded again queues it again.

SCAN_SEEN is free during disposeEligibleCleanupEntries​

Claim: no node has SCAN_SEEN (2) outside a call of disposeEligibleCleanupEntries, which disposeOlderThanUpdates calls, and while a call runs, only that call reads or writes the bit. disposeOlderThanUpdates does not touch traversalFlags itself.

  • No other code reads the bit. The other writes of traversalFlags are |= and &= ~ of MARKED_BEYOND (marking.ts), which keep every other bit. createDerivedNode sets traversalFlags to 0 on a new node. disposeNode and disposeMarkedUnneededNodes do not write traversalFlags.
  • Inside the call, the first loop sets the bit on a node only when it keeps an entry of that node, and keeps an entry only of a node that does not have the bit, so each node that has the bit afterwards has exactly one kept entry, in the range [write, length). The second loop visits that range and clears the bit on each node in it. The two loops call no function and run no code of the caller, so nothing else runs between the first set and the last clear. The disposals start after the second loop.
  • By induction over calls, starting from traversalFlags 0 on every node, no node has the bit when a call starts or after it returns.

The update boundaries of disposeOlderThanUpdates​

An update is a call of writeSource or endWriteBatch that reaches countUpdateAndScheduleCleanupIfIdle (batch.ts) with no batch open and no flush running, the condition under which scheduleCleanupIfOutsideBatchAndFlush calls scheduleCleanupIfRequested. countUpdateAndScheduleCleanupIfIdle increments updateCount there, once per update. A writeSource that returns before marking is not an update. A drain is a call of disposeOlderThanUpdates. The true update age of an entry is the number of updates that ended after it was queued. The count an entry carries is the value of updateCount at the first drain after it was queued, and its judged age is the current updateCount minus that count. Updates that end after the entry was queued and before that drain are not in its judged age, so the judged age is the true age minus the number of those updates: short by at most the number of updates between its enqueue and the next drain, never longer. The age rule applies to the entries that releases, unlinks, and top-level reads queue. An entry that a drain's own disposals queue is a cascade entry: the drain that queued it disposes its node in the same call if the node is still unneeded, whatever minAge is, and drops it otherwise.

Claim U: whenever boundaryCount > 0 and the queue holds this strategy's marker at index positions[boundaryCount - 1], the positions are positive and non-decreasing, the update counts are increasing, and every entry below positions[i] and at or above positions[i - 1] (0 for i = 0) was queued before a drain at which updateCount was updates[i], so its true age is at least the current count minus updates[i]. Every entry above the marker was queued after the last drain, so it is judged 0. A call that finds boundaryCount 0 or the marker missing judges every entry 0. A drain cut off by its budget can leave one more kind of segment, the cascade segment: the first segment, with count -Infinity, holding the entries that its disposals queued and its cascade did not reach. Its entries are exempt from the age rule, as cascade entries are when no budget stops the cascade, and now - (-Infinity) makes them eligible at every minAge. Each of their nodes had no other entry when the drain ended, because it was needed at the scan, by the dependent whose disposal released it, so the scan dropped its entries; an entry queued after the drain is appended behind the segment and is newer. Every other entry is in an age segment, whose judged age is at most the true age.

marker is an UNCOMPUTED node that no computation reads and no caller holds, so no path passes it to addToCleanupQueue, and only disposeOlderThanUpdates puts it on the queue. disposeNext and disposeAll skip an UNCOMPUTED node, takeUnneeded filters it out, and disposeEligibleCleanupEntries drops it. A reset judges entries younger, never older.

Each operation that changes the queue keeps U:

  • An enqueue appends at index length. While the marker is in the queue at the last boundary, that boundary is less than length, so the new entry is above the marker and judged 0. No other entry moves.

  • disposeNext and disposeAll remove entries from the end, and takeUnneeded removes all of them. An entry below the marker can be removed only after the marker, so while the marker is still at the last boundary, every entry below it is where the last drain left it, in the same segment, and its true age has not decreased. Once the marker is removed, it never returns, so the next call finds it missing.

  • A comparison of the queue length with the last boundary would not be enough: after a disposeAll and enough new entries, the length exceeds the last boundary again, and new entries below it would be judged old. The marker detects this, because only a removal of the marker lets the queue shrink below the boundary.

  • An update changes no position and no count. It increments updateCount, which raises every judged age by one and every true age by one.

  • disposeOlderThanUpdates itself, below.

  • The eligible end E is positions[i] for the largest i whose count is at least minAge updates behind the current count, and 0 when there is none (length when minAge is 0 or less). The counts increase with i, so every entry below E is in a segment at least minAge updates old, and by U its true age is at least minAge.

  • disposeEligibleCleanupEntries keeps the young entries in their order and maps each position p to the number of kept young entries below p, so an entry stays in a segment with the same count. Positions that become 0 or less are removed with their counts. The rest stay positive and non-decreasing, and their counts stay increasing.

  • With a budget, the first disposal needs no check, and each later disposal, of an old entry or in the cascade, first checks the budget and stops the drain if it ran out. Let K be the kept entries, O of them old, D of the old ones disposed, and C the cascade entries not reached. The queue then holds, oldest first, the C cascade entries, the O - D old entries not disposed, the K - O young entries, and the marker. Each old position p maps to C plus the kept entries below p minus D. The old entries keep their order, so a position that cut through them still cuts them at the same entry, with the same count, and the O - D remaining old entries keep their judged age, which by U is at most their true age. Positions at C or less are removed, and when C is more than 0, a first boundary at C with count -Infinity is added. The counts stay non-decreasing: -Infinity, then the old counts in order, then the current count.

  • The call then appends a boundary at the number of kept young entries with the current count, because the entries above the old marker were queued before this drain, and puts the marker there. If the last remaining boundary already has the current count, no update ended since that drain, so the two segments have the same count and the call moves that boundary instead, which keeps the counts increasing and bounds the arrays by one boundary per distinct count. The entries that the disposals queue are disposed or dropped by the cascade of the same call, so none of them is left above the marker. When no young entry is kept, the call sets boundaryCount to 0 and puts no marker, so the queue never holds only the marker, and an enqueue onto a queue that was emptied still calls schedule.

Schedule calls after disposeOlderThanUpdates​

Claim S: after a call of disposeOlderThanUpdates that returns more than 0, pico-js calls scheduler.schedule exactly once at the end of the first outermost operation that follows, and not before it, so a scheduler that drains once per call never drains while the app makes no call into pico-js, and drains at most once more per burst of calls than the updates require.

  • scheduleStatus (cleanup.ts) becomes pending in two places: addToCleanupQueue, when the queue was empty, and requestCleanupScheduling, which disposeOlderThanUpdates calls when it returns more than 0 and disposeIfUnneeded calls when it moves the queue from empty to non-empty. It becomes not pending in clearPendingCleanupRequest, which scheduleCleanupIfRequested (schedule.ts) calls right before the call of schedule, which disposeOldNodesWithinTimeBudget (schedule.ts) calls before continuing a cut-off drain, and which takeUnneeded and disposeOlderThanUpdates call when they empty the queue, and in disposeNext when it leaves the queue empty, and in disposeAll.
  • Only scheduleCleanupIfRequested calls schedule, and under the contracts it runs only at the end of an outermost operation: writeSource and endWriteBatch through countUpdateAndScheduleCleanupIfIdle, releaseRetain through scheduleCleanupIfOutsideBatchAndFlush, readDerivedOutsideComputation through scheduleCleanupIfNotFlushing (batch.ts), and retainDerivedNode directly (retain.ts), each when no batch is open and no flush runs. No timer or callback of pico-js calls it: the default scheduler's callbacks call disposeOlderThanUpdates, which does not call it.
  • So between the drain and the next outermost operation, nothing calls schedule. That operation finds the status pending, calls schedule once, and clears it. Later operations call schedule again only after another drain that leaves entries, or after an enqueue onto an empty queue, which calls it under the rule that holds without disposeOlderThanUpdates.
  • The drain itself is not an outermost operation and does not call scheduleCleanupIfRequested, so it never calls schedule from inside the scheduler.
  • A drain that empties the queue calls clearPendingCleanupRequest, as disposeAll, disposeNext, and takeUnneeded do when they empty it, so no schedule call is left pending for an empty queue.
  • The default scheduler enforces single-flight (defaultScheduleStatus in schedule.ts), skips empty queues in disposeOldNodesWithinTimeBudget, and continues after a cut-off by clearing the pending schedule call and calling scheduleCleanupDuringIdleTime directly. A drain sets drainReachedTimeLimit (age-drain.ts) only when it skipped a disposal for its budget, which requires that it made at least one disposal first. The default then requests one more idle callback or setTimeout task, and makes no request otherwise, so a drain that leaves only young entries waits for the re-arm. Each drain in a chain of continued callbacks disposes at least one node, unless it finds no eligible entry, and then it is not cut off and the chain ends. Each node is disposed at most once in the chain, because disposal makes it UNCOMPUTED and only a computation can make it CLEAN again. So a chain has at most E + R + 1 callbacks, where E is the number of eligible entries left at the cut-off and R the number of nodes that the chain's disposals release into its cascades. With R = 0 and no reset of the boundaries in between, the bound is E: then every callback in the chain disposes at least one of the E nodes, and the one that disposes the last of them is not cut off. The chain needs no call into pico-js and runs on the idle callbacks or tasks it requests, but each of them disposes a node, so it does not poll.

Taken nodes​

A node that takeUnneeded returns was unneeded and not UNCOMPUTED at the take. It keeps its value, its status, and its edges, and pico-js holds no entry for it. The caller may read it, retain it, and pass it to disposeIfUnneeded, outside write batches, computations, and change callbacks. A node that becomes needed while the caller holds it is an ordinary needed node: disposeIfUnneeded returns false for it and changes nothing, and the release or unlink that makes it unneeded again queues it again. A write that marks it while it is unneeded disposes it through disposeMarkedUnneededNodes, after which disposeIfUnneeded returns false. A taken node that never becomes needed again, and that the caller never passes to disposeIfUnneeded, stays cached with its value and edges. That keeps every result correct, because a cached node is brought up to date by every read, but its memory is not freed. disposeIfUnneeded disposes only a node with no retain and no dependent, so it keeps "Disposal sets UNCOMPUTED only on a node with no dependents" above.

Stack depth​

A first read runs each computation so it can discover its inputs. If each computation reads another uncomputed node, the calls nest. A write can also cause nested calls when it directly dirties every node in a chain. Verifying a chain with callbacks can nest calls even when the final value stays the same.

These measurements used Node 24.12 with its default stack size. The depth at overflow depends on the computation and whether V8 has optimized it.

ChainObservation
Each node reads the node below it and adds one shared sourceThe first read overflowed at 1,358 nodes in a fresh process and at 1,757 after optimization. A write to the shared source followed by a read overflowed at 1,757–1,867 nodes.
Each node has a callback and adds one to the value below itAfter a write that left the bottom node’s result unchanged, a read that verified the chain overflowed at 2,308 nodes.
Only the bottom node of an already computed lazy chain reads the written sourceThe verifier uses an explicit stack. The write and subsequent read completed at 200,000 nodes.

The recursive resolver benchmark exercises a different computation. Its first read overflowed at depth 1,000 in all three libraries.

Outside the contract​

The contracts page describes known consequences of violating a contract. Once an exception escapes into pico-js, the engine state is unspecified. Two documented failure modes follow directly from the code.

  • A write inside an onChange to a source that a node with a callback depends on reaches flushQueuedNodesOrDisposeMarkedNodes (batch/batch.ts) with no batch open, which calls refreshQueuedNodesAndNotifyCallbacks without looking at the flush state. The nested refreshQueuedNodesAndNotifyCallbacks refreshes its flush queue, then its notifyRetainsOfChangedNodes starts at index 0 of the list of changed nodes. The outer notifyRetainsOfChangedNodes cleared that entry before it called the running onChange, and changedCount is still the outer count, which is at least 1, so the nested loop reads value of undefined and throws a TypeError. A write to a source that no node with a callback depends on returns from markDependentsOfWrittenSource with no flush queue, so flushQueuedNodesOrDisposeMarkedNodes only disposes the unneeded nodes it marked.
  • A computation that reads its own node, or a node above it, pulls a node that is not CLEAN (by C, with the running node counted as not CLEAN), and that pull reaches the running node's computation again, so the recursion does not end.