Artifact e78fb960e0f8c6a1add822221f1eac7857824c652aa909ef38c17cff0c87ae85:
- File
internal/content/deltify.go
— part of check-in
[9864120a32]
at
2026-07-20 02:36:37
on branch trunk
— perf: memoize delta-chain interiors during crosslink (#107)
* perf: memoize delta-chain interiors during crosslink (#89)
manifest.Crosslink ran at roughly 1.4 events/sec on the Fossil SCM repository, which puts a 27,000-artifact clone at two and a half hours of CPU after the transfer has already finished. A CPU profile of a sweep over that corpus attributes 152.77s of Crosslink's 167.20s -- 91% -- to content.Expand, and 126.35s of that to the single blob.Load inside its delta-replay loop.
The cause is chain depth, not per-event overhead: not a transaction per event, not a missing index, not a full-table scan. content_deltify stores a file's older versions as deltas against its newer ones, so one file's history is a single chain -- 469 nodes deep on average across that repository, 1,032 for the blobs carrying artifacts, 2,546 at worst. Expand walked each chain from its root on every call and Crosslink calls it once per blob, so the sweep performed 31.7 million delta applications to expand 67,451 blobs.
Cache.Expand now stops the chain walk at the deepest ancestor it already holds and keeps every node it materializes on the way forward, and Crosslink runs one such cache for the sweep. Blob content is immutable once written and the candidate rids are snapshotted before the loop, so nothing a sweep does can invalidate an entry.
Every node handed to the cache is verified against the UUID its blob row is stored under before it is stored, because a cached interior is served later as if it had been expanded in its own right. The number of hash checks per sweep does not change: each blob is materialized once and verified once, where before each was expanded once and verified once. A plain Expand, with no cache, walks and verifies exactly as it did.
IsAvailable folds its two-statements-per-chain-node walk into one. It runs once per F-card of every check-in being crosslinked, over the same deep chains, and every SQL round trip there pays a WAL read-lock acquisition -- the round trips, not the work they do, are the cost.
No transaction boundary moves and no batching is introduced. A manifest that fails to crosslink still fails on its own, exactly where it did.
Measured on the Fossil SCM repository, 67,451 content blobs and 27,060 artifacts. Time for Crosslink to write its first 300 event rows: 221s before, 131s after. Over the expansion path in isolation, sweeping the same corpus in rid order: 22.9 blobs/sec with no cache, 50.1 at the 256 MiB budget set here, 414 at 1 GiB -- where the process needs 2.9 GB resident, which is why 1 GiB is not the number.
A bounded cache cannot close the gap on its own. Chains run from a high-rid root down to low-rid ancestors while the sweep visits rids ascending, so the first candidate of a chain materializes all of it and the remaining nodes are consumed arbitrarily far in the future; the working set of a whole-repository sweep in rid order is the whole repository expanded, 8 GiB for this corpus. Closing it means visiting candidates in delta-chain order, which is how Fossil's own rebuild avoids the cost, and which changes the order-sensitive state Crosslink writes -- leaf, tag propagation, tech-note event replacement, forum thread titles. That is a separate change.
TestFossilBinaryReadsCrosslinkedRepo covers the acceptance criterion this cannot self-certify: a repository whose relational tables were written through the accelerated path passes fossil 2.28's test-integrity, shows its tip in fossil timeline, survives fossil rebuild, and its event, plink, leaf and mlink rows match, column for column, what fossil derives from the same blobs.
* fix: bound and cycle-check the delta-chain walks (#89)
IsAvailable walked the delta chain with no cycle detection, to a bound of 100,000 against real chains whose deepest observed node count is 2,546. It is wire-reachable -- sync/clone.go, sync/handler.go, and once per F-card of every check-in Crosslink processes -- so a peer that plants a two-node delta cycle bought a 100,000-iteration query loop on every call, inside whatever process embeds this library.
Both halves are fixed. Each walk now carries a visited set and stops at the first repeat, which is the actual defence: a cycle costs its own length, not the bound. maxDeltaChainDepth replaces the old constant at 16,384, roughly six times the deepest chain measured on the Fossil SCM repository, and it is now a backstop for an acyclic-but-absurd chain rather than a number an attacker spends. walkDeltaChain, which the memoizing expansion path made hotter, previously had no bound at all and now shares the same one.
This is what made TestIsAvailable_CyclicChainTerminates sit at ~99% of its 30s budget on main and fail outright under -race here: the cyclic walk was running the full bound. It now finishes in about a second under -race, six runs out of six.
walkDeltaChain returns the content it stopped on instead of leaving expandChain to ask the store a second time. The truncation decision and the use of it were separate steps, so a concurrent eviction between them would send a delta row to blob.Load and hand raw delta bytes to the replay as full text. bindToName caught that and failed closed, but the caller saw a hash mismatch on an artifact that was not corrupt, and Crosslink's error path drops those silently. Unreachable while the cache is a single-goroutine local, but Cache is documented concurrency-safe and takes its mutex on every method, so the type promised something the expansion path did not deliver.
Cache entries are clipped to their length before being stored, so curSize is the bytes actually retained rather than an allocator-dependent approximation of them.
Test corrections: the corpus harness no longer closes the repository handle out from under the sweep goroutine when it returns at the event target; the sweep owns the handle and closes it. snapshotDerived now fails on an empty digest rather than comparing "" to "" and passing without examining a row. The fail-closed injector matches the merged chain-step statement specifically rather than any query mentioning delta, and says what it can and cannot prove now that the two lookups are one statement. The fossilbin comparison documents that it is not full-table equivalence, and which tables it leaves uncompared.
MEASUREMENTS, SUPERSEDING THOSE IN 2426591
The figures in the parent commit were taken before clipping, and its "221s -> 131s" pair predates the double-hash and IsAvailable fixes that landed in that same commit. Everything below was re-measured on the code as it ships, one run at a time on an idle machine, against the Fossil SCM repository (67,451 content blobs, 27,060 artifacts).
Crosslink to its first 300 event rows, cpuprofile on throughout:
original code 221.4s as shipped 103.9s 2.1x
Expanding the first 4,000 blobs, which isolates the expansion path:
budget throughput peak RSS entries held none 22.1 blobs/s 169 MB 0 0 256 MiB 52.0 blobs/s 1036 MB 543 255 MiB 1 GiB 468.3 blobs/s 2278 MB 15,842 1021 MiB
Clipping changed neither throughput nor memory. Crosslink to 300 events runs 103.9s clipped against 105.9s unclipped, peak RSS 1067 MB against 1050 MB, and the cache holds the identical 543 entries and 255 MiB at a 256 MiB budget either way -- at these sizes the buffers already arrive tightly sized. It is worth keeping as an accounting guarantee, not as a saving, and the comment on clip says so.
The earlier claim that capacity slack was why a 256 MiB cache reached nearly a gigabyte resident was wrong. Peak RSS tracks the no-cache baseline plus roughly twice the budget, because the cache is live data and the collector sizes the heap against it: 169 + 2x1021 = 2211 against 2278 observed at 1 GiB. That is why the budget stays at 256 MiB -- a gigabyte of cache costs over two gigabytes resident to clone a 72 MB repository. The shape of the curve did not move.
* docs: correct the claims around the chain bound and the RSS model (#89)
Three claims did not survive checking, and one bound was a node out.
maxDeltaChainDepth said it bounds "every delta-chain walk in this package". It does not: deltifyBreaksLoop is a third walk, under deltifyMaxChainWalk, which is 64 times larger. The rationale on the new constant applies to that walk just as well, but changing it would change deltify's shipped behaviour, so the sentence is narrowed to the two read-path walks it actually governs and points at the third rather than quietly covering it.
Two comments still named maxAvailabilityChainDepth, which no longer exists, and argued from IsAvailable having a bound "of its own" -- the framing of a world where the two walks had separate bounds. Against a shared constant that argument reads backwards. Both now name the shared bound, and the reason deltifyBreaksLoop keeps its own visited set and its own step cap is stated as the general rule it is: every walk over the peer-shaped delta graph carries both, and none of them relies on another walk's guard.
The retraction in the previous commit replaced one unsupported mechanism with another. "Peak RSS runs at roughly the baseline plus twice the budget" is a two-point fit whose worse point is the shipped one: it is 3% off at 1 GiB and 53% under at 256 MiB, where resident memory is four times the budget rather than twice. The measured table stays; the model is demoted to the direction the data supports, that peak RSS grows faster than the budget, with the fit's own weakness stated.
walkDeltaChain counted loop iterations where IsAvailable counts nodes visited, so the shared bound bit a node apart: a chain of exactly maxDeltaChainDepth+1 was unavailable to one walk and complete to the other. It now counts nodes, and TestChainBoundBitesAtSameLength pins the agreement at both boundaries -- nothing else ties the two loops together. (user: [email protected], size: 11719) [annotate] [blame] [check-ins using]
package content import ( "database/sql" "errors" "fmt" "github.com/danmestas/libfossil/db" "github.com/danmestas/libfossil/internal/blob" "github.com/danmestas/libfossil/internal/delta" libfossil "github.com/danmestas/libfossil/internal/fsltype" ) // Deltification policy, ported from canonical Fossil's content_deltify() // (fossil-2.28 src/content.c:852-947). Every rule below is canonical's; this // package is the only place any of them is stated, so the commit path and the // crosslink path cannot drift apart on the question of what gets deltified. // // The shape of the policy is easy to get backwards. Fossil deltifies // BACKWARDS: a newly created artifact is always stored whole, and its // PREDECESSOR is then rewritten as a delta against it. Callers therefore pass // the OLD rid as rid and the NEW one as srcRid -- see checkin.c:3133 // (content_deltify(rid, &nrid, ...) after content_put of the new file // content) and manifest.c:1562 (content_deltify(pid, &fid, ...) in // add_mlink). The consequence is that the tip of every delta chain is full // content, so reading the newest version of a file is always O(1) blobs, and // an artifact's chain depth is its age in revisions. // // Chain depth is bounded by deltifyMinRatio and by the never-redeltify rule: // an artifact that is already a delta is left alone (content.c:869), so each // artifact is converted at most once and depth grows by one per subsequent // revision of the same file rather than compounding. Canonical caps depth no // further at store time; `fossil rebuild` re-runs the pass offline // (rebuild.c:533). const ( // Artifacts below this size are left whole: the delta header and // checksum would cost more than the copy instructions save. // content.c:881 ("Do not try to create a delta for objects smaller // than 50 bytes") and content.c:911 for the source side. deltifyMinBytes = 50 // A delta must be smaller than this fraction of the target content to // be worth the extra indirection on every read. content.c:917 // (blob_size(&delta) < blob_size(&data)*0.75). deltifyMinRatio = 0.75 // Upper bound on how far the ancestor walk will follow delta links // before declaring the graph malformed. A well-formed chain is at most // as long as the repository has artifacts, but this walk runs on a // graph a sync peer can shape: blob.StoreDeltaRaw records // delta(rid,srcid) links from the wire without a cycle check, so an // A->B->A graph is reachable and must terminate the walk rather than // spin inside the write transaction. TigerStyle: every loop bounded. deltifyMaxChainWalk = 1 << 20 ) // Deltify tries to rewrite the artifact rid, currently stored whole, as a // delta against srcRid. It returns the number of stored bytes saved; 0 means // the policy above declined and rid was left untouched, which is a normal // outcome and not an error. // // The rewrite changes only how rid is stored, never what it expands to, so // callers need not tell anyone the representation changed. // // Deltify takes a *db.Tx rather than a db.Querier because rewriting an // artifact is two statements -- the blob content and the delta link -- that // must land together. A blob holding delta bytes with no delta row expands as // though it were full content, which is silent corruption rather than a // detectable error. Canonical wraps the same pair in db_begin_transaction / // db_end_transaction (content.c:938-941); requiring the transaction in the // signature makes that non-negotiable at compile time. func Deltify(tx *db.Tx, rid, srcRid libfossil.FslID) (saved int, err error) { if tx == nil { panic("content.Deltify: tx must not be nil") } defer func() { if err == nil && saved < 0 { panic("content.Deltify: postcondition violated: negative saving with no error") } }() // Canonical tolerates rid 0 rather than making every call site check // (content.c:864). Callers pass "the previous version", which legitimately // does not exist for a file's first revision. if rid <= 0 || srcRid <= 0 || rid == srcRid { return 0, nil } // Already a delta: leave it. This is the rule that keeps chain depth // linear in revision count instead of compounding (content.c:869). source, err := deltaSource(tx, rid) if err != nil { return 0, err } if source > 0 { return 0, nil } // Phantoms have no content to delta (content.c:874). // // The srcRid half of this check is OURS, not canonical's: content.c // guards only content_is_available(rid) and then calls // content_get(srcid) unguarded. It is load-bearing beyond phantoms. // IsAvailable follows the same delta.srcid links as the ancestor walk // below, under maxDeltaChainDepth, and returns false on a cycle -- so a // cyclic srcRid is declined here and never reaches deltifyBreaksLoop. // Weakening or reordering this guard exposes that walk to a delta graph a // sync peer can shape; it carries its own visited set and its own step // cap so that exposure is survivable rather than a hang. if !IsAvailable(tx, rid) || !IsAvailable(tx, srcRid) { return 0, nil } // The target-size check comes before anything destructive, matching // canonical: content.c:877-885 returns on a sub-50-byte target *before* // entering the candidate loop, so it never reaches the content_undelta // on :902. Running the ancestor walk first would inflate srcRid to full // content and then decline anyway -- a pure storage regression, and a // divergence from canonical's layout for identical input. data, err := Expand(tx, rid) if err != nil { return 0, fmt.Errorf("content.Deltify: expand rid=%d: %w", rid, err) } if len(data) < deltifyMinBytes { return 0, nil } // Never carry a private artifact into a public one: the far side of a // sync would receive the public artifact but never be allowed the // source it deltas against (content.c:895). if IsPrivate(tx, int64(srcRid)) && !IsPrivate(tx, int64(rid)) { return 0, nil } loops, err := deltifyBreaksLoop(tx, rid, srcRid) if err != nil || loops { return 0, err } src, err := Expand(tx, srcRid) if err != nil { return 0, fmt.Errorf("content.Deltify: expand srcid=%d: %w", srcRid, err) } if len(src) < deltifyMinBytes { return 0, nil } deltaBytes := delta.Create(src, data) if float64(len(deltaBytes)) >= float64(len(data))*deltifyMinRatio { return 0, nil } return deltifyWrite(tx, rid, srcRid, deltaBytes) } // deltifyBreaksLoop reports whether rid is already an ancestor of srcRid, in // which case storing rid as a delta of srcRid would close a loop. When it is, // srcRid is undeltaed to break the existing dependency and true is returned: // canonical undeltas and then still declines this pairing, because after its // `break` the loop variable holds rid rather than 0, so `if( s!=0 ) continue` // on content.c:907 skips the candidate. Deltifying rid against the now-whole // srcRid would be safe, but diverging here would make our storage layout // differ from canonical's for the same input. A later revision offers the // pair again. // // Before reordering Deltify's prologue: this walk is currently unreachable // with a cyclic srcRid, because the IsAvailable(srcRid) guard above screens // one out first. That is why the seen-set below never fires in practice, and // it is not an argument for removing it -- IsAvailable is answering // groundedness, not loop safety, and the delta graph is peer-shaped // (blob.StoreDeltaRaw records links from the wire without a cycle check). // The ordering is asserted, not just documented: // TestDeltifyDeclinesUngroundedSource forges A->B->A and pins that Deltify // declines it with no error, so a reorder that exposes this walk turns that // decline into an error and fails the test. func deltifyBreaksLoop(tx *db.Tx, rid, srcRid libfossil.FslID) (bool, error) { seen := make(map[libfossil.FslID]bool) cur := srcRid for steps := 0; ; steps++ { // Two independent bounds, the same pairing the read-path walks // use. The seen set catches a cycle that does not pass through rid // -- StoreDeltaRaw can record one from the wire -- and the step cap // catches any walk that escapes it. The cap here is // deltifyMaxChainWalk, not maxDeltaChainDepth; see the note on that // constant for why the two differ. if seen[cur] { return false, fmt.Errorf("content.Deltify: delta chain cycle detected at rid=%d", cur) } if steps > deltifyMaxChainWalk { return false, fmt.Errorf("content.Deltify: delta chain from rid=%d exceeds %d links", srcRid, deltifyMaxChainWalk) } seen[cur] = true next, err := deltaSource(tx, cur) if err != nil { return false, err } if next <= 0 { return false, nil } if next == rid { return true, Undelta(tx, srcRid) } cur = next } } func deltifyWrite(tx *db.Tx, rid, srcRid libfossil.FslID, deltaBytes []byte) (int, error) { var before int if err := tx.QueryRow("SELECT length(content) FROM blob WHERE rid=?", rid).Scan(&before); err != nil { return 0, fmt.Errorf("content.Deltify: size rid=%d: %w", rid, err) } compressed, err := blob.Compress(deltaBytes) if err != nil { return 0, fmt.Errorf("content.Deltify: compress: %w", err) } // blob.size stays the target's uncompressed length: it describes what // the artifact expands to, not how many bytes the row holds. Canonical // deliberately leaves size alone here (content.c:935) even though // content_undelta does update it (content.c:761). if _, err := tx.Exec("UPDATE blob SET content=? WHERE rid=?", compressed, rid); err != nil { return 0, fmt.Errorf("content.Deltify: update rid=%d: %w", rid, err) } if _, err := tx.Exec("REPLACE INTO delta(rid, srcid) VALUES(?, ?)", rid, srcRid); err != nil { return 0, fmt.Errorf("content.Deltify: link rid=%d: %w", rid, err) } // Canonical calls verify_before_commit here (content.c:940). Expand // re-hashes the expanded result against the row's declared UUID, so a // bad delta cannot survive this call. if _, err := Expand(tx, rid); err != nil { return 0, fmt.Errorf("content.Deltify: verify rid=%d: %w", rid, err) } saved := before - len(compressed) if saved < 0 { saved = 0 } return saved, nil } // Undelta rewrites rid as full content, dropping its delta link. Mirrors // content_undelta (src/content.c:745-769), including its update of blob.size, // which content_deltify deliberately does not touch. func Undelta(tx *db.Tx, rid libfossil.FslID) error { if tx == nil { panic("content.Undelta: tx must not be nil") } if rid <= 0 { panic("content.Undelta: rid must be > 0") } source, err := deltaSource(tx, rid) if err != nil { return err } if source <= 0 { return nil } full, err := Expand(tx, rid) if err != nil { return fmt.Errorf("content.Undelta: expand rid=%d: %w", rid, err) } compressed, err := blob.Compress(full) if err != nil { return fmt.Errorf("content.Undelta: compress rid=%d: %w", rid, err) } if _, err := tx.Exec("UPDATE blob SET content=?, size=? WHERE rid=?", compressed, len(full), rid); err != nil { return fmt.Errorf("content.Undelta: update rid=%d: %w", rid, err) } if _, err := tx.Exec("DELETE FROM delta WHERE rid=?", rid); err != nil { return fmt.Errorf("content.Undelta: unlink rid=%d: %w", rid, err) } return nil } // deltaSource returns the rid that rid is stored as a delta against, or 0 if // rid holds full content. func deltaSource(q db.Querier, rid libfossil.FslID) (libfossil.FslID, error) { var srcid int64 err := q.QueryRow("SELECT srcid FROM delta WHERE rid=?", rid).Scan(&srcid) switch { case errors.Is(err, sql.ErrNoRows): return 0, nil case err != nil: return 0, fmt.Errorf("content.deltaSource rid=%d: %w", rid, err) } return libfossil.FslID(srcid), nil }