//! Test fixtures the sync-family verb tests share: seeded stores, wire
//! stores and canned replies. Test-only; no verb calls into it.
const std = @import("std");
const artifact = zit.artifact;
const digest_len = zit.digest_name.digest_len;
const logstore = @import("zit").logstore;
const repeat = @import("zit").repeat;
const repo_filename = zit.repo_filename;
const storage = @import("zit").storage;
const zit = @import("zit");
// --- D4: client verbatim retention + the §7.7 persist hook ------------------
/// Create a fresh, empty (header-only, committed) `.zit` in `dir` so a
/// `persistStore` test can persist into it, exactly like a just-cloned repo.
pub fn d4SeedEmptyRepo(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir) !void {
const hash_kind: u8 = @backingInt(zit.artifact.defaultPolicy(false, false));
var f = try dir.createFile(io, repo_filename, .{ .read = true, .exclusive = true });
defer f.close(io);
var fs = storage.FileStorage.init(io, f, 0);
var seed = try logstore.LogStore.open(gpa, fs.storageFile(), hash_kind);
defer seed.deinit(gpa);
try seed.commit();
}
/// Reopen the persisted `.zit` in `dir` for reading. `fs_out` is a caller-owned
/// `FileStorage` that MUST outlive the returned `LogStore` (its `storageFile()`
/// vtable borrows `fs_out`); the caller closes `fs_out.file` and deinits `log`.
pub fn d4OpenLog(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, fs_out: *storage.FileStorage) !logstore.LogStore {
const file = try dir.openFile(io, repo_filename, .{ .mode = .read_write });
const st = try file.stat(io);
fs_out.* = storage.FileStorage.init(io, file, st.size);
return try logstore.LogStore.open(gpa, fs_out.storageFile(), 0);
}
pub fn d4SeedConfiguredRepo(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir) !void {
const hash_kind: u8 = @backingInt(zit.artifact.defaultPolicy(false, false));
var f = try dir.createFile(io, repo_filename, .{ .read = true, .exclusive = true });
defer f.close(io);
var fs = storage.FileStorage.init(io, f, 0);
var seed = try logstore.LogStore.open(gpa, fs.storageFile(), hash_kind);
defer seed.deinit(gpa);
try seed.putConfig(.{
.hash_policy = 9,
.default_branch = "stable",
.project_id = "project",
.project_code = "init-code",
.login_user = "operator",
.login_secret_hex = repeat("0", 40),
.remote_url = "https://example.test/remote",
.seen_submanifest = true,
.enable_submanifests = false,
.submanifest_k = 3,
.submanifest_auto_retune = false,
.submanifest_settled_cost_shape = @as([32]u8, @splat(0x42)),
});
try seed.commit();
}
/// A tree manifest naming `subs` (submanifests §3.6), plus the §6.2 Z card, so
/// the fixture is a well-formed card sequence rather than a bare S run.
pub fn treeManifestBytes(gpa: std.mem.Allocator, subs: []const []const u8) ![]u8 {
var body: std.ArrayListUnmanaged(u8) = .empty;
defer body.deinit(gpa);
try body.appendSlice(gpa, "C tree\nD 2026-07-27T12:00:00.000\n");
// §3.4 — the S run ascends by filename; `a`, `b`, ... keeps it legal.
for (subs, 0..) |h, i| {
try body.print(gpa, "S {c}.txt {s}\n", .{ @as(u8, 'a') + @as(u8, @intCast(i)), h });
}
try body.appendSlice(gpa, "U u\n");
var digest: [16]u8 = undefined;
std.crypto.hash.Md5.hash(body.items, &digest, .{});
return std.fmt.allocPrint(gpa, "{s}Z {x}\n", .{ body.items, &digest });
}
/// Build a full-form 3-check-in chain over an evolving file into `log`, plus a
/// live config frame; returns the tip check-in's 64-hex name. Every blob and
/// manifest lands as a FULL frame — pack's re-delta target.
pub fn packSeedFullStore(gpa: std.mem.Allocator, log: *logstore.LogStore, tip_out: *[64]u8) !void {
try log.putConfig(.{ .hash_policy = 2, .default_branch = "trunk", .project_id = "pid", .project_code = "code-abc" });
var root_name: [64]u8 = undefined;
var mid_name: [64]u8 = undefined;
const v1 = try packEvolvingBlob(gpa, 1);
defer gpa.free(v1);
const b1 = try packSeedBlob(log, v1);
try packSeedCheckin(gpa, log, "2020-01-01T00:00:00", null, "f.txt", &b1, &root_name);
const v2 = try packEvolvingBlob(gpa, 2);
defer gpa.free(v2);
const b2 = try packSeedBlob(log, v2);
try packSeedCheckin(gpa, log, "2020-01-02T00:00:00", &root_name, "f.txt", &b2, &mid_name);
const v3 = try packEvolvingBlob(gpa, 3);
defer gpa.free(v3);
const b3 = try packSeedBlob(log, v3);
try packSeedCheckin(gpa, log, "2020-01-03T00:00:00", &mid_name, "f.txt", &b3, tip_out);
try log.commit();
}
/// Store `content` under its sha3-256 name, delta-encoded against `base` when
/// one is given (the evolving blobs delta to a fraction, so the frame lands as a
/// `.delta`), and return its rid. Models a fossil-clone store that RETAINED
/// compact wire deltas rather than full frames.
fn packSeedDeltaBlob(log: *logstore.LogStore, content: []const u8, base: ?logstore.Rid) !logstore.Rid {
var digest: [digest_len]u8 = undefined;
std.crypto.hash.sha3.Sha3_256.hash(content, &digest, .{});
return log.putArtifact(&digest, content, base);
}
/// Build a clone-shaped store whose successive blobs are RETAINED as `.delta`
/// frames (the compact wire form), under DISTINCT filenames so pack's
/// same-path-blob lineage hint finds NO base for them — exactly the case where
/// the old pack reconstructed every delta to a full frame and inflated the
/// store. `.zit` therefore holds real delta frames whose bases pack cannot
/// re-derive, so a correct pack must preserve them verbatim. Returns the tip
/// check-in's 64-hex name.
pub fn packSeedDeltaStore(gpa: std.mem.Allocator, log: *logstore.LogStore, tip_out: *[64]u8) !void {
try log.putConfig(.{ .hash_policy = 2, .default_branch = "trunk", .project_id = "pid", .project_code = "code-abc" });
var root_name: [64]u8 = undefined;
var mid_name: [64]u8 = undefined;
const v1 = try packEvolvingBlob(gpa, 1);
defer gpa.free(v1);
const r1 = try packSeedDeltaBlob(log, v1, null); // first version: full frame (base of the chain)
var b1: [64]u8 = undefined;
_ = zit.artifact.artifactName(.sha3_256, v1, &b1);
try packSeedCheckin(gpa, log, "2020-01-01T00:00:00", null, "f1.txt", &b1, &root_name);
const v2 = try packEvolvingBlob(gpa, 2);
defer gpa.free(v2);
const r2 = try packSeedDeltaBlob(log, v2, r1); // delta of v1
var b2: [64]u8 = undefined;
_ = zit.artifact.artifactName(.sha3_256, v2, &b2);
try packSeedCheckin(gpa, log, "2020-01-02T00:00:00", &root_name, "f2.txt", &b2, &mid_name);
const v3 = try packEvolvingBlob(gpa, 3);
defer gpa.free(v3);
_ = try packSeedDeltaBlob(log, v3, r2); // delta of v2
var b3: [64]u8 = undefined;
_ = zit.artifact.artifactName(.sha3_256, v3, &b3);
try packSeedCheckin(gpa, log, "2020-01-03T00:00:00", &mid_name, "f3.txt", &b3, tip_out);
try log.commit();
}
/// Append one content frame (raw `digest` naming `bytes`) to the `.zit` in
/// `dir`, creating the repository on first call — a separate writer's committed
/// append, exactly what a `zit commit` alongside a live `zit serve` performs.
pub fn serveAppendFrame(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, digest: []const u8, bytes: []const u8) !void {
const hash_kind: u8 = @backingInt(zit.artifact.defaultPolicy(false, false));
var f = dir.openFile(io, repo_filename, .{ .mode = .read_write }) catch
try dir.createFile(io, repo_filename, .{ .read = true });
defer f.close(io);
const st = try f.stat(io);
var fs = storage.FileStorage.init(io, f, st.size);
var log = try logstore.LogStore.open(gpa, fs.storageFile(), hash_kind);
defer log.deinit(gpa);
_ = try log.put(digest, bytes);
try log.commit();
}
// ---------------------------------------------------------------------------
// sync §3.3 L553-556 / §8.8 L1839-1841 — the durable side of the phantom-scan
// shun filter: the repository shun table, snapshotted off the log and answered
// as a wire-name question. `RepoShunSet` lives above with `LogIndexStore`; these
// tests pin the key domain and the end-to-end suppression.
// ---------------------------------------------------------------------------
/// The shunned artifact's digest and its complete 64-hex wire name. 's' is 0x73,
/// so the name is the byte pattern spelled out — no runtime encode in the vector.
pub const shun_test_digest = repeat("s", digest_len);
pub const shun_test_name = repeat("73", digest_len);
/// A second artifact the repo actually holds ('h' is 0x68), to prove the filter
/// suppresses only the shunned name.
pub const shun_test_held_digest = repeat("h", digest_len);
pub const shun_test_held_name = repeat("68", digest_len);
/// A third shunned digest whose hex spelling contains LETTER nibbles, so the
/// uppercase-spelling question below is a real one.
const shun_test_letter_digest = repeat("\xab", digest_len);
comptime {
std.debug.assert(shun_test_name.len == 2 * digest_len);
std.debug.assert(logstore.isCompleteDigest(shun_test_digest.len));
}
/// Seed `dir`'s repository with one held artifact and one shun row naming an
/// artifact it does NOT hold — exactly the state a `zit shun` on a hash the peer
/// still offers leaves behind.
pub fn seedShunnedRepo(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir) !void {
const hk: u8 = @backingInt(zit.artifact.defaultPolicy(false, false));
var f = try dir.createFile(io, repo_filename, .{ .read = true });
defer f.close(io);
var fs = storage.FileStorage.init(io, f, 0);
var log = try logstore.LogStore.open(gpa, fs.storageFile(), hk);
defer log.deinit(gpa);
try log.putConfig(.{ .hash_policy = hk, .default_branch = "trunk", .project_id = "", .project_code = "" });
_ = try log.put(shun_test_held_digest, "held content\n");
try log.putShun(shun_test_digest, "operator request", 1);
try log.putShun(shun_test_letter_digest, "operator request", 1);
try log.commit();
}
// ---------------------------------------------------------------------------
// sync §9.5 L2170-2174 — the SEND side of the shun filter.
//
// "A subsequent read-authorized transfer path requests igot for every
// eligible holding after the Section 3.3 shun, phantom, private, and
// peer-has filters"
//
// `LogIndexStore`'s enumeration is that "every eligible holding", so the shun
// filter belongs in the enumeration itself: a shunned holding is masked, which
// makes the server neither `igot`-announce it (the §3.2 walk's `held()` gate
// answers false) nor serve it in a clone batch (no wire form, no content), and
// makes an inbound `gimme` for it land on §3.3 L569-572's *"If absent, silently
// skip"* with no code on that path — the name is simply not in `by_name`.
//
// Which of those three the MASK is load-bearing for, stated honestly: the igot
// announcement and the `gimme` miss are new here — nothing else suppressed them.
// The clone batch was already covered by `LogStore.wire`/`content`'s own rid-keyed
// read mask, which the pager gates on; the mask's contribution there is that the
// pager's cursor stays contiguous over the survivors (see the clone-pager test).
//
// The mask is a MASK, not a removal, and §8.2 L1551-1553 is why:
//
// "SEQNO is a server blob-table RID. Iterate from supplied RID through
// current maximum, silently skipping gaps; clients MUST NOT infer count
// or size from range."
//
// Dropping the shunned frame from the enumeration would renumber every survivor
// above it. The server is stateless (§8.9 L1855-1856) — the client's SEQNO *is* the
// clone cursor — and a shun row appended between two rounds of one clone grows
// the log, which is exactly what trips `ServeCtx.baseSnapshot`'s append-only stat
// gate and forces a rebuild. Under renumbering the resuming client's cursor would
// then step over a survivor and still be told the sequence was complete: a
// silently short clone, the failure class `read_fault` exists to prevent. Keeping
// the slot and answering it as a §8.2 GAP makes adapter-rid identity a pure
// function of the log, independent of the shun table.
// ---------------------------------------------------------------------------
/// Five artifact digests in persisted order. Distinct byte fills, so each wire
/// name is the pattern spelled out and no vector needs a runtime encode.
pub const send_shun_digests = [5][]const u8{
repeat("\x11", digest_len),
repeat("\x22", digest_len),
repeat("\x33", digest_len),
repeat("\x44", digest_len),
repeat("\x55", digest_len),
};
pub const send_shun_names = [5][]const u8{
repeat("11", digest_len),
repeat("22", digest_len),
repeat("33", digest_len),
repeat("44", digest_len),
repeat("55", digest_len),
};
// ---------------------------------------------------------------------------
// sync §7.7 L1463-1467 — the hash-policy half of the receive-side admission
// predicate, from the REPOSITORY's stored config to the receiver that asks it.
//
// "shun-sha1 applies exactly when the receiving repository's effective
// hash-policy value at the start of processing that card is the shun-sha1
// value defined by [FossilArtifact], Section 7."
//
// The tests below exist because every §7.7 unit test in `sync_test.zig` sets
// `Client.hash_policy` / `Server.hash_policy` on a struct literal. That pins the
// RULE and proves nothing about the WIRING, so a regression that dropped
// `effectiveHashPolicy` — or read the wrong config field — would ship green.
// These two close that: one over the stored byte, one over the served round.
// ---------------------------------------------------------------------------
/// Seed `dir` with a repository whose config frame names `policy` and which
/// holds nothing. The empty holdings matter: the push below must be the only
/// thing that could ever land.
pub fn s77SeedPolicyRepo(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, policy: artifact.HashPolicy) !void {
const hk: u8 = @backingInt(zit.artifact.defaultPolicy(false, false));
var f = try dir.createFile(io, repo_filename, .{ .read = true, .exclusive = true });
defer f.close(io);
var fs = storage.FileStorage.init(io, f, 0);
var log = try logstore.LogStore.open(gpa, fs.storageFile(), hk);
defer log.deinit(gpa);
try log.putConfig(.{
.hash_policy = @backingInt(policy),
.default_branch = "trunk",
.project_id = "",
.project_code = "",
});
try log.commit();
}
// ===========================================================================
// `zit pack` — repack/GC tests. Storage on-disk layout is unspecified by the
// RFCs, so the oracle is the store's OWN semantics: every artifact's content
// and name survive a repack byte-for-byte, the set is preserved (no drop), the
// §7.7 name↔content invariant is re-checked before every write, the packed
// bytes are a deterministic function of the source content (idempotent), and a
// crash before the atomic rename leaves the original store untouched. Stores
// are built as FULL frames (the migration shape pack exists to compact),
// through the real `LogStore`/`artifact` — never seeded from fossil.
// ===========================================================================
/// Store `content` as a FULL raw frame and return its 64-hex artifact name.
pub fn packSeedBlob(log: *logstore.LogStore, content: []const u8) ![64]u8 {
var digest: [zit.digest_name.digest_len]u8 = undefined;
std.crypto.hash.sha3.Sha3_256.hash(content, &digest, .{});
_ = try log.put(&digest, content);
var name: [64]u8 = undefined;
_ = zit.artifact.artifactName(.sha3_256, content, &name);
return name;
}
/// Serialize and store (as a FULL frame) a one-file check-in manifest snapshotting
/// `file_name` → `blob_name`, optionally descended from `parent_name`. Writes the
/// manifest's own 64-hex name into `name_out`. Root check-ins carry a propagating
/// `branch=trunk` T card; children carry the parent P card and inherit trunk.
pub fn packSeedCheckin(
gpa: std.mem.Allocator,
log: *logstore.LogStore,
ts: []const u8,
parent_name: ?[]const u8,
file_name: []const u8,
blob_name: []const u8,
name_out: *[64]u8,
) !void {
var pbuf: [1]zit.artifact.PCard = undefined;
var p_slice: []const zit.artifact.PCard = &.{};
if (parent_name) |pn| {
pbuf[0] = .{ .parents = pn, .count = 1 };
p_slice = pbuf[0..1];
}
const fcards = [_]zit.artifact.FCard{
.{ .filename = file_name, .hash = blob_name, .perm = null, .old_name = null, .mode = .regular },
};
const root_tags = [_]zit.artifact.TCard{
.{ .sign = .propagate, .name = "branch", .target = null, .value = "trunk" },
};
var m: zit.artifact.Manifest = .{
.arena_state = std.heap.ArenaAllocator.init(gpa),
.kind = .manifest,
.a = null,
.b = null,
.c = .{ .comment = "c" },
.d = .{ .timestamp = ts },
.e = null,
.g = null,
.h = null,
.i = null,
.k = null,
.l = null,
.n = null,
.r = null,
.u = .{ .login = "u" },
.z = null,
.w = null,
.f = &fcards,
.j = &.{},
.m = &.{},
.p = p_slice,
.q = &.{},
.t = if (parent_name == null) &root_tags else &.{},
};
defer m.deinit();
const bytes = try zit.artifact.create(&m, gpa);
defer gpa.free(bytes);
var digest: [zit.digest_name.digest_len]u8 = undefined;
std.crypto.hash.sha3.Sha3_256.hash(bytes, &digest, .{});
_ = try log.put(&digest, bytes);
_ = zit.artifact.artifactName(.sha3_256, bytes, name_out);
}
/// A large, near-identical evolving file: 128 identical lines plus a per-version
/// trailer, so successive versions delta to a fraction of the full blob (the
/// change is materially < 90%). Caller frees.
pub fn packEvolvingBlob(gpa: std.mem.Allocator, version: u8) ![]u8 {
var buf: std.ArrayList(u8) = .empty;
errdefer buf.deinit(gpa);
var i: usize = 0;
while (i < 128) : (i += 1) try buf.print(gpa, "line {d} of the tracked file\n", .{i});
try buf.print(gpa, "trailer version {d}\n", .{version});
return buf.toOwnedSlice(gpa);
}
/// Open a fresh, empty (header + config-less) writable `.zit` in `dir`.
pub fn packOpenWritable(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, fs_out: *storage.FileStorage) !logstore.LogStore {
const hash_kind: u8 = @backingInt(zit.artifact.defaultPolicy(false, false));
const f = try dir.createFile(io, repo_filename, .{ .read = true, .exclusive = true });
fs_out.* = storage.FileStorage.init(io, f, 0);
return logstore.LogStore.open(gpa, fs_out.storageFile(), hash_kind);
}
/// Reopen an existing `.zit` in `dir` read-only.
pub fn packOpenReadOnly(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, fs_out: *storage.FileStorage) !logstore.LogStore {
const f = try dir.openFile(io, repo_filename, .{});
const st = try f.stat(io);
fs_out.* = storage.FileStorage.init(io, f, st.size);
return logstore.LogStore.openReadOnly(gpa, fs_out.storageFile());
}