const std = @import("std"); const zat = @import("zat"); const hegel = @import("hegel"); const Mst = zat.mst.Mst; const Cid = zat.Cid; const Allocator = std.mem.Allocator; const key_count = 16; const value_count = 4; const slot_count = 3; /// keys per MST layer, lowest layer first. a pool this small makes overwrites /// and delete-then-reinsert common; the spread of layers makes those hit /// splits, merges, and layer-bridging nodes. const keys_per_layer = [_]usize{ 6, 4, 3, 2, 1 }; comptime { var total: usize = 0; for (keys_per_layer) |n| total += n; std.debug.assert(total == key_count); } const Model = [key_count]?u8; const Fixture = struct { /// sorted, so key index order is MST walk order keys: [key_count][]const u8, values: [value_count]Cid, min_steps: u64, max_steps: u64, engine_machine: bool, fn init(gpa: Allocator) !Fixture { const pool: usize = @intCast(envInt("PBT_MST_POOL") orelse 0); const candidate_count = 4096; var by_layer: [keys_per_layer.len]std.ArrayList([]const u8) = @splat(.empty); for (0..candidate_count) |i| { const key = try std.fmt.allocPrint(gpa, "pbt.mst.key/{d:0>4}", .{i}); const layer = zat.mst.keyHeight(key); if (layer < by_layer.len) try by_layer[layer].append(gpa, key); } var fixture: Fixture = undefined; var filled: usize = 0; for (keys_per_layer, by_layer) |want, candidates| { // spread each layer's picks across the key space so that layers interleave const len = candidates.items.len; for (0..want) |j| { fixture.keys[filled] = candidates.items[((2 * j + 1) * len / (2 * want) + pool * 7) % len]; filled += 1; } } std.mem.sort([]const u8, &fixture.keys, {}, struct { fn lessThan(_: void, a: []const u8, b: []const u8) bool { return std.mem.order(u8, a, b) == .lt; } }.lessThan); for (&fixture.values, 0..) |*value, i| { value.* = try Cid.forDagCbor(gpa, try std.fmt.allocPrint(gpa, "pbt.mst.value/{d}", .{i})); } fixture.engine_machine = if (std.c.getenv("PBT_MST_ENGINE")) |engine| std.mem.eql(u8, std.mem.span(engine), "machine") else true; fixture.min_steps = envInt("PBT_MST_MIN_STEPS") orelse 0; fixture.max_steps = @max(fixture.min_steps, envInt("PBT_MST_MAX_STEPS") orelse 60); return fixture; } fn describe(self: *const Fixture) void { std.debug.print("key pool:\n", .{}); for (self.keys, 0..) |key, i| { std.debug.print(" k{d:<2} layer {d} {s}\n", .{ i, zat.mst.keyHeight(key), key }); } } }; const Slot = struct { tree: Mst, model: Model, /// false while the tree may hold unresolved stubs. `get` resolves nothing /// and cannot see below a stub, so only `getLazy` is checked until a walk /// has loaded everything. loaded: bool, /// false for a partial tree with no block reader, whose stubs cannot resolve resolvable: bool = true, }; const Store = std.StringHashMapUnmanaged([]const u8); /// how much of the state space a run actually exercised. the final size is /// the keys held by t0 when a history ends. var tally: hegel.Tally(Op) = .{}; var fault_counts: struct { armed: u64 = 0, fired: u64 = 0 } = .{}; const Op = enum { put, delete, root, get, walk, copy, commit, reload_eager, reload_lazy, reload_partial, reload_bare, arm_fault }; /// drawn uniformly, so mutation makes up most of a history. the index shrinks /// toward 0, which is why the plainest operation comes first. const op_weights = [_]Op{ .put, .put, .put, .put, .put, .put, .delete, .delete, .delete, .root, .root, .get, .walk, .copy, .commit, .reload_eager, .reload_lazy, .reload_partial, .reload_bare, .arm_fault, }; /// the same weights for Hegel's own state machine, in `Op` tag order const machine_weights = blk: { var weights: [std.meta.tags(Op).len]f64 = @splat(0); for (op_weights) |op| weights[@backingInt(op)] += 1; break :blk weights; }; /// who picks the next operation. `table` draws an index into `op_weights` /// for each step of an engine-sized sequence. `machine` hands selection to /// Hegel's state machine, which adds swarm testing and its own stopping rule. const Driver = union(enum) { table: hegel.Steps, machine: hegel.Machine(Op), fn next(self: *Driver, case: *hegel.TestCase) !?Op { switch (self.*) { .table => |*steps| { if (!try steps.next()) return null; return op_weights[try case.index(op_weights.len)]; }, .machine => |*machine| return machine.next(), } } fn deinit(self: *Driver) void { switch (self.*) { inline else => |*driver| driver.deinit(), } } }; const Machine = struct { fixture: *const Fixture, case: *hegel.TestCase, arena: Allocator, min_steps: u64, max_steps: u64, slots: [slot_count]?Slot, /// every block any tree has committed. content-addressed, so shared. store: Store = .empty, /// reads a tree may make before its block reader fails once fault_countdown: ?u32 = null, /// oracle reads never see an injected fault faults_paused: bool = false, fault_fired: bool = false, fn run(self: *Machine) !void { const case = self.case; var driver: Driver = if (self.fixture.engine_machine) .{ .machine = try case.machine(Op, &machine_weights, @intCast(self.max_steps)) } else .{ .table = try case.steps(self.min_steps, self.max_steps) }; defer driver.deinit(); tally.case(); // a uniformly drawn starting set gives large trees from the first step, // where a history of single puts would spend its whole length building one const initial = try case.int(u16, 0, std.math.maxInt(u16)); if (initial != 0) { case.note("t0 = fresh tree holding v0 at keys 0b{b:0>16} (bit i is k{{i}})", .{initial}); const slot = &self.slots[0].?; for (self.fixture.keys, 0..) |key, k| { if (initial >> @intCast(k) & 1 == 0) continue; try slot.tree.put(key, self.fixture.values[0]); slot.model[k] = 0; } } while (try driver.next(case)) |op| { tally.step(op); if (op == .reload_bare) case.event("bare partial reload"); if (op == .copy) case.event("copy followed by further operations"); const t = try self.drawLiveSlot(); const slot = &self.slots[t].?; self.fault_fired = false; switch (op) { .arm_fault => { if (self.fault_countdown != null) continue; const reads = try case.int(u32, 0, 6); case.note("arm a block reader fault after {d} reads", .{reads}); self.fault_countdown = reads; fault_counts.armed += 1; }, .put => { const k = try case.index(key_count); const v: u8 = @intCast(try case.index(value_count)); case.note("t{d}.put(k{d}, v{d})", .{ t, k, v }); const previous = slot.tree.putReturn(self.fixture.keys[k], self.fixture.values[v]) catch |err| { try self.refused(slot, err); continue; }; if (!self.sameValue(previous, slot.model[k])) return case.fail("putReturn returned the wrong previous value"); slot.model[k] = v; }, .delete => { const k = try case.index(key_count); case.note("t{d}.delete(k{d})", .{ t, k }); const previous = slot.tree.deleteReturn(self.fixture.keys[k]) catch |err| { try self.refused(slot, err); continue; }; if (!self.sameValue(previous, slot.model[k])) return case.fail("deleteReturn returned the wrong previous value"); slot.model[k] = null; }, .root => { case.note("t{d}.rootCid()", .{t}); try self.checkRoot(slot); }, .get => { const k = try case.index(key_count); case.note("t{d}.get(k{d})", .{ t, k }); const key = self.fixture.keys[k]; const found = slot.tree.getLazy(key) catch |err| { try self.refused(slot, err); continue; }; if (!self.sameValue(found, slot.model[k])) return case.fail("getLazy disagrees with the model"); if (slot.loaded and !self.sameValue(slot.tree.get(key), slot.model[k])) return case.fail("get disagrees with the model"); }, .walk => { case.note("t{d}.walk()", .{t}); self.checkWalk(slot) catch |err| try self.refused(slot, err); }, .copy => { const to = try case.index(slot_count); case.note("t{d} = t{d}.copy()", .{ to, t }); var copied = slot.*; copied.tree = try slot.tree.copy(); self.slots[to] = copied; }, .commit => { case.note("t{d}.collectBlocks()", .{t}); _ = try self.commit(slot); }, .reload_eager => { case.note("t{d} = loadFromBlocks(every block of t{d})", .{ t, t }); const committed = try self.commit(slot); slot.tree = try Mst.loadFromBlocks(self.arena, .{ .roots = &.{}, .blocks = committed.blocks }, committed.root.raw); slot.loaded = true; slot.resolvable = true; }, .reload_lazy => { case.note("t{d} = loadLazy(root of t{d})", .{ t, t }); const committed = try self.commit(slot); slot.tree = try Mst.loadLazy(self.arena, committed.root.raw, self.reader()); slot.loaded = false; slot.resolvable = true; }, .reload_partial, .reload_bare => { const committed = try self.commit(slot); const dropped = try case.int(u16, 0, std.math.maxInt(u16)); const with_reader = op == .reload_partial; case.note("t{d} = loadFromBlocks(blocks of t{d}, dropping non-root block i (preorder) where bit i%16 of 0b{b:0>16} is set), {s}", .{ t, t, dropped, if (with_reader) "reader attached" else "no reader", }); var kept: std.ArrayList(zat.car.Block) = .empty; for (committed.blocks, 0..) |block, i| { if (i != 0 and dropped >> @intCast(i % 16) & 1 == 1) continue; try kept.append(self.arena, block); } slot.tree = try Mst.loadFromBlocks(self.arena, .{ .roots = &.{}, .blocks = kept.items }, committed.root.raw); if (with_reader) slot.tree.block_reader = self.reader(); slot.loaded = false; slot.resolvable = with_reader; }, } } var final_keys: u64 = 0; for (self.slots[0].?.model) |value| final_keys += @intFromBool(value != null); tally.finish(final_keys); self.fault_countdown = null; for (&self.slots, 0..) |*maybe_slot, t| { const slot = &(maybe_slot.* orelse continue); case.note("final check of t{d}", .{t}); try self.checkRoot(slot); self.checkWalk(slot) catch |err| try self.refused(slot, err); try self.checkRoot(slot); } } /// an operation failed. the one failure a history may contain is a partial /// tree with no reader refusing to cross a stub, which must change nothing. fn refused(self: *Machine, slot: *Slot, err: anyerror) !void { const injected = err == error.ReaderUnavailable and self.fault_fired; if (!injected and (err != error.PartialTree or slot.resolvable)) return err; self.case.note(" refused: {s}", .{@errorName(err)}); if (injected) self.case.event("operation refused by a block reader fault"); self.case.event("refused operation checked for atomicity"); const actual = try slot.tree.rootCid(); const expected = try self.freshRoot(&slot.model); if (!std.mem.eql(u8, actual.raw, expected.raw)) { return self.case.fail("an operation refused with PartialTree still changed the tree's root"); } } fn paused(self: *Machine) bool { const was = self.faults_paused; self.faults_paused = true; return was; } fn drawLiveSlot(self: *Machine) !usize { var live: [slot_count]usize = undefined; var count: usize = 0; for (self.slots, 0..) |slot, i| { if (slot != null) { live[count] = i; count += 1; } } return live[try self.case.index(count)]; } fn sameValue(self: *const Machine, actual: ?Cid, expected: ?u8) bool { const want = self.fixture.values[expected orelse return actual == null]; const got = actual orelse return false; return std.mem.eql(u8, got.raw, want.raw); } fn checkRoot(self: *Machine, slot: *Slot) !void { const was = self.paused(); defer self.faults_paused = was; const actual = try slot.tree.rootCid(); const expected = try self.freshRoot(&slot.model); if (!std.mem.eql(u8, actual.raw, expected.raw)) { return self.case.fail("rootCid differs from a tree built fresh from the same contents"); } } fn freshRoot(self: *Machine, model: *const Model) !Cid { var fresh = Mst.init(self.arena); for (model, self.fixture.keys) |value, key| { if (value) |v| try fresh.put(key, self.fixture.values[v]); } return fresh.rootCid(); } fn checkWalk(self: *Machine, slot: *Slot) !void { var seen: Seen = .{ .machine = self, .model = &slot.model }; try slot.tree.walk(.{ .ctx = &seen, .entryFn = Seen.entry }); if (seen.mismatch) return self.case.fail("walk yielded an entry out of order, or one the model does not hold"); while (seen.next < key_count) : (seen.next += 1) { if (slot.model[seen.next] != null) return self.case.fail("walk skipped an entry the model holds"); } slot.loaded = true; } const Seen = struct { machine: *Machine, model: *const Model, next: usize = 0, mismatch: bool = false, fn entry(ctx: *anyopaque, e: zat.mst.WalkEntry) anyerror!void { const self: *Seen = @ptrCast(@alignCast(ctx)); while (self.next < key_count and self.model[self.next] == null) self.next += 1; if (self.next == key_count or !std.mem.eql(u8, e.key, self.machine.fixture.keys[self.next]) or !self.machine.sameValue(e.value, self.model[self.next])) { self.mismatch = true; return; } self.next += 1; } }; /// `blocks` is every node block of the committed tree, root first const Committed = struct { root: Cid, blocks: []const zat.car.Block }; /// collect a tree's blocks into the store, as a repo commit would, and /// check that the store can then serve the whole tree. fn commit(self: *Machine, slot: *Slot) !Committed { const was = self.paused(); defer self.faults_paused = was; var blocks: std.ArrayList(zat.car.Block) = .empty; try slot.tree.collectBlocks(&blocks); for (blocks.items) |*block| { const hashed = try Cid.forDagCbor(self.arena, block.data); if (!std.mem.eql(u8, hashed.raw, block.cid_raw)) { return self.case.fail("collectBlocks emitted a block whose cid is not the hash of its data"); } // the store is the disk: it must not alias memory the tree still owns block.* = .{ .cid_raw = hashed.raw, .data = try self.arena.dupe(u8, block.data) }; try self.store.put(self.arena, block.cid_raw, block.data); } try self.checkRoot(slot); const root = try slot.tree.rootCid(); if (!self.store.contains(root.raw)) return self.case.fail("after collectBlocks the root block is in neither the output nor the store"); var reachable: std.ArrayList(zat.car.Block) = .empty; zat.mst.collectReachableBlocks(self.arena, root.raw, self.reader(), &reachable, .{ .include_records = false }) catch |err| switch (err) { error.OutOfMemory => return err, else => return self.case.fail("after collectBlocks a reachable node is in neither the output nor the store"), }; return .{ .root = root, .blocks = reachable.items }; } fn reader(self: *Machine) zat.mst.BlockReader { return .{ .ctx = self, .getFn = readBlock }; } fn readBlock(ctx: *anyopaque, cid_raw: []const u8) anyerror!?[]const u8 { const self: *Machine = @ptrCast(@alignCast(ctx)); if (!self.faults_paused) { if (self.fault_countdown) |remaining| { if (remaining == 0) { self.fault_countdown = null; self.fault_fired = true; fault_counts.fired += 1; return error.ReaderUnavailable; } self.fault_countdown = remaining - 1; } } return self.store.get(cid_raw); } }; fn property(fixture: *const Fixture, case: *hegel.TestCase) !void { var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); defer arena.deinit(); var machine: Machine = .{ .fixture = fixture, .case = case, .arena = arena.allocator(), .min_steps = fixture.min_steps, .max_steps = fixture.max_steps, .slots = @splat(null), }; machine.slots[0] = .{ .tree = Mst.init(machine.arena), .model = @splat(null), .loaded = true }; try machine.run(); } fn envInt(name: [*:0]const u8) ?u64 { const text = std.c.getenv(name) orelse return null; return std.fmt.parseInt(u64, std.mem.span(text), 10) catch null; } pub fn main() !void { var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); defer arena.deinit(); const fixture = try Fixture.init(arena.allocator()); fixture.describe(); // 100 cases catch each planted dirty-flag bug in 9 or 10 runs of 10; this // is headroom for bugs nobody planted const test_cases: ?u64 = if (envInt("HEGEL_TEST_CASES") == null) 5000 else null; const outcome = hegel.run(.{ .key = "mst", .test_cases = test_cases }, &fixture, property); std.debug.print("\n", .{}); tally.print(); std.debug.print("block reader faults: {d} armed, {d} fired, {d} never reached\n", .{ fault_counts.armed, fault_counts.fired, fault_counts.armed - fault_counts.fired }); outcome catch std.process.exit(1); std.debug.print("mst state machine: no failures\n", .{}); }