Skip to content
zit Artifact [a6191ac80e]
Login

Artifact [a6191ac80e]

Artifact a6191ac80ebae1cda5a6d32234355daf30f8f641a5350cbfadc35865c964a840:


//! The same-path lineage walk: which file blob each check-in records under
//! each path, and which sub-manifest node of a check-in pairs with its primary
//! parent's node under the same partition key. `zit pack` derives its base
//! hints from it over one log (pack.zig), and a pull or a served push derives
//! the delta bases for artifacts that arrived whole from it over the received
//! set and the store beside it (receive.zig). One walk, two sources.
//!
//! `Walker(Source)` is generic over where artifacts come from. `Source`
//! supplies:
//!
//!   * `Id` — an artifact identity, compared with `==`;
//!   * `find(self, hex, digest) Error!?Id` — the artifact a card names when it is
//!     held, readable and kept; null for an absent, phantom or filtered one;
//!   * `content(self, gpa, id) Error!?[]u8` — its plaintext, owned by the
//!     caller; null when it does not read;
//!   * `offerBase(self, gpa, child, base) Error!void` — a changed sub-manifest
//!     node and a candidate base from its primary parent's tree: the node of
//!     the same kind under the same partition key, or failing that its key
//!     neighbours (`pairAgainstParent`). A node may be offered twice. The
//!     source decides whether a pair is usable (pack: the base must precede
//!     the child in the log) and which of several to keep.
//!
//! `find` is the filter, and it runs before `content`: a dropped artifact's
//! bytes may be corrupt, so the walk never reconstructs one (pack.zig states
//! why that ordering is normative).

const std = @import("std");
const artifact = @import("../artifact/artifact.zig");
const digest_name = @import("../core/digest_name.zig");
const digest_len = digest_name.digest_len;
const hexToDigest = digest_name.hexToDigest;

pub const Error = error{ OutOfMemory, Storage, Corrupt };

/// Whether `prefix` -- the first bytes of an artifact -- could begin a
/// structural artifact under [FossilArtifact] §4.4, where a card is a card-type
/// letter followed by zero or more space-separated tokens.
///
/// One-sided by design: false means the artifact provably is not structural,
/// true means only "not ruled out", and the parser still decides. Fewer than
/// two bytes is not enough to rule anything out, so it answers true. Keeping
/// the error on the permissive side is what lets a caller skip the reject case
/// without changing any answer.
pub fn couldStartStructural(prefix: []const u8) bool {
    if (prefix.len < 2) return true;
    if (prefix[0] < 'A' or prefix[0] > 'Z') return false;
    // The delimiter after a card's type letter: a space before its first token,
    // or the LF of a card that carries none.
    return prefix[1] == ' ' or prefix[1] == '\n';
}

pub fn Walker(comptime Source: type) type {
    return struct {
        pub const Id = Source.Id;
        /// path → the distinct blob versions recorded under it, in walk order
        /// (a consecutive repeat is recorded once). Keys are owned dups.
        pub const Paths = std.StringHashMapUnmanaged(std.ArrayListUnmanaged(Id));
        /// (kind, partition key) → node. Each key is an owned
        /// `kindTag ++ filename`, so a leaf and the interior node above it,
        /// which share a partition key (the interior node's key is its first
        /// leaf's), never collide.
        const Keys = std.StringHashMapUnmanaged(Id);
        const Seen = std.AutoHashMapUnmanaged(Id, void);

        pub fn deinitPaths(gpa: std.mem.Allocator, paths: *Paths) void {
            var it = paths.iterator();
            while (it.next()) |e| {
                e.value_ptr.deinit(gpa);
                gpa.free(e.key_ptr.*);
            }
            paths.deinit(gpa);
        }

        /// Record check-in `m`'s file blobs under their paths and offer its
        /// changed sub-manifest nodes against `parent`'s. A tree check-in is
        /// diffed LOCKSTEP against its primary parent (`diffTreeVersions`),
        /// descending only where the two trees differ, so the walk costs
        /// O(changed paths) rather than O(tree). Without a usable parent -- a
        /// root, or a parent that does not read or parse -- or for a flat
        /// check-in, the child is walked in full. The parent's own blobs are
        /// never recorded here: it records them on its own walk, and recording
        /// them twice would let a revert reappear as a duplicate version.
        pub fn checkin(
            gpa: std.mem.Allocator,
            src: *Source,
            paths: *Paths,
            m: *const artifact.Manifest,
            parent: ?Id,
        ) Error!void {
            var child_keys: Keys = .empty;
            defer deinitPartitionKeys(gpa, &child_keys);
            var child_seen: Seen = .empty;
            defer child_seen.deinit(gpa);
            var walked_lockstep = false;
            // A child without S nodes fills no partition-key map, so there is
            // nothing to pair -- skip the parent read and parse outright.
            if (m.s.len != 0) {
                if (parent) |prid| lockstep: {
                    // `pbytes` must outlive the parse: the manifest's card
                    // slices borrow it, and freeing it at block exit left every
                    // S-card hash pointing into freed memory -- which surfaced
                    // as a "corrupt" store on a perfectly healthy tree
                    // repository.
                    const pbytes = (try src.content(gpa, prid)) orelse break :lockstep;
                    defer gpa.free(pbytes);
                    var pl = artifact.parseForImport(gpa, pbytes) catch |e| switch (e) {
                        error.OutOfMemory => return error.OutOfMemory,
                        else => break :lockstep,
                    };
                    defer pl.deinit(gpa);
                    if (pl.manifest.kind != .manifest) break :lockstep;
                    // The S nodes pair with the PRIMARY parent's, by kind and
                    // canonical partition key. Walked rather than pooled
                    // because the design names the parent specifically -- an
                    // offset-nearest node from an unrelated branch is the
                    // heuristic the storage design forbids.
                    var parent_keys: Keys = .empty;
                    defer deinitPartitionKeys(gpa, &parent_keys);
                    var parent_seen: Seen = .empty;
                    defer parent_seen.deinit(gpa);
                    try diffTreeVersions(gpa, src, paths, &child_keys, &child_seen, &parent_keys, &parent_seen, m.f, m.s, pl.manifest.s, 0);
                    try pairAgainstParent(gpa, src, &child_keys, &child_seen, &parent_keys, &parent_seen);
                    walked_lockstep = true;
                }
            }
            if (!walked_lockstep) {
                try recordTreeVersions(gpa, src, paths, &child_keys, &child_seen, m.f, m.s, 0);
            }
        }

        /// Offer each changed child node a base from the parent's tree: the
        /// parent's node of the same kind under the same partition key, or, when
        /// there is none, the parent's same-kind nodes just below and just above
        /// that key in key order.
        ///
        /// The neighbours cover a key that SHIFTED: a file added before a
        /// subtree's first file renames the subtree after the new file (the
        /// parent's node is the next key up), and removing the first file
        /// renames it after the second (the next key down). Both are offered and
        /// the source's size bar picks the smaller delta, or none.
        ///
        /// A child node the parent tree also holds (a moved subtree) is offered
        /// nothing. No base is a node the child tree itself holds (`child_seen`): that
        /// excludes the node itself, every descendant the walk reached, and the
        /// shared subtrees, which need no base. A descendant the walk did not
        /// reach sits below a shared subtree, and the parent reaches it only
        /// through that same shared subtree, which it never walks.
        ///
        /// Deterministic: the candidates are sorted by their distinct keys, and
        /// the offers follow `child_keys`' iteration order, as before. Bounded:
        /// one sort and one binary search per changed node over the parent
        /// nodes the walk visited, at most two extra offers each.
        fn pairAgainstParent(
            gpa: std.mem.Allocator,
            src: *Source,
            child_keys: *const Keys,
            child_seen: *const Seen,
            parent_keys: *const Keys,
            parent_seen: *const Seen,
        ) Error!void {
            var cands: std.ArrayListUnmanaged(KeyedNode) = .empty;
            defer cands.deinit(gpa);
            cands.ensureTotalCapacity(gpa, parent_keys.count()) catch return error.OutOfMemory;
            var pit = parent_keys.iterator();
            while (pit.next()) |e| {
                if (child_seen.contains(e.value_ptr.*)) continue;
                cands.appendAssumeCapacity(.{ .key = e.key_ptr.*, .id = e.value_ptr.* });
            }
            std.mem.sortUnstable(KeyedNode, cands.items, {}, KeyedNode.lessThan);

            var kit = child_keys.iterator();
            while (kit.next()) |e| {
                const key = e.key_ptr.*;
                const child = e.value_ptr.*;
                std.debug.assert(child_seen.contains(child));
                // A node the parent also holds is not new: the check-in that
                // introduced it was offered its bases.
                if (parent_seen.contains(child)) continue;
                if (parent_keys.get(key)) |base| {
                    if (!child_seen.contains(base)) {
                        try src.offerBase(gpa, child, base);
                        continue;
                    }
                }
                // No usable same-key node. `at` is the first candidate whose
                // key is not below `key`.
                const at = std.sort.lowerBound(KeyedNode, cands.items, key, KeyedNode.order);
                const floor: ?KeyedNode = if (at > 0) cands.items[at - 1] else null;
                const ceil: ?KeyedNode = if (at < cands.items.len) cands.items[at] else null;
                var pair = [2]?KeyedNode{ floor, ceil };
                for (&pair) |*n| {
                    if (n.*) |node| if (node.key[0] != key[0]) {
                        n.* = null;
                    };
                }
                // The neighbour sharing the longer key prefix is likelier the
                // same subtree; it goes first, for a source that keeps only
                // its first offer (receive). A tie keeps the floor first.
                if (pair[0] != null and pair[1] != null and
                    commonPrefix(pair[1].?.key, key) > commonPrefix(pair[0].?.key, key))
                {
                    std.mem.swap(?KeyedNode, &pair[0], &pair[1]);
                }
                for (pair) |n| {
                    const node = n orelse continue;
                    std.debug.assert(node.id != child);
                    try src.offerBase(gpa, child, node.id);
                }
            }
        }

        const KeyedNode = struct {
            key: []const u8,
            id: Id,

            fn lessThan(_: void, a: KeyedNode, b: KeyedNode) bool {
                return std.mem.lessThan(u8, a.key, b.key);
            }

            fn order(key: []const u8, n: KeyedNode) std.math.Order {
                return std.mem.order(u8, key, n.key);
            }
        };

        fn commonPrefix(a: []const u8, b: []const u8) usize {
            const n = @min(a.len, b.len);
            for (0..n) |i| if (a[i] != b[i]) return i;
            return n;
        }

        /// Walk one check-in's complete file enumeration -- F leaves and S
        /// children to the full tree height (submanifests §5.1). Blobs go into
        /// `paths`, shared across check-ins, because same-path versions are a
        /// property of the whole history; S nodes go into `keys`, private to
        /// this check-in, because a node pairs only with its PRIMARY parent's
        /// node under the same partition key. Reading `m.f` alone would give a
        /// tree-shaped repository no file versions at all.
        ///
        /// Recursion is bounded by `artifact.max_tree_depth`, and `seen`
        /// collapses a diamond and rejects a cycle. A node the source does not
        /// hold is a valid absence (a phantom reference, as Fossil treats one);
        /// a held node that will not parse is corruption and aborts.
        fn recordTreeVersions(
            gpa: std.mem.Allocator,
            src: *Source,
            paths: ?*Paths,
            keys: *Keys,
            seen: *Seen,
            files: []const artifact.FCard,
            subs: []const artifact.SCard,
            depth: usize,
        ) Error!void {
            std.debug.assert(depth <= artifact.max_tree_depth);

            try recordFileBlobs(gpa, src, paths, files);

            for (subs) |sc| {
                // An absent, phantom or filtered node is excluded rather than
                // fatal: a phantom reference is valid, and a filter removing
                // it is a decision the caller already made.
                const sub = (try heldNode(src, sc.hash)) orelse continue;
                if ((try seen.getOrPut(gpa, sub)).found_existing) continue;

                if (depth == artifact.max_tree_depth) return error.Corrupt; // §5.3 bound
                var ls = try loadSubManifest(gpa, src, sub);
                // The recursion borrows `ls`'s card slices, which this defer
                // keeps alive for exactly this scope (`bytes` backs them).
                defer ls.deinit(gpa);
                // The S card's filename IS the canonical partition key (§3.6),
                // qualified by the node's kind. First writer wins so a
                // duplicate key inside one tree cannot silently retarget the
                // pair. Inserted before the recursion: an interior node keeps
                // its key ahead of a same-kind first child.
                _ = try putPartitionKey(gpa, keys, ls.kind(), sc.filename, sub);
                try recordTreeVersions(gpa, src, paths, keys, seen, ls.loaded.manifest.f, ls.loaded.manifest.s, depth + 1);
            }
        }

        /// The leaf rule, shared by every walk that visits a tree level: each
        /// held, kept, non-phantom F-card blob is recorded under its path. A
        /// `null` map is the parent-side walk, which records nothing.
        fn recordFileBlobs(
            gpa: std.mem.Allocator,
            src: *Source,
            paths: ?*Paths,
            files: []const artifact.FCard,
        ) Error!void {
            const pmap = paths orelse return;
            for (files) |fc| {
                const bh = fc.hash orelse continue;
                var digest_buf: [digest_len]u8 = undefined;
                const digest = hexToDigest(bh, &digest_buf) orelse continue;
                const blob = (try src.find(bh, digest)) orelse continue;
                try recordPathBlob(gpa, pmap, fc.filename, blob);
            }
        }

        /// First-writer-wins insert of `(kind, key) → id` into a partition-key
        /// map, OWNING the composite key. The caller's `key` borrows the
        /// manifest bytes of the node being walked, and for every node below
        /// depth 0 those are the `bytes`/`loaded` pair the walking frame frees
        /// on return -- so a borrowed key would outlive its backing store by
        /// exactly one recursion level. Returns whether this call was the
        /// first writer.
        fn putPartitionKey(gpa: std.mem.Allocator, keys: *Keys, kind: Kind, key: []const u8, id: Id) Error!bool {
            const owned = gpa.alloc(u8, key.len + 1) catch return error.OutOfMemory;
            owned[0] = @backingInt(kind);
            @memcpy(owned[1..], key);
            const gop = keys.getOrPut(gpa, owned) catch {
                gpa.free(owned);
                return error.OutOfMemory;
            };
            if (gop.found_existing) {
                gpa.free(owned);
                return false;
            }
            gop.value_ptr.* = id;
            return true;
        }

        /// A sub-manifest node's kind, the first byte of its partition-map
        /// key. §4.4 admits no node with both F and S cards.
        const Kind = enum(u8) { leaf = 'F', interior = 'S' };

        /// One resolved, validated sub-manifest node. `bytes` backs every card
        /// slice in `loaded`, so both live and die together.
        const LoadedSub = struct {
            bytes: []u8,
            loaded: artifact.ImportedManifest,

            fn deinit(self: *LoadedSub, gpa: std.mem.Allocator) void {
                self.loaded.deinit(gpa);
                gpa.free(self.bytes);
                self.* = undefined;
            }

            fn kind(self: *const LoadedSub) Kind {
                return if (self.loaded.manifest.s.len != 0) .interior else .leaf;
            }
        };

        /// Read and parse the sub-manifest node `id` under the corruption rule
        /// every tree walk shares: a referenced S node that will not
        /// reconstruct, parse, or claim the `.submanifest` kind is CORRUPTION
        /// and aborts.
        fn loadSubManifest(gpa: std.mem.Allocator, src: *Source, id: Id) Error!LoadedSub {
            const bytes = (try src.content(gpa, id)) orelse return error.Corrupt;
            errdefer gpa.free(bytes);
            var loaded = artifact.parseForImport(gpa, bytes) catch |e| switch (e) {
                error.OutOfMemory => return error.OutOfMemory,
                else => return error.Corrupt,
            };
            if (loaded.manifest.kind != .submanifest) {
                loaded.deinit(gpa);
                return error.Corrupt;
            }
            return .{ .bytes = bytes, .loaded = loaded };
        }

        /// The node an S card names, or null when the source does not hold
        /// it (absent, a phantom, or filtered): a valid absence for hint
        /// gathering. A hash that is not hex is malformed and aborts.
        fn heldNode(src: *Source, hash: []const u8) Error!?Id {
            var digest_buf: [digest_len]u8 = undefined;
            const digest = hexToDigest(hash, &digest_buf) orelse return error.Corrupt;
            return try src.find(hash, digest);
        }

        /// Record blobs and pair nodes in ONE pass: walk the child's tree
        /// LOCKSTEP against the primary parent's, descending only where the
        /// two trees DIFFER.
        ///
        /// The prune rule: an S card whose canonical partition key AND
        /// resolved node both match the parent's names the SAME subtree in
        /// both check-ins, and nothing below it can contribute. It needs no
        /// base and is no base (`pairAgainstParent` skips every node the child
        /// holds), so it enters neither flat map, and every blob under it was
        /// recorded by the check-in that INTRODUCED the subtree -- which walked
        /// it as a changed one, recursively back to a full root or fallback
        /// walk. This is what turns the walk from O(check-ins x tree size)
        /// into O(check-ins x changed paths).
        ///
        /// The match at one level is by bare key, so a new interior node
        /// meets the leaf it replaced; the two descend together, and the flat
        /// maps, keyed by kind, keep them apart.
        ///
        /// Corruption detection is preserved: every DISTINCT sub-manifest a
        /// walked check-in references is still resolved and parsed at least
        /// once -- at the first check-in that references it, its key has no
        /// parent counterpart, a differing one, or the same node in a parent
        /// walked before it, back to a root or fallback full walk. The §5.3
        /// depth bound and the `seen` cycle/diamond guards apply to both sides.
        fn diffTreeVersions(
            gpa: std.mem.Allocator,
            src: *Source,
            paths: *Paths,
            child_keys: *Keys,
            child_seen: *Seen,
            parent_keys: *Keys,
            parent_seen: *Seen,
            c_files: []const artifact.FCard,
            c_subs: []const artifact.SCard,
            p_subs: []const artifact.SCard,
            depth: usize,
        ) Error!void {
            std.debug.assert(depth <= artifact.max_tree_depth);

            // The child's F leaves at this (visited) level. The parent's F
            // leaves are never recorded.
            try recordFileBlobs(gpa, src, paths, c_files);

            // Index the parent's S cards at this level by canonical partition
            // key -- first writer wins, mirroring the flat maps' own insert
            // rule. Keys borrow the parent node's card bytes, which the caller
            // keeps alive for exactly this frame. `matched` marks cards
            // consumed by the child loop so the sweep below descends only the
            // parent-only remainder.
            var pidx: std.StringHashMapUnmanaged(usize) = .empty;
            defer pidx.deinit(gpa);
            for (p_subs, 0..) |psc, i| {
                const gop = pidx.getOrPut(gpa, psc.filename) catch return error.OutOfMemory;
                if (!gop.found_existing) gop.value_ptr.* = i;
            }
            const matched = gpa.alloc(bool, p_subs.len) catch return error.OutOfMemory;
            defer gpa.free(matched);
            @memset(matched, false);

            for (c_subs) |sc| {
                // The child-side checks, in `recordTreeVersions`'s exact order.
                const sub = (try heldNode(src, sc.hash)) orelse continue;
                if ((try child_seen.getOrPut(gpa, sub)).found_existing) continue;

                // The parent's same-key node at this level, resolved with the
                // same strictness.
                var parent_node: ?Id = null;
                if (pidx.get(sc.filename)) |pi| {
                    if (!matched[pi]) {
                        if (try heldNode(src, p_subs[pi].hash)) |pnode| {
                            matched[pi] = true;
                            if (!(try parent_seen.getOrPut(gpa, pnode)).found_existing) {
                                parent_node = pnode;
                            }
                        }
                    }
                }

                // THE PRUNE: same key, same artifact -- the subtree below is
                // byte-shared with the parent, so nothing under it can pair or
                // add a version.
                if (parent_node == sub) continue;

                if (depth == artifact.max_tree_depth) return error.Corrupt; // §5.3 bound
                var cls = try loadSubManifest(gpa, src, sub);
                defer cls.deinit(gpa);
                _ = try putPartitionKey(gpa, child_keys, cls.kind(), sc.filename, sub);

                if (parent_node) |pnode| {
                    // Same key, different node: a changed subtree. Descend
                    // both sides together.
                    var pls = try loadSubManifest(gpa, src, pnode);
                    defer pls.deinit(gpa);
                    _ = try putPartitionKey(gpa, parent_keys, pls.kind(), sc.filename, pnode);
                    try diffTreeVersions(gpa, src, paths, child_keys, child_seen, parent_keys, parent_seen, cls.loaded.manifest.f, cls.loaded.manifest.s, pls.loaded.manifest.s, depth + 1);
                } else {
                    // No same-key counterpart: a new, renamed, or split
                    // subtree, or a filtered/diamond-collapsed parent side.
                    // Walk the child side alone, in full -- this node's own
                    // checks and inserts already ran, so recurse with its
                    // cards directly.
                    try recordTreeVersions(gpa, src, paths, child_keys, child_seen, cls.loaded.manifest.f, cls.loaded.manifest.s, depth + 1);
                }
            }

            // Parent-only cards: subtrees the child dropped, renamed, or merged
            // away at this level. Their keys can still pair a child key found
            // ELSEWHERE in the tree -- a subtree that moved between levels --
            // so they keep the full parent-side descent.
            for (p_subs, 0..) |psc, i| {
                if (matched[i]) continue;
                const pnode = (try heldNode(src, psc.hash)) orelse continue;
                if ((try parent_seen.getOrPut(gpa, pnode)).found_existing) continue;
                if (depth == artifact.max_tree_depth) return error.Corrupt; // §5.3 bound
                var pls = try loadSubManifest(gpa, src, pnode);
                defer pls.deinit(gpa);
                _ = try putPartitionKey(gpa, parent_keys, pls.kind(), psc.filename, pnode);
                try recordTreeVersions(gpa, src, null, parent_keys, parent_seen, pls.loaded.manifest.f, pls.loaded.manifest.s, depth + 1);
            }
        }

        /// Tear down a partition-key map, whose keys `putPartitionKey` owns.
        fn deinitPartitionKeys(gpa: std.mem.Allocator, keys: *Keys) void {
            var it = keys.keyIterator();
            while (it.next()) |key| gpa.free(key.*);
            keys.deinit(gpa);
        }

        fn recordPathBlob(gpa: std.mem.Allocator, paths: *Paths, path: []const u8, blob: Id) Error!void {
            std.debug.assert(path.len > 0); // an F-card filename is never empty
            const gop = paths.getOrPut(gpa, path) catch return error.OutOfMemory;
            if (!gop.found_existing) {
                // The slot's key is still the caller's borrowed `path`. Own it
                // before any later free can touch it; on a dupe OOM, drop the
                // half-inserted slot so the map's teardown never frees
                // borrowed bytes or reads an undefined list.
                const owned = gpa.dupe(u8, path) catch {
                    const removed = paths.remove(path);
                    std.debug.assert(removed);
                    return error.OutOfMemory;
                };
                gop.key_ptr.* = owned;
                gop.value_ptr.* = .empty;
            }
            const list = gop.value_ptr;
            if (list.items.len > 0 and list.items[list.items.len - 1] == blob) return;
            list.append(gpa, blob) catch return error.OutOfMemory;
        }
    };
}

// ---- tests ----------------------------------------------------------------

/// An in-memory `Source`: artifacts are indices into `bodies`, every held
/// artifact is kept, and each offered pair is recorded in order.
const TestSource = struct {
    pub const Id = u32;

    gpa: std.mem.Allocator,
    arena: std.heap.ArenaAllocator,
    names: std.ArrayListUnmanaged([64]u8) = .empty,
    bodies: std.ArrayListUnmanaged([]const u8) = .empty,
    offers: std.ArrayListUnmanaged([2]Id) = .empty,

    fn init(gpa: std.mem.Allocator) TestSource {
        return .{ .gpa = gpa, .arena = std.heap.ArenaAllocator.init(gpa) };
    }

    fn deinit(self: *TestSource) void {
        self.names.deinit(self.gpa);
        self.bodies.deinit(self.gpa);
        self.offers.deinit(self.gpa);
        self.arena.deinit();
    }

    fn add(self: *TestSource, bytes: []const u8) !Id {
        var hex: [64]u8 = undefined;
        _ = artifact.artifactName(.sha3_256, bytes, &hex);
        try self.names.append(self.gpa, hex);
        try self.bodies.append(self.gpa, bytes);
        return @intCast(self.bodies.items.len - 1);
    }

    fn name(self: *const TestSource, id: Id) []const u8 {
        return &self.names.items[id];
    }

    /// A leaf over `files`, each F card's hash derived from its name and
    /// `version`, so a leaf edited in one file differs in exactly that card.
    fn leaf(self: *TestSource, files: []const []const u8, version: []const u8) !Id {
        const a = self.arena.allocator();
        const cards = try a.alloc(artifact.FCard, files.len);
        for (files, cards) |f, *c| {
            const body = try std.fmt.allocPrint(a, "{s} {s}\n", .{ f, version });
            const hex = try a.alloc(u8, 64);
            _ = artifact.artifactName(.sha3_256, body, hex[0..64]);
            c.* = .{ .filename = f, .hash = hex, .perm = null, .old_name = null, .mode = .regular };
        }
        return self.add(try artifact.serializeSubmanifestLeaf(a, cards));
    }

    fn sCards(self: *TestSource, keys: []const []const u8, ids: []const Id) ![]artifact.SCard {
        const s = try self.arena.allocator().alloc(artifact.SCard, keys.len);
        for (keys, ids, s) |k, id, *c| c.* = .{ .filename = k, .hash = self.name(id) };
        return s;
    }

    fn interior(self: *TestSource, keys: []const []const u8, ids: []const Id) !Id {
        return self.add(try artifact.serializeSubmanifestInterior(self.arena.allocator(), try self.sCards(keys, ids)));
    }

    fn checkinBytes(self: *TestSource, keys: []const []const u8, ids: []const Id, parent: ?Id) ![]u8 {
        var parents: [1]artifact.PCard = undefined;
        var p: []const artifact.PCard = &.{};
        if (parent) |pid| {
            parents[0] = .{ .parents = self.name(pid), .count = 1 };
            p = parents[0..1];
        }
        var m: artifact.Manifest = .{
            .arena_state = std.heap.ArenaAllocator.init(self.gpa),
            .kind = .manifest,
            .a = null,
            .b = null,
            .c = .{ .comment = if (parent == null) "root" else "child" },
            .d = .{ .timestamp = if (parent == null) "2026-11-01T00:00:00" else "2026-11-01T00:00:01" },
            .e = null,
            .g = null,
            .h = null,
            .i = null,
            .k = null,
            .l = null,
            .n = null,
            .r = null,
            .u = .{ .login = "tester" },
            .z = null,
            .w = null,
            .f = &.{},
            .j = &.{},
            .m = &.{},
            .p = p,
            .q = &.{},
            .s = try self.sCards(keys, ids),
            .t = &.{},
        };
        defer m.deinit();
        const bytes = try artifact.create(&m, self.arena.allocator());
        return bytes;
    }

    /// Walk the child check-in over `keys`/`ids` against the parent check-in
    /// over `pkeys`/`pids`, recording what the walk offered.
    fn walk(self: *TestSource, pkeys: []const []const u8, pids: []const Id, keys: []const []const u8, ids: []const Id) !void {
        const parent = try self.add(try self.checkinBytes(pkeys, pids, null));
        const child = try self.checkinBytes(keys, ids, parent);
        _ = try self.add(child);
        var loaded = try artifact.parseForImport(self.gpa, child);
        defer loaded.deinit(self.gpa);
        var paths: TestWalker.Paths = .empty;
        defer TestWalker.deinitPaths(self.gpa, &paths);
        try TestWalker.checkin(self.gpa, self, &paths, &loaded.manifest, parent);
    }

    fn offered(self: *const TestSource, child: Id, base: Id) bool {
        for (self.offers.items) |o| if (o[0] == child and o[1] == base) return true;
        return false;
    }

    fn offeredFor(self: *const TestSource, child: Id) usize {
        var n: usize = 0;
        for (self.offers.items) |o| n += @intFromBool(o[0] == child);
        return n;
    }

    pub fn find(self: *TestSource, hex: []const u8, digest: []const u8) Error!?Id {
        _ = digest;
        for (self.names.items, 0..) |*n, i| if (std.mem.eql(u8, n, hex)) return @intCast(i);
        return null;
    }

    pub fn content(self: *TestSource, gpa: std.mem.Allocator, id: Id) Error!?[]u8 {
        return gpa.dupe(u8, self.bodies.items[id]) catch error.OutOfMemory;
    }

    pub fn offerBase(self: *TestSource, gpa: std.mem.Allocator, child: Id, base: Id) Error!void {
        _ = gpa;
        self.offers.append(self.gpa, .{ child, base }) catch return error.OutOfMemory;
    }
};

const TestWalker = Walker(TestSource);

test "lineage: a file added before a leaf's first file shifts its key, and the parent's next leaf up is offered" {
    var src = TestSource.init(std.testing.allocator);
    defer src.deinit();
    const a = try src.leaf(&.{ "a/1", "a/2" }, "v1");
    const old = try src.leaf(&.{ "b/distinfo", "b/x", "b/y" }, "v1");
    const z = try src.leaf(&.{ "c/1", "c/2" }, "v1");
    // `b/PLIST` sorts before `b/distinfo`, so the leaf's key moves.
    const new = try src.leaf(&.{ "b/PLIST", "b/distinfo", "b/x", "b/y" }, "v1");
    try src.walk(&.{ "a/1", "b/distinfo", "c/1" }, &.{ a, old, z }, &.{ "a/1", "b/PLIST", "c/1" }, &.{ a, new, z });
    try std.testing.expect(src.offered(new, old));
}

test "lineage: a leaf whose first file was removed is offered the parent's next leaf down" {
    var src = TestSource.init(std.testing.allocator);
    defer src.deinit();
    const a = try src.leaf(&.{ "a/1", "a/2" }, "v1");
    const old = try src.leaf(&.{ "b/PLIST", "b/distinfo", "b/x", "b/y" }, "v1");
    const z = try src.leaf(&.{ "c/1", "c/2" }, "v1");
    const new = try src.leaf(&.{ "b/distinfo", "b/x", "b/y" }, "v1");
    try src.walk(&.{ "a/1", "b/PLIST", "c/1" }, &.{ a, old, z }, &.{ "a/1", "b/distinfo", "c/1" }, &.{ a, new, z });
    try std.testing.expect(src.offered(new, old));
    // The shared leaves are no one's base: the child already holds them.
    try std.testing.expect(!src.offered(new, a));
    try std.testing.expect(!src.offered(new, z));
}

test "lineage: a leaf split under a new interior node pairs leaf with leaf, never interior with leaf" {
    var src = TestSource.init(std.testing.allocator);
    defer src.deinit();
    const old = try src.leaf(&.{ "a", "b", "c", "d" }, "v1");
    const m = try src.leaf(&.{ "m", "n" }, "v1");
    const first = try src.leaf(&.{ "a", "b" }, "v1");
    const second = try src.leaf(&.{ "c", "d" }, "v2");
    // The new interior node takes its first leaf's key, `a`.
    const node = try src.interior(&.{ "a", "c" }, &.{ first, second });
    try src.walk(&.{ "a", "m" }, &.{ old, m }, &.{ "a", "m" }, &.{ node, m });
    try std.testing.expect(src.offered(first, old));
    try std.testing.expect(src.offered(second, old));
    try std.testing.expectEqual(@as(usize, 0), src.offeredFor(node));
}

test "lineage: a neighbour the child tree itself holds is never offered, so no node is based on its descendant or itself" {
    var src = TestSource.init(std.testing.allocator);
    defer src.deinit();
    const la = try src.leaf(&.{ "a", "b" }, "v1");
    const lk = try src.leaf(&.{ "k", "l" }, "v1");
    const lm = try src.leaf(&.{ "m", "n" }, "v1");
    const kept = try src.interior(&.{ "a", "k" }, &.{ la, lk });
    const other = try src.interior(&.{"m"}, &.{lm});
    const l0 = try src.leaf(&.{ "0", "1" }, "v1");
    const inner = try src.interior(&.{"0"}, &.{l0});
    // The child's new top node holds `kept`, the parent's interior node just
    // above its key, as a descendant.
    const top = try src.interior(&.{ "0", "a" }, &.{ inner, kept });
    try src.walk(&.{ "a", "m" }, &.{ kept, other }, &.{"0"}, &.{top});
    const below_top = [_]TestSource.Id{ inner, l0, kept, la, lk, top };
    for (src.offers.items) |o| {
        try std.testing.expect(o[0] != o[1]);
        if (o[0] == top) for (below_top) |d| try std.testing.expect(o[1] != d);
    }
    // A neighbour the child does not hold is still offered.
    try std.testing.expect(src.offered(top, other));
}