~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zat

atproto utils for zig · mirror of https://tangled.org/zat.dev/zat

0
0
2683 lines · 100.6 KB Raw History
//! merkle search tree (MST)
//!
//! the AT Protocol repository data structure. a deterministic search tree
//! where each key's tree layer is derived from the leading zero bits of
//! SHA-256(key). keys are stored sorted within each node, with subtree
//! pointers interleaved between entries.
//!
//! supports partial and lazy trees for sync 1.1 and repo mutation: nodes not
//! present in memory are represented as stubs (known CID, no block data).
//! when a block reader is attached, operations resolve stubs on demand.
//!
//! see: https://atproto.com/specs/repository#mst-structure

const std = @import("std");
const cbor = @import("cbor.zig");
const car = @import("car.zig");
const Allocator = std.mem.Allocator;

/// compute MST tree layer for a key.
/// layer = count leading zero bits in SHA-256(key), divided by 2, rounded down.
pub fn keyHeight(key: []const u8) u32 {
    var digest: [32]u8 = undefined;
    std.crypto.hash.sha2.Sha256.hash(key, &digest, .{});
    var leading_zeros: u32 = 0;
    for (digest) |byte| {
        if (byte == 0) {
            leading_zeros += 8;
        } else {
            leading_zeros += @clz(byte);
            break;
        }
    }
    return leading_zeros / 2;
}

/// byte-level common prefix length between two strings, eight bytes at a time
/// since ATProto keys often share long prefixes (see keyOrder)
pub fn commonPrefixLen(a: []const u8, b: []const u8) usize {
    const min_len = @min(a.len, b.len);
    var i: usize = 0;
    while (i + 8 <= min_len) : (i += 8) {
        const diff = std.mem.readInt(u64, a[i..][0..8], .big) ^ std.mem.readInt(u64, b[i..][0..8], .big);
        if (diff != 0) return i + @clz(diff) / 8;
    }
    while (i < min_len) : (i += 1) {
        if (a[i] != b[i]) break;
    }
    return i;
}

/// Lexicographic byte ordering for MST keys.
///
/// `std.mem.order(u8, ...)` is intentionally generic and scalar. MST lookup is
/// dominated by key comparisons, and ATProto keys often share long prefixes, so
/// compare eight bytes at a time while preserving byte-order semantics.
fn keyOrder(a: []const u8, b: []const u8) std.math.Order {
    if (a.ptr != b.ptr) {
        const min_len = @min(a.len, b.len);
        var i: usize = 0;
        while (i + 8 <= min_len) : (i += 8) {
            const a_word = std.mem.readInt(u64, a[i..][0..8], .big);
            const b_word = std.mem.readInt(u64, b[i..][0..8], .big);
            if (a_word != b_word) return std.math.order(a_word, b_word);
        }
        while (i < min_len) : (i += 1) {
            if (a[i] != b[i]) return std.math.order(a[i], b[i]);
        }
    }
    return std.math.order(a.len, b.len);
}

fn keyEql(a: []const u8, b: []const u8) bool {
    if (a.len != b.len) return false;
    if (a.ptr == b.ptr) return true;
    var i: usize = 0;
    while (i + 8 <= a.len) : (i += 8) {
        const a_word = std.mem.readInt(u64, a[i..][0..8], .big);
        const b_word = std.mem.readInt(u64, b[i..][0..8], .big);
        if (a_word != b_word) return false;
    }
    while (i < a.len) : (i += 1) {
        if (a[i] != b[i]) return false;
    }
    return true;
}

/// parse a CID string (base32lower multibase, e.g. "bafyrei...")
pub fn parseCidString(allocator: Allocator, s: []const u8) !cbor.Cid {
    return cbor.Cid.fromString(allocator, s);
}

/// content-addressed block reader used by lazy MST loading.
///
/// The returned block bytes only need to live for the duration of the call:
/// MST loading copies all keys and CID bytes it retains.
pub const BlockReader = struct {
    ctx: *anyopaque,
    getFn: *const fn (ctx: *anyopaque, cid_raw: []const u8) anyerror!?[]const u8,

    pub fn get(self: BlockReader, cid_raw: []const u8) anyerror!?[]const u8 {
        return self.getFn(self.ctx, cid_raw);
    }
};

/// MST node. stores a left subtree pointer and a list of entries.
/// each entry has a key, CID value, and optional right subtree.
pub const Node = struct {
    left: ?*Node,
    entries: std.ArrayList(Entry),
    layer: u32,
    dirty: bool,
    cid: ?cbor.Cid,
    /// dag-cbor encoding cached by the last collectBlocks pass. only
    /// meaningful while `dirty` is false — mutation marks the node dirty,
    /// which invalidates this implicitly. without the cache, every
    /// collectBlocks re-serializes the entire tree, which makes repeated
    /// commit/collect cycles quadratic in allocations.
    encoded: ?[]const u8,

    pub const Entry = struct {
        key: []const u8,
        right: ?*Node,
        value: cbor.Cid,
    };

    fn init(layer: u32, dirty: bool) Node {
        return .{
            .left = null,
            .entries = .empty,
            .layer = layer,
            .dirty = dirty,
            .cid = null,
            .encoded = null,
        };
    }
};

/// an operation on the MST (create, update, or delete a record)
pub const Operation = struct {
    path: []const u8, // "collection/rkey"
    value: ?[]const u8, // raw CID bytes — non-null for create/update
    prev: ?[]const u8, // raw CID bytes — non-null for update/delete

    fn isCreate(self: Operation) bool {
        return self.value != null and self.prev == null;
    }

    fn isDelete(self: Operation) bool {
        return self.value == null and self.prev != null;
    }

    fn isUpdate(self: Operation) bool {
        return self.value != null and self.prev != null;
    }
};

pub const WalkEntry = struct {
    key: []const u8,
    value: cbor.Cid,
};

pub const Walker = struct {
    ctx: *anyopaque,
    entryFn: *const fn (ctx: *anyopaque, entry: WalkEntry) anyerror!void,

    pub fn entry(self: Walker, e: WalkEntry) anyerror!void {
        return self.entryFn(self.ctx, e);
    }
};

/// merkle search tree
pub const Mst = struct {
    allocator: Allocator,
    root: ?*Node,
    root_layer: ?u32,
    block_reader: ?BlockReader,

    pub fn init(allocator: Allocator) Mst {
        return .{
            .allocator = allocator,
            .root = null,
            .root_layer = null,
            .block_reader = null,
        };
    }

    /// load an MST lazily from a root CID and block reader.
    ///
    /// This mirrors Atmos's `LoadTree(store, root)`: construction does not
    /// fetch storage. The root block is loaded only when an operation needs it.
    pub fn loadLazy(allocator: Allocator, root_cid_raw: []const u8, block_reader: BlockReader) !Mst {
        return .{
            .allocator = allocator,
            .root = try createStubNode(allocator, root_cid_raw, null),
            .root_layer = null,
            .block_reader = block_reader,
        };
    }

    /// insert or update a key-value pair
    pub fn put(self: *Mst, key: []const u8, value: cbor.Cid) !void {
        _ = try self.putReturn(key, value);
    }

    /// insert or update a key-value pair without copying the key bytes.
    ///
    /// The key must outlive the tree.
    pub fn putBorrowed(self: *Mst, key: []const u8, value: cbor.Cid) !void {
        _ = try self.putReturnInternal(key, value, false);
    }

    /// insert or update a key-value pair, returning the previous value CID if it existed
    pub fn putReturn(self: *Mst, key: []const u8, value: cbor.Cid) !?cbor.Cid {
        return try self.putReturnInternal(key, value, true);
    }

    fn putReturnInternal(self: *Mst, key: []const u8, value: cbor.Cid, copy_key: bool) !?cbor.Cid {
        try self.ensureRootLoaded();
        const height = keyHeight(key);

        if (self.root == null) {
            // empty tree: create root at key's height
            const node = try self.createNode(height);
            try node.entries.append(self.allocator, .{
                .key = try self.storeKey(key, copy_key),
                .value = value,
                .right = null,
            });
            self.root = node;
            self.root_layer = height;
            return null;
        }

        const root_layer = self.root_layer.?;

        if (height > root_layer) {
            // key belongs above the current root — lift (new key, never an update)
            self.root = try self.insertAbove(self.root.?, root_layer, key, value, height, copy_key);
            self.root_layer = height;
            return null;
        } else if (height == root_layer) {
            // key belongs at root layer
            var prev: ?cbor.Cid = null;
            self.root = try self.insertAtLayer(self.root.?, key, value, height, &prev, copy_key);
            return prev;
        } else {
            // key belongs below — recurse into subtree
            return try self.insertBelow(self.root.?, root_layer, key, value, height, copy_key);
        }
    }

    /// look up a key, returning its CID value if present
    pub fn get(self: *const Mst, key: []const u8) ?cbor.Cid {
        return findKey(self.root, key);
    }

    /// look up a key when its MST height has already been computed.
    pub fn getWithHeight(self: *const Mst, key: []const u8, height: u32) ?cbor.Cid {
        _ = height;
        return findKey(self.root, key);
    }

    /// look up a key, resolving lazy stubs on demand.
    pub fn getLazy(self: *Mst, key: []const u8) !?cbor.Cid {
        try self.ensureRootLoaded();
        return try self.findKeyLazy(self.root, key);
    }

    fn entryLowerBound(entries: []const Node.Entry, key: []const u8) usize {
        var lo: usize = 0;
        var hi: usize = entries.len;
        while (lo < hi) {
            const mid = lo + (hi - lo) / 2;
            if (keyOrder(entries[mid].key, key) == .lt) {
                lo = mid + 1;
            } else {
                hi = mid;
            }
        }
        return lo;
    }

    fn childAtIndex(node: *Node, idx: usize) *?*Node {
        return if (idx == 0) &node.left else &node.entries.items[idx - 1].right;
    }

    fn findKey(root: ?*Node, key: []const u8) ?cbor.Cid {
        var maybe_node = root;
        while (maybe_node) |node| {
            var next = node.left;
            for (node.entries.items) |entry| {
                switch (keyOrder(key, entry.key)) {
                    .lt => break,
                    .eq => return entry.value,
                    .gt => next = entry.right,
                }
            }
            maybe_node = next;
        }
        return null;
    }

    fn findKeyLazy(self: *Mst, root: ?*Node, key: []const u8) !?cbor.Cid {
        var maybe_node = root;
        while (maybe_node) |node| {
            const loaded = try self.ensureNodeLoaded(node);
            var child_ref: *?*Node = &loaded.left;
            for (loaded.entries.items) |*entry| {
                switch (keyOrder(key, entry.key)) {
                    .lt => break,
                    .eq => return entry.value,
                    .gt => child_ref = &entry.right,
                }
            }
            maybe_node = try self.ensureChildNode(child_ref);
        }
        return null;
    }

    /// delete a key from the tree
    pub fn delete(self: *Mst, key: []const u8) !void {
        _ = try self.deleteReturn(key);
    }

    /// delete a key from the tree, returning the removed value CID if it existed.
    ///
    /// if this fails, the tree is unchanged. a partial tree, or one whose block
    /// reader fails, can refuse a delete and still be used.
    pub fn deleteReturn(self: *Mst, key: []const u8) !?cbor.Cid {
        try self.ensureRootLoaded();
        const start = self.root orelse return null;
        // a loaded tree may carry entry-less nodes above its first entry. adopt
        // the trimmed root only once the delete can no longer fail.
        const trimmed = try self.trimmedRoot(start, self.root_layer.?);
        const root = trimmed.root orelse {
            self.root = null;
            self.root_layer = null;
            return null;
        };
        const layer = trimmed.layer.?;
        const entries = root.entries.items;
        if (entries.len != 1 or !keyEql(entries[0].key, key)) {
            // the root keeps an entry, so it stays the root and nothing below
            // has to resolve after the removal
            const prev = try self.deleteFromNode(root, layer, key);
            self.root = root;
            self.root_layer = layer;
            return prev;
        }

        // removing the root's only entry hands the root to whatever is left
        // beneath it, which may sit behind stubs. find it before removing
        // anything: a stub that fails to resolve must not strand a root with
        // no entries, whose CID belongs to no tree.
        const merged = try self.mergeSubtrees(root.left, entries[0].right);
        const next: TrimmedRoot = if (merged != null and layer > 0)
            try self.trimmedRoot(merged.?, layer - 1)
        else
            .empty;
        self.root = next.root;
        self.root_layer = next.layer;
        return entries[0].value;
    }

    const TrimmedRoot = struct {
        root: ?*Node,
        layer: ?u32,

        const empty: TrimmedRoot = .{ .root = null, .layer = null };
    };

    /// the canonical root of the tree under `start`: the topmost node holding
    /// an entry. a node with no entries and only a left subtree is a bridge
    /// between layers, which belongs under an entry, never at the root.
    fn trimmedRoot(self: *Mst, start: *Node, start_layer: u32) !TrimmedRoot {
        var node = start;
        var layer = start_layer;
        while (true) {
            const loaded = try self.ensureNodeLoaded(node);
            if (loaded.entries.items.len > 0) return .{ .root = loaded, .layer = layer };
            node = loaded.left orelse return .empty;
            if (layer == 0) return .empty;
            layer -= 1;
        }
    }

    fn deleteFromNode(self: *Mst, node: *Node, layer: u32, key: []const u8) !?cbor.Cid {
        const height = keyHeight(key);

        if (height >= layer) {
            // find and remove the entry
            const i = entryLowerBound(node.entries.items, key);
            if (i < node.entries.items.len and keyEql(node.entries.items[i].key, key)) {
                const entry = node.entries.items[i];
                const prev_value = entry.value;
                // merge left and right subtrees around the deleted entry
                const left_sub = if (i == 0) node.left else node.entries.items[i - 1].right;
                const right_sub = entry.right;
                const merged = try self.mergeSubtrees(left_sub, right_sub);

                if (i == 0) {
                    node.left = merged;
                } else {
                    node.entries.items[i - 1].right = merged;
                }

                _ = node.entries.orderedRemove(i);
                node.dirty = true;
                return prev_value;
            }
            return null; // key not found
        }

        // height < layer: recurse into the appropriate gap
        if (layer == 0) return null; // can't go deeper
        const child_ref = if (node.entries.items.len == 0)
            &node.left
        else
            childAtIndex(node, entryLowerBound(node.entries.items, key));

        if (try self.ensureChildNode(child_ref)) |sub| {
            const prev = try self.deleteFromNode(sub, layer - 1, key);
            if (prev != null) {
                node.dirty = true;
                pruneIfEmpty(child_ref);
            }
            return prev;
        } else return null;
    }

    /// Drop a subtree pointer whose node no longer holds anything. MST nodes are
    /// content-addressed, so an emptied node left in place serializes as a real
    /// block and changes every ancestor CID — the tree would no longer match the
    /// one that never contained the deleted key, breaking commit-proof inversion.
    fn pruneIfEmpty(child_ref: *?*Node) void {
        const child = child_ref.* orelse return;
        if (child.entries.items.len == 0 and child.left == null) child_ref.* = null;
    }

    /// merge two subtrees that were separated by a deleted entry.
    /// both nodes are at the same layer. concatenate their entries
    /// and recursively merge if the junction creates adjacent children.
    /// follows the Go reference `appendMerge` / `mergeNodes` algorithm.
    fn mergeSubtrees(self: *Mst, left: ?*Node, right: ?*Node) !?*Node {
        const l = try self.ensureNodeLoaded(left orelse return right);
        const r = try self.ensureNodeLoaded(right orelse return left);

        // create merged node: takes left's `left` pointer and all entries from both
        const merged = try self.createNode(l.layer);
        merged.left = l.left;

        // copy left entries
        for (l.entries.items) |entry| {
            try merged.entries.append(self.allocator, entry);
        }

        // check junction: last entry of left's `right` vs right's `left`
        if (merged.entries.items.len > 0) {
            const last = &merged.entries.items[merged.entries.items.len - 1];
            if (last.right != null and r.left != null) {
                // both sides of the junction are subtrees — recursively merge
                last.right = try self.mergeSubtrees(last.right, r.left);
            } else if (last.right == null and r.left != null) {
                last.right = r.left;
            }
            // if last.right is present and r.left is not, keep last.right as-is
        } else {
            // left has no entries: junction is merged.left vs r.left
            if (merged.left != null and r.left != null) {
                merged.left = try self.mergeSubtrees(merged.left, r.left);
            } else if (merged.left == null) {
                merged.left = r.left;
            }
        }

        // copy right entries
        for (r.entries.items) |entry| {
            try merged.entries.append(self.allocator, entry);
        }

        return merged;
    }

    pub const MstError = error{ PartialTree, WriteFailed } || Allocator.Error;

    /// compute the root CID of the tree
    pub fn rootCid(self: *Mst) MstError!cbor.Cid {
        if (self.root) |root| {
            return self.nodeCid(root);
        }
        return self.nodeCid(null);
    }

    /// append DAG-CBOR MST blocks for the loaded tree surface.
    ///
    /// Clean unresolved stubs are skipped: their CIDs already point at blocks
    /// held elsewhere. This is the shape needed for commit CAR construction,
    /// where only the newly materialized path needs to be emitted.
    pub fn collectBlocks(self: *Mst, out: *std.ArrayList(car.Block)) MstError!void {
        return self.collectBlocksInto(self.allocator, out);
    }

    /// like `collectBlocks`, but the output list grows with `gpa` instead
    /// of the tree's allocator. callers collecting per-commit into scratch
    /// memory use this to keep list growth out of the tree's arena.
    pub fn collectBlocksInto(self: *Mst, gpa: Allocator, out: *std.ArrayList(car.Block)) MstError!void {
        if (self.root) |root| {
            try self.collectNodeBlocks(root, gpa, out);
            return;
        }

        const encoded = try self.serializeEmptyNode();
        errdefer self.allocator.free(encoded);
        const cid = try cbor.Cid.forDagCbor(self.allocator, encoded);
        try out.append(gpa, .{
            .cid_raw = try self.allocator.dupe(u8, cid.raw),
            .data = encoded,
        });
    }

    /// walk loaded records in MST key order.
    ///
    /// If the tree contains unresolved stubs and no block reader can resolve
    /// them, this returns `error.PartialTree`.
    pub fn walk(self: *Mst, walker: Walker) anyerror!void {
        try self.ensureRootLoaded();
        if (self.root) |root| {
            try self.walkNode(root, walker);
        }
    }

    fn nodeCid(self: *Mst, child: ?*Node) MstError!cbor.Cid {
        const node = child orelse {
            const encoded = try self.serializeEmptyNode();
            defer self.allocator.free(encoded);
            return cbor.Cid.forDagCbor(self.allocator, encoded);
        };

        if (!node.dirty) {
            if (node.cid) |cid| return cid;
        }
        const loaded = self.ensureNodeLoaded(node) catch |err| switch (err) {
            error.OutOfMemory => return error.OutOfMemory,
            error.PartialTree => return error.PartialTree,
            else => return error.PartialTree,
        };
        const encoded = try self.serializeNode(loaded);
        const cid = try cbor.Cid.forDagCbor(self.allocator, encoded);
        loaded.cid = .{ .raw = try self.allocator.dupe(u8, cid.raw) };
        // cache the encoding alongside the cid: anything that clears `dirty`
        // after serializing MUST keep the (cid, encoded) pair consistent, or
        // a later collectBlocks emits the new cid with stale bytes
        loaded.encoded = encoded;
        loaded.dirty = false;
        return cid;
    }

    fn collectNodeBlocks(self: *Mst, node: *Node, gpa: Allocator, out: *std.ArrayList(car.Block)) MstError!void {
        if (isUnloadedStub(node)) {
            // A stub and a serialized empty node are structurally identical (see
            // `isUnloadedStub`), so emptiness cannot be judged by inspection. Content
            // addressing separates them: only the empty node hashes to the empty-node
            // cid. Skipping a stub is right — its block is already in the store — but
            // skipping an empty node strands it, because nothing else ever writes one.
            // Emitting it costs a 7-byte encode and heals a tree that inherited a
            // stranded node from a writer that predates `pruneIfEmpty`.
            const cid = node.cid.?;
            const encoded = try self.serializeEmptyNode();
            const empty_cid = try cbor.Cid.forDagCbor(self.allocator, encoded);
            if (!std.mem.eql(u8, cid.raw, empty_cid.raw)) {
                self.allocator.free(encoded);
                return;
            }
            try out.append(gpa, .{ .cid_raw = cid.raw, .data = encoded });
            return;
        }

        const loaded = self.ensureNodeLoaded(node) catch |err| switch (err) {
            error.OutOfMemory => return error.OutOfMemory,
            error.PartialTree => return error.PartialTree,
            else => return error.PartialTree,
        };

        if (loaded.left) |left| try self.collectNodeBlocks(left, gpa, out);
        for (loaded.entries.items) |entry| {
            if (entry.right) |right| try self.collectNodeBlocks(right, gpa, out);
        }

        // clean node with a cached encoding: reuse, no allocation
        if (!loaded.dirty) {
            if (loaded.cid) |cid| {
                if (loaded.encoded) |enc| {
                    try out.append(gpa, .{ .cid_raw = cid.raw, .data = enc });
                    return;
                }
            }
        }

        const encoded = try self.serializeNode(loaded);
        errdefer self.allocator.free(encoded);
        const cid = try cbor.Cid.forDagCbor(self.allocator, encoded);
        loaded.cid = cid;
        loaded.encoded = encoded;
        loaded.dirty = false;
        try out.append(gpa, .{
            .cid_raw = cid.raw,
            .data = encoded,
        });
    }

    fn walkNode(self: *Mst, node: *Node, walker: Walker) anyerror!void {
        const loaded = try self.ensureNodeLoaded(node);
        if (loaded.left) |left| try self.walkNode(left, walker);
        for (loaded.entries.items) |entry| {
            try walker.entry(.{ .key = entry.key, .value = entry.value });
            if (entry.right) |right| try self.walkNode(right, walker);
        }
    }

    fn serializeEmptyNode(self: *Mst) MstError![]u8 {
        return cbor.encodeAlloc(self.allocator, .{ .map = &.{
            .{ .key = "e", .value = .{ .array = &.{} } },
            .{ .key = "l", .value = .null },
        } });
    }

    fn serializeNode(self: *Mst, node: *Node) MstError![]u8 {
        var encoded: std.ArrayList(u8) = .empty;
        errdefer encoded.deinit(self.allocator);
        try encoded.ensureTotalCapacity(self.allocator, 64 + node.entries.items.len * 60);

        try appendNodeHeader(&encoded, self.allocator, node.entries.items.len);
        var previous: []const u8 = "";
        for (node.entries.items) |entry| {
            const right = if (entry.right) |child| try self.nodeCid(child) else null;
            try appendNodeEntry(&encoded, self.allocator, previous, entry.key, entry.value, right);
            previous = entry.key;
        }
        const left = if (node.left) |child| try self.nodeCid(child) else null;
        try appendNodeFooter(&encoded, self.allocator, left);

        return try encoded.toOwnedSlice(self.allocator);
    }

    /// deep copy the tree. loaded nodes stay loaded; stubs stay stubs.
    pub fn copy(self: *Mst) !Mst {
        var new = Mst.init(self.allocator);
        if (self.root) |root| {
            new.root = try self.copyNode(root);
        }
        new.root_layer = self.root_layer;
        new.block_reader = self.block_reader;
        return new;
    }

    fn copyNode(self: *Mst, node: *Node) !*Node {
        const new_node = try self.createNode(node.layer);
        new_node.dirty = node.dirty;
        if (node.cid) |cid| {
            new_node.cid = .{ .raw = try self.allocator.dupe(u8, cid.raw) };
        }
        new_node.left = try self.copyChild(node.left);
        for (node.entries.items) |entry| {
            try new_node.entries.append(self.allocator, .{
                .key = try self.allocator.dupe(u8, entry.key),
                .value = .{ .raw = try self.allocator.dupe(u8, entry.value.raw) },
                .right = try self.copyChild(entry.right),
            });
        }
        return new_node;
    }

    fn copyChild(self: *Mst, child: ?*Node) Allocator.Error!?*Node {
        return if (child) |n| try self.copyNode(n) else null;
    }

    /// load a partial MST from CAR blocks. nodes present in the CAR are
    /// fully loaded; child CIDs not present become stubs.
    pub fn loadFromBlocks(allocator: Allocator, repo_car: car.Car, root_cid_raw: []const u8) !Mst {
        const root_data = car.findBlock(repo_car, root_cid_raw) orelse return error.CommitBlockNotFound;
        const root_node_data = try decodeMstNode(allocator, root_data);

        if (root_node_data.entries.len == 0 and root_node_data.left == null) {
            return Mst.init(allocator);
        }

        const root_node = try loadNodeFromData(allocator, repo_car, root_node_data);
        root_node.cid = .{ .raw = try allocator.dupe(u8, root_cid_raw) };
        root_node.dirty = false;

        var tree = Mst{
            .allocator = allocator,
            .root = root_node,
            .root_layer = null,
            .block_reader = null,
        };
        tree.root_layer = try tree.inferNodeLayer(root_node);
        tree.seedNodeLayers(root_node, tree.root_layer.?);
        return tree;
    }

    fn loadNodeFromData(allocator: Allocator, repo_car: ?car.Car, data: MstNodeData) !*Node {
        const node = try allocator.create(Node);
        node.* = Node.init(0, false);

        // load left child
        node.left = if (data.left) |left_cid_raw|
            try loadChild(allocator, repo_car, left_cid_raw)
        else
            null;

        // load entries, reconstructing full keys from prefix compression
        var prev_key: []const u8 = "";
        for (data.entries) |entry_data| {
            // reconstruct full key
            if (entry_data.prefix_len > prev_key.len) return error.InvalidMstNode;
            const full_key = try allocator.alloc(u8, entry_data.prefix_len + entry_data.key_suffix.len);
            if (entry_data.prefix_len > 0) {
                @memcpy(full_key[0..entry_data.prefix_len], prev_key[0..entry_data.prefix_len]);
            }
            @memcpy(full_key[entry_data.prefix_len..], entry_data.key_suffix);

            const right_child = if (entry_data.tree) |tree_cid_raw|
                try loadChild(allocator, repo_car, tree_cid_raw)
            else
                null;

            try node.entries.append(allocator, .{
                .key = full_key,
                .value = .{ .raw = try allocator.dupe(u8, entry_data.value) },
                .right = right_child,
            });

            prev_key = full_key;
        }

        return node;
    }

    fn loadChild(allocator: Allocator, repo_car: ?car.Car, cid_raw: []const u8) (MstDecodeError || error{CommitBlockNotFound})!*Node {
        if (repo_car) |rc| {
            if (car.findBlock(rc, cid_raw)) |block_data| {
                const child_data = try decodeMstNode(allocator, block_data);
                const child = try loadNodeFromData(allocator, rc, child_data);
                child.cid = .{ .raw = try allocator.dupe(u8, cid_raw) };
                child.dirty = false;
                return child;
            }
        }
        return try createStubNode(allocator, cid_raw, null);
    }

    // === internal helpers ===

    fn ensureRootLoaded(self: *Mst) !void {
        const root = self.root orelse return;
        _ = try self.ensureNodeLoaded(root);
        if (self.root_layer == null) {
            self.root_layer = try self.inferNodeLayer(root);
            self.seedNodeLayers(root, self.root_layer.?);
        }
    }

    fn ensureChildNode(self: *Mst, child: *?*Node) !?*Node {
        const node = child.* orelse return null;
        return try self.ensureNodeLoaded(node);
    }

    fn ensureNodeLoaded(self: *Mst, node: *Node) !*Node {
        if (node.dirty or node.entries.items.len > 0 or node.left != null) return node;
        const cid = node.cid orelse return node;
        const reader = self.block_reader orelse return error.PartialTree;
        const block_data = (try reader.get(cid.raw)) orelse return error.PartialTree;
        const node_data = try decodeMstNode(self.allocator, block_data);
        const loaded = try loadNodeFromData(self.allocator, null, node_data);

        node.left = loaded.left;
        node.entries = loaded.entries;
        node.layer = if (node.layer != 0) node.layer else try self.inferNodeLayer(node);
        node.cid = .{ .raw = try self.allocator.dupe(u8, cid.raw) };
        node.dirty = false;
        self.seedNodeLayers(node, node.layer);
        return node;
    }

    fn inferNodeLayer(self: *Mst, node: *Node) anyerror!u32 {
        if (node.entries.items.len > 0) {
            return keyHeight(node.entries.items[0].key);
        }
        if (try self.ensureChildNode(&node.left)) |left| {
            return (try self.inferNodeLayer(left)) + 1;
        }
        return 0;
    }

    fn seedNodeLayers(self: *Mst, node: *Node, layer: u32) void {
        node.layer = layer;
        if (layer == 0) return;
        self.seedChildLayer(&node.left, layer - 1);
        for (node.entries.items) |*entry| {
            self.seedChildLayer(&entry.right, layer - 1);
        }
    }

    fn seedChildLayer(self: *Mst, child: *?*Node, layer: u32) void {
        if (child.*) |node| self.seedNodeLayers(node, layer);
    }

    fn createNode(self: *Mst, layer: u32) !*Node {
        const node = try self.allocator.create(Node);
        node.* = Node.init(layer, true);
        return node;
    }

    fn createStubNode(allocator: Allocator, cid_raw: []const u8, layer: ?u32) !*Node {
        const node = try allocator.create(Node);
        node.* = Node.init(layer orelse 0, false);
        node.cid = .{ .raw = try allocator.dupe(u8, cid_raw) };
        return node;
    }

    fn isUnloadedStub(node: *const Node) bool {
        return !node.dirty and node.cid != null and node.left == null and node.entries.items.len == 0;
    }

    fn storeKey(self: *Mst, key: []const u8, copy_key: bool) Allocator.Error![]const u8 {
        return if (copy_key) try self.allocator.dupe(u8, key) else key;
    }

    /// insert a key that belongs above the current root.
    /// splits the tree at its own layer, wraps each half in parent nodes
    /// to bridge the layer gap, then assembles the new root.
    fn insertAbove(self: *Mst, node: *Node, node_layer: u32, key: []const u8, value: cbor.Cid, target_layer: u32, copy_key: bool) !*Node {
        // 1. split the tree at its current layer around the key
        const splits = try self.splitNode(node, key);
        var left = splits.left;
        var right = splits.right;

        // 2. wrap each half in parent layers (bridge the gap)
        const extra_layers = target_layer - node_layer;
        var i: u32 = 1;
        while (i < extra_layers) : (i += 1) {
            if (left != null) {
                const parent = try self.createNode(node_layer + i);
                parent.left = left;
                left = parent;
            }
            if (right != null) {
                const parent = try self.createNode(node_layer + i);
                parent.left = right;
                right = parent;
            }
        }

        // 3. assemble new root: [left_tree, key_leaf, right_tree]
        const new_root = try self.createNode(target_layer);
        new_root.left = left;
        try new_root.entries.append(self.allocator, .{
            .key = try self.storeKey(key, copy_key),
            .value = value,
            .right = right,
        });
        return new_root;
    }

    /// insert a key at the same layer as the node
    fn insertAtLayer(self: *Mst, node: *Node, key: []const u8, value: cbor.Cid, layer: u32, prev_out: *?cbor.Cid, copy_key: bool) !*Node {
        _ = layer;
        // find insertion position
        const insert_idx = entryLowerBound(node.entries.items, key);
        if (insert_idx < node.entries.items.len and keyEql(key, node.entries.items[insert_idx].key)) {
            // update existing — return previous value
            prev_out.* = node.entries.items[insert_idx].value;
            node.entries.items[insert_idx].value = value;
            node.dirty = true;
            return node;
        }

        // split the subtree that spans the insertion gap
        const gap_child = if (insert_idx == 0) node.left else node.entries.items[insert_idx - 1].right;

        var left_split: ?*Node = null;
        var right_split: ?*Node = null;

        if (gap_child) |subtree| {
            const splits = try self.splitNode(try self.ensureNodeLoaded(subtree), key);
            left_split = splits.left;
            right_split = splits.right;
        }

        // update the pointer before the gap
        if (insert_idx == 0) {
            node.left = left_split;
        } else {
            node.entries.items[insert_idx - 1].right = left_split;
        }

        // insert the new entry
        try node.entries.insert(self.allocator, insert_idx, .{
            .key = try self.storeKey(key, copy_key),
            .value = value,
            .right = right_split,
        });
        node.dirty = true;

        return node;
    }

    /// insert a key below the current node's layer
    fn insertBelow(self: *Mst, node: *Node, node_layer: u32, key: []const u8, value: cbor.Cid, target_height: u32, copy_key: bool) anyerror!?cbor.Cid {
        // find which gap the key falls into
        const idx = entryLowerBound(node.entries.items, key);
        if (idx < node.entries.items.len and keyEql(key, node.entries.items[idx].key)) {
            // update existing
            const prev = node.entries.items[idx].value;
            node.entries.items[idx].value = value;
            node.dirty = true;
            return prev;
        }
        const prev = try self.insertIntoGap(childAtIndex(node, idx), node_layer - 1, key, value, target_height, copy_key);
        node.dirty = true;
        return prev;
    }

    fn insertIntoGap(self: *Mst, subtree_ptr: *?*Node, gap_layer: u32, key: []const u8, value: cbor.Cid, target_height: u32, copy_key: bool) anyerror!?cbor.Cid {
        if (target_height == gap_layer) {
            // insert at this layer
            if (subtree_ptr.*) |existing| {
                var prev: ?cbor.Cid = null;
                subtree_ptr.* = try self.insertAtLayer(try self.ensureNodeLoaded(existing), key, value, gap_layer, &prev, copy_key);
                return prev;
            } else {
                const new_node = try self.createNode(gap_layer);
                try new_node.entries.append(self.allocator, .{
                    .key = try self.storeKey(key, copy_key),
                    .value = value,
                    .right = null,
                });
                subtree_ptr.* = new_node;
                return null;
            }
        } else if (target_height > gap_layer) {
            // need to lift — split and wrap
            if (subtree_ptr.*) |existing| {
                subtree_ptr.* = try self.insertAbove(try self.ensureNodeLoaded(existing), gap_layer, key, value, target_height, copy_key);
                return null;
            } else {
                const new_node = try self.createNode(target_height);
                try new_node.entries.append(self.allocator, .{
                    .key = try self.storeKey(key, copy_key),
                    .value = value,
                    .right = null,
                });
                subtree_ptr.* = new_node;
                return null;
            }
        } else {
            // target_height < gap_layer: recurse deeper
            if (subtree_ptr.*) |existing| {
                return try self.insertBelow(try self.ensureNodeLoaded(existing), gap_layer, key, value, target_height, copy_key);
            } else {
                // create node at gap_layer and recurse
                const new_node = try self.createNode(gap_layer);
                subtree_ptr.* = new_node;
                return try self.insertBelow(new_node, gap_layer, key, value, target_height, copy_key);
            }
        }
    }

    /// split a subtree around a key: everything < key goes left, everything >= key goes right.
    fn splitNode(self: *Mst, node: *Node, key: []const u8) !struct { left: ?*Node, right: ?*Node } {
        // find the first entry >= key
        const split_idx = entryLowerBound(node.entries.items, key);

        // left gets entries [0..split_idx), right gets entries [split_idx..]
        var left_node = try self.createNode(node.layer);
        var right_node = try self.createNode(node.layer);

        // left node takes the original node's left subtree
        left_node.left = node.left;

        // copy entries to left
        for (node.entries.items[0..split_idx]) |entry| {
            try left_node.entries.append(self.allocator, entry);
        }

        // copy entries to right
        for (node.entries.items[split_idx..]) |entry| {
            try right_node.entries.append(self.allocator, entry);
        }

        // split the gap subtree between the two halves
        if (left_node.entries.items.len > 0) {
            const last_left = &left_node.entries.items[left_node.entries.items.len - 1];
            if (last_left.right) |gap_subtree| {
                const sub_split = try self.splitNode(try self.ensureNodeLoaded(gap_subtree), key);
                last_left.right = sub_split.left;
                right_node.left = sub_split.right;
            }
        } else if (left_node.left != null and split_idx == 0) {
            // all entries went right — the gap is the original node's left subtree
            if (left_node.left) |gap_subtree| {
                const sub_split = try self.splitNode(try self.ensureNodeLoaded(gap_subtree), key);
                left_node.left = sub_split.left;
                right_node.left = sub_split.right;
            }
        }

        const left_result: ?*Node = if (left_node.entries.items.len > 0 or left_node.left != null)
            left_node
        else
            null;
        const right_result: ?*Node = if (right_node.entries.items.len > 0 or right_node.left != null)
            right_node
        else
            null;

        return .{ .left = left_result, .right = right_result };
    }
};

fn appendCborArgument(out: *std.ArrayList(u8), allocator: Allocator, major: u3, val: u64) Allocator.Error!void {
    const major_byte: u8 = @as(u8, major) << 5;
    if (val < 24) {
        try out.append(allocator, major_byte | @as(u8, @intCast(val)));
    } else if (val <= std.math.maxInt(u8)) {
        try out.appendSlice(allocator, &.{ major_byte | 24, @intCast(val) });
    } else if (val <= std.math.maxInt(u16)) {
        try out.append(allocator, major_byte | 25);
        var bytes: [2]u8 = undefined;
        std.mem.writeInt(u16, &bytes, @intCast(val), .big);
        try out.appendSlice(allocator, &bytes);
    } else if (val <= std.math.maxInt(u32)) {
        try out.append(allocator, major_byte | 26);
        var bytes: [4]u8 = undefined;
        std.mem.writeInt(u32, &bytes, @intCast(val), .big);
        try out.appendSlice(allocator, &bytes);
    } else {
        try out.append(allocator, major_byte | 27);
        var bytes: [8]u8 = undefined;
        std.mem.writeInt(u64, &bytes, val, .big);
        try out.appendSlice(allocator, &bytes);
    }
}

fn appendCborBytes(out: *std.ArrayList(u8), allocator: Allocator, bytes: []const u8) Allocator.Error!void {
    try appendCborArgument(out, allocator, 2, @intCast(bytes.len));
    try out.appendSlice(allocator, bytes);
}

fn appendCborCid(out: *std.ArrayList(u8), allocator: Allocator, cid: cbor.Cid) Allocator.Error!void {
    try appendCborArgument(out, allocator, 6, 42);
    try appendCborArgument(out, allocator, 2, @intCast(cid.raw.len + 1));
    try out.append(allocator, 0x00);
    try out.appendSlice(allocator, cid.raw);
}

// === inversion primitives ===

/// normalize operations: check for duplicate paths, sort deletions first then by path
pub fn normalizeOps(allocator: Allocator, ops: []const Operation) ![]Operation {
    if (ops.len == 0) return try allocator.alloc(Operation, 0);

    const sorted = try allocator.dupe(Operation, ops);
    errdefer allocator.free(sorted);

    // sort: deletions first, then by path
    std.mem.sort(Operation, sorted, {}, struct {
        fn lessThan(_: void, a: Operation, b: Operation) bool {
            // deletions before creates/updates
            const a_del: u1 = if (a.isDelete()) 0 else 1;
            const b_del: u1 = if (b.isDelete()) 0 else 1;
            if (a_del != b_del) return a_del < b_del;
            return std.mem.order(u8, a.path, b.path) == .lt;
        }
    }.lessThan);

    // check for duplicate paths
    var i: usize = 1;
    while (i < sorted.len) : (i += 1) {
        if (std.mem.eql(u8, sorted[i].path, sorted[i - 1].path)) {
            allocator.free(sorted);
            return error.DuplicatePath;
        }
    }

    return sorted;
}

/// invert a single operation against the tree.
/// create → delete, update → reverse update, delete → put back
pub fn invertOp(tree: *Mst, op: Operation) !void {
    if (op.isCreate()) {
        // create → delete: remove the path, verify removed CID matches op.value
        const removed = try tree.deleteReturn(op.path) orelse return error.InversionMismatch;
        if (!std.mem.eql(u8, removed.raw, op.value.?)) return error.InversionMismatch;
    } else if (op.isUpdate()) {
        // update → reverse: put op.prev back, verify displaced CID matches op.value
        const displaced = try tree.putReturn(op.path, .{ .raw = op.prev.? }) orelse return error.InversionMismatch;
        if (!std.mem.eql(u8, displaced.raw, op.value.?)) return error.InversionMismatch;
    } else if (op.isDelete()) {
        // delete → put back: insert op.prev, verify path didn't already exist
        const displaced = try tree.putReturn(op.path, .{ .raw = op.prev.? });
        if (displaced != null) return error.InversionMismatch;
    } else {
        return error.InversionMismatch;
    }
}

// === specialized MST node decoder ===
//
// parses the known MST node CBOR schema directly, avoiding generic Value
// union construction. all byte data is zero-copy (slices into input buffer).
// only allocation: the entries array.
//
// MST node schema:
//   map(2) { "e": array [ map(4) {k,p,t,v}, ... ], "l": CID|null }

pub const MstNodeData = struct {
    left: ?[]const u8, // raw CID bytes, or null
    entries: []const MstEntryData,
};

pub const MstEntryData = struct {
    key_suffix: []const u8,
    prefix_len: usize,
    tree: ?[]const u8, // raw CID bytes, or null
    value: []const u8, // raw CID bytes
};

const max_mst_depth: u32 = 256;
const max_mst_entries: usize = 10_000;
const max_mst_key_len: usize = 1024;

pub const ReachableCollectOptions = struct {
    max_depth: u32 = max_mst_depth,
    include_records: bool = true,
};

pub const ReachableBlocksError = error{
    PartialTree,
    InvalidMstNode,
    MaxDepthExceeded,
} || Allocator.Error;

/// Collect blocks reachable from an MST root CID using a content-addressed
/// block reader.
///
/// This is for full repo export and audit paths. It differs from
/// `Mst.collectBlocks`, which intentionally emits only the loaded/dirty MST
/// surface needed for commit diff CARs. Blocks appended here are copied into
/// `allocator`, so they remain valid after each `BlockReader.get` call returns.
pub fn collectReachableBlocks(
    allocator: Allocator,
    root_cid_raw: []const u8,
    block_reader: BlockReader,
    out: *std.ArrayList(car.Block),
    options: ReachableCollectOptions,
) ReachableBlocksError!void {
    var seen: std.StringHashMapUnmanaged(void) = .empty;
    defer seen.deinit(allocator);
    try collectReachableNode(allocator, root_cid_raw, block_reader, out, &seen, options, 0);
}

pub fn decodeMstNode(allocator: Allocator, data: []const u8) !MstNodeData {
    var pos: usize = 0;

    const map_hdr = cbor.readMapHeader(data, pos) catch return error.InvalidMstNode;
    pos = map_hdr.end;
    if (map_hdr.val != 2) return error.InvalidMstNode;

    // "e" key
    const key_e = cbor.readText(data, pos) catch return error.InvalidMstNode;
    pos = key_e.end;
    if (!std.mem.eql(u8, key_e.val, "e")) return error.InvalidMstNode;

    // entries array
    const arr_hdr = cbor.readArrayHeader(data, pos) catch return error.InvalidMstNode;
    pos = arr_hdr.end;
    if (arr_hdr.val > max_mst_entries) return error.InvalidMstNode;
    const entries = try allocator.alloc(MstEntryData, @intCast(arr_hdr.val));
    errdefer allocator.free(entries);
    for (entries) |*entry| {
        const result = readMstEntry(data, pos) catch return error.InvalidMstNode;
        entry.* = result.entry;
        pos = result.end;
    }

    // "l" key
    const key_l = cbor.readText(data, pos) catch return error.InvalidMstNode;
    pos = key_l.end;
    if (!std.mem.eql(u8, key_l.val, "l")) return error.InvalidMstNode;

    // left CID or null
    const left_result = readCidOrNull(data, pos) catch return error.InvalidMstNode;
    pos = left_result.end;
    if (pos != data.len) return error.InvalidMstNode;

    return .{ .left = left_result.val, .entries = entries };
}

fn collectReachableNode(
    allocator: Allocator,
    cid_raw: []const u8,
    block_reader: BlockReader,
    out: *std.ArrayList(car.Block),
    seen: *std.StringHashMapUnmanaged(void),
    options: ReachableCollectOptions,
    depth: u32,
) ReachableBlocksError!void {
    if (depth > options.max_depth) return error.MaxDepthExceeded;

    const block_data = try appendReachableBlock(allocator, cid_raw, block_reader, out, seen);
    if (block_data == null) return;

    const node = decodeMstNode(allocator, block_data.?) catch return error.InvalidMstNode;
    defer allocator.free(node.entries);

    if (node.left) |left| {
        try collectReachableNode(allocator, left, block_reader, out, seen, options, depth + 1);
    }

    for (node.entries) |entry| {
        if (options.include_records) {
            _ = try appendReachableBlock(allocator, entry.value, block_reader, out, seen);
        }
        if (entry.tree) |right| {
            try collectReachableNode(allocator, right, block_reader, out, seen, options, depth + 1);
        }
    }
}

fn appendReachableBlock(
    allocator: Allocator,
    cid_raw: []const u8,
    block_reader: BlockReader,
    out: *std.ArrayList(car.Block),
    seen: *std.StringHashMapUnmanaged(void),
) ReachableBlocksError!?[]const u8 {
    if (seen.contains(cid_raw)) return null;

    const block_data = block_reader.get(cid_raw) catch |err| switch (err) {
        error.OutOfMemory => return error.OutOfMemory,
        else => return error.PartialTree,
    };
    const data = block_data orelse return error.PartialTree;

    const cid_copy = try allocator.dupe(u8, cid_raw);
    errdefer allocator.free(cid_copy);
    const data_copy = try allocator.dupe(u8, data);
    errdefer allocator.free(data_copy);

    try seen.put(allocator, cid_copy, {});
    errdefer _ = seen.remove(cid_copy);
    try out.append(allocator, .{
        .cid_raw = cid_copy,
        .data = data_copy,
    });
    return data_copy;
}

const MstEntryResult = struct {
    entry: MstEntryData,
    end: usize,
};

fn readMstEntry(data: []const u8, pos: usize) !MstEntryResult {
    var p = pos;

    const map_hdr = cbor.readMapHeader(data, p) catch return error.InvalidMstNode;
    p = map_hdr.end;
    if (map_hdr.val != 4) return error.InvalidMstNode;

    // "k" → key suffix (byte string)
    const key_k = cbor.readText(data, p) catch return error.InvalidMstNode;
    p = key_k.end;
    if (!std.mem.eql(u8, key_k.val, "k")) return error.InvalidMstNode;
    const key_suffix = cbor.readBytes(data, p) catch return error.InvalidMstNode;
    p = key_suffix.end;

    // "p" → prefix length (unsigned int)
    const key_p = cbor.readText(data, p) catch return error.InvalidMstNode;
    p = key_p.end;
    if (!std.mem.eql(u8, key_p.val, "p")) return error.InvalidMstNode;
    const prefix_len = cbor.readUint(data, p) catch return error.InvalidMstNode;
    p = prefix_len.end;
    if (prefix_len.val > max_mst_key_len) return error.InvalidMstNode;

    // "t" → right subtree CID or null
    const key_t = cbor.readText(data, p) catch return error.InvalidMstNode;
    p = key_t.end;
    if (!std.mem.eql(u8, key_t.val, "t")) return error.InvalidMstNode;
    const tree_result = readCidOrNull(data, p) catch return error.InvalidMstNode;
    p = tree_result.end;

    // "v" → value CID
    const key_v = cbor.readText(data, p) catch return error.InvalidMstNode;
    p = key_v.end;
    if (!std.mem.eql(u8, key_v.val, "v")) return error.InvalidMstNode;
    const value = cbor.readCidLink(data, p) catch return error.InvalidMstNode;
    p = value.end;

    return .{
        .entry = .{
            .key_suffix = key_suffix.val,
            .prefix_len = @intCast(prefix_len.val),
            .tree = tree_result.val,
            .value = value.val,
        },
        .end = p,
    };
}

const CidOrNullResult = struct {
    val: ?[]const u8,
    end: usize,
};

fn readCidOrNull(data: []const u8, pos: usize) !CidOrNullResult {
    if (pos >= data.len) return error.InvalidMstNode;
    if (data[pos] == 0xf6) return .{ .val = null, .end = pos + 1 };
    const cid_result = cbor.readCidLink(data, pos) catch return error.InvalidMstNode;
    return .{ .val = cid_result.val, .end = cid_result.end };
}

pub const MstDecodeError = error{InvalidMstNode} || Allocator.Error;

// === tests ===

test "keyHeight" {
    // values from interop test fixtures
    try std.testing.expectEqual(@as(u32, 0), keyHeight(""));
    try std.testing.expectEqual(@as(u32, 0), keyHeight("asdf"));
    try std.testing.expectEqual(@as(u32, 1), keyHeight("blue"));
    try std.testing.expectEqual(@as(u32, 0), keyHeight("2653ae71"));
    try std.testing.expectEqual(@as(u32, 2), keyHeight("88bfafc7"));
    try std.testing.expectEqual(@as(u32, 4), keyHeight("2a92d355"));
    try std.testing.expectEqual(@as(u32, 6), keyHeight("884976f5"));
    try std.testing.expectEqual(@as(u32, 4), keyHeight("app.bsky.feed.post/454397e440ec"));
    try std.testing.expectEqual(@as(u32, 8), keyHeight("app.bsky.feed.post/9adeb165882c"));
}

test "commonPrefixLen" {
    try std.testing.expectEqual(@as(usize, 0), commonPrefixLen("", ""));
    try std.testing.expectEqual(@as(usize, 3), commonPrefixLen("abc", "abc"));
    try std.testing.expectEqual(@as(usize, 0), commonPrefixLen("", "abc"));
    try std.testing.expectEqual(@as(usize, 2), commonPrefixLen("ab", "abc"));
    try std.testing.expectEqual(@as(usize, 3), commonPrefixLen("abcde", "abc"));
    try std.testing.expectEqual(@as(usize, 0), commonPrefixLen("abcde", "qbb"));
}

test "commonPrefixLen agrees with a byte loop across word boundaries" {
    var a: [24]u8 = undefined;
    var b: [24]u8 = undefined;
    for (0..a.len + 1) |len_a| {
        for (0..b.len + 1) |len_b| {
            for (0..@min(len_a, len_b) + 1) |diff_at| {
                @memset(&a, 'k');
                @memset(&b, 'k');
                if (diff_at < @min(len_a, len_b)) b[diff_at] = 'z';
                var expected: usize = 0;
                while (expected < @min(len_a, len_b) and a[expected] == b[expected]) expected += 1;
                try std.testing.expectEqual(expected, commonPrefixLen(a[0..len_a], b[0..len_b]));
            }
        }
    }
}

test "decodeMstNode rejects non-canonical node map keys" {
    const data = &[_]u8{
        0xa2, // map(2)
        0x61, 'l', 0xf6, // "l": null
        0x61, 'e', 0x80, // "e": []
    };

    try std.testing.expectError(error.InvalidMstNode, decodeMstNode(std.testing.allocator, data));
}

test "decodeMstNode rejects duplicate node map keys" {
    const data = &[_]u8{
        0xa2, // map(2)
        0x61, 'e', 0x80, // "e": []
        0x61, 'e', 0x80, // duplicate "e"
    };

    try std.testing.expectError(error.InvalidMstNode, decodeMstNode(std.testing.allocator, data));
}

test "decodeMstNode rejects non-canonical entry field order" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    const cid = try cbor.Cid.forDagCbor(a, "value");
    var data: std.ArrayList(u8) = .empty;
    defer data.deinit(a);

    try data.appendSlice(a, &.{ 0xa2, 0x61, 'e', 0x81 }); // {"e": [
    try data.appendSlice(a, &.{ 0xa4, 0x61, 'k' }); // { "k":
    try appendCborBytes(&data, a, "key");
    try data.appendSlice(a, &.{ 0x61, 't', 0xf6 }); // "t": null before "p"
    try data.appendSlice(a, &.{ 0x61, 'p', 0x00 }); // "p": 0
    try data.appendSlice(a, &.{ 0x61, 'v' });
    try appendCborCid(&data, a, cid);
    try data.appendSlice(a, &.{ 0x61, 'l', 0xf6 }); // ], "l": null }

    try std.testing.expectError(error.InvalidMstNode, decodeMstNode(a, data.items));
}

test "decodeMstNode rejects trailing bytes" {
    const data = &[_]u8{
        0xa2, // map(2)
        0x61, 'e', 0x80, // "e": []
        0x61, 'l', 0xf6, // "l": null
        0xf6, // trailing null
    };

    try std.testing.expectError(error.InvalidMstNode, decodeMstNode(std.testing.allocator, data));
}

test "decodeMstNode rejects oversized prefix length" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    const cid = try cbor.Cid.forDagCbor(a, "value");
    var data: std.ArrayList(u8) = .empty;
    defer data.deinit(a);

    try data.appendSlice(a, &.{ 0xa2, 0x61, 'e', 0x81 }); // {"e": [
    try data.appendSlice(a, &.{ 0xa4, 0x61, 'k' });
    try appendCborBytes(&data, a, "key");
    try data.appendSlice(a, &.{ 0x61, 'p' });
    try appendCborArgument(&data, a, 0, max_mst_key_len + 1);
    try data.appendSlice(a, &.{ 0x61, 't', 0xf6, 0x61, 'v' });
    try appendCborCid(&data, a, cid);
    try data.appendSlice(a, &.{ 0x61, 'l', 0xf6 });

    try std.testing.expectError(error.InvalidMstNode, decodeMstNode(a, data.items));
}

test "put and get" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    var tree = Mst.init(a);

    const cid1 = try cbor.Cid.forDagCbor(a, "value1");
    const cid2 = try cbor.Cid.forDagCbor(a, "value2");

    try tree.put("key1", cid1);
    try tree.put("key2", cid2);

    const got1 = tree.get("key1") orelse return error.NotFound;
    try std.testing.expectEqualSlices(u8, cid1.raw, got1.raw);

    const got2 = tree.get("key2") orelse return error.NotFound;
    try std.testing.expectEqualSlices(u8, cid2.raw, got2.raw);

    try std.testing.expect(tree.get("nonexistent") == null);
}

test "lookup walks ordered tree like lazy lookup" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    var tree = Mst.init(a);
    const keys = [_][]const u8{
        "A0/374913",
        "B1/986427",
        "C0/451630",
        "D2/269196",
        "E0/670489",
        "F1/085263",
        "G0/765327",
        "app.bsky.feed.post/9adeb165882c",
    };

    for (keys) |key| {
        const value = try cbor.Cid.forDagCbor(a, key);
        try tree.put(key, value);
    }
    try std.testing.expect((tree.root_layer orelse 0) > 0);

    var store = TestBlockStore{};
    const root_cid = try store.putNode(a, &tree, tree.root.?);
    var lazy = try Mst.loadLazy(a, root_cid.raw, store.reader());

    for (keys) |key| {
        const expected = tree.get(key) orelse return error.NotFound;
        const with_height = tree.getWithHeight(key, std.math.maxInt(u32)) orelse return error.NotFound;
        const lazy_got = try lazy.getLazy(key) orelse return error.NotFound;
        try std.testing.expectEqualSlices(u8, expected.raw, with_height.raw);
        try std.testing.expectEqualSlices(u8, expected.raw, lazy_got.raw);
    }

    const misses = [_][]const u8{
        "A0/000000",
        "B1/999999",
        "D2/269197",
        "app.bsky.feed.post/000000000000",
        "z",
    };
    for (misses) |key| {
        try std.testing.expect(tree.get(key) == null);
        try std.testing.expect(tree.getWithHeight(key, 0) == null);
        try std.testing.expect(try lazy.getLazy(key) == null);
    }
}

test "put and delete" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    var tree = Mst.init(a);
    const cid = try cbor.Cid.forDagCbor(a, "value");

    try tree.put("key1", cid);
    try tree.put("key2", cid);

    try std.testing.expect(tree.get("key1") != null);
    try tree.delete("key1");
    try std.testing.expect(tree.get("key1") == null);
    try std.testing.expect(tree.get("key2") != null);
}

test "putReturn and deleteReturn" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    var tree = Mst.init(a);
    const cid1 = try cbor.Cid.forDagCbor(a, "v1");
    const cid2 = try cbor.Cid.forDagCbor(a, "v2");

    // first insert returns null (no previous)
    const prev1 = try tree.putReturn("key1", cid1);
    try std.testing.expect(prev1 == null);

    // update returns old value
    const prev2 = try tree.putReturn("key1", cid2);
    try std.testing.expect(prev2 != null);
    try std.testing.expectEqualSlices(u8, cid1.raw, prev2.?.raw);

    // delete returns removed value
    const removed = try tree.deleteReturn("key1");
    try std.testing.expect(removed != null);
    try std.testing.expectEqualSlices(u8, cid2.raw, removed.?.raw);

    // delete nonexistent returns null
    const removed2 = try tree.deleteReturn("key1");
    try std.testing.expect(removed2 == null);
}

test "copy produces independent tree" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    var tree = Mst.init(a);
    const cid1 = try cbor.Cid.forDagCbor(a, "v1");
    const cid2 = try cbor.Cid.forDagCbor(a, "v2");

    try tree.put("key1", cid1);
    try tree.put("key2", cid1);

    var tree2 = try tree.copy();

    // modify copy
    try tree2.put("key1", cid2);
    try tree2.delete("key2");

    // original unchanged
    const got1 = tree.get("key1") orelse return error.NotFound;
    try std.testing.expectEqualSlices(u8, cid1.raw, got1.raw);
    try std.testing.expect(tree.get("key2") != null);

    // copy has changes
    const got1_copy = tree2.get("key1") orelse return error.NotFound;
    try std.testing.expectEqualSlices(u8, cid2.raw, got1_copy.raw);
    try std.testing.expect(tree2.get("key2") == null);
}

test "rootCid is deterministic" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    const cid_val = try cbor.Cid.forDagCbor(a, "leaf");

    // build tree 1
    var tree1 = Mst.init(a);
    try tree1.put("a", cid_val);
    try tree1.put("b", cid_val);
    const root1 = try tree1.rootCid();

    // build tree 2 (same keys, same order)
    var tree2 = Mst.init(a);
    try tree2.put("a", cid_val);
    try tree2.put("b", cid_val);
    const root2 = try tree2.rootCid();

    try std.testing.expectEqualSlices(u8, root1.raw, root2.raw);
}

test "empty tree rootCid matches reference" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    var tree = Mst.init(a);
    const root = try tree.rootCid();
    try std.testing.expectEqual(@as(u64, 1), root.version().?);

    // known empty tree CID from Go reference implementation
    const expected = try parseCidString(a, "bafyreie5737gdxlw5i64vzichcalba3z2v5n6icifvx5xytvske7mr3hpm");
    try std.testing.expectEqualSlices(u8, expected.raw, root.raw);
}

test "single key rootCid matches reference" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    var tree = Mst.init(a);
    // use a known CID value (the leaf CID from commit-proof fixtures)
    const leaf_cid = try parseCidString(a, "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454");

    // single layer-0 key
    try tree.put("com.example.record/3jqfcqzm3fo2j", leaf_cid);

    const root = try tree.rootCid();
    const expected = try parseCidString(a, "bafyreibj4lsc3aqnrvphp5xmrnfoorvru4wynt6lwidqbm2623a6tatzdu");
    try std.testing.expectEqualSlices(u8, expected.raw, root.raw);
}

test "single layer-2 key rootCid matches reference" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    var tree = Mst.init(a);
    const leaf_cid = try parseCidString(a, "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454");

    // single layer-2 key
    try tree.put("com.example.record/3jqfcqzm3fx2j", leaf_cid);

    const root = try tree.rootCid();
    const expected = try parseCidString(a, "bafyreih7wfei65pxzhauoibu3ls7jgmkju4bspy4t2ha2qdjnzqvoy33ai");
    try std.testing.expectEqualSlices(u8, expected.raw, root.raw);
}

test "5 key tree matches reference" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    var tree = Mst.init(a);
    const leaf_cid = try parseCidString(a, "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454");

    // 5 keys from Go test (note: last key has 4fc not 3ft)
    const keys = [_][]const u8{
        "com.example.record/3jqfcqzm3fp2j",
        "com.example.record/3jqfcqzm3fr2j",
        "com.example.record/3jqfcqzm3fs2j",
        "com.example.record/3jqfcqzm3ft2j",
        "com.example.record/3jqfcqzm4fc2j",
    };

    for (keys) |key| {
        try tree.put(key, leaf_cid);
    }

    const root = try tree.rootCid();
    const expected = try parseCidString(a, "bafyreicmahysq4n6wfuxo522m6dpiy7z7qzym3dzs756t5n7nfdgccwq7m");
    try std.testing.expectEqualSlices(u8, expected.raw, root.raw);
}

test "two deep split fixture" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    const leaf_cid = try parseCidString(a, "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454");

    var tree = Mst.init(a);
    const initial_keys = [_][]const u8{
        "A0/374913", "B1/986427", "C0/451630",
        "E0/670489", "F1/085263", "G0/765327",
    };
    for (initial_keys) |key| {
        try tree.put(key, leaf_cid);
    }

    const expected_before = try parseCidString(a, "bafyreicraprx2xwnico4tuqir3ozsxpz46qkcpox3obf5bagicqwurghpy");
    try std.testing.expectEqualSlices(u8, expected_before.raw, (try tree.rootCid()).raw);

    try tree.put("D2/269196", leaf_cid);

    const expected_after = try parseCidString(a, "bafyreihvay6pazw3dfa47u5d2tn3rd6pa57sr37bo5bqyvjuqc73ib65my");
    try std.testing.expectEqualSlices(u8, expected_after.raw, (try tree.rootCid()).raw);
}

test "complex multi-op commit" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    const leaf_cid = try parseCidString(a, "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454");

    var tree = Mst.init(a);
    const initial_keys = [_][]const u8{
        "B0/601692", "C2/014073", "D0/952776",
        "E2/819540", "F0/697858", "H0/131238",
    };
    for (initial_keys) |key| {
        try tree.put(key, leaf_cid);
    }

    const expected_before = try parseCidString(a, "bafyreigr3plnts7dax6yokvinbhcqpyicdfgg6npvvyx6okc5jo55slfqi");
    try std.testing.expectEqualSlices(u8, expected_before.raw, (try tree.rootCid()).raw);

    // adds
    try tree.put("A2/827942", leaf_cid);
    try tree.put("G2/611528", leaf_cid);
    // del
    try tree.delete("C2/014073");

    const expected_after = try parseCidString(a, "bafyreiftrcrbhrwmi37u4egedlg56gk3jeh3tvmqvwgowoifuklfysyx54");
    try std.testing.expectEqualSlices(u8, expected_after.raw, (try tree.rootCid()).raw);
}

const TestBlockStore = struct {
    blocks: std.StringHashMapUnmanaged([]const u8) = .empty,
    loads: usize = 0,

    fn putBlock(self: *TestBlockStore, allocator: Allocator, data: []const u8) !cbor.Cid {
        const block_data = try allocator.dupe(u8, data);
        const cid = try cbor.Cid.forDagCbor(allocator, block_data);
        try self.blocks.put(allocator, cid.raw, block_data);
        return cid;
    }

    fn putNode(self: *TestBlockStore, allocator: Allocator, tree: *Mst, node: *Node) !cbor.Cid {
        if (node.left) |left| _ = try self.putNode(allocator, tree, left);
        for (node.entries.items) |entry| {
            if (entry.right) |right| _ = try self.putNode(allocator, tree, right);
        }

        const data = try tree.serializeNode(node);
        const cid = try cbor.Cid.forDagCbor(allocator, data);
        try self.blocks.put(allocator, cid.raw, data);
        return cid;
    }

    fn reader(self: *TestBlockStore) BlockReader {
        return .{
            .ctx = self,
            .getFn = getBlock,
        };
    }

    fn getBlock(ctx: *anyopaque, cid_raw: []const u8) anyerror!?[]const u8 {
        const self: *TestBlockStore = @ptrCast(@alignCast(ctx));
        self.loads += 1;
        return self.blocks.get(cid_raw);
    }
};

test "loadLazy keeps root as CID stub until first access" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    const leaf_cid = try parseCidString(a, "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454");
    var eager = Mst.init(a);
    const keys = [_][]const u8{
        "A0/374913", "B1/986427", "C0/451630",
        "E0/670489", "F1/085263", "G0/765327",
    };
    for (keys) |key| try eager.put(key, leaf_cid);

    var store = TestBlockStore{};
    const root_cid = try store.putNode(a, &eager, eager.root.?);

    var lazy = try Mst.loadLazy(a, root_cid.raw, store.reader());
    try std.testing.expectEqual(@as(usize, 0), store.loads);
    try std.testing.expect(lazy.root != null);
    try std.testing.expect(lazy.root.?.cid != null);
    try std.testing.expectEqual(@as(usize, 0), lazy.root.?.entries.items.len);

    const lazy_root = try lazy.rootCid();
    try std.testing.expectEqualSlices(u8, root_cid.raw, lazy_root.raw);
    try std.testing.expectEqual(@as(usize, 0), store.loads);
}

test "rootCid caches clean root and put dirties it" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    const leaf_cid = try parseCidString(a, "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454");
    var tree = Mst.init(a);
    try tree.put("app.bsky.feed.post/0000000000001", leaf_cid);
    try tree.put("app.bsky.feed.post/0000000000002", leaf_cid);

    try std.testing.expect(tree.root.?.dirty);
    const root1 = try tree.rootCid();
    try std.testing.expect(!tree.root.?.dirty);
    try std.testing.expect(tree.root.?.cid != null);

    const root2 = try tree.rootCid();
    try std.testing.expectEqualSlices(u8, root1.raw, root2.raw);
    try std.testing.expect(!tree.root.?.dirty);

    try tree.put("app.bsky.feed.post/0000000000003", leaf_cid);
    try std.testing.expect(tree.root.?.dirty);

    const root3 = try tree.rootCid();
    try std.testing.expect(!tree.root.?.dirty);
    try std.testing.expect(!std.mem.eql(u8, root1.raw, root3.raw));
}

test "collectReachableBlocks includes records once" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    var store = TestBlockStore{};
    const record_cid = try store.putBlock(a, "shared record block");

    var tree = Mst.init(a);
    try tree.put("app.bsky.feed.post/1", record_cid);
    try tree.put("app.bsky.feed.post/2", record_cid);
    const root_cid = try store.putNode(a, &tree, tree.root.?);

    var blocks: std.ArrayList(car.Block) = .empty;
    try collectReachableBlocks(a, root_cid.raw, store.reader(), &blocks, .{});

    try std.testing.expectEqual(@as(usize, 2), blocks.items.len);
    try std.testing.expectEqual(@as(usize, 2), store.loads);
    try std.testing.expectEqualSlices(u8, root_cid.raw, blocks.items[0].cid_raw);
    try std.testing.expectEqualSlices(u8, record_cid.raw, blocks.items[1].cid_raw);
    try std.testing.expectEqualStrings("shared record block", blocks.items[1].data);
}

test "collectReachableBlocks reports missing record block" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    var store = TestBlockStore{};
    const record_cid = try cbor.Cid.forDagCbor(a, "missing record block");

    var tree = Mst.init(a);
    try tree.put("app.bsky.feed.post/1", record_cid);
    const root_cid = try store.putNode(a, &tree, tree.root.?);

    var blocks: std.ArrayList(car.Block) = .empty;
    try std.testing.expectError(
        error.PartialTree,
        collectReachableBlocks(a, root_cid.raw, store.reader(), &blocks, .{}),
    );
}

const WalkCollector = struct {
    allocator: Allocator,
    keys: std.ArrayList([]const u8) = .empty,

    fn walker(self: *WalkCollector) Walker {
        return .{
            .ctx = self,
            .entryFn = onEntry,
        };
    }

    fn onEntry(ctx: *anyopaque, entry: WalkEntry) anyerror!void {
        const self: *WalkCollector = @ptrCast(@alignCast(ctx));
        try self.keys.append(self.allocator, try self.allocator.dupe(u8, entry.key));
    }
};

test "walk visits entries in key order" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    const leaf_cid = try parseCidString(a, "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454");
    var tree = Mst.init(a);
    try tree.put("app.bsky.feed.post/3", leaf_cid);
    try tree.put("app.bsky.feed.post/1", leaf_cid);
    try tree.put("app.bsky.feed.post/2", leaf_cid);

    var collector = WalkCollector{ .allocator = a };
    try tree.walk(collector.walker());

    try std.testing.expectEqual(@as(usize, 3), collector.keys.items.len);
    try std.testing.expectEqualStrings("app.bsky.feed.post/1", collector.keys.items[0]);
    try std.testing.expectEqualStrings("app.bsky.feed.post/2", collector.keys.items[1]);
    try std.testing.expectEqualStrings("app.bsky.feed.post/3", collector.keys.items[2]);
}

test "collectBlocks emits a loadable MST root" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    const leaf_cid = try parseCidString(a, "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454");
    var tree = Mst.init(a);
    try tree.put("app.bsky.feed.post/1", leaf_cid);
    try tree.put("app.bsky.feed.post/2", leaf_cid);

    const root = try tree.rootCid();
    var blocks: std.ArrayList(car.Block) = .empty;
    try tree.collectBlocks(&blocks);

    const repo_car = car.Car{ .roots = &.{root}, .blocks = blocks.items };
    var loaded = try Mst.loadFromBlocks(a, repo_car, root.raw);
    const got = loaded.get("app.bsky.feed.post/1") orelse return error.NotFound;
    try std.testing.expectEqualSlices(u8, leaf_cid.raw, got.raw);
}

test "getLazy resolves root and child stubs on demand" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    const leaf_cid = try parseCidString(a, "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454");
    var eager = Mst.init(a);
    const keys = [_][]const u8{
        "A0/374913", "B1/986427", "C0/451630",
        "E0/670489", "F1/085263", "G0/765327",
    };
    for (keys) |key| try eager.put(key, leaf_cid);

    var store = TestBlockStore{};
    const root_cid = try store.putNode(a, &eager, eager.root.?);

    var child_key: []const u8 = keys[0];
    for (keys) |key| {
        if (keyHeight(key) < eager.root_layer.?) {
            child_key = key;
            break;
        }
    }

    var lazy = try Mst.loadLazy(a, root_cid.raw, store.reader());
    const got = try lazy.getLazy(child_key) orelse return error.NotFound;
    try std.testing.expectEqualSlices(u8, leaf_cid.raw, got.raw);
    try std.testing.expect(store.loads > 1);
}

test "putReturn mutates through lazy stubs and matches eager root" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    const leaf_cid = try parseCidString(a, "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454");
    var eager = Mst.init(a);
    const initial_keys = [_][]const u8{
        "A0/374913", "B1/986427", "C0/451630",
        "E0/670489", "F1/085263", "G0/765327",
    };
    for (initial_keys) |key| try eager.put(key, leaf_cid);

    var store = TestBlockStore{};
    const root_cid = try store.putNode(a, &eager, eager.root.?);

    var expected = try eager.copy();
    try expected.put("D2/269196", leaf_cid);
    const expected_root = try expected.rootCid();

    var lazy = try Mst.loadLazy(a, root_cid.raw, store.reader());
    const prev = try lazy.putReturn("D2/269196", leaf_cid);
    try std.testing.expect(prev == null);

    const lazy_root = try lazy.rootCid();
    try std.testing.expectEqualSlices(u8, expected_root.raw, lazy_root.raw);
    try std.testing.expect(store.loads > 1);
}

test "deleteReturn mutates through lazy stubs and matches eager root" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    const leaf_cid = try parseCidString(a, "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454");
    var eager = Mst.init(a);
    const keys = [_][]const u8{
        "A0/374913", "B1/986427", "C0/451630",
        "E0/670489", "F1/085263", "G0/765327",
    };
    for (keys) |key| try eager.put(key, leaf_cid);

    var store = TestBlockStore{};
    const root_cid = try store.putNode(a, &eager, eager.root.?);

    var delete_key: []const u8 = keys[0];
    for (keys) |key| {
        if (keyHeight(key) < eager.root_layer.?) {
            delete_key = key;
            break;
        }
    }

    var expected = try eager.copy();
    const expected_removed = try expected.deleteReturn(delete_key) orelse return error.NotFound;
    const expected_root = try expected.rootCid();

    var lazy = try Mst.loadLazy(a, root_cid.raw, store.reader());
    const removed = try lazy.deleteReturn(delete_key) orelse return error.NotFound;
    try std.testing.expectEqualSlices(u8, expected_removed.raw, removed.raw);

    const lazy_root = try lazy.rootCid();
    try std.testing.expectEqualSlices(u8, expected_root.raw, lazy_root.raw);
    try std.testing.expect(store.loads > 1);
}

test "deleting the only key in a subtree prunes the empty node" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    // heights 1 and 0, so the second key is the sole occupant of a subtree
    // hanging off the first key's entry — the shape a real two-record repo has
    const high = "app.bsky.feed.post/3lsync00001zz";
    const low = "app.bsky.feed.post/3lsync00002zz";
    try std.testing.expectEqual(@as(u32, 1), keyHeight(high));
    try std.testing.expectEqual(@as(u32, 0), keyHeight(low));

    const cid1 = try cbor.Cid.forDagCbor(a, "record-one");
    const cid2 = try cbor.Cid.forDagCbor(a, "record-two");

    // the tree as it was before `low` was ever added
    var before = Mst.init(a);
    try before.put(high, cid1);
    const before_root = try before.rootCid();

    // add then remove `low`: the root must return to its previous CID, which
    // requires dropping the emptied subtree rather than serializing an empty node
    var after = Mst.init(a);
    try after.put(high, cid1);
    try after.put(low, cid2);
    const removed = try after.deleteReturn(low) orelse return error.NotFound;
    try std.testing.expectEqualSlices(u8, cid2.raw, removed.raw);

    const after_root = try after.rootCid();
    try std.testing.expectEqualSlices(u8, before_root.raw, after_root.raw);
}

// The canonical oracle for any delete: a tree freshly built from the surviving
// keyset. The MST is content-addressed and canonical, so a correct delete must
// land on exactly that root — asserting against a second code path (lazy vs
// eager) only proves the two agree, which a shared bug satisfies.
fn expectDeleteMatchesFreshBuild(
    a: Allocator,
    keys: []const []const u8,
    values: []const cbor.Cid,
    remove_idx: usize,
) !void {
    var tree = Mst.init(a);
    for (keys, values) |key, value| try tree.put(key, value);
    _ = try tree.deleteReturn(keys[remove_idx]) orelse return error.NotFound;
    const after = try tree.rootCid();

    var oracle = Mst.init(a);
    for (keys, values, 0..) |key, value, i| {
        if (i == remove_idx) continue;
        try oracle.put(key, value);
    }
    const expected = try oracle.rootCid();

    try std.testing.expectEqualSlices(u8, expected.raw, after.raw);

    // every surviving key must still be reachable
    for (keys, values, 0..) |key, value, i| {
        if (i == remove_idx) continue;
        const found = tree.get(key) orelse return error.SurvivorDropped;
        try std.testing.expectEqualSlices(u8, value.raw, found.raw);
    }
}

test "delete collapses a right-side subtree to the canonical root" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    // one height-2 key at the root, one height-0 key either side of it.
    // removing the right-hand key empties its subtree, which must be pruned.
    const keys = [_][]const u8{
        "app.bsky.feed.like/32f5052c9fd15", // height 0, sorts left
        "app.bsky.feed.like/388dbf612972c", // height 2, the root entry
        "app.bsky.feed.like/394091dd64a21", // height 0, sorts right
    };
    try std.testing.expectEqual(@as(u32, 0), keyHeight(keys[0]));
    try std.testing.expectEqual(@as(u32, 2), keyHeight(keys[1]));
    try std.testing.expectEqual(@as(u32, 0), keyHeight(keys[2]));

    const value = try cbor.Cid.forDagCbor(a, "record");
    const values = [_]cbor.Cid{ value, value, value };
    try expectDeleteMatchesFreshBuild(a, &keys, &values, 2);
}

test "delete keeps an empty intermediate that fills a height gap" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    // removing the height-1 key leaves its node with no entries but a surviving
    // height-0 child. That node must stay as an empty pass-through: dropping it
    // would promote the leaf a level and produce a non-canonical root.
    const keys = [_][]const u8{
        "app.bsky.feed.like/32f5052c9fd15", // height 0
        "app.bsky.feed.like/36ab9f1eb8f7d", // height 1, removed
        "app.bsky.feed.like/388dbf612972c", // height 2, the root entry
    };
    try std.testing.expectEqual(@as(u32, 0), keyHeight(keys[0]));
    try std.testing.expectEqual(@as(u32, 1), keyHeight(keys[1]));
    try std.testing.expectEqual(@as(u32, 2), keyHeight(keys[2]));

    const value = try cbor.Cid.forDagCbor(a, "record");
    const values = [_]cbor.Cid{ value, value, value };
    try expectDeleteMatchesFreshBuild(a, &keys, &values, 1);
}

test "delete through unloaded stubs does not prune a populated subtree" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    // An unloaded stub is indistinguishable from an empty node by inspection
    // (no entries, no left child) — emptiness may only be judged after loading.
    // Reading it bare would drop every record beneath the removed key.
    const root_key = "col.lection/0000019"; // height 2, removed
    const leaf_key = "col.lection/0000005"; // height 1, lone survivor
    try std.testing.expectEqual(@as(u32, 2), keyHeight(root_key));
    try std.testing.expectEqual(@as(u32, 1), keyHeight(leaf_key));
    try std.testing.expect(std.mem.lessThan(u8, leaf_key, root_key));

    const value = try cbor.Cid.forDagCbor(a, "record");

    var staged = Mst.init(a);
    try staged.put(root_key, value);
    try staged.put(leaf_key, value);

    var store = TestBlockStore{};
    const staged_root = try store.putNode(a, &staged, staged.root.?);

    var reloaded = try Mst.loadLazy(a, staged_root.raw, store.reader());
    _ = try reloaded.deleteReturn(root_key) orelse return error.NotFound;
    const got = try reloaded.rootCid();

    var oracle = Mst.init(a);
    try oracle.put(leaf_key, value);
    const want = try oracle.rootCid();

    try std.testing.expectEqualSlices(u8, want.raw, got.raw);

    const survivor = reloaded.get(leaf_key) orelse return error.SurvivorDropped;
    try std.testing.expectEqualSlices(u8, value.raw, survivor.raw);
}

test "inversion: create then invert" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    const cid1 = try cbor.Cid.forDagCbor(a, "record1");

    var tree = Mst.init(a);
    const root_before = try tree.rootCid();

    // apply forward: create
    try tree.put("col/rkey1", cid1);

    // invert: should remove it
    try invertOp(&tree, .{
        .path = "col/rkey1",
        .value = cid1.raw,
        .prev = null,
    });

    const root_after = try tree.rootCid();
    try std.testing.expectEqualSlices(u8, root_before.raw, root_after.raw);
}

test "inversion: update then invert" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    const cid1 = try cbor.Cid.forDagCbor(a, "v1");
    const cid2 = try cbor.Cid.forDagCbor(a, "v2");

    var tree = Mst.init(a);
    try tree.put("col/rkey1", cid1);
    const root_before = try tree.rootCid();

    // apply forward: update cid1 → cid2
    try tree.put("col/rkey1", cid2);

    // invert
    try invertOp(&tree, .{
        .path = "col/rkey1",
        .value = cid2.raw,
        .prev = cid1.raw,
    });

    const root_after = try tree.rootCid();
    try std.testing.expectEqualSlices(u8, root_before.raw, root_after.raw);
}

test "inversion: delete then invert" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    const cid1 = try cbor.Cid.forDagCbor(a, "v1");

    var tree = Mst.init(a);
    try tree.put("col/rkey1", cid1);
    const root_before = try tree.rootCid();

    // apply forward: delete
    try tree.delete("col/rkey1");

    // invert
    try invertOp(&tree, .{
        .path = "col/rkey1",
        .value = null,
        .prev = cid1.raw,
    });

    const root_after = try tree.rootCid();
    try std.testing.expectEqualSlices(u8, root_before.raw, root_after.raw);
}

test "inversion: multi-op commit round-trip" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    const cid1 = try cbor.Cid.forDagCbor(a, "v1");
    const cid2 = try cbor.Cid.forDagCbor(a, "v2");
    const cid3 = try cbor.Cid.forDagCbor(a, "v3");

    // build initial tree
    var tree = Mst.init(a);
    try tree.put("col/existing", cid1);
    try tree.put("col/to_update", cid1);
    try tree.put("col/to_delete", cid2);
    const root_before = try tree.rootCid();

    // apply forward ops
    try tree.put("col/new_record", cid3); // create
    try tree.put("col/to_update", cid2); // update
    try tree.delete("col/to_delete"); // delete

    // normalize and invert
    const ops = [_]Operation{
        .{ .path = "col/new_record", .value = cid3.raw, .prev = null }, // create
        .{ .path = "col/to_update", .value = cid2.raw, .prev = cid1.raw }, // update
        .{ .path = "col/to_delete", .value = null, .prev = cid2.raw }, // delete
    };
    const sorted = try normalizeOps(a, &ops);

    for (sorted) |op| {
        try invertOp(&tree, op);
    }

    const root_after = try tree.rootCid();
    try std.testing.expectEqualSlices(u8, root_before.raw, root_after.raw);
}

test "normalizeOps rejects duplicates" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    const ops = [_]Operation{
        .{ .path = "col/same", .value = "cid1", .prev = null },
        .{ .path = "col/same", .value = "cid2", .prev = null },
    };

    try std.testing.expectError(error.DuplicatePath, normalizeOps(a, &ops));
}

test "parseCidString" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    const cid = try parseCidString(a, "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454");
    try std.testing.expectEqual(@as(u64, 1), cid.version().?);
    try std.testing.expectEqual(@as(u64, 0x71), cid.codec().?);
    try std.testing.expectEqual(@as(u64, 0x12), cid.hashFn().?);
    try std.testing.expectEqual(@as(usize, 32), cid.digest().?.len);
}

test "collectBlocks emits consistent (cid, data) pairs across repeated commit cycles" {
    // regression: nodeCid (the rootCid path) re-serialized dirty nodes and
    // cleared `dirty` without refreshing the cached encoding, so the next
    // collectBlocks paired the new cid with stale bytes — BadBlockHash on
    // any CAR reload after the second commit.
    const testing = std.testing;
    var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
    defer arena_state.deinit();
    const arena = arena_state.allocator();

    var tree = Mst.init(arena);
    var round: usize = 0;
    while (round < 5) : (round += 1) {
        var key_buf: [32]u8 = undefined;
        const key = try std.fmt.bufPrint(&key_buf, "io.test.rec/key-{d:0>3}", .{round});
        var data_buf: [8]u8 = undefined;
        const data = try std.fmt.bufPrint(&data_buf, "v{d}", .{round});
        const value_cid = try cbor.Cid.forDagCbor(arena, data);
        try tree.put(key, value_cid);

        // the commit sequence: rootCid first (marks nodes clean), then collect
        _ = try tree.rootCid();
        var blocks: std.ArrayList(car.Block) = .empty;
        try tree.collectBlocks(&blocks);

        for (blocks.items) |block| {
            const computed = try cbor.Cid.forDagCbor(arena, block.data);
            try testing.expect(std.mem.eql(u8, computed.raw, block.cid_raw));
        }
    }
}

test "collectBlocks emits a stranded empty node inherited from a pre-prune writer" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    // Rebuild the shape zat <= v0.3.18 produced: deleting the sole occupant of a
    // subtree left the emptied node in place instead of dropping the pointer.
    // See docs/incident-2026-08-18-empty-mst-node.md in zds.
    const parent_key = "com.atproto.lexicon.schema/place.birds.speciesPhoto";
    const child_key = "place.birds.sighting/3msvg56t43skv";
    try std.testing.expectEqual(@as(u32, 1), keyHeight(parent_key));
    try std.testing.expectEqual(@as(u32, 0), keyHeight(child_key));

    const value = try cbor.Cid.forDagCbor(a, "record");

    var tree = Mst.init(a);
    try tree.put(parent_key, value);
    try tree.put(child_key, value);

    // strand the subtree the way the old delete did: empty it, but keep the pointer
    const root = tree.root.?;
    const idx = Mst.entryLowerBound(root.entries.items, parent_key);
    const stranded = root.entries.items[idx].right.?;
    stranded.entries.clearRetainingCapacity();
    stranded.left = null;
    const empty_encoded = try tree.serializeEmptyNode();
    stranded.cid = try cbor.Cid.forDagCbor(a, empty_encoded);
    stranded.encoded = null;
    stranded.dirty = false;
    root.dirty = true;

    var blocks: std.ArrayList(car.Block) = .empty;
    defer blocks.deinit(a);
    _ = try tree.rootCid();
    try tree.collectBlocksInto(a, &blocks);

    // the closure invariant: every MST node cid a collected block points at must
    // itself be collected, or the tree references a block nobody stored
    var have: std.StringHashMapUnmanaged(void) = .empty;
    defer have.deinit(a);
    for (blocks.items) |b| try have.put(a, b.cid_raw, {});

    for (blocks.items) |b| {
        const nd = decodeMstNode(a, b.data) catch continue;
        if (nd.left) |l| try std.testing.expect(have.contains(l));
        for (nd.entries) |e| if (e.tree) |t| try std.testing.expect(have.contains(t));
    }

    // and specifically: the stranded empty node's block is emitted
    try std.testing.expect(have.contains(stranded.cid.?.raw));
}

test "a lazily loaded tree heals a stranded empty node whose block is absent" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    // the production repair path: the repo's store is missing the empty node's
    // block entirely (that is the outage), and the next write must put it back.
    const parent_key = "com.atproto.lexicon.schema/place.birds.speciesPhoto";
    const child_key = "place.birds.sighting/3msvg56t43skv";
    const value = try cbor.Cid.forDagCbor(a, "record");

    var staged = Mst.init(a);
    try staged.put(parent_key, value);
    try staged.put(child_key, value);
    const root = staged.root.?;
    const idx = Mst.entryLowerBound(root.entries.items, parent_key);
    const stranded = root.entries.items[idx].right.?;
    stranded.entries.clearRetainingCapacity();
    stranded.left = null;
    const empty_encoded = try staged.serializeEmptyNode();
    const empty_cid = try cbor.Cid.forDagCbor(a, empty_encoded);
    stranded.cid = empty_cid;
    stranded.encoded = null;
    stranded.dirty = false;
    root.dirty = true;

    // store every block EXCEPT the empty node's, exactly as production looked
    var store = TestBlockStore{};
    var staged_blocks: std.ArrayList(car.Block) = .empty;
    defer staged_blocks.deinit(a);
    const staged_root = try staged.rootCid();
    try staged.collectBlocksInto(a, &staged_blocks);
    for (staged_blocks.items) |b| {
        if (std.mem.eql(u8, b.cid_raw, empty_cid.raw)) continue;
        try store.blocks.put(a, b.cid_raw, b.data);
    }
    try std.testing.expect(store.blocks.get(empty_cid.raw) == null);

    // a write that does not descend into the stranded branch must still succeed...
    var tree = try Mst.loadLazy(a, staged_root.raw, store.reader());
    try tree.put("app.bsky.feed.post/3lsync00001zz", value);

    var blocks: std.ArrayList(car.Block) = .empty;
    defer blocks.deinit(a);
    _ = try tree.rootCid();
    try tree.collectBlocksInto(a, &blocks);

    // ...and must re-emit the stranded block, healing the store
    var healed = false;
    for (blocks.items) |b| {
        if (std.mem.eql(u8, b.cid_raw, empty_cid.raw)) {
            try std.testing.expectEqualSlices(u8, empty_encoded, b.data);
            healed = true;
        }
    }
    try std.testing.expect(healed);
}

test "create+delete through an empty left child prunes it back to canonical" {
    const alloc = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const a = arena.allocator();

    // zat.dev's surviving shape: an h2 entry whose right subtree (layer 1) has the
    // stranded empty node as its LEFT child. Nothing lives under it, so an ordinary
    // delete cannot descend into it; only a create that lands inside, followed by a
    // delete, makes pruneIfEmpty fire.
    const anchor = "io.atcr.manifest/1009a8cbfd067c58a9a273f7442d61307bedb0bdd4b53d71ccc1a6dd44f4441f";
    const first = "io.atcr.manifest/1f07f214ea05b602d7cf56c572af9d3ea580a35ac85863d5ad1f8c1beea0bab1";
    const trigger = "io.atcr.manifest/1b00000000000000000000000000000000000000000000000000000000000000";
    try std.testing.expectEqual(@as(u32, 2), keyHeight(anchor));
    try std.testing.expectEqual(@as(u32, 1), keyHeight(first));
    try std.testing.expectEqual(@as(u32, 0), keyHeight(trigger));
    try std.testing.expect(std.mem.lessThan(u8, anchor, trigger));
    try std.testing.expect(std.mem.lessThan(u8, trigger, first));

    const value = try cbor.Cid.forDagCbor(a, "record");

    var staged = Mst.init(a);
    try staged.put(anchor, value);
    try staged.put(first, value);

    var store = TestBlockStore{};
    // strand an empty node as the left child of the layer-1 subtree, as v0.3.10 did,
    // and store its block — which is what the incident mitigation restored
    const sroot = staged.root.?;
    const sub = sroot.entries.items[Mst.entryLowerBound(sroot.entries.items, anchor)].right.?;
    const empty_cid = try store.putBlock(a, try staged.serializeEmptyNode());
    const stranded = try staged.createNode(0);
    stranded.cid = empty_cid;
    stranded.dirty = false;
    sub.left = stranded;
    sub.dirty = true;
    sroot.dirty = true;

    var staged_blocks: std.ArrayList(car.Block) = .empty;
    defer staged_blocks.deinit(a);
    const stranded_root = try staged.rootCid();
    try staged.collectBlocksInto(a, &staged_blocks);
    for (staged_blocks.items) |b| try store.blocks.put(a, b.cid_raw, b.data);

    var oracle = Mst.init(a);
    try oracle.put(anchor, value);
    try oracle.put(first, value);
    const canonical = try oracle.rootCid();
    try std.testing.expect(!std.mem.eql(u8, stranded_root.raw, canonical.raw));

    // the forward commit, against the repo as it actually sits: create the trigger
    // key, then delete it
    var tree = try Mst.loadLazy(a, stranded_root.raw, store.reader());
    try tree.put(trigger, value);
    _ = try tree.deleteReturn(trigger) orelse return error.NotFound;

    try std.testing.expectEqualSlices(u8, canonical.raw, (try tree.rootCid()).raw);
}

fn appendNodeHeader(out: *std.ArrayList(u8), a: Allocator, count: usize) !void {
    try out.appendSlice(a, &.{ 0xa2, 0x61, 0x65 });
    try appendCborArgument(out, a, 4, @intCast(count));
}
fn appendNodeEntry(out: *std.ArrayList(u8), a: Allocator, previous: []const u8, key: []const u8, value: cbor.Cid, right: ?cbor.Cid) !void {
    const prefix = commonPrefixLen(previous, key);
    try out.appendSlice(a, &.{ 0xa4, 0x61, 0x6b });
    try appendCborBytes(out, a, key[prefix..]);
    try out.appendSlice(a, &.{ 0x61, 0x70 });
    try appendCborArgument(out, a, 0, @intCast(prefix));
    try out.appendSlice(a, &.{ 0x61, 0x74 });
    if (right) |cid| try appendCborCid(out, a, cid) else try out.append(a, 0xf6);
    try out.appendSlice(a, &.{ 0x61, 0x76 });
    try appendCborCid(out, a, value);
}
fn appendNodeFooter(out: *std.ArrayList(u8), a: Allocator, left: ?cbor.Cid) !void {
    try out.appendSlice(a, &.{ 0x61, 0x6c });
    if (left) |cid| try appendCborCid(out, a, cid) else try out.append(a, 0xf6);
}

const Link = [36]u8;
const SortedEntry = struct { key: []const u8, value: Link, right: ?Link = null };
const SortedNode = struct {
    left: ?Link = null,
    entries: std.ArrayList(SortedEntry) = .empty,

    fn clear(self: *SortedNode, allocator: std.mem.Allocator) void {
        for (self.entries.items) |entry| allocator.free(entry.key);
        self.entries.deinit(allocator);
        self.* = .{};
    }

    fn empty(self: SortedNode) bool {
        return self.left == null and self.entries.items.len == 0;
    }

    fn link(self: *SortedNode, cid: Link) void {
        if (self.entries.items.len == 0) self.left = cid else self.entries.items[self.entries.items.len - 1].right = cid;
    }

    fn hash(self: SortedNode, allocator: std.mem.Allocator) !Link {
        var encoded: std.ArrayList(u8) = .empty;
        defer encoded.deinit(allocator);
        try appendNodeHeader(&encoded, allocator, self.entries.items.len);
        var previous: []const u8 = "";
        for (self.entries.items) |entry| {
            try appendNodeEntry(&encoded, allocator, previous, entry.key, .{ .raw = &entry.value }, if (entry.right) |*right| .{ .raw = right } else null);
            previous = entry.key;
        }
        try appendNodeFooter(&encoded, allocator, if (self.left) |*left| .{ .raw = left } else null);
        return hashBlock(encoded.items);
    }
};

fn hashBlock(bytes: []const u8) Link {
    var link: Link = undefined;
    link[0..4].* = .{ 1, 0x71, 0x12, 0x20 };
    std.crypto.hash.sha2.Sha256.hash(bytes, link[4..36], .{});
    return link;
}

/// Builds a root from strictly sorted key/CID pairs, copying retained keys.
/// max_node_entries is a caller-adjustable resource policy, not a format limit.
pub const SortedBuilder = struct {
    allocator: std.mem.Allocator,
    nodes: std.ArrayList(SortedNode) = .empty,
    previous: [830]u8 = undefined,
    previous_len: usize = 0,
    finished: bool = false,
    failed: bool = false,
    max_node_entries: usize = 10000,

    pub fn init(allocator: std.mem.Allocator) SortedBuilder {
        return .{ .allocator = allocator };
    }

    pub fn deinit(self: *SortedBuilder) void {
        for (self.nodes.items) |*node| node.clear(self.allocator);
        self.nodes.deinit(self.allocator);
        self.* = undefined;
    }

    pub fn add(self: *SortedBuilder, key_bytes: []const u8, value: cbor.Cid) !void {
        if (self.failed or self.finished) return error.SortedBuilderClosed;
        errdefer self.failed = true;
        if (key_bytes.len == 0 or key_bytes.len > self.previous.len) return error.InvalidKeyLength;
        if (self.previous_len > 0 and !std.mem.lessThan(u8, self.previous[0..self.previous_len], key_bytes)) return error.KeysNotIncreasing;
        if (value.raw.len != 36 or !std.mem.eql(u8, value.raw[0..4], &.{ 1, 0x71, 0x12, 0x20 })) return error.InvalidRecordCid;
        const height = keyHeight(key_bytes);
        while (self.nodes.items.len <= height) try self.nodes.append(self.allocator, .{});
        for (0..height) |i| try self.fold(i);
        const node = &self.nodes.items[height];
        if (node.entries.items.len >= self.max_node_entries) return error.NodeTooLarge;
        const key = try self.allocator.dupe(u8, key_bytes);
        errdefer self.allocator.free(key);
        try node.entries.append(self.allocator, .{ .key = key, .value = value.raw[0..36].* });
        @memcpy(self.previous[0..key_bytes.len], key_bytes);
        self.previous_len = key_bytes.len;
    }

    fn fold(self: *SortedBuilder, i: usize) !void {
        const node = &self.nodes.items[i];
        if (node.empty()) return;
        const cid = try node.hash(self.allocator);
        self.nodes.items[i + 1].link(cid);
        node.clear(self.allocator);
    }

    pub fn finish(self: *SortedBuilder) ![36]u8 {
        if (self.failed or self.finished) return error.SortedBuilderClosed;
        errdefer self.failed = true;
        if (self.nodes.items.len == 0) try self.nodes.append(self.allocator, .{});
        for (0..self.nodes.items.len - 1) |i| try self.fold(i);
        const actual = try self.nodes.items[self.nodes.items.len - 1].hash(self.allocator);
        self.finished = true;
        return actual;
    }
};

test "sorted builder owns input and closes on resource and ordering failures" {
    const a = std.testing.allocator;
    var cid = hashBlock(&.{0xa0});
    var builder = SortedBuilder.init(a);
    defer builder.deinit();
    var key = "app.bsky.feed.post/1".*;
    try builder.add(&key, .{ .raw = &cid });
    @memset(&key, 0);
    @memset(&cid, 0);
    _ = try builder.finish();
    try std.testing.expectError(error.SortedBuilderClosed, builder.finish());
    var limited = SortedBuilder.init(a);
    defer limited.deinit();
    limited.max_node_entries = 0;
    const valid = hashBlock(&.{0xa0});
    try std.testing.expectError(error.NodeTooLarge, limited.add("a", .{ .raw = &valid }));
    try std.testing.expectError(error.SortedBuilderClosed, limited.finish());
    var unordered = SortedBuilder.init(a);
    defer unordered.deinit();
    try unordered.add("b", .{ .raw = &valid });
    try std.testing.expectError(error.KeysNotIncreasing, unordered.add("a", .{ .raw = &valid }));
    try std.testing.expectError(error.SortedBuilderClosed, unordered.finish());
    var invalid = SortedBuilder.init(a);
    defer invalid.deinit();
    try std.testing.expectError(error.InvalidRecordCid, invalid.add("a", .{ .raw = "bad" }));
}