perf(cojson): incremental CoList entries cache and faster list maintenance - #3540
Open
gdorsi wants to merge 1 commit into
Open
perf(cojson): incremental CoList entries cache and faster list maintenance#3540gdorsi wants to merge 1 commit into
gdorsi wants to merge 1 commit into
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Makes CoList view maintenance incremental instead of rebuild-on-every-update (measured same-machine vs the base branch):
RawCoListnow links insertion entries directly instead of through nested string-keyed lookups, tracks deletions with a counter instead of a separate map lookup, and uses a generation counter for traversal instead of aSet. Appends (the common case) extend the cached entries incrementally instead of invalidating and re-traversing the whole list on every update.Benchmark table (same machine, best-of-N, vs base branch = #3537):
Benchmark is
bench/colist.load.bench.tsfrom the base branch (pnpm bench:colist; env knobsSUBSCRIBED,VERIFY,PROFILE,SKIP_VERIFY).The incremental CoList algorithm
Data model
RawCoList's source of truth is an insertion graph (RGA-style CRDT). Eachappop attaches a new entry after an existing entry (or afterstart), eachpreop attaches before one (or beforeend), anddelops mark insertions as deleted. The visible list is produced by a depth-first traversal (fillArrayFromEntry) over the roots —afterStartroots in arrival order, thenbeforeEndroots — where successors of an entry are visited newest-first:flowchart TB S((start)) -.-> A A --> B["B (after A, attached 1st)"] A --> C["C (after A, attached 2nd)"] C --> D["D (after C)"]Traversal emits A, C, D, B — C wins over B because successors are visited newest-first. This is also why
appendItemswrites multi-item appends in reverse order: they read back in the original order.entries()caches the traversal result in_cachedEntries. The invariant the whole design hangs on:On the base branch, any new transaction invalidated the cache, so a subscribed client re-traversed the entire graph per arriving chunk — quadratic in list size while streaming. The new code keeps the cache alive across the common case (appends arriving in order) by extending it in place.
Per-batch pipeline
Every batch of new transactions flows through three cleanly separated stages: pure graph ingestion, a rebuild check, and a cache decision made after the graph is up to date.
flowchart TD TX["batch of new transactions"] --> SNAP["beginBatchSummary()<br/>summary only if there is a live, non-time-travel cache;<br/>snapshots tail entry + prior successor/root counts"] SNAP --> ING["for each op: ingestChange()<br/>pure graph mutation, returns whether the op was applied"] ING --> REC["summary.record(change, isValid, applied)<br/>del / pre / duplicate → hasUnsupportedOps<br/>applied valid append → newValidAppends++"] REC --> OOO{"batch contains txs older<br/>than already-processed ones?"} OOO -- yes --> RB["rebuildFromCore()<br/>reset state, reprocess everything<br/>(also re-attaches orphaned ops)"] OOO -- no --> HAS{"summary exists?"} HAS -- no --> INV1["invalidate cache"] HAS -- yes --> CTS["computeCacheTailSuffix(summary)"] CTS -- "suffix (possibly empty)" --> EXT["append suffix to _cachedEntries"] CTS -- "null" --> INV2["invalidate cache<br/>(next read does a full traversal)"]ingestChangeknows nothing about the cache;computeCacheTailSuffixis a pure decision function over the graph plus the batch summary. That separation is what makes the fast path auditable.The tail-extension check
A batch may extend the cache iff every entry it made visible renders after the previous last visible entry (the tail). Rather than proving that op by op, the suffix pass exploits a structural fact: the batch's new entries can only attach to the old tail, to
afterStart, or to each other (an old op can never reference an op that didn't exist yet). So it collects the subtrees the batch hung off the tail region:flowchart LR a --> b --> T["c (old tail)"] T ==> d["d (new)"] d ==> e["e (new, after d)"] T ==> f["f (new, after c)"]Suffix roots are the tail's new successors (newest-first, matching DFS pop order) plus any new
afterStartroots (in order) — then it runs the samefillArrayFromEntryused for full rebuilds over just those roots. Emitted entries:f, d, e(f is newer than d, so it wins). Because it is the same traversal over the same graph, the suffix order cannot disagree with a full rebuild.The acceptance test is a single count comparison: the traversal must emit exactly
newValidAppendsentries. Anything the batch inserted that is not reachable from the tail region comes up missing and invalidates the cache:flowchart LR a --> b --> c["c (tail)"] b -. "new append after b<br/>(mid-list, NOT reachable<br/>from suffix roots)" .-> x["x (new)"]Here
newValidAppends = 1but the suffix traversal emits 0 entries → mismatch → invalidate. The same mechanism catches orphaned appends (target op not yet arrived) and inserts that were already deleted by an earlier batch'sdel.When the cache survives a batch
preop)startroots whilebeforeEndroots existbeforeEndsectionatTime/atFrontier)Invalidation is always safe — it just costs one full traversal on the next read. The correctness of the extension path is additionally cross-checked at runtime by the benchmark's
VERIFY=1mode, which compares the incrementally maintained cache against a fresh full traversal.Net complexity: a streamed append-only load does O(new ops) work per chunk instead of O(list), which is where the subscribed-load speedup comes from.
Caveats
Test plan
pnpm exec vitest --run --root ../../ --project cojson— 76 files, 1397 passed, 13 skipped, 0 failedcoList,coList.unique,coList.branch,coFeed,coFeed.branch) — 7 files, 225 passed, 0 failedVERIFY=1, plain andSUBSCRIBED=1) — incremental-cache-vs-full-traversal divergence checks pass