summaryrefslogtreecommitdiff
path: root/core/replica.zig
diff options
context:
space:
mode:
Diffstat (limited to 'core/replica.zig')
-rw-r--r--core/replica.zig312
1 files changed, 302 insertions, 10 deletions
diff --git a/core/replica.zig b/core/replica.zig
index ae93be17..214cc34e 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -296,7 +296,8 @@ pub const Authority = struct {
const u = try a.unit(0, a.seq);
var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty;
defer blobs.deinit(a.core.gpa);
- const state = try pardes.dump.dumpJoin(a.core, &blobs);
+ const dumped = try pardes.dump.dumpJoin(a.core, &blobs);
+ const state = dumped.bytes;
defer a.core.gpa.free(state);
tape.resync(&a.t);
var whole: std.ArrayListUnmanaged(u8) = .empty;
@@ -308,7 +309,7 @@ pub const Authority = struct {
pos = b.at;
}
try whole.appendSlice(a.gpa, state[pos..]);
- return .{ .view = k, .unit = u, .dump = try whole.toOwnedSlice(a.gpa), .digest = tape.digestOf(a.core) };
+ return .{ .view = k, .unit = u, .dump = try whole.toOwnedSlice(a.gpa), .digest = dumped.digest };
}
/// Client `client` gone as `Peers.leave` lets one go: its view kept for
@@ -1974,7 +1975,7 @@ pub const Peers = struct {
// undo, registers) left out, pinned, and streamed by the client's
// writer thread: the step pays for the state, not for the text.
var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty;
- const bytes = pardes.dump.dumpJoin(core, &blobs) catch |err| {
+ const dumped = pardes.dump.dumpJoin(core, &blobs) catch |err| {
blobs.deinit(core.gpa);
core.undrawn &= ~(@as(u8, 1) << @intCast(k));
core.closeView(.at(k));
@@ -1983,6 +1984,7 @@ pub const Peers = struct {
var why: [96]u8 = undefined;
return daemon.refuseReplica(fd, std.fmt.bufPrint(&why, "that session could not be dumped: {t}", .{err}) catch "that session could not be dumped");
};
+ const bytes = dumped.bytes;
var whole = bytes.len;
for (blobs.items) |b| {
pardes.memory.pin(b.bytes);
@@ -2004,7 +2006,7 @@ pub const Peers = struct {
if (ps.next_id == 0) ps.next_id = 1;
// The session's digest as dumped, for the joiner to check its load by
// (a pair's client, its own boot: `writeJoin`).
- const digest = tape.digestOf(core);
+ const digest = dumped.digest;
peer.digest = digest;
peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = @intCast(libc.getpid()), .session = ps.name[0..@min(ps.name.len, wire.max_name)], .client = peer.id, .view = peer.view, .dump_len = whole, .gmtoff = gmtoff(), .digest = digest, .semantics = wire.semantics, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len;
if (ps.threads) peer.writer = std.Thread.spawn(.{}, Peer.writeLoop, .{peer}) catch null;
@@ -2828,14 +2830,33 @@ fn fromDump(gpa: Allocator, j: *Joined, o: pardes.Options, have: ?*Have, why: []
return null;
};
if (!r.loaded(j.digest)) {
+ var named: [400]u8 = undefined;
+ const fields = loadDiffers(r, j.dump, &named);
r.deinit();
- _ = std.fmt.bufPrint(why, "the session's dump loaded as another session (a build's dump is not complete)\x00", .{}) catch {};
+ log.warn("client {d}: the session's dump loaded as another session: {s}", .{ j.client, fields });
+ _ = std.fmt.bufPrint(why, "the session's dump loaded as another session: {s}differs\x00", .{fields}) catch {};
return null;
}
takeJoined(r, j, have, t0);
return r;
}
+/// The fields a replica loaded from the join's dump `bytes` has other than
+/// the session as it dumped them (the digest a field at a time the dump
+/// ends with: dump.joinParts), named in `out`.
+fn loadDiffers(r: *Replica, bytes: []const u8, out: []u8) []const u8 {
+ const want = pardes.dump.joinParts(r.gpa, bytes) orelse return "(the dump names no field) ";
+ defer r.gpa.free(want);
+ var arena: std.heap.ArenaAllocator = .init(r.gpa);
+ defer arena.deinit();
+ const got = arena.allocator().create(tape.Parts) catch return "";
+ const was = Stepping.begin(&r.t, &r.epoch);
+ const parts = tape.digestParts(r.core(), got);
+ was.end();
+ const fields = tape.partsDiffer(parts, want, arena.allocator());
+ return std.fmt.bufPrint(out, "{s}", .{fields[0..@min(fields.len, out.len)]}) catch out;
+}
+
/// What a replica joined by `j` takes of it, and of the environment.
fn takeJoined(r: *Replica, j: *Joined, have: ?*Have, t0: u64) void {
// PARDES_NO_ECHO: no predicted echo (the gates' baseline).
@@ -3376,11 +3397,11 @@ fn farJoinOnce(ps: *Peers, core: *Pardes, have: ?*Have) !Joined {
var fds: [2]c_int = undefined;
if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket;
var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty;
- const state = pardes.dump.dumpJoin(core, &blobs) catch |err| {
+ const state = (pardes.dump.dumpJoin(core, &blobs) catch |err| {
_ = libc.close(fds[0]);
_ = libc.close(fds[1]);
return err;
- };
+ }).bytes;
var whole = state.len;
for (blobs.items) |b| whole += b.bytes.len;
const peer = try ps.gpa.create(Peer);
@@ -3427,7 +3448,7 @@ fn joinedNow(a: *Authority, id: u16, view: u8) !*Replica {
const was = Stepping.begin(&a.t, null);
var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty;
defer blobs.deinit(a.core.gpa);
- const state = try pardes.dump.dumpJoin(a.core, &blobs);
+ const state = (try pardes.dump.dumpJoin(a.core, &blobs)).bytes;
defer a.core.gpa.free(state);
tape.resync(&a.t);
was.end();
@@ -4948,7 +4969,7 @@ test "a join's dump, its blobs put back where they go, is the session's dump" {
defer a.core.gpa.free(whole);
var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty;
defer blobs.deinit(a.core.gpa);
- const state = try pardes.dump.dumpJoin(a.core, &blobs);
+ const state = (try pardes.dump.dumpJoin(a.core, &blobs)).bytes;
defer a.core.gpa.free(state);
try std.testing.expect(blobs.items.len > 0);
try std.testing.expect(state.len + 20000 <= whole.len);
@@ -5081,7 +5102,7 @@ test "a far join is sent each blob once: joined again with them on disk or in th
// What the session's list will say: its blobs, those of one text once.
var listed: std.ArrayListUnmanaged(walk.Deferred) = .empty;
defer listed.deinit(a.core.gpa);
- a.core.gpa.free(try pardes.dump.dumpJoin(a.core, &listed));
+ a.core.gpa.free((try pardes.dump.dumpJoin(a.core, &listed)).bytes);
var distinct: std.AutoHashMapUnmanaged([32]u8, usize) = .empty;
defer distinct.deinit(gpa);
var distinct_bytes: u64 = 0;
@@ -7687,8 +7708,279 @@ const NinepJoin = struct {
fn agree(n: *NinepJoin) !void {
try agrees(n.a, n.late.?);
}
+
+ fn opened(n: *NinepJoin, at: u64, mode: u8) !u32 {
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = at, .omode = mode }, true)).handle;
+ if (h == 0) return error.NoRecord;
+ return h;
+ }
+
+ fn wrote(n: *NinepJoin, at: u64, h: u32, data: []const u8) !void {
+ _ = try n.serve(.{ .tag = 2, .op = .write, .node = at, .handle = h, .data = data }, true);
+ }
+
+ fn loadsSame(n: *NinepJoin) !void {
+ try loadsAsSession(n.a, 1);
+ }
+};
+
+/// A client `client` of the session `a` joined now, as `Peers.join` joins
+/// one, and let go: its load is the session as dumped, at the welcome's
+/// digest; the fields that differ named (`loadDiffers`) when it is not.
+/// A test's session ends with it to say its state crosses a join whole.
+pub fn loadsAsSession(a: *Authority, client: u16) !void {
+ const gpa = std.testing.allocator;
+ const joined = (try a.join(client, null)) orelse return error.NoView;
+ defer gpa.free(joined.dump);
+ const r = try Replica.initDump(gpa, client, joined.view, joined.dump, .{ .cols = 80, .rows = 24 });
+ defer r.deinit();
+ if (!r.loaded(joined.digest)) {
+ var named: [400]u8 = undefined;
+ std.debug.print("the client's load is not the session: {s}\n", .{loadDiffers(r, joined.dump, &named)});
+ return error.LoadedAnother;
+ }
+ _ = try a.leave(client, false);
+}
+
+/// Every type the core's walk reaches that walks itself by hand
+/// (walk.handWalked: a `digest` or a dump of its own, which can take what
+/// the other does not), and the test that joins a client from a dump of a
+/// session holding it and checks the load by the welcome's digest. The one
+/// walk holds every other field: its digest, its dump and its rollback copy
+/// are the same fields by one declaration (walk.zig `replica`).
+const hand_walked = .{
+ .{ pardes.filesystem.Namespace, "a client joined while 9P requests hold each kind of state the core keeps for them" },
+ .{ pardes.ctlfs.Open.What, "a client joined while 9P requests hold each kind of state the core keeps for them" },
+ .{ pardes.ctlfs.pane.State, "a client joined after a script set a pane's addr, its limit, or truncated its dot" },
+ .{ Term.State, "bytes: a client joins from a dump with its terminals whole" },
+ .{ pardes.Kind.Slot, "a client joined from a dump numbers a kind's next job as the session does" },
+ .{ @import("locations.zig").Row, "a client joined from a dump makes a `/` query's rows as the session does" },
+ .{ @import("jj.zig").Session, "a client replays Changes from what the session's jj answered and ends equal" },
+ .{ pardes.panes.File.Layers, "a client replays Changes from what the session's jj answered and ends equal" },
+};
+
+test "every type the core's walk reaches that hashes or dumps itself by hand has a test joining a client over it (hand_walked)" {
+ inline for (comptime walk.handWalked(&.{Pardes})) |T| {
+ const listed = comptime for (hand_walked) |entry| {
+ if (entry[0] == T) break true;
+ } else false;
+ if (!listed) {
+ std.debug.print("{s} walks itself by hand and no test joins a client over it: one, and its line in hand_walked\n", .{@typeName(T)});
+ return error.NotListed;
+ }
+ }
+ // ...and every line is a type that does: one that walks itself by the
+ // one walk again leaves no line behind.
+ inline for (hand_walked) |entry| {
+ const reached = comptime for (walk.handWalked(&.{Pardes})) |T| {
+ if (entry[0] == T) break true;
+ } else false;
+ if (!reached) {
+ std.debug.print("{s} no longer walks itself by hand: its line in hand_walked goes\n", .{@typeName(entry[0])});
+ return error.Stale;
+ }
+ }
+}
+
+test "a client whose load is not the session says which field, in its words and its log" {
+ const gpa = std.testing.allocator;
+ var n = try NinepJoin.init("one\n", TestHost.host());
+ defer n.deinit();
+ const before = (try n.a.join(1, null)).?;
+ defer gpa.free(before.dump);
+ _ = try n.a.leave(1, false);
+ _ = try n.serve(.{ .tag = 1, .op = .open, .node = @backingInt(pardes.ctlfs.TopFile.screen) }, true);
+ const after = (try n.a.join(1, null)).?;
+ defer gpa.free(after.dump);
+ // The dump before the open, checked by the digest after it and named
+ // by its fields: what a dump made at one moment and a digest taken at
+ // another said.
+ const Tail = struct {
+ fn at(dump: []const u8) usize {
+ const parts = pardes.dump.joinParts(std.testing.allocator, dump).?;
+ defer std.testing.allocator.free(parts);
+ return dump.len - parts.len * 8 - 16;
+ }
+ };
+ var spliced: std.ArrayListUnmanaged(u8) = .empty;
+ defer spliced.deinit(gpa);
+ try spliced.appendSlice(gpa, before.dump[0..Tail.at(before.dump)]);
+ try spliced.appendSlice(gpa, after.dump[Tail.at(after.dump)..]);
+ var j: Joined = .{ .fd = -1, .pid = 0, .client = 1, .view = before.view, .gmtoff = 0, .dump = spliced.items, .digest = after.digest, .semantics = wire.semantics };
+ var why: [600]u8 = @splat(0);
+ try std.testing.expect(fromDump(gpa, &j, .{ .cols = 80, .rows = 24 }, null, &why, nowNs()) == null);
+ try std.testing.expectEqualStrings("the session's dump loaded as another session: fs differs", std.mem.sliceTo(&why, 0));
+}
+
+/// Each kind of state 9P requests leave in the core between two requests
+/// of a script's (fs.Namespace and the `tree.Open` records it holds: what
+/// each `What` holds, a half line, a line being discarded, a name taken, a
+/// look's results, writes held as one edit, a header's truncation), made by
+/// the requests a script makes.
+const NinepKinds = struct {
+ const top = pardes.ctlfs.TopFile;
+ fn screen(n: *NinepJoin) !void {
+ _ = try n.opened(@backingInt(top.screen), 0);
+ }
+ fn logReader(n: *NinepJoin) !void {
+ _ = try n.opened(@backingInt(top.log), 0);
+ }
+ fn listing(n: *NinepJoin) !void {
+ _ = try n.opened(@backingInt(top.index), 0);
+ }
+ fn event(n: *NinepJoin) !void {
+ _ = try n.opened(n.node(.event), 2);
+ }
+ fn lock(n: *NinepJoin) !void {
+ try n.wrote(n.node(.ctl), try n.opened(n.node(.ctl), 1), "lock\n");
+ }
+ fn halfLine(n: *NinepJoin) !void {
+ try n.wrote(n.node(.exec), try n.opened(n.node(.exec), 1), "Ne");
+ }
+ fn discarding(n: *NinepJoin) !void {
+ try n.wrote(n.node(.exec), try n.opened(n.node(.exec), 1), "a\x01b");
+ }
+ fn named(n: *NinepJoin) !void {
+ try n.wrote(n.node(.name), try n.opened(n.node(.name), 1), "/tmp/named.txt\n");
+ }
+ fn results(n: *NinepJoin) !void {
+ try n.wrote(n.node(.exec), try n.opened(n.node(.exec), 2), "Zerox\n");
+ }
+ fn heldWrites(n: *NinepJoin) !void {
+ try n.wrote(n.node(.body), try n.opened(n.node(.body), 1), "two\n");
+ }
+ fn sel(n: *NinepJoin) !void {
+ try n.wrote(n.node(.sel), try n.opened(n.node(.sel), 1), "a");
+ }
+ fn pager(n: *NinepJoin) !void {
+ try n.wrote(@backingInt(top.pager), try n.opened(@backingInt(top.pager), 1), "/\nheld text");
+ }
+ fn plumb(n: *NinepJoin) !void {
+ try n.wrote(@backingInt(top.send), try n.opened(@backingInt(top.send), 1), "src\n");
+ }
+ fn port(n: *NinepJoin) !void {
+ _ = try n.opened(pardes.ctlfs.Node.ofPort(pardes.Plumb.portIndex(n.a.core, "edit") orelse return error.NoPort), 0);
+ }
+ fn headerCut(n: *NinepJoin) !void {
+ // Its open holds no record: the truncation is the session's.
+ const h = (try n.serve(.{ .tag = 1, .op = .open, .node = @backingInt(top.tag), .omode = 1 }, true)).handle;
+ _ = try n.serve(.{ .tag = 3, .op = .setattr, .node = @backingInt(top.tag), .handle = h, .truncate = true }, true);
+ }
+ const all = .{
+ .{ "an open of /screen (What.snapshot)", screen },
+ .{ "a reader of /log (What.log)", logReader },
+ .{ "a listing frozen at its open (What.frozen)", listing },
+ .{ "a pane's event reader (What.event)", event },
+ .{ "a ctl open holding a pane's lock (What.ctl)", lock },
+ .{ "half a line held on exec (What.lines, Open.pending)", halfLine },
+ .{ "a refused line's tail being discarded (Open.discarding)", discarding },
+ .{ "a name taken by an open (Open.named)", named },
+ .{ "a look's results on its open and the session's (Open.results, Namespace.results)", results },
+ .{ "writes to a body held as one edit (What.writes, Namespace.batch)", heldWrites },
+ .{ "an open of sel writing on from its last (What.writes)", sel },
+ .{ "a /pager open holding its text (What.pager)", pager },
+ .{ "a plumb message short of its data (What.plumb)", plumb },
+ .{ "a reader of a plumb port (What.port)", port },
+ .{ "the workspace's tag truncated (Namespace.header_*)", headerCut },
+ };
};
+test "a client joined while 9P requests hold each kind of state the core keeps for them loads the session: digest(load(dump)) is the session's, kind by kind" {
+ inline for (NinepKinds.all) |case| {
+ var n = try NinepJoin.init("one\n", TestHost.host());
+ defer n.deinit();
+ const empty = walk.digest(pardes.filesystem.Namespace, &n.a.core.fs);
+ try case[1](&n);
+ // The kind is there: the core's 9P state holds something.
+ try std.testing.expect(walk.digest(pardes.filesystem.Namespace, &n.a.core.fs) != empty);
+ n.loadsSame() catch |err| {
+ std.debug.print("the kind: {s}\n", .{case[0]});
+ return err;
+ };
+ }
+}
+
+test "a client joined at any point of a script's random 9P requests (opens of every kind, writes, reads, releases, truncations) loads the session: a seeded few hundred joins" {
+ var prng = std.Random.DefaultPrng.init(0x5eed_d16e);
+ const rand = prng.random();
+ var n = try NinepJoin.init("one two\nthree\n", TestHost.host());
+ defer n.deinit();
+ const top = pardes.ctlfs.TopFile;
+ const nodes = [_]u64{
+ @backingInt(top.screen), @backingInt(top.log), @backingInt(top.index), @backingInt(top.tag),
+ @backingInt(top.pager), @backingInt(top.send), pardes.ctlfs.Node.ofPort(pardes.Plumb.portIndex(n.a.core, "edit").?), @backingInt(top.exec),
+ n.node(.exec), n.node(.body), n.node(.ctl), n.node(.event),
+ n.node(.sel), n.node(.look), n.node(.data), n.node(.addr),
+ };
+ const words = [_][]const u8{ "Ne", "w\n", "a\x01", "b\n", "lock\n", "unlock\n", "one", "\n", "src\n", "#0,#3", "x" };
+ var held: [24]struct { node: u64, h: u32 } = undefined;
+ var nheld: usize = 0;
+ var joins: usize = 0;
+ var tag: u64 = 10;
+ while (joins < 300) {
+ tag += 1;
+ const pick = rand.uintLessThan(u8, 10);
+ if (pick >= 8) {
+ try n.loadsSame();
+ joins += 1;
+ continue;
+ }
+ if (pick < 3 or nheld == 0) {
+ if (nheld == held.len) continue;
+ const node = nodes[rand.uintLessThan(usize, nodes.len)];
+ const h = (try n.serve(.{ .tag = tag, .op = .open, .node = node, .omode = rand.uintLessThan(u8, 3) }, true)).handle;
+ if (h != 0) {
+ held[nheld] = .{ .node = node, .h = h };
+ nheld += 1;
+ }
+ continue;
+ }
+ const at = rand.uintLessThan(usize, nheld);
+ const o = held[at];
+ switch (pick) {
+ 3, 4 => _ = try n.serve(.{ .tag = tag, .op = .write, .node = o.node, .handle = o.h, .data = words[rand.uintLessThan(usize, words.len)] }, true),
+ 5 => _ = try n.serve(.{ .tag = tag, .op = .read, .node = o.node, .handle = o.h, .size = 64 }, true),
+ 6 => _ = try n.serve(.{ .tag = tag, .op = .setattr, .node = o.node, .handle = o.h, .truncate = true }, true),
+ else => {
+ _ = try n.serve(.{ .tag = tag, .op = .release, .node = o.node, .handle = o.h, .opened = true }, true);
+ held[at] = held[nheld - 1];
+ nheld -= 1;
+ },
+ }
+ }
+}
+
+test "a 9P request answered while a join's dump is out in the host is the client's next unit's, not its load's: a join asks the host nothing, and the client loads the session at the welcome's digest" {
+ var n = try NinepJoin.init("one\n", TestHost.host());
+ defer n.deinit();
+ // The session's io, whose stat lets a connection task in first, as the
+ // turn's yield around a host call does (tape.out): a script's open of
+ // /screen, a request that waits for no quiet (ninep/tree.zig needsQuiet).
+ const Gap = struct {
+ var on: *NinepJoin = undefined;
+ var base: std.Io = undefined;
+ var vtable: std.Io.VTable = undefined;
+ var served: u32 = 0;
+ fn stat(ud: ?*anyopaque, dir: std.Io.Dir, path: []const u8, o: std.Io.Dir.StatFileOptions) std.Io.Dir.StatFileError!std.Io.File.Stat {
+ served += 1;
+ _ = on.a.core.serveFs(.{ .tag = 9, .op = .open, .node = @backingInt(pardes.ctlfs.TopFile.screen) });
+ return base.vtable.dirStatFile(ud, dir, path, o);
+ }
+ };
+ Gap.on = &n;
+ Gap.base = n.a.t.io;
+ Gap.vtable = n.a.t.io.vtable.*;
+ Gap.vtable.dirStatFile = Gap.stat;
+ n.a.t.io = .{ .userdata = Gap.base.userdata, .vtable = &Gap.vtable };
+ const yields = pardes.turn.yields;
+ n.loadsSame() catch |err| {
+ std.debug.print("the join's dump asked the host {d} times, gave up the turn {d} times\n", .{ Gap.served, pardes.turn.yields - yields });
+ return err;
+ };
+ try std.testing.expectEqual(yields, pardes.turn.yields);
+ try std.testing.expectEqual(0, Gap.served);
+}
+
test "a client joined while a script's open of a pane's exec holds half a line runs the line its session runs" {
var n = try NinepJoin.init("one\n", TestHost.host());
defer n.deinit();