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 -> Ymeans 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
readDerivedcallsgetCurrentDerivedValuebefore linking or reusing the caller's edge. The input is current by the time the reader records it.getCurrentDerivedValueof aCLEANnode returnsnode.value.- For a
MAYBE_DIRTYnode,getCurrentDerivedValueverifies the derived inputs. If verification returnsCLEAN, the cached value is current. Otherwise this read continues on path 4. - A read reruns a
DIRTYcomputation. If the node has a callback and a flush is refreshing nodes, the read refreshes the node just as the queue would. Otherwise it usesrecomputeValueAndMarkDependents. verifyDerivedDependencieschecks each derived input. It skips aCLEANinput and recomputes aDIRTYone. A linked input cannot be disposed while the reader holds the edge, so the remaining case isMAYBE_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 readerDIRTY. It recomputes a dirty intermediate reader and returnsDIRTYfor a dirty requested node. Reaching the end of the input list makes the readerCLEAN.- The flush skips a queued node if an earlier refresh already made it
CLEAN, or if the node isMAYBE_DIRTYand verifying its inputs shows it can reuse its value. - 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. refreshQueuedNodesAndNotifyCallbacksinbatch/flush.tscallsrefreshNodesInFlushQueueingraph/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.readDerivedOutsideComputation(read.ts) andretainDerivedNode(retain.ts) callgetCurrentDerivedValueand return or keep its value.- The flush clears the active refresh queue before
notifyRetainsOfChangedNodesruns. A read in anonChangeuses path 9. A dirty read usesrecomputeValueAndMarkDependents. - First computes and recomputes nested inside any of the above:
computeInitialDerivedValueandrerunComputationAndUpdateDependenciesrun a computation whose reads are path 1. - The walk that sets
MARKED_BEYOND,markReadersBeyondQueuedCallbacks(marking.ts), which walks only edges beforefirstKnownMarkedDependentEdge. It returns no value, but it decides which nodes stayCLEAN, 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.
rerunComputationAndUpdateDependenciessetslastSourceDependencyandlastDerivedDependencytoundefinedbefore it runs the computation, so every derived edge that the node keeps afterunlinkUnreadDependencieswas moved or reused by areadDerivedof this run, andunlinkUnreadDependenciesdrops the rest. ThatreadDerivedpulled the dependency, so by F the dependency wasCLEANwhen read. It is stillCLEANwhen 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 notCLEAN. If it were below an earlier dependency D, C applied to D, which wasCLEAN, would have failed before this step. So no marking reaches D.computeInitialDerivedValuedoes not reset either cursor and does not callunlinkUnreadDependencies. AnUNCOMPUTEDnode N enterscomputeInitialDerivedValuewith no edges and with both cursorsundefined.createDerivedNodecreates it so, and disposal (disposeNodeanddisposeMarkedUnneededNodesin cleanup.ts) unlinks every edge and resets both cursors before it setsUNCOMPUTED. No other code makes a nodeUNCOMPUTED. While the computation of N runs, onlyreadSourceandreadDerivedcalled with N ascallingNodewrite N's dependency lists or N's cursors. The computation reads only through those two functions with thecallingNodeit receives, and does not keep it (the contract ofcreateDerivedNode). A nested computation writes the lists of its own node.removeEdgeFromSourceDependents,removeEdgeFromDerivedDependents,addEdgeToSourceDependents,addEdgeToDerivedDependents, andmoveEdgeBeforeKnownMarkedDependentswrite lists of dependents and nevernextDependencyEdge. No disposal of N runs inside a computation:disposeNext,disposeAll,disposeOlderThanUpdates, anddisposeIfUnneededrun outside computations (their contract), anddisposeMarkedUnneededNodesruns only fromwriteSource,endWriteBatch, andreleaseRetain(throughflushQueuedNodesOrDisposeMarkedNodesin batch/batch.ts), none of which a computation calls. By induction over N's reads, each cursor isundefinedwhile 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 isundefinedand the list is empty, sonextisfirstSourceDependencyorfirstDerivedDependency, which isundefined; or the cursor is the tail, sonextis itsnextDependencyEdge, which isundefined. 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 whosenextDependencyEdgeisundefinedand moves the cursor to it. When the computation returns, each cursor isundefinedwith its list empty, or is the tail of its list, sounlinkUnreadDependencieswould unlink nothing and store nothing new. No computation throws, so everycomputeInitialDerivedValuereturns, every edge N keeps was linked by areadDerivedof this run, and the argument of the first bullet holds for N.verifyDerivedDependencies: an input was alreadyCLEAN, verifiedCLEAN, or recomputed. The argument of the first bullet shows that earlier inputs stayCLEAN. If refreshing any input marked the nodeDIRTY, the verifier reruns an intermediate node or returnsDIRTYfor its caller to rerun the requested node.
Status changes away from CLEAN
markDependentsOfWrittenSourcefor a write. Its first loop sets eachCLEANreader of the sourceDIRTY.markTransitiveDependentsMaybeDirtywalks from a lazy one through lazy nodes, sets everyCLEANnode it meetsMAYBE_DIRTYwithoutMARKED_BEYOND, and goes on through the lazy ones. A one with a callback goes on the flush queue and, whenfirstDependent !== undefinedandfirstDependent !== firstKnownMarkedDependentEdge, onbeyondCallbackStack, and the walk that setsMARKED_BEYONDwalks edges beforefirstKnownMarkedDependentEdge, sets everyCLEANnode it meetsMAYBE_DIRTYwithMARKED_BEYOND, and goes on through it. Each walk stops only at a node that is notCLEAN, above which nothing isCLEANby C before the step, or atfirstKnownMarkedDependentEdge, at and after which nothing isCLEANby BS and C. After the step, every node above a node that the step took out ofCLEANis notCLEAN.markDependentsOfChangedDerivedNodeafter the refresh of a node P with a callback changed its value. P was notCLEANbefore its refresh, so by C no dependent of P wasCLEANthen. During P's computation only nodes below P run, so no dependent of P becomesCLEAN. So under the contractmarkDependentsOfChangedDerivedNodefinds noCLEANnode, and itsCLEANcase does nothing. Its other branches changeMAYBE_DIRTYtoDIRTYor clearMARKED_BEYOND, which does not change whether a node isCLEAN.markMaybeDirtyDependentsDirtychanges onlyMAYBE_DIRTYtoDIRTY.clearCallbackStateIfNoCallbackRetainsRemain(retain.ts) runsmarkTransitiveDependentsMaybeDirtyfrom the node, and its walk through lazy nodes marks the node's dependents as the walk of a write does.- Disposal sets
UNCOMPUTEDonly on a node with no dependents.
Edge changes
- Only
readDerivedlinks a derived edge or moves one to another dependency, from the running node, which is notCLEAN, to a node thatgetCurrentDerivedValuejust madeCLEAN(F). C constrains only the dependencies ofCLEANnodes, so an edge from a node that is notCLEANcannot break it, and the running node becomesCLEANonly 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.
addEdgeToDerivedDependentsprepends every new or moved edge atdependency.firstDependent, strictly beforefirstKnownMarkedDependentEdge, so no newly linked edge enters[firstKnownMarkedDependentEdge, undefined).removeEdgeFromDerivedDependentsadvancesdependency.firstKnownMarkedDependentEdge = edge.nextDependentEdgewheneveredge === dependency.firstKnownMarkedDependentEdge, sofirstKnownMarkedDependentEdgealways stays in the list or becomesundefined, and the suffix only shrinks.moveEdgeBeforeKnownMarkedDependents(edge)runs only whendependency.firstKnownMarkedDependentEdge !== undefined. Ifedge === dependency.firstKnownMarkedDependentEdge, it advancesdependency.firstKnownMarkedDependentEdge = edge.nextDependentEdgefirst; ifedge.previousDependentEdge !== undefined, it movesedgetodependency.firstDependent. In every position (head or non-head, before, at, or afterfirstKnownMarkedDependentEdge),edgeends strictly beforedependency.firstKnownMarkedDependentEdgeand the suffix[firstKnownMarkedDependentEdge, undefined)contains only edges from the previous suffix.- A dependent becomes
CLEANbycomputeInitialDerivedValueorrerunComputationAndUpdateDependencies, which read each kept derived dependency throughreadDerived(see the proof of C). A new or moved edge was prepended byaddEdgeToDerivedDependents, a reused edge hadmoveEdgeBeforeKnownMarkedDependentscalled whenfirstKnownMarkedDependentEdge !== undefined, and an adjacent duplicate read kept the edge already placed beforefirstKnownMarkedDependentEdgeearlier in the same run. By W, every kept edge stays strictly beforefirstKnownMarkedDependentEdgeuntil the store ofCLEAN. Or the dependent becomesCLEANbyverifyDerivedDependencies, which callsmoveEdgeBeforeKnownMarkedDependents(edge)wheneverdependency.firstKnownMarkedDependentEdge !== undefinedon every edge it visits before setting the nodeCLEAN.verifyDerivedDependenciesruns no walk that movesfirstKnownMarkedDependentEdgeback, so every edge stays strictly beforefirstKnownMarkedDependentEdge. markDependentsOfChangedDerivedNoderesetsnode.firstKnownMarkedDependentEdge = undefined, which makes the suffix empty. Disposal (disposeNode) setsnode.firstKnownMarkedDependentEdge = undefinedon 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
markDependentsOfWrittenSourceandmarkDependentsOfChangedDerivedNode, and the walk through lazy nodes ofmarkTransitiveDependentsMaybeDirty, whichmarkDependentsOfChangedDerivedNoderuns too, setCLEANtoDIRTYor toMAYBE_DIRTYwithoutMARKED_BEYOND, or clearMARKED_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 alreadyDIRTY, orMAYBE_DIRTYwithoutMARKED_BEYOND, whose dependents are in one of those states by M. markMaybeDirtyDependentsDirtysets a nodeDIRTY. Take the first time this breaks M: it is called for the dependents of a lazy node K whose recompute changed its value (inrecomputeValueAndMarkDependents), and one dependent J isMAYBE_DIRTYwithMARKED_BEYOND. K's value changed, so a dependency of K changed since K last ran. If that dependency is a source, the write made KDIRTY. If it is a node with a callback whose refresh in the flush changed its value, itsmarkDependentsOfChangedDerivedNodemade KDIRTY, orMAYBE_DIRTYwithoutMARKED_BEYOND. If it is a lazy node, or a node with a callback that a pull outside the flush recomputed throughrecomputeValueAndMarkDependents, itsmarkMaybeDirtyDependentsDirtyset KDIRTY, and by the choice of the first break that left M intact. So K wasDIRTY, orMAYBE_DIRTYwithoutMARKED_BEYOND, and by M its dependent J was in one of those states, notMAYBE_DIRTYwithMARKED_BEYOND. The break cannot happen.- The walk that sets
MARKED_BEYONDsets it only on aCLEANnode, and by C every node below aCLEANnode isCLEAN.
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 isCLEAN, and by C nothing unrefreshed is below it. - Path 1, edge reused by position or moved: the same, because
readDerivedpulls before it looks at the edge. - Path 2: by C.
- Path 3:
verifyDerivedDependenciesset the nodeCLEANunder the rule proved forverifyDerivedDependenciesin 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.
retainDerivedNoderuns outside flushes (contract).readDerivedOutsideComputationinside a flush runs only from anonChange, which is path 10. - Path 10: when
notifyRetainsOfChangedNodesruns, the walk has reachedflushQueue.length, so every entry was refreshed or skipped, and no node is unrefreshed. AnonChangeread can recompute lazy nodes (path 4, lazy branch), whoserecomputeValueAndMarkDependentscalls onlymarkMaybeDirtyDependentsDirty, which puts nothing on a flush queue. AnonChangewrites 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 isDIRTYorUNCOMPUTED.computeInitialDerivedValueruns on anUNCOMPUTEDnode, and a rerun begins only after the node status orverifyDerivedDependenciesestablishes that the node isDIRTY. The node keeps that status untilcomputeInitialDerivedValueorrerunComputationAndUpdateDependenciessets itCLEAN. A nested refresh'smarkDependentsOfChangedDerivedNodecan reach the running node N through N's edge from its previous run, and both loops ofmarkDependentsOfChangedDerivedNodeleave aDIRTYorUNCOMPUTEDnode 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 forrerunComputationAndUpdateDependenciesin 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
recordChangedNodeonly 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 isCLEAN. A change in a flush starts only at a node that is notCLEAN, 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 thatnotifyRetainsOfChangedNodespasses 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 notCLEANisMAYBE_DIRTYwithMARKED_BEYOND. A lazy node below it that isDIRTY, orMAYBE_DIRTYwithoutMARKED_BEYOND, would put it in one of those states by M, so no such node is below it, and its value is current, and anonChangeread of it verifies itCLEANwith no recompute that changes it. - The first compute of a node calls no
onChange, becausecomputeInitialDerivedValuerecords nothing, and a node gets a callback only afterretainDerivedNodepulled 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:
- No node on the descent path gains a dependent before ascent passes it. A node gains a dependent only through
readDerivedduring 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 sourceDIRTY, and every path node isMAYBE_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. - No edge on the descent path is unlinked before ascent passes it. An edge
u -> von the descent path is removed only byreadDerivedorunlinkUnreadDependenciesofu, or by disposal ofu. No disposal runs duringverifyDerivedDependencies, anduisMAYBE_DIRTYand does not recompute until ascent reachesu. - 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:
disposeEligibleCleanupEntriesdrops an entry only if its node is needed, isUNCOMPUTED, or has a newer entry that the same call keeps or disposes. It disposes only nodes that are unneeded, which makes themUNCOMPUTED. 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 bydisposeNode, and the cascade of the same call disposes it if it is still unneeded and notUNCOMPUTED, or drops its entry if it is needed again or already disposed. So when the call returns, every node that it left unneeded isUNCOMPUTED, 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.takeUnneededdrops the entries of needed andUNCOMPUTEDnodes, and hands the others to the caller, which the extended Q allows.disposeIfUnneededdisposes only an unneeded node, asdisposeNodedoes indisposeNext.
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
traversalFlagsare|=and&= ~ofMARKED_BEYOND(marking.ts), which keep every other bit.createDerivedNodesetstraversalFlagsto 0 on a new node.disposeNodeanddisposeMarkedUnneededNodesdo not writetraversalFlags. - 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
traversalFlags0 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 thanlength, so the new entry is above the marker and judged 0. No other entry moves. -
disposeNextanddisposeAllremove entries from the end, andtakeUnneededremoves 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
disposeAlland 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. -
disposeOlderThanUpdatesitself, below. -
The eligible end
Eispositions[i]for the largestiwhose count is at leastminAgeupdates behind the current count, and 0 when there is none (lengthwhenminAgeis 0 or less). The counts increase withi, so every entry belowEis in a segment at leastminAgeupdates old, and by U its true age is at leastminAge. -
disposeEligibleCleanupEntrieskeeps the young entries in their order and maps each positionpto the number of kept young entries belowp, 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
pmaps to C plus the kept entries belowpminus 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-Infinityis 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
boundaryCountto 0 and puts no marker, so the queue never holds only the marker, and an enqueue onto a queue that was emptied still callsschedule.
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, andrequestCleanupScheduling, whichdisposeOlderThanUpdatescalls when it returns more than 0 anddisposeIfUnneededcalls when it moves the queue from empty to non-empty. It becomes not pending inclearPendingCleanupRequest, whichscheduleCleanupIfRequested(schedule.ts) calls right before the call ofschedule, whichdisposeOldNodesWithinTimeBudget(schedule.ts) calls before continuing a cut-off drain, and whichtakeUnneededanddisposeOlderThanUpdatescall when they empty the queue, and indisposeNextwhen it leaves the queue empty, and indisposeAll.- Only
scheduleCleanupIfRequestedcallsschedule, and under the contracts it runs only at the end of an outermost operation:writeSourceandendWriteBatchthroughcountUpdateAndScheduleCleanupIfIdle,releaseRetainthroughscheduleCleanupIfOutsideBatchAndFlush,readDerivedOutsideComputationthroughscheduleCleanupIfNotFlushing(batch.ts), andretainDerivedNodedirectly (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 calldisposeOlderThanUpdates, which does not call it. - So between the drain and the next outermost operation, nothing calls
schedule. That operation finds the status pending, callsscheduleonce, and clears it. Later operations callscheduleagain only after another drain that leaves entries, or after an enqueue onto an empty queue, which calls it under the rule that holds withoutdisposeOlderThanUpdates. - The drain itself is not an outermost operation and does not call
scheduleCleanupIfRequested, so it never callsschedulefrom inside the scheduler. - A drain that empties the queue calls
clearPendingCleanupRequest, asdisposeAll,disposeNext, andtakeUnneededdo when they empty it, so no schedule call is left pending for an empty queue. - The default scheduler enforces single-flight (
defaultScheduleStatusin schedule.ts), skips empty queues indisposeOldNodesWithinTimeBudget, and continues after a cut-off by clearing the pending schedule call and callingscheduleCleanupDuringIdleTimedirectly. A drain setsdrainReachedTimeLimit(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 orsetTimeouttask, 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 itUNCOMPUTEDand only a computation can make itCLEANagain. 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.
| Chain | Observation |
|---|---|
| Each node reads the node below it and adds one shared source | The 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 it | After 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 source | The 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
onChangeto a source that a node with a callback depends on reachesflushQueuedNodesOrDisposeMarkedNodes(batch/batch.ts) with no batch open, which callsrefreshQueuedNodesAndNotifyCallbackswithout looking at the flush state. The nestedrefreshQueuedNodesAndNotifyCallbacksrefreshes its flush queue, then itsnotifyRetainsOfChangedNodesstarts at index 0 of the list of changed nodes. The outernotifyRetainsOfChangedNodescleared that entry before it called the runningonChange, andchangedCountis still the outer count, which is at least 1, so the nested loop readsvalueofundefinedand throws aTypeError. A write to a source that no node with a callback depends on returns frommarkDependentsOfWrittenSourcewith no flush queue, soflushQueuedNodesOrDisposeMarkedNodesonly 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 notCLEAN), and that pull reaches the running node's computation again, so the recursion does not end.