@isograph/pico 0.0.0-main-5f205c00

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/graph/marking.ts","../src/graph/edges.ts","../src/disposal/cleanup.ts","../src/batch/notifications.ts","../src/graph/recompute.ts","../src/graph/refresh.ts","../src/batch/flush.ts","../src/disposal/age-drain.ts","../src/graph/nodes.ts","../src/disposal/update-counter.ts","../src/disposal/older-than-updates.ts","../src/disposal/schedule.ts","../src/batch/batch.ts","../src/graph/read.ts","../src/retention/retain.ts","../src/disposal/take.ts"],"sourcesContent":["import {\n UNCOMPUTED,\n DIRTY,\n MAYBE_DIRTY,\n CLEAN,\n DEPENDENTS_KNOWN_TO_BE_ALL_DIRTY,\n HAS_CALLBACK,\n MARKED_BEYOND,\n NO_FLAGS,\n} from '../state';\nimport type { Edge, SourceEdge } from './edges';\nimport type { MutableDerivedNode, MutableSourceNode } from './nodes';\n\nexport function storeSourceValueAndFindDependentsToMark<TValue>(\n source: MutableSourceNode<TValue>,\n value: TValue,\n): SourceEdge | undefined {\n source.value = value;\n if (source.dependentsStatus === DEPENDENTS_KNOWN_TO_BE_ALL_DIRTY) {\n return undefined;\n }\n source.dependentsStatus = DEPENDENTS_KNOWN_TO_BE_ALL_DIRTY;\n return source.firstDependent;\n}\n\n/**\n * A source write makes its direct readers DIRTY. Readers farther up the\n * graph become MAYBE_DIRTY. Queue the first node with a callback on each\n * path. If its value changes, its refresh queues the next affected callbacks.\n */\nexport function markDependentsOfWrittenSource(\n initialQueue: Array<MutableDerivedNode<unknown>> | undefined,\n first: SourceEdge,\n): Array<MutableDerivedNode<unknown>> | undefined {\n let queue = initialQueue;\n // Keep one lazy reader in a local. A single chain needs no stack.\n // When several lazy readers have dependents, save the other branches.\n let pendingLazyBranches: Array<MutableDerivedNode<unknown>> | undefined;\n let firstLazyBranch: MutableDerivedNode<unknown> | undefined;\n let beyondCallbackStack: Array<MutableDerivedNode<unknown>> | undefined;\n let edge: SourceEdge | undefined = first;\n while (edge !== undefined) {\n const node = edge.dependent;\n edge = edge.nextDependentEdge;\n const status = node.status;\n if (status === CLEAN) {\n node.status = DIRTY;\n if (node.callbackState === HAS_CALLBACK) {\n queue = queueNodeWithCallback(queue, node);\n const firstDependent = node.firstDependent;\n if (\n firstDependent !== undefined &&\n firstDependent !== node.firstKnownMarkedDependentEdge\n ) {\n (beyondCallbackStack ??= []).push(node);\n }\n } else if (node.firstDependent !== undefined) {\n if (firstLazyBranch !== undefined) {\n (pendingLazyBranches ??= []).push(firstLazyBranch);\n }\n firstLazyBranch = node;\n } else if (node.firstRetain === undefined) {\n recordMarkedUnneededNode(node);\n }\n } else if (status === MAYBE_DIRTY) {\n // Internal invariant: a `MAYBE_DIRTY` node marked its dependents when it\n // left `CLEAN`, or has a callback and went on the flush queue then. One with\n // `MARKED_BEYOND` loses the bit and is marked again by the walk through\n // lazy nodes. It goes on the flush queue if it has a callback, and the walk\n // goes on through it if it is lazy.\n node.status = DIRTY;\n if ((node.traversalFlags & MARKED_BEYOND) !== NO_FLAGS) {\n node.traversalFlags &= ~MARKED_BEYOND;\n if (node.callbackState === HAS_CALLBACK) {\n queue = queueNodeWithCallback(queue, node);\n } else if (node.firstDependent !== undefined) {\n if (firstLazyBranch !== undefined) {\n (pendingLazyBranches ??= []).push(firstLazyBranch);\n }\n firstLazyBranch = node;\n }\n }\n }\n }\n if (firstLazyBranch !== undefined) {\n return markTransitiveDependentsMaybeDirty(\n queue,\n firstLazyBranch,\n pendingLazyBranches,\n beyondCallbackStack,\n );\n }\n if (beyondCallbackStack !== undefined) {\n markReadersBeyondQueuedCallbacks(beyondCallbackStack);\n }\n return queue;\n}\n\nfunction queueNodeWithCallback(\n queue: Array<MutableDerivedNode<unknown>> | undefined,\n node: MutableDerivedNode<unknown>,\n): Array<MutableDerivedNode<unknown>> {\n if (queue === undefined) {\n return [node];\n }\n queue.push(node);\n return queue;\n}\n\nfunction recordMarkedUnneededNode(node: MutableDerivedNode<unknown>): void {\n markedUnneeded[markedUnneededCount] = node;\n markedUnneededCount += 1;\n}\n\n/**\n * Internal invariant: the first `markedUnneededCount` entries of\n * `markedUnneeded` are the nodes that marking took out of `CLEAN` while they\n * were unneeded, and every later entry is `undefined`. `markedUnneededCount`\n * is 0 when an outermost operation returns.\n */\nexport const markedUnneeded: Array<MutableDerivedNode<unknown> | undefined> =\n [];\n\nexport let markedUnneededCount = 0;\n\n/**\n * Follow lazy readers until each path reaches a node with a callback.\n * Queue that node for refresh. Collect its readers for marking beyond the\n * callback after this walk finishes.\n */\nexport function markTransitiveDependentsMaybeDirty(\n initialQueue: Array<MutableDerivedNode<unknown>> | undefined,\n firstLazyBranch: MutableDerivedNode<unknown>,\n initialLazyStack: Array<MutableDerivedNode<unknown>> | undefined,\n initialBeyondCallbackStack: Array<MutableDerivedNode<unknown>> | undefined,\n): Array<MutableDerivedNode<unknown>> | undefined {\n let queue = initialQueue;\n let pendingLazyBranches = initialLazyStack;\n let beyondCallbackStack = initialBeyondCallbackStack;\n let marked: MutableDerivedNode<unknown> | undefined = firstLazyBranch;\n while (marked !== undefined) {\n let dependentEdge = marked.firstDependent;\n while (dependentEdge !== undefined) {\n const dependent = dependentEdge.dependent;\n dependentEdge = dependentEdge.nextDependentEdge;\n switch (dependent.status) {\n case CLEAN:\n dependent.status = MAYBE_DIRTY;\n dependent.traversalFlags &= ~MARKED_BEYOND;\n if (dependent.callbackState === HAS_CALLBACK) {\n queue = queueNodeWithCallback(queue, dependent);\n const firstDependent = dependent.firstDependent;\n if (\n firstDependent !== undefined &&\n firstDependent !== dependent.firstKnownMarkedDependentEdge\n ) {\n (beyondCallbackStack ??= []).push(dependent);\n }\n } else if (dependent.firstDependent !== undefined) {\n if (dependentEdge === undefined) {\n // Last sibling: follow its readers directly.\n dependentEdge = dependent.firstDependent;\n } else {\n // Finish the siblings first, then visit this reader's branch.\n (pendingLazyBranches ??= []).push(dependent);\n }\n } else if (dependent.firstRetain === undefined) {\n recordMarkedUnneededNode(dependent);\n }\n break;\n case MAYBE_DIRTY:\n if ((dependent.traversalFlags & MARKED_BEYOND) !== NO_FLAGS) {\n dependent.traversalFlags &= ~MARKED_BEYOND;\n if (dependent.callbackState === HAS_CALLBACK) {\n queue = queueNodeWithCallback(queue, dependent);\n } else if (dependent.firstDependent !== undefined) {\n if (dependentEdge === undefined) {\n dependentEdge = dependent.firstDependent;\n } else {\n (pendingLazyBranches ??= []).push(dependent);\n }\n }\n }\n break;\n // Internal invariant: a lazy node that is not `CLEAN` has no `CLEAN`\n // dependents.\n case DIRTY:\n case UNCOMPUTED:\n break;\n }\n }\n marked =\n pendingLazyBranches === undefined ? undefined : pendingLazyBranches.pop();\n }\n if (beyondCallbackStack !== undefined) {\n markReadersBeyondQueuedCallbacks(beyondCallbackStack);\n }\n return queue;\n}\n\n/**\n * A queued callback node may keep its value. Mark its readers MAYBE_DIRTY so\n * a nested read can verify them. If the callback node changes, its refresh\n * queues the readers that need to run.\n */\nfunction markReadersBeyondQueuedCallbacks(\n beyondCallbackStack: Array<MutableDerivedNode<unknown>>,\n): void {\n let marked = beyondCallbackStack.pop();\n while (marked !== undefined) {\n let dependentEdge = marked.firstDependent;\n const stop = marked.firstKnownMarkedDependentEdge;\n if (dependentEdge !== stop) {\n marked.firstKnownMarkedDependentEdge = dependentEdge;\n while (dependentEdge !== stop) {\n const dependent = dependentEdge!.dependent;\n dependentEdge = dependentEdge!.nextDependentEdge;\n if (dependent.status === CLEAN) {\n dependent.status = MAYBE_DIRTY;\n dependent.traversalFlags |= MARKED_BEYOND;\n const firstDependent = dependent.firstDependent;\n if (firstDependent !== undefined) {\n if (firstDependent !== dependent.firstKnownMarkedDependentEdge) {\n beyondCallbackStack.push(dependent);\n }\n } else if (dependent.firstRetain === undefined) {\n recordMarkedUnneededNode(dependent);\n }\n }\n }\n }\n marked = beyondCallbackStack.pop();\n }\n}\n\n/**\n * A callback node changed during the flush. Its direct readers now need\n * recomputing. A reader marked only through this callback (MARKED_BEYOND)\n * still needs its callbacks queued. Follow its lazy readers until the\n * next callback on each path, which will propagate its own change in turn.\n *\n * Every direct reader was already marked by the write. A reader reached\n * earlier without crossing a callback already has its callbacks queued.\n */\nexport function markDependentsOfChangedDerivedNode(\n flushQueue: Array<MutableDerivedNode<unknown>>,\n node: MutableDerivedNode<unknown>,\n): void {\n node.firstKnownMarkedDependentEdge = undefined;\n let pendingLazyBranches: Array<MutableDerivedNode<unknown>> | undefined;\n let firstLazyBranch: MutableDerivedNode<unknown> | undefined;\n let edge = node.firstDependent;\n while (edge !== undefined) {\n const dependent = edge.dependent;\n edge = edge.nextDependentEdge;\n switch (dependent.status) {\n case MAYBE_DIRTY:\n dependent.status = DIRTY;\n if ((dependent.traversalFlags & MARKED_BEYOND) !== NO_FLAGS) {\n dependent.traversalFlags &= ~MARKED_BEYOND;\n if (dependent.callbackState === HAS_CALLBACK) {\n flushQueue.push(dependent);\n } else if (dependent.firstDependent !== undefined) {\n if (firstLazyBranch !== undefined) {\n (pendingLazyBranches ??= []).push(firstLazyBranch);\n }\n firstLazyBranch = dependent;\n }\n }\n break;\n case CLEAN:\n case DIRTY:\n case UNCOMPUTED:\n break;\n }\n }\n if (firstLazyBranch !== undefined) {\n // The walk appends to flushQueue in place. Its return value is the\n // same queue whenever the caller supplies one.\n markTransitiveDependentsMaybeDirty(\n flushQueue,\n firstLazyBranch,\n pendingLazyBranches,\n undefined,\n );\n }\n}\n\nexport function markMaybeDirtyDependentsDirty(\n first: Edge<MutableDerivedNode<unknown>> | undefined,\n): void {\n let edge = first;\n while (edge !== undefined) {\n const node = edge.dependent;\n edge = edge.nextDependentEdge;\n if (node.status === MAYBE_DIRTY) {\n node.status = DIRTY;\n }\n }\n}\n\n/**\n * Keep the allocated array for the next write without retaining the nodes.\n */\nexport function clearMarkedUnneededNodes(): void {\n for (let index = 0; index < markedUnneededCount; index += 1) {\n markedUnneeded[index] = undefined;\n }\n markedUnneededCount = 0;\n}\n","import type { MutableDerivedNode, MutableSourceNode } from './nodes';\n\n/*\n * How dependency edges work\n *\n * The derived node `total` reads `count` and `pricePerItem` to compute their\n * product. Either input can be a source node or a derived node.\n *\n * The edge `total → count` has `edge.dependent === total` and\n * `edge.dependency === count`. Both nodes link to this same edge:\n *\n * - From `total`, start at `total.firstSourceDependency` if `count` is a\n * source, or `total.firstDerivedDependency` if it is derived. Follow\n * `nextDependencyEdge` to visit each input of that kind.\n * - From `count`, start at `count.firstDependent` and follow `nextDependentEdge`\n * to visit each computation that reads `count`.\n *\n * Within each dependency list, Pico reuses edges in read order. Suppose both inputs\n * are sources and `total` reads `count` first. On its next run:\n *\n * - If it reads `count` and `pricePerItem` again, it reuses both edges.\n * - If it reads `count` and a different source, `salePrice`, the second edge\n * moves from the dependents of `pricePerItem` to the dependents of `salePrice`.\n * - If `count` is zero and `total` returns early, Pico removes the unread\n * price edge from both lists.\n *\n * Dependency lists are singly linked: recomputation walks forward and trims\n * unused edges from the end. Dependent lists are doubly linked: a new edge\n * goes at the head, and any edge can be removed in constant time.\n *\n * Marking a node `DIRTY` or `MAYBE_DIRTY` preserves its dependency edges.\n * If verification finds no changed input, a `MAYBE_DIRTY` node becomes\n * `CLEAN` with the same edges. Disposal unlinks all its dependency edges.\n */\nexport interface Edge<TDependency> {\n /** For `total → pricePerItem`, the input being read: `pricePerItem`. */\n dependency: TDependency;\n /** The derived node doing the reading: `total`. */\n readonly dependent: MutableDerivedNode<unknown>;\n /** The next edge from `total` to an input of the same kind. */\n nextDependencyEdge: this | undefined;\n /** The preceding edge in the list of computations that read `pricePerItem`. */\n previousDependentEdge: this | undefined;\n /** The following edge in that same list. */\n nextDependentEdge: this | undefined;\n}\n\n/** An edge from a derived node to a source. Its list links also point to source edges. */\nexport interface SourceEdge extends Edge<MutableSourceNode<unknown>> {\n readonly [sourceEdgeBrand]: true;\n}\n\ndeclare const sourceEdgeBrand: unique symbol;\n\nexport function createSourceEdge(\n dependency: MutableSourceNode<unknown>,\n dependent: MutableDerivedNode<unknown>,\n): SourceEdge {\n const fields: Omit<SourceEdge, typeof sourceEdgeBrand> = {\n dependency,\n dependent,\n nextDependencyEdge: undefined,\n previousDependentEdge: undefined,\n nextDependentEdge: undefined,\n };\n return fields as SourceEdge;\n}\n\n// Linking and unlinking are intentionally monomorphized for performance.\n// Each firstDependent access sees only sources or only derived nodes.\nexport function addEdgeToSourceDependents(edge: SourceEdge): void {\n const dependency = edge.dependency;\n const head = dependency.firstDependent;\n edge.previousDependentEdge = undefined;\n edge.nextDependentEdge = head;\n if (head !== undefined) {\n head.previousDependentEdge = edge;\n }\n dependency.firstDependent = edge;\n}\n\nexport function addEdgeToDerivedDependents(\n edge: Edge<MutableDerivedNode<unknown>>,\n): void {\n const dependency = edge.dependency;\n const head = dependency.firstDependent;\n edge.previousDependentEdge = undefined;\n edge.nextDependentEdge = head;\n if (head !== undefined) {\n head.previousDependentEdge = edge;\n }\n dependency.firstDependent = edge;\n}\n\nexport function unlinkRemainingSourceDependencies(first: SourceEdge): void {\n let edge: SourceEdge | undefined = first;\n do {\n removeEdgeFromSourceDependents(edge);\n edge = edge.nextDependencyEdge;\n } while (edge !== undefined);\n}\n\n/**\n * Unlinking preserves `nextDependencyEdge` so traversal can continue through the removed edge.\n */\nexport function removeEdgeFromSourceDependents(edge: SourceEdge): void {\n const previous = edge.previousDependentEdge;\n const next = edge.nextDependentEdge;\n if (previous === undefined) {\n edge.dependency.firstDependent = next;\n } else {\n previous.nextDependentEdge = next;\n }\n if (next !== undefined) {\n next.previousDependentEdge = previous;\n }\n}\n\n/**\n * Unlinking preserves `nextDependencyEdge` so traversal can continue through the removed edge.\n */\nexport function removeEdgeFromDerivedDependents(\n edge: Edge<MutableDerivedNode<unknown>>,\n): void {\n const dependency = edge.dependency;\n const next = edge.nextDependentEdge;\n if (dependency.firstKnownMarkedDependentEdge === edge) {\n dependency.firstKnownMarkedDependentEdge = next;\n }\n const previous = edge.previousDependentEdge;\n if (previous === undefined) {\n dependency.firstDependent = next;\n } else {\n previous.nextDependentEdge = next;\n }\n if (next !== undefined) {\n next.previousDependentEdge = previous;\n }\n}\n\n/**\n * Moves `edge` strictly before `edge.dependency.firstKnownMarkedDependentEdge` so `edge`'s\n * dependent can become `CLEAN` while preserving the `firstKnownMarkedDependentEdge` invariant.\n *\n * Contract: `edge.dependency.firstKnownMarkedDependentEdge !== undefined`.\n */\nexport function moveEdgeBeforeKnownMarkedDependents(\n edge: Edge<MutableDerivedNode<unknown>>,\n): void {\n const dependency = edge.dependency;\n if (edge === dependency.firstKnownMarkedDependentEdge) {\n dependency.firstKnownMarkedDependentEdge = edge.nextDependentEdge;\n }\n const previous = edge.previousDependentEdge;\n if (previous !== undefined) {\n const next = edge.nextDependentEdge;\n previous.nextDependentEdge = next;\n if (next !== undefined) {\n next.previousDependentEdge = previous;\n }\n const head = dependency.firstDependent!;\n edge.previousDependentEdge = undefined;\n edge.nextDependentEdge = head;\n head.previousDependentEdge = edge;\n dependency.firstDependent = edge;\n }\n}\n","import {\n UNCOMPUTED,\n CLEAN,\n SCHEDULE_NOT_PENDING,\n SCHEDULE_PENDING,\n DISPOSE_FROM_CLEANUP_QUEUE,\n DISPOSE_MARKED,\n} from '../state';\nimport {\n unlinkRemainingSourceDependencies,\n removeEdgeFromDerivedDependents,\n} from '../graph/edges';\nimport {\n clearMarkedUnneededNodes,\n markedUnneeded,\n markedUnneededCount,\n} from '../graph/marking';\nimport type { MutableDerivedNode } from '../graph/nodes';\n\n/**\n * Pops one entry off the cleanup queue and disposes its node if the node is\n * still unneeded and not `UNCOMPUTED`. Disposing a node puts each of its\n * derived dependencies that becomes unneeded on the cleanup queue. Returns\n * whether the cleanup queue is non-empty.\n *\n * Contract: called outside computations, batches, and `onChange` callbacks.\n */\nexport function disposeNext(): boolean {\n const node = cleanupQueue.pop();\n if (\n node !== undefined &&\n node.firstRetain === undefined &&\n node.firstDependent === undefined &&\n node.status !== UNCOMPUTED\n ) {\n disposeNode(node, DISPOSE_FROM_CLEANUP_QUEUE, undefined);\n }\n if (cleanupQueue.length > 0) {\n return true;\n }\n scheduleStatus = SCHEDULE_NOT_PENDING;\n return false;\n}\n\n/**\n * The same node can be queued more than once and can become needed again\n * before disposal. Each queue entry must be checked when it is drained.\n * An unneeded node with a cached value belongs here or on the current write's\n * marked-unneeded list. A tracked read can briefly hold it between pulling\n * its value and linking its new dependent.\n */\nexport const cleanupQueue: Array<MutableDerivedNode<unknown>> = [];\n\n/** A pending request runs at the end of the outermost operation. */\nexport let scheduleStatus: ScheduleStatus = SCHEDULE_NOT_PENDING;\n\ntype ScheduleStatus = typeof SCHEDULE_NOT_PENDING | typeof SCHEDULE_PENDING;\n\n/**\n * During a drain, push dependencies directly to the cleanup queue so the\n * drain cannot schedule itself again. Queue callers pass no stack and can\n * ignore the return value. Only DISPOSE_MARKED can create a stack to return:\n * it collects newly unneeded dirty dependencies for disposal in the same pass.\n * Clean dependencies go on the cleanup queue.\n */\nexport function disposeNode(\n node: MutableDerivedNode<unknown>,\n kind: DisposalKind,\n initialStack: Array<MutableDerivedNode<unknown>> | undefined,\n): Array<MutableDerivedNode<unknown>> | undefined {\n let stack = initialStack;\n const firstSource = node.firstSourceDependency;\n if (firstSource !== undefined) {\n unlinkRemainingSourceDependencies(firstSource);\n }\n let edge = node.firstDerivedDependency;\n while (edge !== undefined) {\n removeEdgeFromDerivedDependents(edge);\n const dependency = edge.dependency;\n if (\n dependency.firstDependent === undefined &&\n dependency.firstRetain === undefined\n ) {\n if (kind === DISPOSE_MARKED) {\n if (dependency.status === CLEAN) {\n addToCleanupQueue(dependency);\n } else {\n (stack ??= []).push(dependency);\n }\n } else {\n cleanupQueue.push(dependency);\n }\n }\n edge = edge.nextDependencyEdge;\n }\n node.firstSourceDependency = undefined;\n node.lastSourceDependency = undefined;\n node.firstDerivedDependency = undefined;\n node.lastDerivedDependency = undefined;\n node.firstKnownMarkedDependentEdge = undefined;\n node.status = UNCOMPUTED;\n node.value = undefined;\n return stack;\n}\n\ntype DisposalKind = typeof DISPOSE_FROM_CLEANUP_QUEUE | typeof DISPOSE_MARKED;\n\nexport function addToCleanupQueue(node: MutableDerivedNode<unknown>): void {\n if (cleanupQueue.length === 0) {\n scheduleStatus = SCHEDULE_PENDING;\n }\n cleanupQueue.push(node);\n}\n\n/**\n * Disposes every unneeded node on the cleanup queue, and each node that a\n * disposal leaves unneeded.\n *\n * Guarantee: after `disposeNext` returns false, and after `disposeAll`\n * returns, the cleanup queue is empty and no scheduler call is pending.\n *\n * Contract: as `disposeNext`.\n */\nexport function disposeAll(): void {\n while (true) {\n const node = cleanupQueue.pop();\n if (node === undefined) {\n scheduleStatus = SCHEDULE_NOT_PENDING;\n return;\n }\n if (\n node.firstRetain === undefined &&\n node.firstDependent === undefined &&\n node.status !== UNCOMPUTED\n ) {\n disposeNode(node, DISPOSE_FROM_CLEANUP_QUEUE, undefined);\n }\n }\n}\n\n/**\n * Internal invariant: a dependency that a disposal here leaves unneeded is\n * disposed too if it is not `CLEAN`, because the same write marked it. If it\n * is `CLEAN`, it goes on the cleanup queue with its value.\n */\nexport function disposeMarkedUnneededNodes(): void {\n let stack: Array<MutableDerivedNode<unknown>> | undefined;\n for (let index = 0; index < markedUnneededCount; index += 1) {\n let node: MutableDerivedNode<unknown> | undefined = markedUnneeded[index];\n while (node !== undefined) {\n if (\n node.firstRetain === undefined &&\n node.firstDependent === undefined &&\n node.status !== UNCOMPUTED &&\n node.status !== CLEAN\n ) {\n stack = disposeNode(node, DISPOSE_MARKED, stack);\n }\n node = stack?.pop();\n }\n }\n clearMarkedUnneededNodes();\n}\n\nexport function requestCleanupScheduling(): void {\n scheduleStatus = SCHEDULE_PENDING;\n}\n\nexport function clearPendingCleanupRequest(): void {\n scheduleStatus = SCHEDULE_NOT_PENDING;\n}\n","import type { MutableDerivedNode } from '../graph/nodes';\n\n/** Called once for each callback node whose recomputation changed its value. */\nexport function recordChangedNode(node: MutableDerivedNode<unknown>): void {\n changedNodes[changedCount] = node;\n changedCount += 1;\n}\n\n/**\n * Nodes whose callbacks are due after the current flush. Each changed node\n * becomes `CLEAN` during refresh, so a later queue entry for it cannot add it\n * again. Callbacks finish before another flush can reuse this array.\n */\nconst changedNodes: Array<MutableDerivedNode<unknown> | undefined> = [];\n\nlet changedCount = 0;\n\n/**\n * Calls the `onChange` of each retain of each node whose refresh changed its\n * value, in the order of each node's first refresh that changed it.\n */\nexport function notifyRetainsOfChangedNodes(): void {\n for (let index = 0; index < changedCount; index += 1) {\n const node = changedNodes[index]!;\n // The array survives the flush. Release its reference before notifying.\n changedNodes[index] = undefined;\n // Contract: no computation or `onChange` retains or releases, so the\n // retain list is the one the node had when the refresh changed its value.\n const value = node.value;\n let retain = node.firstRetain;\n while (retain !== undefined) {\n if (retain.onChange !== undefined) {\n retain.onChange(value);\n }\n retain = retain.nextRetain;\n }\n }\n changedCount = 0;\n}\n","import { addToCleanupQueue } from '../disposal/cleanup';\nimport { CHANGED, CLEAN, UNCHANGED } from '../state';\nimport {\n type Edge,\n removeEdgeFromDerivedDependents,\n unlinkRemainingSourceDependencies,\n} from './edges';\nimport {\n markDependentsOfChangedDerivedNode,\n markMaybeDirtyDependentsDirty,\n} from './marking';\nimport type { MutableDerivedNode } from './nodes';\n\n/**\n * The first run starts with empty dependency lists. Every edge it creates\n * belongs to this run, so there are no old edges to unlink.\n */\nexport function computeInitialDerivedValue<TValue>(\n node: MutableDerivedNode<TValue>,\n): TValue {\n const value = node.computation(node, undefined);\n node.status = CLEAN;\n node.value = value;\n return value;\n}\n\nexport function recomputeValueAndMarkDependents<TValue>(\n node: MutableDerivedNode<TValue>,\n): TValue {\n const previous = node.value;\n const value = rerunComputationAndUpdateDependencies(node, previous);\n if (value === previous) {\n return previous;\n }\n node.value = value;\n // A reader marked `MAYBE_DIRTY` now has a confirmed change to a direct\n // input. Its next refresh can skip verification and rerun immediately.\n markMaybeDirtyDependentsDirty(node.firstDependent);\n return value;\n}\n\nfunction rerunComputationAndUpdateDependencies<TValue>(\n node: MutableDerivedNode<TValue>,\n previous: TValue,\n): TValue {\n // Reuse the source and derived dependency lists in read order. Each\n // last*Dependency marks the end of the part used by this computation.\n // Reset both cursors to start before the first edge. As reads arrive, reuse\n // the next edge (retargeting it if the input changed) or append a new edge\n // when needed. The cursor then points to the edge for that read.\n node.lastSourceDependency = undefined;\n node.lastDerivedDependency = undefined;\n const value = node.computation(node, previous);\n // If the previous run read sources A then B, its list has two edges.\n // If this run reads only A, lastSourceDependency points to the edge for A.\n // Only the edge for B needs to be unlinked.\n unlinkUnreadDependencies(node);\n node.status = CLEAN;\n return value;\n}\n\n/**\n * Unlink the edges after the last read in each dependency list. If the\n * computation read no inputs of that kind, unlink the whole list.\n */\nfunction unlinkUnreadDependencies(node: MutableDerivedNode<unknown>): void {\n const lastSource = node.lastSourceDependency;\n if (lastSource === undefined) {\n const first = node.firstSourceDependency;\n if (first !== undefined) {\n unlinkRemainingSourceDependencies(first);\n node.firstSourceDependency = undefined;\n }\n } else if (lastSource.nextDependencyEdge !== undefined) {\n unlinkRemainingSourceDependencies(lastSource.nextDependencyEdge);\n lastSource.nextDependencyEdge = undefined;\n }\n const lastDerived = node.lastDerivedDependency;\n if (lastDerived === undefined) {\n const first = node.firstDerivedDependency;\n if (first !== undefined) {\n unlinkRemainingDerivedDependencies(first);\n node.firstDerivedDependency = undefined;\n }\n } else if (lastDerived.nextDependencyEdge !== undefined) {\n unlinkRemainingDerivedDependencies(lastDerived.nextDependencyEdge);\n lastDerived.nextDependencyEdge = undefined;\n }\n}\n\nfunction unlinkRemainingDerivedDependencies(\n first: Edge<MutableDerivedNode<unknown>>,\n): void {\n let edge: Edge<MutableDerivedNode<unknown>> | undefined = first;\n do {\n removeEdgeFromDerivedDependents(edge);\n const dependency = edge.dependency;\n if (\n dependency.firstDependent === undefined &&\n dependency.firstRetain === undefined\n ) {\n addToCleanupQueue(dependency);\n }\n edge = edge.nextDependencyEdge;\n } while (edge !== undefined);\n}\n\n/**\n * A downstream node with a callback can be waiting for this result. If it\n * changes, `markDependentsOfChangedDerivedNode` queues those readers for refresh. Returning\n * `CHANGED` tells `refreshNodeAndRecordChange` to record this node for notification.\n */\nexport function recomputeAndQueueAffectedDependents(\n flushQueue: Array<MutableDerivedNode<unknown>>,\n node: MutableDerivedNode<unknown>,\n): typeof CHANGED | typeof UNCHANGED {\n const previous = node.value;\n const value = rerunComputationAndUpdateDependencies(node, previous);\n if (value === previous) {\n return UNCHANGED;\n }\n node.value = value;\n if (node.firstDependent !== undefined) {\n markDependentsOfChangedDerivedNode(flushQueue, node);\n }\n return CHANGED;\n}\n","import {\n UNCOMPUTED,\n DIRTY,\n MAYBE_DIRTY,\n CLEAN,\n HAS_CALLBACK,\n CHANGED,\n UNCHANGED,\n} from '../state';\nimport { recordChangedNode } from '../batch/notifications';\nimport type { MutableDerivedNode } from './nodes';\nimport { type Edge, moveEdgeBeforeKnownMarkedDependents } from './edges';\nimport {\n computeInitialDerivedValue,\n recomputeValueAndMarkDependents,\n recomputeAndQueueAffectedDependents,\n} from './recompute';\n\n/**\n * Returns the current value of a derived node. During a flush, reading a node\n * with a callback can refresh it ahead of its turn in the queue. The flush\n * records any change so it can notify the callback after all refreshes finish.\n */\nexport function getCurrentDerivedValue<TValue>(\n node: MutableDerivedNode<TValue>,\n): TValue {\n switch (node.status) {\n case CLEAN:\n return node.value;\n case DIRTY:\n return node.callbackState === HAS_CALLBACK\n ? getCurrentValueForNodeWithCallback(node)\n : recomputeValueAndMarkDependents(node);\n case MAYBE_DIRTY:\n return node.callbackState === HAS_CALLBACK\n ? getCurrentValueForNodeWithCallback(node)\n : getValueAfterVerifyingDependencies(node);\n case UNCOMPUTED:\n return computeInitialDerivedValue(node);\n }\n}\n\nfunction getValueAfterVerifyingDependencies<TValue>(\n node: MutableDerivedNode<TValue>,\n): TValue {\n return verifyDerivedDependencies(node) === DIRTY\n ? recomputeValueAndMarkDependents(node)\n : node.value;\n}\n\n/**\n * During a flush, use the active queue so this read can record a change\n * and queue downstream nodes that need refreshing. Outside a flush,\n * a node can still be `MAYBE_DIRTY` after an input kept its value. A read\n * verifies that input before deciding whether to rerun the node.\n */\nfunction getCurrentValueForNodeWithCallback<TValue>(\n node: MutableDerivedNode<TValue>,\n): TValue {\n const queue = refreshQueue;\n if (queue !== undefined) {\n refreshNodeAndRecordChange(queue, node);\n return node.value;\n }\n return node.status === DIRTY\n ? recomputeValueAndMarkDependents(node)\n : getValueAfterVerifyingDependencies(node);\n}\n\n/**\n * Can requestedNode reuse its cached value? A write to a direct source\n * already marks its reader DIRTY. Here the reader is MAYBE_DIRTY, so only\n * its derived inputs need checking.\n *\n * Suppose A read B1, then B2. The outer loop checks A → B1 first. If B1\n * is lazy and MAYBE_DIRTY, the loop starts checking B1's inputs. Once B1\n * is up to date, the inner loop recovers A → B1 to get back to A.\n * A must rerun if either B1 or B2 changed. If A is still MAYBE_DIRTY\n * after checking B1, check B2. If either input marks A DIRTY, stop\n * checking. A's rerun will read the inputs it needs. If both inputs kept\n * their values, A becomes CLEAN and keeps its cached value.\n */\nfunction verifyDerivedDependencies(\n requestedNode: MutableDerivedNode<unknown>,\n): typeof DIRTY | typeof CLEAN {\n let savedReaderEdges: Array<Edge<MutableDerivedNode<unknown>>> | undefined;\n let nodeBeingVerified = requestedNode;\n let nextInputEdge = requestedNode.firstDerivedDependency;\n while (true) {\n if (nextInputEdge !== undefined) {\n const derivedInput = nextInputEdge.dependency;\n // This reader may become CLEAN. Keep its edge out of the part of\n // the input's reader list that future writes can skip.\n if (derivedInput.firstKnownMarkedDependentEdge !== undefined) {\n moveEdgeBeforeKnownMarkedDependents(nextInputEdge);\n }\n if (\n derivedInput.status === MAYBE_DIRTY &&\n derivedInput.callbackState !== HAS_CALLBACK\n ) {\n // To get back to A, we need this exact edge and its nextDependencyEdge.\n // Both links below belong to B1's list of reader edges. If both are\n // undefined, A → B1 is the only edge and B1.firstDependent gives it\n // back. If either exists, save A → B1 before descending. This lets\n // a single-reader chain skip every push and pop.\n if (\n nextInputEdge.previousDependentEdge !== undefined ||\n nextInputEdge.nextDependentEdge !== undefined\n ) {\n (savedReaderEdges ??= []).push(nextInputEdge);\n }\n nodeBeingVerified = derivedInput;\n nextInputEdge = derivedInput.firstDerivedDependency;\n continue; // Check B1's own inputs before deciding whether A must run.\n }\n if (derivedInput.status !== CLEAN) {\n // A changed input marks this reader DIRTY. Verification only needs\n // that status, so it discards the value returned by the read.\n getCurrentDerivedValue(derivedInput);\n }\n if (nodeBeingVerified.status !== DIRTY) {\n // No input marked A dirty during the refresh. Check B2.\n nextInputEdge = nextInputEdge.nextDependencyEdge;\n continue;\n }\n if (nodeBeingVerified === requestedNode) {\n // An input changed. The caller recomputes requestedNode and marks\n // its readers DIRTY only if requestedNode's own value changes.\n return DIRTY;\n }\n // Rerun an intermediate reader here so its own readers see any change.\n recomputeValueAndMarkDependents(nodeBeingVerified);\n } else {\n // Every input kept its value, so this node can reuse its cached result.\n nodeBeingVerified.status = CLEAN;\n }\n\n while (true) {\n if (nodeBeingVerified === requestedNode) {\n return CLEAN;\n }\n // We're at B1. Did the descent from A push A → B1? Any edges saved\n // deeper in the traversal have already been popped, so if we pushed\n // this edge it must be on top, with B1 as its dependency.\n let edgeBackToReader: Edge<MutableDerivedNode<unknown>>;\n if (\n savedReaderEdges !== undefined &&\n savedReaderEdges.length > 0 &&\n savedReaderEdges[savedReaderEdges.length - 1]!.dependency ===\n nodeBeingVerified\n ) {\n // We pushed A → B1 because B1 had multiple reader edges.\n edgeBackToReader = savedReaderEdges.pop()!;\n } else {\n // B1 had one reader edge, so B1.firstDependent gives us A → B1.\n // If the stack has a top entry, it belongs to a reader farther up\n // the chain. Popping it here would skip A.\n edgeBackToReader = nodeBeingVerified.firstDependent!;\n }\n nodeBeingVerified = edgeBackToReader.dependent;\n if (nodeBeingVerified.status !== DIRTY) {\n // A is still MAYBE_DIRTY. Step from A → B1 to A → B2 in A's inputs.\n // After the last input, the outer loop sees undefined and marks A CLEAN.\n nextInputEdge = edgeBackToReader.nextDependencyEdge;\n break;\n }\n if (nodeBeingVerified === requestedNode) {\n // A direct input changed. The caller will rerun A and read its inputs.\n return DIRTY;\n }\n // For an intermediate reader, rerun it here. Its value determines\n // whether the next reader up also needs to run.\n recomputeValueAndMarkDependents(nodeBeingVerified);\n }\n }\n}\n\nfunction refreshNodeAndRecordChange(\n flushQueue: Array<MutableDerivedNode<unknown>>,\n node: MutableDerivedNode<unknown>,\n): void {\n const result = refreshNodeIfItHasCallback(flushQueue, node);\n if (result === CHANGED) {\n recordChangedNode(node);\n }\n}\n\ntype RefreshResult = typeof CHANGED | typeof UNCHANGED;\n\nfunction refreshNodeIfItHasCallback(\n flushQueue: Array<MutableDerivedNode<unknown>>,\n node: MutableDerivedNode<unknown>,\n): RefreshResult {\n if (node.callbackState !== HAS_CALLBACK) {\n return UNCHANGED;\n }\n switch (node.status) {\n case DIRTY:\n return recomputeAndQueueAffectedDependents(flushQueue, node);\n case MAYBE_DIRTY:\n return verifyDerivedDependencies(node) === DIRTY\n ? recomputeAndQueueAffectedDependents(flushQueue, node)\n : UNCHANGED;\n // Internal invariant: a `CLEAN` node on the flush queue was recomputed after\n // marking put it there, by a pull or by an earlier entry of the same node.\n // A node that reaches this switch has a callback, so it is retained and never\n // `UNCOMPUTED`.\n case CLEAN:\n case UNCOMPUTED:\n return UNCHANGED;\n }\n}\n\n/**\n * While the flush refreshes A, A's computation can read B before B's turn\n * in the queue. That read refreshes B immediately. If B changes, the pull\n * uses this same queue for B's affected readers and records B for notification.\n * The refresh loop clears this reference before callbacks run.\n */\nlet refreshQueue: Array<MutableDerivedNode<unknown>> | undefined;\n\nexport function refreshNodesInFlushQueue(\n flushQueue: Array<MutableDerivedNode<unknown>>,\n): void {\n refreshQueue = flushQueue;\n // Refresh can append downstream callbacks. Read the current length so\n // every queued node has its final value before the first notification.\n for (let index = 0; index < flushQueue.length; index += 1) {\n refreshNodeAndRecordChange(flushQueue, flushQueue[index]!);\n }\n refreshQueue = undefined;\n}\n","import { disposeMarkedUnneededNodes } from '../disposal/cleanup';\nimport { markedUnneededCount } from '../graph/marking';\nimport type { MutableDerivedNode } from '../graph/nodes';\nimport { refreshNodesInFlushQueue } from '../graph/refresh';\nimport { FLUSH_IDLE, FLUSH_RUNNING } from '../state';\nimport { notifyRetainsOfChangedNodes } from './notifications';\n\ntype FlushState = typeof FLUSH_IDLE | typeof FLUSH_RUNNING;\n\nexport let flushState: FlushState = FLUSH_IDLE;\n\n/**\n * Guarantee: every `onChange` runs after the flush has refreshed every node\n * on the flush queue, in the order of each node's first recompute that\n * changed its value.\n *\n * Internal invariant: an `onChange` writes nothing, so it puts no node on the\n * flush queue and no node on the marked-unneeded list.\n */\nexport function refreshQueuedNodesAndNotifyCallbacks(\n flushQueue: Array<MutableDerivedNode<unknown>>,\n): void {\n flushState = FLUSH_RUNNING;\n refreshNodesInFlushQueue(flushQueue);\n if (markedUnneededCount > 0) {\n disposeMarkedUnneededNodes();\n }\n notifyRetainsOfChangedNodes();\n flushState = FLUSH_IDLE;\n}\n","import {\n UNCOMPUTED,\n SCAN_SEEN,\n DISPOSE_FROM_CLEANUP_QUEUE,\n NO_FLAGS,\n} from '../state';\nimport { cleanupQueue, disposeNode } from './cleanup';\nimport type { MutableDerivedNode } from '../graph/nodes';\n\n/**\n * Disposes unneeded nodes whose newest queue entry is older than the age\n * boundary, then any dependencies those disposals leave unneeded. Returns\n * the number of remaining entries, excluding the boundary marker.\n *\n * Each boundary in positions must still refer to the same group of surviving\n * entries after compaction. The backward scan counts entries after each\n * boundary. The final pass converts those counts back into queue indices.\n * All SCAN_SEEN bits are clear on entry and again before disposal begins.\n */\nexport function disposeEligibleCleanupEntries(\n eligibleEnd: number,\n positions: Array<number>,\n count: number,\n marker: MutableDerivedNode<unknown>,\n outOfTime: (() => boolean) | undefined,\n): number {\n const queue = cleanupQueue;\n const originalLength = queue.length;\n // Pack the newest entry for each unneeded node into the tail of the\n // original queue. A backward scan sees the newest duplicate first.\n let firstKept = originalLength;\n let eligibleCount = 0;\n let boundaryIndex = count - 1;\n for (let index = originalLength - 1; index >= 0; index -= 1) {\n while (boundaryIndex >= 0 && (positions[boundaryIndex] as number) > index) {\n positions[boundaryIndex] = originalLength - firstKept;\n boundaryIndex -= 1;\n }\n const node = queue[index] as MutableDerivedNode<unknown>;\n if (\n node.firstRetain !== undefined ||\n node.firstDependent !== undefined ||\n node.status === UNCOMPUTED ||\n (node.traversalFlags & SCAN_SEEN) !== NO_FLAGS\n ) {\n continue;\n }\n node.traversalFlags |= SCAN_SEEN;\n firstKept -= 1;\n queue[firstKept] = node;\n if (index < eligibleEnd) {\n eligibleCount += 1;\n }\n }\n for (let index = firstKept; index < originalLength; index += 1) {\n (queue[index] as MutableDerivedNode<unknown>).traversalFlags &= ~SCAN_SEEN;\n }\n // Oldest first, so a dependency's entry is judged before the disposal of a\n // newer dependent can leave it unneeded. The first disposal runs whatever\n // the budget, so each budgeted drain that has an old entry disposes one.\n const firstYoung = firstKept + eligibleCount;\n let nextEligible = firstKept;\n let budgetExpired = false;\n for (; nextEligible < firstYoung; nextEligible += 1) {\n if (nextEligible > firstKept && outOfTime !== undefined && outOfTime()) {\n budgetExpired = true;\n break;\n }\n disposeNode(\n queue[nextEligible] as MutableDerivedNode<unknown>,\n DISPOSE_FROM_CLEANUP_QUEUE,\n undefined,\n );\n }\n const disposedCount = nextEligible - firstKept;\n // Disposing a node can leave its inputs unneeded. disposeNode appends\n // them after the original queue. Follow that growing list in this drain.\n let nextCascade = originalLength;\n if (!budgetExpired) {\n for (; nextCascade < queue.length; nextCascade += 1) {\n const node = queue[nextCascade] as MutableDerivedNode<unknown>;\n if (\n node.firstRetain === undefined &&\n node.firstDependent === undefined &&\n node.status !== UNCOMPUTED\n ) {\n if (outOfTime !== undefined && outOfTime()) {\n budgetExpired = true;\n break;\n }\n disposeNode(node, DISPOSE_FROM_CLEANUP_QUEUE, undefined);\n }\n }\n }\n // Keep unfinished cascade entries first so the next drain can dispose\n // them at any age. Old entries still waiting and then young entries follow.\n const pendingCascade = budgetExpired ? queue.slice(nextCascade) : undefined;\n const pendingCount = pendingCascade === undefined ? 0 : pendingCascade.length;\n const keptCount = originalLength - firstKept;\n const remainingCount = keptCount - disposedCount;\n queue.copyWithin(pendingCount, firstKept + disposedCount, originalLength);\n if (pendingCascade !== undefined) {\n for (let index = 0; index < pendingCount; index += 1) {\n queue[index] = pendingCascade[index] as MutableDerivedNode<unknown>;\n }\n }\n queue.length = pendingCount + remainingCount;\n for (let index = 0; index < count; index += 1) {\n positions[index] =\n pendingCount + keptCount - (positions[index] as number) - disposedCount;\n }\n if (pendingCount + remainingCount > 0) {\n queue.push(marker);\n }\n drainReachedTimeLimit = budgetExpired;\n pendingCascadeCount = pendingCount;\n return pendingCount + remainingCount;\n}\n\n/** True if the last drain skipped eligible work because its time budget expired. */\nexport let drainReachedTimeLimit = false;\n\n/** Nodes left at the front of the queue for disposal regardless of age. */\nexport let pendingCascadeCount = 0;\n","import {\n UNCOMPUTED,\n type DIRTY,\n type MAYBE_DIRTY,\n type CLEAN,\n type DEPENDENTS_NOT_NECESSARILY_ALL_DIRTY,\n DEPENDENTS_KNOWN_TO_BE_ALL_DIRTY,\n NO_CALLBACK,\n type HAS_CALLBACK,\n type MARKED_BEYOND,\n type SCAN_SEEN,\n NO_FLAGS,\n type ALL_TRAVERSAL_FLAGS,\n} from '../state';\nimport type { Edge, SourceEdge } from './edges';\n\nexport function createSourceNode<TValue>(value: TValue): SourceNode<TValue> {\n const source: Omit<MutableSourceNode<TValue>, typeof sourceBrand> = {\n value,\n firstDependent: undefined,\n // A new source has no readers to invalidate.\n dependentsStatus: DEPENDENTS_KNOWN_TO_BE_ALL_DIRTY,\n };\n return source as MutableSourceNode<TValue>;\n}\n\n/*\n * Public and internal types\n *\n * The public API exposes opaque handles so callers cannot edit the graph\n * directly. Sources also expose a readonly value: writes go through\n * `writeSource` so Pico can invalidate dependents. Internally, Pico casts\n * the same handles to mutable types to access their fields without\n * allocating wrapper objects.\n */\nexport type SourceNode<in out TValue> = {\n /** The committed source value. Reading this field records no dependency. */\n readonly value: TValue;\n readonly [sourceBrand]: (value: TValue) => TValue;\n};\n\ndeclare const sourceBrand: unique symbol;\n\nexport type MutableSourceNode<TValue> = SourceNode<TValue> & {\n value: TValue;\n firstDependent: SourceEdge | undefined;\n // A write can skip marking until a read puts a clean reader back on the list.\n dependentsStatus: DependentsStatus;\n};\n\ntype DependentsStatus =\n | typeof DEPENDENTS_NOT_NECESSARILY_ALL_DIRTY\n | typeof DEPENDENTS_KNOWN_TO_BE_ALL_DIRTY;\n\n/**\n * Returns an `UNCOMPUTED` derived node.\n *\n * Contract: `computation` is synchronous. `computation` reads other nodes\n * only through `readSource` and `readDerived`, called with the `callingNode`\n * that `computation` receives, and does not keep that `callingNode` for use\n * after it returns. `computation` does not write, start or end a batch, retain,\n * release, dispose, or call `readDerivedOutsideComputation`.\n */\nexport function createDerivedNode<TValue>(\n computation: (\n callingNode: CallingNode,\n previous: TValue | undefined,\n ) => TValue,\n): DerivedNode<TValue> {\n const node: Omit<\n MutableDerivedNode<TValue>,\n keyof DerivedNode<TValue> | keyof CallingNode\n > = {\n // An `UNCOMPUTED` node has no value. Every read of `value` follows a\n // status check that excludes `UNCOMPUTED`, so `value` is read only after a\n // computation stored a `TValue` in it. The type cannot make `value` depend\n // on `status`, and typing it `TValue | undefined` would put a cast at\n // every read.\n value: undefined as TValue,\n firstRetain: undefined,\n traversalFlags: NO_FLAGS,\n status: UNCOMPUTED,\n callbackState: NO_CALLBACK,\n firstSourceDependency: undefined,\n lastSourceDependency: undefined,\n firstDerivedDependency: undefined,\n lastDerivedDependency: undefined,\n firstDependent: undefined,\n firstKnownMarkedDependentEdge: undefined,\n computation,\n };\n return node as MutableDerivedNode<TValue>;\n}\n\nexport type CallingNode = { readonly [callingNodeBrand]: true };\n\ndeclare const callingNodeBrand: unique symbol;\n\nexport type DerivedNode<TValue> = { readonly [derivedBrand]: TValue };\n\ndeclare const derivedBrand: unique symbol;\n\nexport type MutableDerivedNode<TValue> = DerivedNode<TValue> &\n CallingNode & {\n value: TValue;\n firstRetain: MutableRetain<TValue> | undefined;\n // If (traversalFlags & SCAN_SEEN) !== NO_FLAGS, the cleanup scan has already\n // kept this node's newest queue entry. It skips older entries for this node.\n // If status is MAYBE_DIRTY and (traversalFlags & MARKED_BEYOND) !== NO_FLAGS,\n // marking reached this node only through a dependency with a callback.\n traversalFlags: TraversalFlags;\n // On read, CLEAN reuses the cached value, MAYBE_DIRTY checks its inputs,\n // DIRTY reruns the computation, and UNCOMPUTED computes from scratch.\n status: Status;\n // HAS_CALLBACK while any retain has an onChange callback. A flush\n // refreshes the node before notifying those callbacks of a changed value.\n callbackState: CallbackState;\n firstSourceDependency: SourceEdge | undefined;\n // The most recent source edge used so far in this computation.\n lastSourceDependency: SourceEdge | undefined;\n firstDerivedDependency: Edge<MutableDerivedNode<unknown>> | undefined;\n // The corresponding cursor for reads of derived nodes.\n lastDerivedDependency: Edge<MutableDerivedNode<unknown>> | undefined;\n firstDependent: Edge<MutableDerivedNode<unknown>> | undefined;\n /**\n * Where marking can stop in this node's list of dependents. The list\n * starts at `firstDependent` and follows `nextDependentEdge`. From this\n * edge to the end of that list, every dependent is already marked\n * `DIRTY` or `MAYBE_DIRTY`. Earlier dependents still need checking.\n *\n * Suppose three siblings read this node. In reader-list order they are\n * R1, R2, R3. If the boundary is the edge to R2, this pass checks only\n * R1, then moves the boundary to the edge to R1. When a reader becomes\n * clean, its edge moves before the boundary so a later write checks it.\n * An undefined boundary means marking must check the whole list.\n */\n firstKnownMarkedDependentEdge:\n | Edge<MutableDerivedNode<unknown>>\n | undefined;\n // Method syntax keeps MutableDerivedNode<TValue> assignable to MutableDerivedNode<unknown>.\n computation(callingNode: CallingNode, previous: TValue | undefined): TValue;\n };\n\n/** Retains form a doubly linked list starting at the node’s firstRetain. */\nexport type MutableRetain<TValue> = Retain<TValue> & {\n node: MutableDerivedNode<TValue> | undefined;\n onChange: OnChange<TValue> | undefined;\n previousRetain: MutableRetain<TValue> | undefined;\n nextRetain: MutableRetain<TValue> | undefined;\n};\n\nexport type Retain<TValue> = { readonly [retainBrand]: TValue };\n\ndeclare const retainBrand: unique symbol;\n\n// The flush queue holds nodes as MutableDerivedNode<unknown>, regardless\n// of their value type.\n// Extracting a method signature gives the callback a bivariant parameter:\n// a number callback can travel through the queue, but Pico calls it only\n// with the value of the number node that owns its retain.\ntype OnChange<TValue> = { onChange(value: TValue): void }['onChange'];\n\ntype TraversalFlags =\n | typeof NO_FLAGS\n | typeof MARKED_BEYOND\n | typeof SCAN_SEEN\n | typeof ALL_TRAVERSAL_FLAGS;\n\n/**\n * These invariants hold for a derived node between runs of its computation.\n *\n * - If the node is `UNCOMPUTED`, it has no cached result, dependencies, or dependents.\n * - If the node is `CLEAN`, its cached result is current and every derived input\n * is `CLEAN`. A read returns the cached result immediately.\n * - If the node is `DIRTY`, one of its source inputs received a write or one\n * of its derived inputs changed value. Pico reruns the node on its next refresh.\n * - If the node is `MAYBE_DIRTY`, an upstream write may have changed a derived\n * input. On the next refresh, Pico checks those inputs. If any changed value,\n * Pico reruns the node. Otherwise it marks the node `CLEAN` and reuses its result.\n *\n * A `DIRTY` or `MAYBE_DIRTY` node retains its last computed result. Once marking\n * finishes, each of its dependents is also `DIRTY` or `MAYBE_DIRTY`.\n */\nexport type Status =\n | typeof UNCOMPUTED\n | typeof DIRTY\n | typeof MAYBE_DIRTY\n | typeof CLEAN;\n\n/**\n * Internal invariant: a node is `HAS_CALLBACK` exactly while it has a retain with\n * an `onChange`. Marking puts a node with a callback that it takes out of `CLEAN` on\n * the flush queue, unless it reached the node only beyond another node\n * with a callback. Every other node is lazy.\n */\ntype CallbackState = typeof NO_CALLBACK | typeof HAS_CALLBACK;\n","export function incrementUpdateCount(): void {\n updateCount += 1;\n}\n\n/**\n * Counts outermost updates that reach the end of write processing. Cleanup\n * uses this count to age queue entries.\n */\nexport let updateCount = 0;\n","import {\n pendingCascadeCount,\n disposeEligibleCleanupEntries,\n} from './age-drain';\nimport {\n cleanupQueue,\n clearPendingCleanupRequest,\n requestCleanupScheduling,\n} from './cleanup';\nimport { createDerivedNode, type MutableDerivedNode } from '../graph/nodes';\nimport { updateCount } from './update-counter';\n\n/**\n * Disposes unneeded nodes whose newest cleanup entry is at least minAge\n * updates old. Age starts at the first drain that sees an entry. A write\n * or batch commit advances the update count. Repeated drains do not.\n * Disposing a node can leave its inputs unneeded; these are eligible immediately.\n *\n * An optional idle deadline or performance.now() timestamp limits disposal.\n * The queue scan always finishes, and the first eligible disposal always\n * runs. Unfinished entries keep their ages for the next drain. If another\n * disposal strategy removed the boundary marker between drains, the\n * remaining entries start aging again at the current update count.\n *\n * Returns the number of entries still queued. When entries remain, request\n * another scheduler call at the end of the next outermost operation.\n * Call outside computations, batches, and callbacks, with an integer minAge.\n */\nexport function disposeOlderThanUpdates<\n TDeadline extends { timeRemaining(): number },\n>(minAge: number, budget?: TDeadline | number): number {\n const length = cleanupQueue.length;\n const now = updateCount;\n let count = boundaryCount;\n if (count > 0 && cleanupQueue[positions[count - 1] as number] !== marker) {\n count = 0;\n }\n let eligibleEnd = minAge <= 0 ? length : 0;\n if (minAge > 0) {\n for (let index = count - 1; index >= 0; index -= 1) {\n if (now - (updates[index] as number) >= minAge) {\n eligibleEnd = positions[index] as number;\n break;\n }\n }\n }\n marker ??= createDerivedNode(() => undefined) as MutableDerivedNode<unknown>;\n const outOfTime =\n budget === undefined\n ? undefined\n : typeof budget === 'number'\n ? () => performance.now() >= budget\n : () => budget.timeRemaining() <= 0;\n const queued = disposeEligibleCleanupEntries(\n eligibleEnd,\n positions,\n count,\n marker,\n outOfTime,\n );\n // The cascade entries that the drain did not reach form the first segment,\n // whose count -Infinity makes it old enough for every `minAge`.\n const front = pendingCascadeCount;\n let next = 0;\n for (let index = 0; index < count; index += 1) {\n const position = positions[index] as number;\n if (position > front) {\n positions[next] = position;\n updates[next] = updates[index] as number;\n next += 1;\n }\n }\n if (front > 0) {\n for (let index = next; index > 0; index -= 1) {\n positions[index] = positions[index - 1] as number;\n updates[index] = updates[index - 1] as number;\n }\n positions[0] = front;\n updates[0] = -Infinity;\n next += 1;\n }\n if (queued === 0) {\n boundaryCount = 0;\n clearPendingCleanupRequest();\n return 0;\n }\n if (next > 0 && positions[next - 1] === queued) {\n // Every queued entry is below an existing boundary.\n boundaryCount = next;\n } else if (next > 0 && updates[next - 1] === now) {\n // A drain with no update since the previous boundary extends that segment.\n positions[next - 1] = queued;\n boundaryCount = next;\n } else {\n positions[next] = queued;\n updates[next] = now;\n boundaryCount = next + 1;\n }\n requestCleanupScheduling();\n return queued;\n}\n\n/*\n * A drain is one call of `disposeOlderThanUpdates`. An update is a\n * `writeSource` or a batch commit (batch.ts,\n * `countUpdateAndScheduleCleanupIfIdle`). The update count of an entry is the value of `updateCount` at\n * the first drain after the entry was queued, and its age is the current\n * `updateCount` minus that. An entry queued before some updates that end\n * before that drain is judged younger than it is by their number, never older.\n *\n * Internal invariant: `positions[0]` to `positions[boundaryCount - 1]` are\n * positive and non-decreasing, and `updates[0]` to `updates[boundaryCount - 1]`\n * are increasing. When `boundaryCount > 0` and the queue holds `marker` at index\n * `positions[boundaryCount - 1]`, every entry below `positions[i]` was queued\n * before a drain at which `updateCount` was at most `updates[i]`, and the\n * entries above the marker were queued after the last drain. Entries are\n * appended only at the end, and `disposeNext`, `disposeAll`, and `takeUnneeded`\n * remove entries only from the end, so no entry below the marker moves while\n * the marker stays.\n */\nconst positions: Array<number> = [];\n\nconst updates: Array<number> = [];\n\nlet boundaryCount = 0;\n\n/**\n * An `UNCOMPUTED` node that a drain puts at its boundary. A disposal skips an\n * `UNCOMPUTED` node, and nothing else queues this node, so it stays at its\n * index until a call removes it together with every entry above it.\n */\nlet marker: MutableDerivedNode<unknown> | undefined;\n","import { SCHEDULE_PENDING, DEFAULT_IDLE, DEFAULT_SCHEDULED } from '../state';\nimport {\n cleanupQueue,\n clearPendingCleanupRequest,\n scheduleStatus,\n} from './cleanup';\nimport { drainReachedTimeLimit } from './age-drain';\nimport { disposeOlderThanUpdates } from './older-than-updates';\n\n/**\n * `scheduler.schedule` is called with no arguments at the end of an outermost\n * operation after the cleanup queue went from empty to non-empty, or after a\n * `disposeOlderThanUpdates` that left entries. A `writeSource` to a source that\n * has no dependents, or that no computation read since the source was created\n * or last written, returns before that call. `schedule` may call `disposeAll`\n * synchronously. The default calls `disposeOlderThanUpdates(2)` once per call\n * of `schedule`, with the time of a `requestIdleCallback` callback where that\n * exists and of a 5 ms `setTimeout` task elsewhere, and requests another\n * callback or task only when that drain ran out of time before an old entry.\n * Assigning `scheduler.schedule` replaces the default.\n *\n * Contract: after a call, the scheduler calls `disposeNext` until it returns\n * false, calls `disposeAll`, or calls `disposeOlderThanUpdates` once.\n */\nexport const scheduler: { schedule: () => void } = {\n schedule: scheduleCleanupDuringIdleTime,\n};\n\nfunction scheduleCleanupDuringIdleTime(): void {\n if (defaultScheduleStatus === DEFAULT_SCHEDULED) {\n return;\n }\n defaultScheduleStatus = DEFAULT_SCHEDULED;\n if (typeof requestIdleCallback === 'function') {\n requestIdleCallback(disposeOldNodesWithinTimeBudget);\n } else {\n setTimeout(disposeOldNodesWithinTimeBudget, 0);\n }\n}\n\n/**\n * One drain with the idle period's time, or 5 ms in a `setTimeout` task,\n * which passes no deadline. A drain disposes at least one old entry before it\n * checks the time, so each callback that a cut-off requests makes progress. A\n * drain that leaves only young entries requests nothing: the next outermost\n * operation calls `schedule` again.\n */\nfunction disposeOldNodesWithinTimeBudget(deadline?: IdleDeadline): void {\n defaultScheduleStatus = DEFAULT_IDLE;\n if (cleanupQueue.length === 0) {\n return;\n }\n // The returned count includes young nodes. Only a drain that set drainReachedTimeLimit\n // left eligible work for another idle callback.\n disposeOlderThanUpdates(\n DEFAULT_MIN_AGE,\n deadline ?? performance.now() + TIMEOUT_DISPOSAL_MS,\n );\n if (drainReachedTimeLimit) {\n clearPendingCleanupRequest();\n scheduleCleanupDuringIdleTime();\n }\n}\n\nconst DEFAULT_MIN_AGE = 2;\n\nconst TIMEOUT_DISPOSAL_MS = 5;\n\nlet defaultScheduleStatus: DefaultScheduleStatus = DEFAULT_IDLE;\n\ntype DefaultScheduleStatus = typeof DEFAULT_IDLE | typeof DEFAULT_SCHEDULED;\n\nexport function scheduleCleanupIfRequested(): void {\n if (scheduleStatus === SCHEDULE_PENDING) {\n clearPendingCleanupRequest();\n scheduler.schedule();\n }\n}\n","import { FLUSH_IDLE } from '../state';\nimport {\n markedUnneededCount,\n markDependentsOfWrittenSource,\n storeSourceValueAndFindDependentsToMark,\n} from '../graph/marking';\nimport type {\n MutableDerivedNode,\n MutableSourceNode,\n SourceNode,\n} from '../graph/nodes';\nimport { disposeMarkedUnneededNodes } from '../disposal/cleanup';\nimport { refreshQueuedNodesAndNotifyCallbacks, flushState } from './flush';\nimport { scheduleCleanupIfRequested } from '../disposal/schedule';\nimport { incrementUpdateCount } from '../disposal/update-counter';\n\n/** Stage a write in the open batch, or publish it immediately when no batch is open. */\nexport function writeSource<TValue>(\n source: SourceNode<TValue>,\n value: TValue,\n): void {\n if (firstPendingSource !== CLOSED_BATCH) {\n // Each entry keeps the value paired with its source at this call. The\n // batch erases the value type because different sources can share a batch.\n const pending = source as MutableSourceNode<unknown>;\n if (firstPendingSource === pending) {\n firstPendingValue = value;\n } else if (firstPendingSource === undefined) {\n firstPendingSource = pending;\n firstPendingValue = value;\n } else {\n (otherWrites ??= new Map()).set(pending, value);\n }\n return;\n }\n const firstDependentToMark = storeSourceValueAndFindDependentsToMark(\n source as MutableSourceNode<TValue>,\n value,\n );\n if (firstDependentToMark === undefined) return;\n flushQueuedNodesOrDisposeMarkedNodes(\n markDependentsOfWrittenSource(undefined, firstDependentToMark),\n );\n countUpdateAndScheduleCleanupIfIdle();\n}\n\n// CLOSED_BATCH means no batch is open. undefined means the open batch has no writes.\nconst CLOSED_BATCH = Symbol('closed batch');\n\nlet firstPendingSource:\n | MutableSourceNode<unknown>\n | undefined\n | typeof CLOSED_BATCH = CLOSED_BATCH;\n\nlet firstPendingValue: unknown;\n\nlet otherWrites: Map<MutableSourceNode<unknown>, unknown> | undefined;\n\nexport function flushQueuedNodesOrDisposeMarkedNodes(\n queue: Array<MutableDerivedNode<unknown>> | undefined,\n): void {\n if (queue !== undefined) {\n refreshQueuedNodesAndNotifyCallbacks(queue);\n } else if (markedUnneededCount > 0) {\n disposeMarkedUnneededNodes();\n }\n}\n\nfunction countUpdateAndScheduleCleanupIfIdle(): void {\n if (flushState === FLUSH_IDLE) {\n incrementUpdateCount();\n scheduleCleanupIfRequested();\n }\n}\n\n/** Open one synchronous write batch. Callers must not nest batches or read or retain nodes inside one. */\nexport function startWriteBatch(): void {\n if (firstPendingSource !== CLOSED_BATCH)\n throw new Error('A write batch is already open.');\n firstPendingSource = undefined;\n}\n\n/** Publish the last write to each source, refresh the graph, then notify subscribers. */\nexport function endWriteBatch(): void {\n const source = firstPendingSource;\n if (source === CLOSED_BATCH) return;\n firstPendingSource = CLOSED_BATCH;\n let queue: Array<MutableDerivedNode<unknown>> | undefined;\n if (source !== undefined) {\n const firstDependentToMark = storeSourceValueAndFindDependentsToMark(\n source,\n firstPendingValue,\n );\n firstPendingValue = undefined;\n if (firstDependentToMark !== undefined)\n queue = markDependentsOfWrittenSource(undefined, firstDependentToMark);\n if (otherWrites !== undefined) {\n for (const [other, value] of otherWrites) {\n const edge = storeSourceValueAndFindDependentsToMark(other, value);\n if (edge !== undefined)\n queue = markDependentsOfWrittenSource(queue, edge);\n }\n otherWrites = undefined;\n }\n }\n flushQueuedNodesOrDisposeMarkedNodes(queue);\n countUpdateAndScheduleCleanupIfIdle();\n}\n\n/**\n * An outermost operation is a call to `writeSource`, `endWriteBatch`,\n * `retainDerivedNode`, `releaseRetain`, or `readDerivedOutsideComputation` made with no\n * batch open and no flush running, or the `endWriteBatch` that commits the writes.\n *\n * Internal invariant: a top-level read never runs inside a computation or a\n * batch body (its contract), so a top-level read inside an `onChange` is the\n * only nesting of operations outside a batch, and the flush state covers it.\n */\nexport function scheduleCleanupIfOutsideBatchAndFlush(): void {\n if (firstPendingSource === CLOSED_BATCH && flushState === FLUSH_IDLE) {\n scheduleCleanupIfRequested();\n }\n}\n\n/**\n * Top-level reads are forbidden in batch bodies. An onChange callback can\n * still read during a flush.\n */\nexport function scheduleCleanupIfNotFlushing(): void {\n if (flushState === FLUSH_IDLE) {\n scheduleCleanupIfRequested();\n }\n}\n","import { scheduleCleanupIfNotFlushing } from '../batch/batch';\nimport { addToCleanupQueue } from '../disposal/cleanup';\nimport { DEPENDENTS_NOT_NECESSARILY_ALL_DIRTY } from '../state';\nimport type {\n CallingNode,\n DerivedNode,\n MutableDerivedNode,\n MutableSourceNode,\n SourceNode,\n} from './nodes';\nimport {\n type Edge,\n addEdgeToDerivedDependents,\n addEdgeToSourceDependents,\n createSourceEdge,\n moveEdgeBeforeKnownMarkedDependents,\n removeEdgeFromDerivedDependents,\n removeEdgeFromSourceDependents,\n} from './edges';\nimport { getCurrentDerivedValue } from './refresh';\n\n/**\n * Returns the value of `source` and records it as a dependency of\n * `callingNode`.\n *\n * Contract: called only while the computation of `callingNode` runs.\n */\nexport function readSource<TValue>(\n callingNode: CallingNode,\n source: SourceNode<TValue>,\n): TValue {\n const mutableCallingNode = callingNode as MutableDerivedNode<unknown>;\n const mutableSource = source as MutableSourceNode<unknown>;\n // A write records that every node in the source's dependents list is\n // `DIRTY`, so the next write skips marking. The calling node is `CLEAN` in\n // that list once this computation finishes, so the read clears the record.\n mutableSource.dependentsStatus = DEPENDENTS_NOT_NECESSARILY_ALL_DIRTY;\n // On a rerun, reuse the old source edges in read order. If the source at\n // this position changed, move the edge to the new source's list of readers.\n const lastReadEdge = mutableCallingNode.lastSourceDependency;\n const reusableEdge =\n lastReadEdge === undefined\n ? mutableCallingNode.firstSourceDependency\n : lastReadEdge.nextDependencyEdge;\n if (reusableEdge !== undefined) {\n if (reusableEdge.dependency !== mutableSource) {\n removeEdgeFromSourceDependents(reusableEdge);\n reusableEdge.dependency = mutableSource;\n addEdgeToSourceDependents(reusableEdge);\n }\n mutableCallingNode.lastSourceDependency = reusableEdge;\n } else if (\n lastReadEdge === undefined ||\n lastReadEdge.dependency !== mutableSource\n ) {\n const edge = createSourceEdge(mutableSource, mutableCallingNode);\n addEdgeToSourceDependents(edge);\n if (lastReadEdge === undefined) {\n mutableCallingNode.firstSourceDependency = edge;\n } else {\n lastReadEdge.nextDependencyEdge = edge;\n }\n mutableCallingNode.lastSourceDependency = edge;\n }\n return source.value;\n}\n\n/**\n * Brings `node` up to date, returns its value, and records it as a dependency\n * of `callingNode`.\n *\n * Contract: called only while the computation of `callingNode` runs.\n */\nexport function readDerived<TValue>(\n callingNode: CallingNode,\n node: DerivedNode<TValue>,\n): TValue {\n const mutableCallingNode = callingNode as MutableDerivedNode<unknown>;\n const mutableNode = node as MutableDerivedNode<TValue>;\n const value = getCurrentDerivedValue(mutableNode);\n // Reuse the next edge in the calling node's derived dependency list. Moving\n // it to another input can leave the old derived input eligible for disposal.\n const lastReadEdge = mutableCallingNode.lastDerivedDependency;\n const reusableEdge =\n lastReadEdge === undefined\n ? mutableCallingNode.firstDerivedDependency\n : lastReadEdge.nextDependencyEdge;\n if (reusableEdge !== undefined) {\n if (reusableEdge.dependency !== mutableNode) {\n const previousDependency = reusableEdge.dependency;\n removeEdgeFromDerivedDependents(reusableEdge);\n reusableEdge.dependency = mutableNode;\n addEdgeToDerivedDependents(reusableEdge);\n if (\n previousDependency.firstDependent === undefined &&\n previousDependency.firstRetain === undefined\n ) {\n addToCleanupQueue(previousDependency);\n }\n } else if (mutableNode.firstKnownMarkedDependentEdge !== undefined) {\n // The calling node becomes `CLEAN` when its computation returns, so its\n // reused edge must lie strictly before `firstKnownMarkedDependentEdge`.\n moveEdgeBeforeKnownMarkedDependents(reusableEdge);\n }\n mutableCallingNode.lastDerivedDependency = reusableEdge;\n } else if (\n lastReadEdge === undefined ||\n lastReadEdge.dependency !== mutableNode\n ) {\n const edge: Edge<MutableDerivedNode<unknown>> = {\n dependency: mutableNode,\n dependent: mutableCallingNode,\n nextDependencyEdge: undefined,\n previousDependentEdge: undefined,\n nextDependentEdge: undefined,\n };\n addEdgeToDerivedDependents(edge);\n if (lastReadEdge === undefined) {\n mutableCallingNode.firstDerivedDependency = edge;\n } else {\n lastReadEdge.nextDependencyEdge = edge;\n }\n mutableCallingNode.lastDerivedDependency = edge;\n }\n return value;\n}\n\n/**\n * Top-level read of `node`: brings `node` up to date and returns its value. A\n * recompute links edges as in a tracked read. A node left unneeded goes on the\n * cleanup queue, so the scheduler can dispose it and each dependency that its\n * disposal leaves unneeded.\n *\n * Contract: called outside computations and write batch bodies. Inside an\n * `onChange`, it is allowed.\n */\nexport function readDerivedOutsideComputation<TValue>(\n node: DerivedNode<TValue>,\n): TValue {\n const mutableNode = node as MutableDerivedNode<TValue>;\n const value = getCurrentDerivedValue(mutableNode);\n if (\n mutableNode.firstRetain === undefined &&\n mutableNode.firstDependent === undefined\n ) {\n addToCleanupQueue(mutableNode);\n }\n scheduleCleanupIfNotFlushing();\n return value;\n}\n","import { CLEAN, NO_CALLBACK, HAS_CALLBACK } from '../state';\nimport {\n scheduleCleanupIfOutsideBatchAndFlush,\n flushQueuedNodesOrDisposeMarkedNodes,\n} from '../batch/batch';\nimport { markTransitiveDependentsMaybeDirty } from '../graph/marking';\nimport type {\n DerivedNode,\n MutableDerivedNode,\n MutableRetain,\n Retain,\n} from '../graph/nodes';\nimport { addToCleanupQueue } from '../disposal/cleanup';\nimport { getCurrentDerivedValue } from '../graph/refresh';\nimport { scheduleCleanupIfRequested } from '../disposal/schedule';\n\n/**\n * Brings `node` up to date, adds a retain to the head of its retain list, and\n * returns the retain. A retained node keeps its value and its edges to its\n * dependencies until its last retain is released. A retain with an\n * `onChange` gives the node a callback.\n *\n * Guarantee: the flush calls `onChange` with the node's value once for each\n * update or batch that changed the node's value, after the flush has\n * refreshed every node on the flush queue. The first recompute of a node does\n * not call `onChange`.\n *\n * Contract: called outside computations, `onChange` callbacks, and write\n * batch bodies, because retaining computes the node. `onChange` does not\n * write, start or end a batch, retain, release, or dispose. It may call\n * `readDerivedOutsideComputation`.\n */\nexport function retainDerivedNode<TValue>(\n node: DerivedNode<TValue>,\n onChange?: (value: TValue) => void,\n): Retain<TValue> {\n const mutableNode = node as MutableDerivedNode<TValue>;\n // Populate the cache before attaching onChange. The retain needs the\n // node to be CLEAN and its dependencies linked, so it discards the value.\n getCurrentDerivedValue(mutableNode);\n const head = mutableNode.firstRetain;\n const retainFields: Omit<MutableRetain<TValue>, keyof Retain<TValue>> = {\n node: mutableNode,\n onChange,\n previousRetain: undefined,\n nextRetain: head,\n };\n const retain = retainFields as MutableRetain<TValue>;\n if (head !== undefined) {\n head.previousRetain = retain;\n }\n mutableNode.firstRetain = retain;\n if (onChange !== undefined) {\n mutableNode.callbackState = HAS_CALLBACK;\n }\n scheduleCleanupIfRequested();\n return retain;\n}\n\n/**\n * Releases `retain`. A release that leaves the node unneeded puts the node on\n * the cleanup queue. The node keeps its value and its edges until a disposal,\n * or the marking of a write, reaches it.\n *\n * Contract: called once per retain, outside computations and `onChange`\n * callbacks.\n */\nexport function releaseRetain<TValue>(retain: Retain<TValue>): void {\n const mutableRetain = retain as MutableRetain<TValue>;\n const mutableNode = mutableRetain.node!;\n mutableRetain.node = undefined;\n const previous = mutableRetain.previousRetain;\n const next = mutableRetain.nextRetain;\n if (previous === undefined) {\n mutableNode.firstRetain = next;\n } else {\n previous.nextRetain = next;\n mutableRetain.previousRetain = undefined;\n }\n if (next !== undefined) {\n next.previousRetain = previous;\n mutableRetain.nextRetain = undefined;\n }\n if (mutableRetain.onChange !== undefined) {\n mutableRetain.onChange = undefined;\n clearCallbackStateIfNoCallbackRetainsRemain(mutableNode);\n }\n // Internal invariant: a retained node is not `UNCOMPUTED`. Retaining pulled\n // it, and no disposal reaches a node with a retain.\n if (\n mutableNode.firstRetain === undefined &&\n mutableNode.firstDependent === undefined\n ) {\n addToCleanupQueue(mutableNode);\n }\n scheduleCleanupIfOutsideBatchAndFlush();\n}\n\n/**\n * Internal invariant: a node that loses its last callback while `DIRTY` or\n * `MAYBE_DIRTY` has no `CLEAN` dependents, and its dependents may be\n * `MAYBE_DIRTY` with `MARKED_BEYOND`, waiting for its refresh to put the\n * nodes with callbacks among them on the flush queue. The walk through lazy nodes\n * from the node clears that bit on them, as the dependents of a lazy node that\n * is `DIRTY` or `MAYBE_DIRTY` require, and puts those nodes with callbacks on the\n * flush queue. A node that gets a callback was brought\n * up to date first, so it is `CLEAN`.\n */\nfunction clearCallbackStateIfNoCallbackRetainsRemain(\n node: MutableDerivedNode<unknown>,\n): void {\n if (hasOnChangeRetain(node)) {\n return;\n }\n node.callbackState = NO_CALLBACK;\n // The retain kept this node computed until this release.\n if (node.status !== CLEAN) {\n flushQueuedNodesOrDisposeMarkedNodes(\n markTransitiveDependentsMaybeDirty(undefined, node, undefined, undefined),\n );\n }\n}\n\nfunction hasOnChangeRetain(node: MutableDerivedNode<unknown>): boolean {\n let retain = node.firstRetain;\n while (retain !== undefined) {\n if (retain.onChange !== undefined) {\n return true;\n }\n retain = retain.nextRetain;\n }\n return false;\n}\n","import { UNCOMPUTED, DISPOSE_FROM_CLEANUP_QUEUE } from '../state';\nimport {\n cleanupQueue,\n clearPendingCleanupRequest,\n disposeNode,\n requestCleanupScheduling,\n} from './cleanup';\nimport type { DerivedNode, MutableDerivedNode } from '../graph/nodes';\n\n/**\n * Empties the cleanup queue and returns the node of each entry whose node is\n * still unneeded and not `UNCOMPUTED`, oldest entry first. A node with several\n * entries appears once per entry. pico-js no longer holds a taken node for\n * disposal: it queues the node again only when the node becomes unneeded again\n * after it is needed, or on a top-level read while it is unneeded.\n *\n * Contract: called outside computations, batches, and `onChange` callbacks.\n */\nexport function takeUnneeded(): ReadonlyArray<DerivedNode<unknown>> {\n const taken = cleanupQueue.filter(isUnneededComputedNode);\n cleanupQueue.length = 0;\n clearPendingCleanupRequest();\n return taken;\n}\n\nfunction isUnneededComputedNode(node: MutableDerivedNode<unknown>): boolean {\n return (\n node.firstRetain === undefined &&\n node.firstDependent === undefined &&\n node.status !== UNCOMPUTED\n );\n}\n\n/**\n * Disposes `node` if it is unneeded and not `UNCOMPUTED`, and returns whether\n * it did. The dependencies that the disposal leaves unneeded go on the cleanup\n * queue.\n *\n * Contract: called outside computations, batches, and `onChange` callbacks.\n */\nexport function disposeIfUnneeded(node: DerivedNode<unknown>): boolean {\n const mutableNode = node as MutableDerivedNode<unknown>;\n if (!isUnneededComputedNode(mutableNode)) {\n return false;\n }\n const wasEmpty = cleanupQueue.length === 0;\n disposeNode(mutableNode, DISPOSE_FROM_CLEANUP_QUEUE, undefined);\n if (wasEmpty && cleanupQueue.length > 0) {\n requestCleanupScheduling();\n }\n return true;\n}\n"],"mappings":";AAaA,SAAgB,wCACd,QACA,OACwB;AACxB,QAAO,QAAQ;AACf,KAAI,OAAO,uBACT;AAEF,QAAO;AACP,QAAO,OAAO;;;;;;;AAQhB,SAAgB,8BACd,cACA,OACgD;CAChD,IAAI,QAAQ;CAGZ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,OAA+B;AACnC,QAAO,SAAS,QAAW;EACzB,MAAM,OAAO,KAAK;AAClB,SAAO,KAAK;EACZ,MAAM,SAAS,KAAK;AACpB,MAAI,cAAkB;AACpB,QAAK;AACL,OAAI,KAAK,qBAAgC;AACvC,YAAQ,sBAAsB,OAAO,KAAK;IAC1C,MAAM,iBAAiB,KAAK;AAC5B,QACE,mBAAmB,UACnB,mBAAmB,KAAK,8BAExB,EAAC,wBAAwB,EAAE,EAAE,KAAK,KAAK;cAEhC,KAAK,mBAAmB,QAAW;AAC5C,QAAI,oBAAoB,OACtB,EAAC,wBAAwB,EAAE,EAAE,KAAK,gBAAgB;AAEpD,sBAAkB;cACT,KAAK,gBAAgB,OAC9B,0BAAyB,KAAK;aAEvB,cAAwB;AAMjC,QAAK;AACL,QAAK,KAAK,2BAA8C;AACtD,SAAK,kBAAkB;AACvB,QAAI,KAAK,oBACP,SAAQ,sBAAsB,OAAO,KAA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
+ slug: /contracts
3
+ ---
4
+
5
+ # Contracts
6
+
7
+ ## Write batches
8
+
9
+ Open one batch at a time. Starting a second batch throws and leaves the first batch open. Inside the batch, callers may write sources and release retains. Read sources and derived nodes, create retains, and run cleanup outside the batch.
10
+
11
+ Close the batch synchronously in the same turn. Use `finally` if the body can throw. `endWriteBatch()` commits the last write to each source, refreshes affected nodes, and delivers callbacks before returning. Writes made before an exception are committed when the `finally` block closes the batch.
12
+
13
+ ## Contracts for correctness
14
+
15
+ These rules define the supported API. The failure descriptions below refer to the current implementation. A future release may behave differently. Where no outcome is specified, callers cannot rely on the result.
16
+
17
+ - Computations must be synchronous and pure, and read other nodes only through `readSource` and `readDerived`, called with the `callingNode` the computation received. A write to a tracked source or a change in a tracked derived value can trigger a rerun. Changing untracked state alone leaves the cached result in place. A read with a `callingNode` that a computation kept after it returned, or that belongs to another node, records the dependency on that `callingNode`'s node. The computation that made the read keeps its cached value when the read node changes, and the other node recomputes the next time it is read. If that other node's computation is running, the behavior is unspecified. An asynchronous computation's value is the promise it returns. Its reads after an `await` are reads with a `callingNode` kept after the computation returned, so they record dependencies of its own node, and a change to what they read makes the node recompute the next time it is read.
18
+ - A computation must not call anything else in pico-js. `readDerivedOutsideComputation` inside a computation returns the node's value without recording a dependency, as a read of state outside pico-js does. If it took the cleanup queue from empty to non-empty, it calls `schedule` while the computation runs, except during a flush, where the call into pico-js that ran the flush calls `schedule` before it returns. If a `schedule` called while the computation runs disposes nodes, the behavior is unspecified. The behavior of a write, a batch, a retain, a release, or a disposal inside a computation is unspecified.
19
+ - Computations and change callbacks must not throw. If your code can throw, wrap it in `try`/`catch` inside the computation or callback, so nothing throws into pico-js. After a throw reaches pico-js, its state is unspecified. [Puchi](../../puchi/README.md#errors) provides constructors that catch exceptions inside the computation and return them as values.
20
+ - The graph must not have cycles. A computation that reads its own node, or a node that depends on its node, recurses until the call stack overflows and throws a `RangeError`. After that, pico-js's state is unspecified.
21
+ - A change callback may call `readDerivedOutsideComputation` and must not do anything else with pico-js. A write inside a callback to a source that no node with a callback depends on, directly or through other nodes, does what that write does outside a callback: it marks the nodes that depend on the source and runs no computation, and the flush goes on calling callbacks. A write to a source that a node with a callback depends on starts a nested flush, which brings the nodes with callbacks that the write reached up to date and then throws a `TypeError` before it calls any callback, whether or not a value changed. After that throw, pico-js's state is unspecified. A batch inside a callback does the same at its `endWriteBatch`, for the sources written in it. The behavior of a retain or a release inside a callback is unspecified. Compute a value that can be computed from the graph in a derived node, not in a source that a callback writes. To reset a value when another changes, keep the raw value in the source and compute the effective value in a derived node:
22
+
23
+ ```ts
24
+ const query = createSourceNode('a');
25
+ const requested = createSourceNode({ page: 3, query: 'a' });
26
+ const page = createDerivedNode((callingNode) => {
27
+ const { page, query: requestedFor } = readSource(callingNode, requested);
28
+ return requestedFor === readSource(callingNode, query) ? page : 1;
29
+ });
30
+ ```
31
+
32
+ Starting work outside the graph from a callback, for example a fetch, is fine, and the `writeSource` from its response runs outside the flush. A write that must follow a change can be deferred with `queueMicrotask(() => writeSource(...))`, which runs after the flush returns.
33
+
34
+ - Release each retain exactly once. The behavior of a second release of the same retain is unspecified. A retain that is never released keeps its node and everything the node depends on cached for good.
35
+ - A write batch must not span an `await`. Requests using the same module share its batch state. Another request’s writes can join an open batch and its callbacks can be delayed. See [server requests](./lifetimes.md#server-requests).
36
+ - pico-js compares values with `===` and counts `===`-equal values as identical. A recompute whose result is `===` to the previous value keeps the previous value, the nodes that depend on the node do not recompute on its account, and no callback runs. A computation whose result depends on the sign of zero breaks this contract. A node that reads `x` and returns `1 / x` keeps `Infinity` when `x` recomputes from `0` to `-0`. `NaN` is never `===` to itself, so a node whose value is `NaN` counts as changed on every recompute: the nodes that depend on it recompute, and its callbacks run, after every update that recomputes it.
37
+ - Do not mutate values after passing them to pico-js or reading them from it. A value changed in place is still `===` to itself, so nodes that depend on it can keep results computed from its old contents.
38
+ - Limit dependency chains to 1,000 nodes or fewer. A shorter chain can still overflow the JavaScript call stack. A first read can nest one computation inside the next. The safe depth depends on the runtime and on what each computation calls. The recursive resolver benchmark overflows at depth 1,000. If a read throws a stack overflow, the engine state is unspecified. [Stack depth measurements](./correctness.md#stack-depth)
39
+
40
+ ## Contracts for performance
41
+
42
+ These practices reduce unnecessary work. They do not affect correctness.
43
+
44
+ - Only update a source when its value changed, for example by checking `deepEqual(current, next)` before calling `writeSource`. `writeSource` does not compare values, so writing the same value marks its direct readers dirty. The next refresh of each reader reruns its computation, usually producing the same result. A second write before any computation reads the source again marks nothing.
45
+ - When a computation's result is structurally equal to its previous value, return the previous value (`previous`), so that `===` sees no change. A new but equal value counts as a change, so the nodes that depend on the node recompute, and its callbacks run, although nothing changed.
@@ -0,0 +1,233 @@
1
+ ---
2
+ slug: /correctness
3
+ ---
4
+
5
+ # pico-js correctness
6
+
7
+ Under the [correctness contracts](./contracts.md#contracts-for-correctness), 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/`.
8
+
9
+ ## Contract and terms
10
+
11
+ 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.
12
+
13
+ - `X -> Y` means that X's dependency list holds an edge to Y, so X read Y in its last run.
14
+ - Below and above follow edges: Y is below X if there is a path `X -> ... -> Y`.
15
+ - 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.
16
+ - 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.
17
+ - 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`.
18
+
19
+ Claim I states that a read cannot return the cached value of a `CLEAN` node while any node below it remains unrefreshed.
20
+
21
+ ## Paths that return a derived value or let a computation continue without recomputing
22
+
23
+ 1. `readDerived` calls `getCurrentDerivedValue` before linking or reusing the caller's edge. The input is current by the time the reader records it.
24
+ 2. `getCurrentDerivedValue` of a `CLEAN` node returns `node.value`.
25
+ 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.
26
+ 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`.
27
+ 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`.
28
+ 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.
29
+ 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.
30
+ 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.
31
+ 9. `readDerivedOutsideComputation` (read.ts) and `retainDerivedNode` (retain.ts) call `getCurrentDerivedValue` and return or keep its value.
32
+ 10. The flush clears the active refresh queue before `notifyRetainsOfChangedNodes` runs. A read in an `onChange` uses path 9. A dirty read uses `recomputeValueAndMarkDependents`.
33
+ 11. First computes and recomputes nested inside any of the above: `computeInitialDerivedValue` and `rerunComputationAndUpdateDependencies` run a computation whose reads are path 1.
34
+ 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.
35
+
36
+ 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.
37
+
38
+ ## Invariants
39
+
40
+ ### C: `CLEAN` is closed downward
41
+
42
+ Every derived dependency of a `CLEAN` node is `CLEAN`. Equivalently, every node above a node that is not `CLEAN` is not `CLEAN`.
43
+
44
+ An unrefreshed node cannot be `CLEAN`. By C, no node above an unrefreshed node can be `CLEAN` either. This proves I between steps.
45
+
46
+ 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.
47
+
48
+ ### BS: `firstKnownMarkedDependentEdge` bounds the non-`CLEAN` suffix of dependents
49
+
50
+ 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.
51
+
52
+ ### W: a move before `firstKnownMarkedDependentEdge` inside a computation stays in effect
53
+
54
+ 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.
55
+
56
+ ### L: a lazy node that is not `CLEAN` has no `CLEAN` dependent
57
+
58
+ 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`).
59
+
60
+ ### M: the dependents of a lazy node that is `DIRTY`, or `MAYBE_DIRTY` without `MARKED_BEYOND`, are in one of those states
61
+
62
+ 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).
63
+
64
+ 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.
65
+
66
+ ### F: what a pull leaves behind
67
+
68
+ 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.
69
+
70
+ ## Proof of C
71
+
72
+ C holds for the empty graph. Every operation that changes a status, an edge, or a flag keeps it.
73
+
74
+ ### Status changes to `CLEAN`
75
+
76
+ Three stores set a node `CLEAN`: in `computeInitialDerivedValue`, in `rerunComputationAndUpdateDependencies`, and in `verifyDerivedDependencies` when the node's edges are exhausted.
77
+
78
+ - `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.
79
+ - `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.
80
+ - `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.
81
+
82
+ ### Status changes away from `CLEAN`
83
+
84
+ - `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`.
85
+ - `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`.
86
+ - `markMaybeDirtyDependentsDirty` changes only `MAYBE_DIRTY` to `DIRTY`.
87
+ - `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.
88
+ - Disposal sets `UNCOMPUTED` only on a node with no dependents.
89
+
90
+ ### Edge changes
91
+
92
+ - 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.
93
+ - `unlinkUnreadDependencies`, `unlinkRemainingDerivedDependencies`, and disposal remove edges. Removing an edge cannot break C.
94
+
95
+ ## Proof of BS
96
+
97
+ 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.
98
+
99
+ - `addEdgeToDerivedDependents` prepends every new or moved edge at `dependency.firstDependent`, strictly before `firstKnownMarkedDependentEdge`, so no newly linked edge enters `[firstKnownMarkedDependentEdge, undefined)`.
100
+ - `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.
101
+ - `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.
102
+ - 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`.
103
+ - `markDependentsOfChangedDerivedNode` resets `node.firstKnownMarkedDependentEdge = undefined`, which makes the suffix empty. Disposal (`disposeNode`) sets `node.firstKnownMarkedDependentEdge = undefined` on a node with no dependents.
104
+
105
+ ## Proof of M
106
+
107
+ 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.
108
+
109
+ - 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.
110
+ - `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.
111
+ - The walk that sets `MARKED_BEYOND` sets it only on a `CLEAN` node, and by C every node below a `CLEAN` node is `CLEAN`.
112
+
113
+ ## Proof of I for each path
114
+
115
+ By C, I holds between steps. For each path:
116
+
117
+ - Path 1, new edge: the value comes from `getCurrentDerivedValue`. By F the node is `CLEAN`, and by C nothing unrefreshed is below it.
118
+ - Path 1, edge reused by position or moved: the same, because `readDerived` pulls before it looks at the edge.
119
+ - Path 2: by C.
120
+ - Path 3: `verifyDerivedDependencies` set the node `CLEAN` under the rule proved for `verifyDerivedDependencies` in the proof of C, so C holds for it.
121
+ - On path 4, a flush refreshes a dirty callback node as soon as a reader needs its value. Its computation reads through path 1.
122
+ - 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.
123
+ - 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.
124
+ - Path 7: the value is the result of a rerun whose reads are path 1.
125
+ - 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.
126
+ - 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.
127
+ - 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.
128
+ - 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.
129
+ - Path 12: proved under C and BS.
130
+
131
+ ## Change callbacks
132
+
133
+ ### Each `onChange` runs after the flush has refreshed every node on the flush queue
134
+
135
+ `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.
136
+
137
+ ### Each `onChange` runs exactly when its node's value changed in the update
138
+
139
+ - The refresh calls `recordChangedNode` only when the rerun returns a value different from the previous one under `===`.
140
+ - 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.
141
+ - 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.
142
+ - The first compute of a node calls no `onChange`, because `computeInitialDerivedValue` records nothing, and a node gets a callback only after `retainDerivedNode` pulled it.
143
+
144
+ ## The ascent of `verifyDerivedDependencies` finds the right edge
145
+
146
+ `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`.
147
+
148
+ This finds the exact descent edge into `nodeBeingVerified` because three properties hold throughout the descent:
149
+
150
+ 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.
151
+ 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`.
152
+ 3. Every node appears at most once on the descent path, because the graph has no cycles.
153
+
154
+ 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.
155
+
156
+ ## Disposal strategies
157
+
158
+ `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.
159
+
160
+ ### Q
161
+
162
+ 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:
163
+
164
+ - `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.
165
+ - `takeUnneeded` drops the entries of needed and `UNCOMPUTED` nodes, and hands the others to the caller, which the extended Q allows.
166
+ - `disposeIfUnneeded` disposes only an unneeded node, as `disposeNode` does in `disposeNext`.
167
+
168
+ 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.
169
+
170
+ ### `SCAN_SEEN` is free during `disposeEligibleCleanupEntries`
171
+
172
+ 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.
173
+
174
+ - 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`.
175
+ - 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.
176
+ - By induction over calls, starting from `traversalFlags` 0 on every node, no node has the bit when a call starts or after it returns.
177
+
178
+ ### The update boundaries of `disposeOlderThanUpdates`
179
+
180
+ 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.
181
+
182
+ 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.
183
+
184
+ `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.
185
+
186
+ Each operation that changes the queue keeps U:
187
+
188
+ - 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.
189
+ - `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.
190
+ - 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.
191
+ - An update changes no position and no count. It increments `updateCount`, which raises every judged age by one and every true age by one.
192
+ - `disposeOlderThanUpdates` itself, below.
193
+
194
+ - 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`.
195
+ - `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.
196
+ - 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.
197
+ - 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`.
198
+
199
+ ### Schedule calls after `disposeOlderThanUpdates`
200
+
201
+ 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.
202
+
203
+ - `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`.
204
+ - 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.
205
+ - 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`.
206
+ - The drain itself is not an outermost operation and does not call `scheduleCleanupIfRequested`, so it never calls `schedule` from inside the scheduler.
207
+ - 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.
208
+ - 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.
209
+
210
+ ### Taken nodes
211
+
212
+ 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.
213
+
214
+ ## Stack depth
215
+
216
+ 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.
217
+
218
+ 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.
219
+
220
+ | Chain | Observation |
221
+ | ------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
222
+ | 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. |
223
+ | 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. |
224
+ | 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. |
225
+
226
+ The [recursive resolver benchmark](https://github.com/isographlabs/isograph/pull/1027#issuecomment-7286974637) exercises a different computation. Its first read overflowed at depth 1,000 in all three libraries.
227
+
228
+ ## Outside the contract
229
+
230
+ The [contracts page](./contracts.md#contracts-for-correctness) 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.
231
+
232
+ - 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.
233
+ - 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.