//! The same-path lineage walk: which file blob each check-in records under
//! each path, and which sub-manifest node of a check-in pairs with its primary
//! parent's node under the same partition key. `zit pack` derives its base
//! hints from it over one log (pack.zig), and a pull or a served push derives
//! the delta bases for artifacts that arrived whole from it over the received
//! set and the store beside it (receive.zig). One walk, two sources.
//!
//! `Walker(Source)` is generic over where artifacts come from. `Source`
//! supplies:
//!
//! * `Id` — an artifact identity, compared with `==`;
//! * `find(self, hex, digest) Error!?Id` — the artifact a card names when it is
//! held, readable and kept; null for an absent, phantom or filtered one;
//! * `content(self, gpa, id) Error!?[]u8` — its plaintext, owned by the
//! caller; null when it does not read;
//! * `offerBase(self, gpa, child, base) Error!void` — a changed sub-manifest
//! node and its parent's node under the same partition key. The source
//! decides whether the pair is usable (pack: the base must precede the
//! child in the log).
//!
//! `find` is the filter, and it runs before `content`: a dropped artifact's
//! bytes may be corrupt, so the walk never reconstructs one (pack.zig states
//! why that ordering is normative).
const std = @import("std");
const artifact = @import("../artifact/artifact.zig");
const digest_name = @import("../core/digest_name.zig");
const digest_len = digest_name.digest_len;
const hexToDigest = digest_name.hexToDigest;
pub const Error = error{ OutOfMemory, Storage, Corrupt };
/// Whether `prefix` -- the first bytes of an artifact -- could begin a
/// structural artifact under [FossilArtifact] §4.4, where a card is a card-type
/// letter followed by zero or more space-separated tokens.
///
/// One-sided by design: false means the artifact provably is not structural,
/// true means only "not ruled out", and the parser still decides. Fewer than
/// two bytes is not enough to rule anything out, so it answers true. Keeping
/// the error on the permissive side is what lets a caller skip the reject case
/// without changing any answer.
pub fn couldStartStructural(prefix: []const u8) bool {
if (prefix.len < 2) return true;
if (prefix[0] < 'A' or prefix[0] > 'Z') return false;
// The delimiter after a card's type letter: a space before its first token,
// or the LF of a card that carries none.
return prefix[1] == ' ' or prefix[1] == '\n';
}
pub fn Walker(comptime Source: type) type {
return struct {
pub const Id = Source.Id;
/// path → the distinct blob versions recorded under it, in walk order
/// (a consecutive repeat is recorded once). Keys are owned dups.
pub const Paths = std.StringHashMapUnmanaged(std.ArrayListUnmanaged(Id));
const Keys = std.StringHashMapUnmanaged(Id);
const Seen = std.AutoHashMapUnmanaged(Id, void);
pub fn deinitPaths(gpa: std.mem.Allocator, paths: *Paths) void {
var it = paths.iterator();
while (it.next()) |e| {
e.value_ptr.deinit(gpa);
gpa.free(e.key_ptr.*);
}
paths.deinit(gpa);
}
/// Record check-in `m`'s file blobs under their paths and offer its
/// changed sub-manifest nodes against `parent`'s. A tree check-in is
/// diffed LOCKSTEP against its primary parent (`diffTreeVersions`),
/// descending only where the two trees differ, so the walk costs
/// O(changed paths) rather than O(tree). Without a usable parent -- a
/// root, or a parent that does not read or parse -- or for a flat
/// check-in, the child is walked in full. The parent's own blobs are
/// never recorded here: it records them on its own walk, and recording
/// them twice would let a revert reappear as a duplicate version.
pub fn checkin(
gpa: std.mem.Allocator,
src: *Source,
paths: *Paths,
m: *const artifact.Manifest,
parent: ?Id,
) Error!void {
var child_keys: Keys = .empty;
defer deinitPartitionKeys(gpa, &child_keys);
var child_seen: Seen = .empty;
defer child_seen.deinit(gpa);
var walked_lockstep = false;
// A child without S nodes fills no partition-key map, so there is
// nothing to pair -- skip the parent read and parse outright.
if (m.s.len != 0) {
if (parent) |prid| lockstep: {
// `pbytes` must outlive the parse: the manifest's card
// slices borrow it, and freeing it at block exit left every
// S-card hash pointing into freed memory -- which surfaced
// as a "corrupt" store on a perfectly healthy tree
// repository.
const pbytes = (try src.content(gpa, prid)) orelse break :lockstep;
defer gpa.free(pbytes);
var pl = artifact.parseForImport(gpa, pbytes) catch |e| switch (e) {
error.OutOfMemory => return error.OutOfMemory,
else => break :lockstep,
};
defer pl.deinit(gpa);
if (pl.manifest.kind != .manifest) break :lockstep;
// The S nodes pair with the PRIMARY parent's under an
// exactly equal canonical partition key. Walked rather than
// pooled because the design names the parent specifically --
// an offset-nearest node from an unrelated branch is the
// heuristic the storage design forbids.
var parent_keys: Keys = .empty;
defer deinitPartitionKeys(gpa, &parent_keys);
var parent_seen: Seen = .empty;
defer parent_seen.deinit(gpa);
try diffTreeVersions(gpa, src, paths, &child_keys, &child_seen, &parent_keys, &parent_seen, m.f, m.s, pl.manifest.s, 0);
try pairAgainstParent(gpa, src, &child_keys, &parent_keys);
walked_lockstep = true;
}
}
if (!walked_lockstep) {
try recordTreeVersions(gpa, src, paths, &child_keys, &child_seen, m.f, m.s, 0);
}
}
/// For every partition key the child and parent both carry, offer the
/// parent's node as a delta base for the child's. An equal id -- the
/// SAME subtree in both check-ins -- pairs nothing, which is exactly why
/// the walk that feeds this never descends into one.
fn pairAgainstParent(
gpa: std.mem.Allocator,
src: *Source,
child_keys: *const Keys,
parent_keys: *const Keys,
) Error!void {
var kit = child_keys.iterator();
while (kit.next()) |e| {
const base = parent_keys.get(e.key_ptr.*) orelse continue;
// "not an interior node delta-based on its own descendant": an
// equal id is the same artifact.
if (base == e.value_ptr.*) continue;
try src.offerBase(gpa, e.value_ptr.*, base);
}
}
/// Walk one check-in's complete file enumeration -- F leaves and S
/// children to the full tree height (submanifests §5.1). Blobs go into
/// `paths`, shared across check-ins, because same-path versions are a
/// property of the whole history; S nodes go into `keys`, private to
/// this check-in, because a node pairs only with its PRIMARY parent's
/// node under the same partition key. Reading `m.f` alone would give a
/// tree-shaped repository no file versions at all.
///
/// Recursion is bounded by `artifact.max_tree_depth`, and `seen`
/// collapses a diamond and rejects a cycle. A node the source does not
/// hold is a valid absence (a phantom reference, as Fossil treats one);
/// a held node that will not parse is corruption and aborts.
fn recordTreeVersions(
gpa: std.mem.Allocator,
src: *Source,
paths: ?*Paths,
keys: *Keys,
seen: *Seen,
files: []const artifact.FCard,
subs: []const artifact.SCard,
depth: usize,
) Error!void {
std.debug.assert(depth <= artifact.max_tree_depth);
try recordFileBlobs(gpa, src, paths, files);
for (subs) |sc| {
// An absent, phantom or filtered node is excluded rather than
// fatal: a phantom reference is valid, and a filter removing
// it is a decision the caller already made.
const sub = (try heldNode(src, sc.hash)) orelse continue;
if ((try seen.getOrPut(gpa, sub)).found_existing) continue;
// The S card's filename IS the canonical partition key (§3.6).
// Exact match only -- the design forbids any nearest-key
// heuristic. First writer wins so a duplicate key inside one
// tree cannot silently retarget the pair.
_ = try putPartitionKey(gpa, keys, sc.filename, sub);
if (depth == artifact.max_tree_depth) return error.Corrupt; // §5.3 bound
var ls = try loadSubManifest(gpa, src, sub);
// The recursion borrows `ls`'s card slices, which this defer
// keeps alive for exactly this scope (`bytes` backs them).
defer ls.deinit(gpa);
try recordTreeVersions(gpa, src, paths, keys, seen, ls.loaded.manifest.f, ls.loaded.manifest.s, depth + 1);
}
}
/// The leaf rule, shared by every walk that visits a tree level: each
/// held, kept, non-phantom F-card blob is recorded under its path. A
/// `null` map is the parent-side walk, which records nothing.
fn recordFileBlobs(
gpa: std.mem.Allocator,
src: *Source,
paths: ?*Paths,
files: []const artifact.FCard,
) Error!void {
const pmap = paths orelse return;
for (files) |fc| {
const bh = fc.hash orelse continue;
var digest_buf: [digest_len]u8 = undefined;
const digest = hexToDigest(bh, &digest_buf) orelse continue;
const blob = (try src.find(bh, digest)) orelse continue;
try recordPathBlob(gpa, pmap, fc.filename, blob);
}
}
/// First-writer-wins insert of `key → id` into a partition-key map,
/// OWNING a dup of the key bytes. The caller's `key` borrows the
/// manifest bytes of the node being walked, and for every node below
/// depth 0 those are the `bytes`/`loaded` pair the walking frame frees
/// on return -- so a borrowed key would outlive its backing store by
/// exactly one recursion level. On a dupe OOM, drop the half-inserted
/// slot so teardown never frees borrowed bytes. Returns whether this
/// call was the first writer for `key`.
fn putPartitionKey(gpa: std.mem.Allocator, keys: *Keys, key: []const u8, id: Id) Error!bool {
const gop = keys.getOrPut(gpa, key) catch return error.OutOfMemory;
if (gop.found_existing) return false;
const owned = gpa.dupe(u8, key) catch {
// The removal is the OPERATION, so it is not an assert's
// argument: under `ReleaseFast` the assert vanishes and would
// take the cleanup with it.
const removed = keys.remove(key);
std.debug.assert(removed);
return error.OutOfMemory;
};
gop.key_ptr.* = owned;
gop.value_ptr.* = id;
return true;
}
/// One resolved, validated sub-manifest node. `bytes` backs every card
/// slice in `loaded`, so both live and die together.
const LoadedSub = struct {
bytes: []u8,
loaded: artifact.ImportedManifest,
fn deinit(self: *LoadedSub, gpa: std.mem.Allocator) void {
self.loaded.deinit(gpa);
gpa.free(self.bytes);
self.* = undefined;
}
};
/// Read and parse the sub-manifest node `id` under the corruption rule
/// every tree walk shares: a referenced S node that will not
/// reconstruct, parse, or claim the `.submanifest` kind is CORRUPTION
/// and aborts.
fn loadSubManifest(gpa: std.mem.Allocator, src: *Source, id: Id) Error!LoadedSub {
const bytes = (try src.content(gpa, id)) orelse return error.Corrupt;
errdefer gpa.free(bytes);
var loaded = artifact.parseForImport(gpa, bytes) catch |e| switch (e) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.Corrupt,
};
if (loaded.manifest.kind != .submanifest) {
loaded.deinit(gpa);
return error.Corrupt;
}
return .{ .bytes = bytes, .loaded = loaded };
}
/// The node an S card names, or null when the source does not hold
/// it (absent, a phantom, or filtered): a valid absence for hint
/// gathering. A hash that is not hex is malformed and aborts.
fn heldNode(src: *Source, hash: []const u8) Error!?Id {
var digest_buf: [digest_len]u8 = undefined;
const digest = hexToDigest(hash, &digest_buf) orelse return error.Corrupt;
return try src.find(hash, digest);
}
/// Record blobs and pair nodes in ONE pass: walk the child's tree
/// LOCKSTEP against the primary parent's, descending only where the
/// two trees DIFFER.
///
/// The prune rule: an S card whose canonical partition key AND
/// resolved node both match the parent's names the SAME subtree in
/// both check-ins, and nothing below it can contribute. Pairing takes
/// only DIFFERING same-key nodes, and every blob under a shared subtree
/// was recorded by the check-in that INTRODUCED the subtree -- which
/// walked it as a changed one, recursively back to a full root or
/// fallback walk. Both flat maps still receive a pruned node's own key,
/// so `pairAgainstParent` over the visited keys yields exactly the
/// pairs two full walks would. This is what turns the walk from
/// O(check-ins x tree size) into O(check-ins x changed paths).
///
/// Corruption detection is preserved: every DISTINCT sub-manifest a
/// walked check-in references is still resolved and parsed at least
/// once -- at the first check-in that references it, its key has no
/// parent counterpart, a differing one, or the same node in a parent
/// walked before it, back to a root or fallback full walk. The §5.3
/// depth bound and the `seen` cycle/diamond guards apply to both sides.
fn diffTreeVersions(
gpa: std.mem.Allocator,
src: *Source,
paths: *Paths,
child_keys: *Keys,
child_seen: *Seen,
parent_keys: *Keys,
parent_seen: *Seen,
c_files: []const artifact.FCard,
c_subs: []const artifact.SCard,
p_subs: []const artifact.SCard,
depth: usize,
) Error!void {
std.debug.assert(depth <= artifact.max_tree_depth);
// The child's F leaves at this (visited) level. The parent's F
// leaves are never recorded.
try recordFileBlobs(gpa, src, paths, c_files);
// Index the parent's S cards at this level by canonical partition
// key -- first writer wins, mirroring the flat maps' own insert
// rule. Keys borrow the parent node's card bytes, which the caller
// keeps alive for exactly this frame. `matched` marks cards
// consumed by the child loop so the sweep below descends only the
// parent-only remainder.
var pidx: std.StringHashMapUnmanaged(usize) = .empty;
defer pidx.deinit(gpa);
for (p_subs, 0..) |psc, i| {
const gop = pidx.getOrPut(gpa, psc.filename) catch return error.OutOfMemory;
if (!gop.found_existing) gop.value_ptr.* = i;
}
const matched = gpa.alloc(bool, p_subs.len) catch return error.OutOfMemory;
defer gpa.free(matched);
@memset(matched, false);
for (c_subs) |sc| {
// The child-side checks, in `recordTreeVersions`'s exact order.
const sub = (try heldNode(src, sc.hash)) orelse continue;
if ((try child_seen.getOrPut(gpa, sub)).found_existing) continue;
const first_key_writer = try putPartitionKey(gpa, child_keys, sc.filename, sub);
// The parent's same-key node at this level, resolved with the
// same strictness. A duplicate child key gets no counterpart --
// the flat map gave a second writer no pairing entry either --
// and falls through to the full descent.
var parent_node: ?Id = null;
if (first_key_writer) {
if (pidx.get(sc.filename)) |pi| {
if (!matched[pi]) {
if (try heldNode(src, p_subs[pi].hash)) |pnode| {
matched[pi] = true;
if (!(try parent_seen.getOrPut(gpa, pnode)).found_existing) {
_ = try putPartitionKey(gpa, parent_keys, p_subs[pi].filename, pnode);
parent_node = pnode;
}
}
}
}
}
if (parent_node) |pnode| {
// THE PRUNE: same key, same artifact -- the subtree below
// is byte-shared with the parent, so nothing under it can
// pair or add a version. Both maps already carry the key.
if (pnode == sub) continue;
// Same key, different node: a changed subtree. Descend
// both sides together.
if (depth == artifact.max_tree_depth) return error.Corrupt; // §5.3 bound
var cls = try loadSubManifest(gpa, src, sub);
defer cls.deinit(gpa);
var pls = try loadSubManifest(gpa, src, pnode);
defer pls.deinit(gpa);
try diffTreeVersions(gpa, src, paths, child_keys, child_seen, parent_keys, parent_seen, cls.loaded.manifest.f, cls.loaded.manifest.s, pls.loaded.manifest.s, depth + 1);
} else {
// No same-key counterpart: a new, renamed, or split
// subtree, or a filtered/diamond-collapsed parent side.
// Walk the child side alone, in full -- this node's own
// checks and inserts already ran, so recurse with its
// cards directly.
if (depth == artifact.max_tree_depth) return error.Corrupt; // §5.3 bound
var cls = try loadSubManifest(gpa, src, sub);
defer cls.deinit(gpa);
try recordTreeVersions(gpa, src, paths, child_keys, child_seen, cls.loaded.manifest.f, cls.loaded.manifest.s, depth + 1);
}
}
// Parent-only cards: subtrees the child dropped, renamed, or merged
// away at this level. Their keys can still pair a child key found
// ELSEWHERE in the tree -- a subtree that moved between levels --
// so they keep the full parent-side descent.
for (p_subs, 0..) |psc, i| {
if (matched[i]) continue;
const pnode = (try heldNode(src, psc.hash)) orelse continue;
if ((try parent_seen.getOrPut(gpa, pnode)).found_existing) continue;
_ = try putPartitionKey(gpa, parent_keys, psc.filename, pnode);
if (depth == artifact.max_tree_depth) return error.Corrupt; // §5.3 bound
var pls = try loadSubManifest(gpa, src, pnode);
defer pls.deinit(gpa);
try recordTreeVersions(gpa, src, null, parent_keys, parent_seen, pls.loaded.manifest.f, pls.loaded.manifest.s, depth + 1);
}
}
/// Tear down a partition-key map, whose keys `putPartitionKey` owns.
fn deinitPartitionKeys(gpa: std.mem.Allocator, keys: *Keys) void {
var it = keys.keyIterator();
while (it.next()) |key| gpa.free(key.*);
keys.deinit(gpa);
}
fn recordPathBlob(gpa: std.mem.Allocator, paths: *Paths, path: []const u8, blob: Id) Error!void {
std.debug.assert(path.len > 0); // an F-card filename is never empty
const gop = paths.getOrPut(gpa, path) catch return error.OutOfMemory;
if (!gop.found_existing) {
// The slot's key is still the caller's borrowed `path`. Own it
// before any later free can touch it; on a dupe OOM, drop the
// half-inserted slot so the map's teardown never frees
// borrowed bytes or reads an undefined list.
const owned = gpa.dupe(u8, path) catch {
const removed = paths.remove(path);
std.debug.assert(removed);
return error.OutOfMemory;
};
gop.key_ptr.* = owned;
gop.value_ptr.* = .empty;
}
const list = gop.value_ptr;
if (list.items.len > 0 and list.items[list.items.len - 1] == blob) return;
list.append(gpa, blob) catch return error.OutOfMemory;
}
};
}