Artifact 9e8b56e598caae3d099808d05e76a7d3ce52164e0acc1f14267e2f484726730d:
- File
internal/content/cache_chain_test.go
— part of check-in
[81fbc0be5f]
at
2026-07-24 17:23:36
on branch trunk
— manifest: fix crosslink's WAL/availability/mlink working-set problems (#158)
* manifest: batch crosslink, memoize availability, preload mlink parents (#89)
Three throughput fixes for the whole-repository crosslink sweep, none of which change its observable output. Profiling the sweep on the Fossil SCM corpus (67,503 blobs, 27,084 events) after the delta-chain-order work (#126) found the earlier bottlenecks had moved on:
- Per-candidate transactions made every SQL statement open its own WAL read-transaction, whose setup cost climbs as the uncheckpointed WAL grows -- throughput collapsed from ~200 events/sec to ~7 within a few seconds of a large sweep. The sweep now commits in batches of crosslinkBatchSize candidates so SQLite checkpoints and truncates the WAL between batches, holding read-transaction cost flat. Batch-granular durability is correct for derived data: an interrupted sweep leaves committed batches and the candidate query re-selects only what is still unlinked. CrosslinkContext is split into crosslinkSweep / collectCrosslinkCandidates / linkCandidatesInOrder / linkBatch, with the per-artifact dispatch pulled into linkArtifact and the deferral rollup into deferCheckin / logDeferredCheckins.
- missingCheckinRefs walked a blob's whole delta chain (content.IsAvailable) once per F-card of every check-in to decide deferral -- ~40% of the sweep, re-walking the same file chains over and over. content.AvailabilityCache memoizes the verdict per rid and stops a walk at the first already-decided ancestor, bounding total walk work by the number of distinct blobs rather than F-card references.
- resolveMlinkParent looked up each F-card's parent version with SELECT ... FROM mlink WHERE mid=? AND fnid=?, which SQLite answers via the fnid index -- returning a file's entire crosslinked history, so the lookup grew as the mlink table did. loadMlinkParents now reads each parent's file set once with a single mid-indexed scan and resolves every F-card from the in-memory map. It reads exactly the same rows, so the mlink output is unchanged.
The crosslink helpers now take the batch's *db.Tx directly (replacing r *repo.Repo + per-helper r.WithTx), matching the single-transaction shape of internal/verify.Rebuild and letting a whole batch commit atomically; tag application routes through tag.ApplyTagWithTx. updateAttachmentComments materializes its cursor before writing so a single connection never runs two statements at once. crosslinkSingle (dephantomize) wraps its one artifact in its own transaction.
Whole suite green (1235 tests, 35 packages, incl. dst and the fossil-binary comparison). This does not by itself land #89's "minutes not hours" target; the dominant remaining cost is a separate, pre-existing mlink over-insertion documented on the issue.
* manifest: diff crosslink mlink against the parent manifest (#89)
insertCheckinMlinks emitted one mlink row per F-card and read pmid/pid from the parent's mlink rows. On the Fossil SCM repository that is ~180x canonical's row count (a full sweep would write ~19M rows against fossil's own 104,880), and because delta-chain order (#102/#126) routinely crosslinks a child before its parent, the parent's mlink rows were usually absent, so ~97% of rows defaulted to pid=0 -- wrong parent-column data independent of the volume.
Rewrite it to diff each check-in's file list against its primary parent's expanded manifest -- the same diff canonical Fossil computes in add_mlink (src/manifest.c) and the rebuild path already does in internal/verify.rebuildMlinks -- and emit a row only for a file that was added, modified, deleted, or renamed. pmid/pid now come from the parent MANIFEST, which is always present once a check-in is eligible to link, so pid is correct regardless of crosslink order. The parent expansion runs through the sweep's shared content cache, so each parent's delta chain is walked at most once across all its children.
Measured on the Fossil SCM corpus: 127,775 mlink rows (canonical: 104,878) with pid populated on 74% of rows (was ~3%); full-repo crosslink completes in ~15 minutes rather than the prior ~hour. The residual gap is 95 PGP-clearsigned parent manifests deck.Parse cannot yet strip, whose ~98 children fall back to the old all-added behavior -- a pre-existing deck limitation tracked separately. (user: [email protected], size: 4668) [annotate] [blame] [check-ins using]
package content import ( "bytes" "database/sql" "fmt" "strings" "testing" "github.com/danmestas/go-libfossil/db" "github.com/danmestas/go-libfossil/internal/blob" libfossil "github.com/danmestas/go-libfossil/internal/fsltype" ) // countingQuerier forwards to an inner Querier and counts the blob-content // reads, the single statement that dominates delta-chain expansion. type countingQuerier struct { inner db.Querier blobLoads int deltaWalks int availSteps int } func (c *countingQuerier) Exec(q string, args ...any) (sql.Result, error) { return c.inner.Exec(q, args...) } func (c *countingQuerier) QueryRow(q string, args ...any) *sql.Row { switch { case strings.HasPrefix(q, "SELECT content, size FROM blob"): c.blobLoads++ case strings.HasPrefix(q, "SELECT srcid FROM delta"): c.deltaWalks++ case strings.HasPrefix(q, "SELECT b.size, d.rid IS NOT NULL, d.srcid"): c.availSteps++ } return c.inner.QueryRow(q, args...) } func (c *countingQuerier) Query(q string, args ...any) (*sql.Rows, error) { return c.inner.Query(q, args...) } // buildDeltaChain stores chainLen versions of a similar body and deltifies // each one against its successor, so version 0 sits at the deep end of a // chain rooted at the last version — the shape a real Fossil repository has // after content_deltify has rewritten older blobs as deltas of newer ones. func buildDeltaChain(t *testing.T, d *db.DB, chainLen int) ([]libfossil.FslID, [][]byte) { t.Helper() rids := make([]libfossil.FslID, chainLen) bodies := make([][]byte, chainLen) for i := range rids { var body bytes.Buffer for line := 0; line < 300; line++ { if line == i { fmt.Fprintf(&body, "line %04d: version %d\n", line, i) } else { fmt.Fprintf(&body, "line %04d: the quick brown fox jumps over the lazy dog\n", line) } } bodies[i] = body.Bytes() rid, _, err := blob.Store(d, bodies[i]) if err != nil { t.Fatalf("store version %d: %v", i, err) } rids[i] = rid } if err := d.WithTx(func(tx *db.Tx) error { for i := 0; i < chainLen-1; i++ { if _, err := Deltify(tx, rids[i], rids[i+1]); err != nil { return fmt.Errorf("deltify %d against %d: %w", i, i+1, err) } } return nil }); err != nil { t.Fatalf("build chain: %v", err) } var deltas int if err := d.QueryRow("SELECT count(*) FROM delta").Scan(&deltas); err != nil { t.Fatalf("count delta: %v", err) } if deltas != chainLen-1 { t.Fatalf("delta rows = %d, want %d — chain was not built", deltas, chainLen-1) } return rids, bodies } // TestCache_MemoizesChainInteriors pins the property Crosslink depends on: // walking a delta chain once must leave every node it materialized in the // cache, so expanding the whole chain costs a number of blob reads linear in // the chain length rather than quadratic. func TestCache_MemoizesChainInteriors(t *testing.T) { const chainLen = 40 d := setupTestDB(t) rids, bodies := buildDeltaChain(t, d, chainLen) q := &countingQuerier{inner: d} c := NewCache(8 << 20) // Ascending rid order is the order Crosslink sweeps in; rid[0] is the // deepest node, so its expansion materializes the entire chain. for i, rid := range rids { got, err := c.Expand(q, rid) if err != nil { t.Fatalf("Expand rid %d (version %d): %v", rid, i, err) } if !bytes.Equal(got, bodies[i]) { t.Fatalf("version %d: content mismatch", i) } } // Without interior memoization this is chainLen*(chainLen+1)/2 = 820. if q.blobLoads > 2*chainLen { t.Fatalf("blob content reads = %d, want <= %d for a %d-node chain", q.blobLoads, 2*chainLen, chainLen) } } // TestCache_ChainInteriorContentIsCorrect checks the memoized interiors are // served as their own content, not as a neighbour's. func TestCache_ChainInteriorContentIsCorrect(t *testing.T) { const chainLen = 12 d := setupTestDB(t) rids, bodies := buildDeltaChain(t, d, chainLen) c := NewCache(8 << 20) if _, err := c.Expand(d, rids[0]); err != nil { t.Fatalf("prime chain: %v", err) } for i := chainLen - 1; i >= 0; i-- { got, err := c.Expand(d, rids[i]) if err != nil { t.Fatalf("Expand version %d: %v", i, err) } if !bytes.Equal(got, bodies[i]) { t.Fatalf("version %d served wrong content", i) } } // Cached interiors must be independent buffers: mutating a returned // slice must not corrupt the next read of the same rid. first, err := c.Expand(d, rids[chainLen/2]) if err != nil { t.Fatal(err) } first[0] ^= 0xFF second, err := c.Expand(d, rids[chainLen/2]) if err != nil { t.Fatal(err) } if !bytes.Equal(second, bodies[chainLen/2]) { t.Fatal("mutating a returned slice corrupted the cached interior") } }