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

zat.dev/zds

atproto pds · mirror of https://tangled.org/zat.dev/zds

0
0
257 lines · 11.9 KB Raw History
//! Generated write histories against one account's repo, checked after every
//! step against a model of which record each key holds. Every write carries a
//! unique number, so each stored record traces to exactly one write. A
//! restart closes and reopens the same database file.
const std = @import("std");
const hegel = @import("hegel");
const zds = @import("zds");
const zat = zds.zat;
const store = zds.storage.store;

const collections = [_][]const u8{ "test.fuzz.alpha", "test.fuzz.beta" };
const rkeys = [_][]const u8{ "a", "b", "c" };
const key_count = collections.len * rkeys.len;

const Rule = enum { create, put, delete, batch, stale_swap, stale_commit, restart };
var tally: hegel.Tally(Rule) = .{};
var db_counter: u64 = 0;

test "campaign repo writes match a record model across batches, swaps and restarts" {
    defer tally.print();
    try hegel.run(.{ .key = "zds-repo-writes" }, {}, property);
}

const Slot = struct { cid: []const u8, n: i64 };

const World = struct {
    a: std.mem.Allocator,
    case: *hegel.TestCase,
    path: []const u8,
    account: zds.auth.tokens.Account,
    model: [key_count]?Slot = @splat(null),
    commit: ?[]const u8 = null,
    rev: ?[]const u8 = null,
    seq: u64 = 0,
    next_n: i64 = 1,

    fn key(self: *World) !usize {
        return self.case.index(key_count);
    }

    fn value(self: *World, k: usize) !struct { std.json.Value, i64 } {
        const n = self.next_n;
        self.next_n += 1;
        var object: std.json.ObjectMap = .empty;
        try object.put(self.a, "$type", .{ .string = collections[k / rkeys.len] });
        try object.put(self.a, "n", .{ .integer = n });
        return .{ .{ .object = object }, n };
    }

    fn op(self: *World, kind: enum { create, put, delete }, k: usize) !struct { store.WriteOp, ?i64 } {
        const collection = collections[k / rkeys.len];
        const rkey = rkeys[k % rkeys.len];
        return switch (kind) {
            .create => blk: {
                const v, const n = try self.value(k);
                break :blk .{ .{ .create = .{ .collection = collection, .rkey = rkey, .value = v } }, n };
            },
            .put => blk: {
                const v, const n = try self.value(k);
                break :blk .{ .{ .update = .{ .collection = collection, .rkey = rkey, .value = v } }, n };
            },
            .delete => .{ .{ .delete = .{ .collection = collection, .rkey = rkey } }, null },
        };
    }

    /// Apply `ops` and update the model the way the protocol says they land:
    /// all at once or not at all.
    fn apply(self: *World, ops: []const store.WriteOp, keys: []const usize, numbers: []const ?i64, options: store.WriteOptions) !?store.WriteResult {
        var next = self.model;
        var refusable = false;
        var create_conflict = false;
        for (ops, keys, numbers) |o, k, n| switch (o) {
            .create => {
                if (next[k] != null) create_conflict = true;
                next[k] = .{ .cid = "", .n = n.? };
            },
            .update => next[k] = .{ .cid = "", .n = n.? },
            .delete => {
                if (next[k] == null) refusable = true;
                next[k] = null;
            },
        };
        for (ops) |o| switch (o) {
            .create => |c| self.case.note("create {s}/{s} n={d}", .{ c.collection, c.rkey.?, c.value.object.get("n").?.integer }),
            .update => |u| self.case.note("put {s}/{s} n={d}", .{ u.collection, u.rkey, u.value.object.get("n").?.integer }),
            .delete => |d| self.case.note("delete {s}/{s}", .{ d.collection, d.rkey }),
        };
        if (ops.len > 1) self.case.note("  (one batch of {d})", .{ops.len});
        const result = store.applyWritesWithOptions(self.a, self.account, ops, options) catch |err| {
            if (!refusable and !create_conflict and options.swap_commit == null) {
                self.case.note("applyWrites: {s}", .{@errorName(err)});
                return self.case.fail("a valid write was refused");
            }
            if (create_conflict) self.case.event("a create over an existing record was refused");
            self.case.event("a conflicting write was refused");
            try self.check();
            return null;
        };
        // a create over an existing record must be refused, as the reference
        // PDS's MST refuses to add a key it already holds
        if (create_conflict) return self.case.fail("a create over an existing record was accepted");
        var written: usize = 0;
        for (ops, keys) |o, k| switch (o) {
            .create, .update => {
                next[k].?.cid = try self.a.dupe(u8, result.records[written].cid);
                written += 1;
            },
            .delete => {},
        };
        if (written != result.records.len) return self.case.fail("applyWrites returned a different number of records");
        if (self.rev) |previous| if (std.mem.order(u8, result.commit.rev, previous) != .gt) return self.case.fail("a commit's rev did not increase");
        // refused writes may burn a sequence number; committed ones must still
        // be numbered in order, across restarts too
        if (result.records.len > 0) {
            const seq = result.records[0].seq;
            if (seq <= self.seq) return self.case.fail("a commit's sequence number did not increase");
            self.seq = seq;
        }
        self.model = next;
        self.commit = try self.a.dupe(u8, result.commit.cid);
        self.rev = try self.a.dupe(u8, result.commit.rev);
        try self.check();
        return result;
    }

    fn check(self: *World) !void {
        var live: usize = 0;
        for (self.model, 0..) |slot, k| {
            const collection = collections[k / rkeys.len];
            const rkey = rkeys[k % rkeys.len];
            const block = store.getRecordBlock(self.a, self.account.did, collection, rkey);
            const expected = slot orelse {
                if (block != null) return self.case.fail("a deleted or never-written record is readable");
                continue;
            };
            live += 1;
            const got = block orelse return self.case.fail("a written record is missing");
            if (!std.mem.eql(u8, got.cid, expected.cid)) return self.case.fail("a record's cid differs from the one its write returned");
            const decoded = zat.cbor.decodeAll(self.a, got.data) catch return self.case.fail("a stored record is not valid DAG-CBOR");
            if (decoded.getInt("n") != expected.n) return self.case.fail("a record holds another write's value");
        }
        const car = try store.writeRepoCar(self.a, self.account.did);
        const keypair = try store.signingKeypair(self.account.did);
        const public_key = try keypair.publicKey();
        const verified = zat.verifyCommitCar(self.a, car, .{ .key_type = keypair.key_type, .raw = &public_key }, .{
            .expected_did = self.account.did,
            .require_complete_repo = true,
        }) catch |err| {
            self.case.note("verifyCommitCar: {s}", .{@errorName(err)});
            return self.case.fail("the exported repo does not verify");
        };
        if (verified.record_count != live) return self.case.fail("the exported repo holds a different number of records");
        if (self.rev) |rev| if (!std.mem.eql(u8, verified.commit_rev, rev)) return self.case.fail("the exported repo is not at the latest commit");
        if (live > 1) self.case.event("checked a repo holding several records");
    }
};

fn property(_: void, case: *hegel.TestCase) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const a = arena.allocator();
    db_counter += 1;
    var tmp_buf: [256]u8 = undefined;
    const tmp = std.c.getenv("TMPDIR") orelse "/tmp";
    const path = try std.fmt.bufPrint(&tmp_buf, "{s}/zds-repo-writes-{d}-{d}.sqlite", .{ std.mem.trimEnd(u8, std.mem.span(tmp), "/"), std.c.getpid(), db_counter });
    defer for ([_][]const u8{ "", "-wal", "-shm" }) |suffix| {
        var buf: [300]u8 = undefined;
        const file = std.fmt.bufPrintSentinel(&buf, "{s}{s}", .{ path, suffix }, 0) catch unreachable;
        _ = std.c.unlink(file);
    };

    try store.init(std.Options.debug_io, path);
    defer store.close();
    var world: World = .{
        .a = a,
        .case = case,
        .path = path,
        .account = try store.createAccount(a, "writes.test", "writes@test.com", "password", "did:plc:fuzzrepowrites", true),
    };
    try store.initializeRepo(a, world.account);
    tally.case();
    var machine = try case.machine(Rule, null, 30);
    defer machine.deinit();
    while (try machine.next()) |rule| {
        tally.step(rule);
        switch (rule) {
            .create, .put, .delete => {
                const k = try world.key();
                const o, const n = try world.op(switch (rule) {
                    .create => .create,
                    .put => .put,
                    else => .delete,
                }, k);
                if (rule == .put and world.model[k] != null) case.event("overwrote an existing record");
                if (rule == .delete and world.model[k] != null) case.event("deleted an existing record");
                _ = try world.apply(&.{o}, &.{k}, &.{n}, .{});
            },
            .batch => {
                const len = 2 + try case.index(2);
                var ops: [3]store.WriteOp = undefined;
                var keys: [3]usize = undefined;
                var numbers: [3]?i64 = undefined;
                var used: [key_count]bool = @splat(false);
                for (0..len) |i| {
                    var k = try world.key();
                    while (used[k]) k = (k + 1) % key_count;
                    used[k] = true;
                    const kind: u8 = @intCast(try case.index(3));
                    ops[i], numbers[i] = try world.op(switch (kind) {
                        0 => .create,
                        1 => .put,
                        else => .delete,
                    }, k);
                    keys[i] = k;
                }
                case.event("applied a multi-operation batch");
                _ = try world.apply(ops[0..len], keys[0..len], numbers[0..len], .{});
            },
            .stale_swap => {
                const k = try world.key();
                if (world.model[k] == null) continue;
                var swapped, _ = try world.op(.put, k);
                // a well-formed cid that no record of this repo has
                swapped.update.swap = .{ .cid = "bafyreie5737gdxlw5i64vzichcalba3z2v5n6icifvx5xytvske7mr3hpm" };
                if (store.applyWritesWithOptions(world.a, world.account, &.{swapped}, .{})) |_| {
                    return case.fail("an update whose swap cid is stale was applied");
                } else |_| {}
                try world.check();
                case.event("a stale record swap was refused");
            },
            .stale_commit => {
                const stale = world.commit orelse continue;
                const k = try world.key();
                const o, const n = try world.op(.put, k);
                // first write moves the head; the second still names the old one
                _ = try world.apply(&.{o}, &.{k}, &.{n}, .{ .swap_commit = stale });
                const o2, _ = try world.op(.put, k);
                if (store.applyWritesWithOptions(world.a, world.account, &.{o2}, .{ .swap_commit = stale })) |_| {
                    return case.fail("a write naming a superseded commit was applied");
                } else |_| {}
                try world.check();
                case.event("a stale commit swap was refused");
            },
            .restart => {
                store.close();
                try store.init(std.Options.debug_io, path);
                case.event("reopened the database");
                try world.check();
            },
        }
    }
    tally.finish(blk: {
        var live: u64 = 0;
        for (world.model) |slot| live += @intFromBool(slot != null);
        break :blk live;
    });
}