diff options
| -rw-r--r-- | test/replicas.zig | 340 |
1 files changed, 339 insertions, 1 deletions
diff --git a/test/replicas.zig b/test/replicas.zig index 126b0410..4adc3240 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -57,6 +57,9 @@ var trace = false; /// the pty's bytes its units carry into an emulator of its own, joined from /// a dump with every emulator whole (core/replica.zig `Peers.bytes`). var bytes_kind = false; +/// `--witness`: the witness judged at every run's end, not only after a +/// divergence (`Witness`). +var witness_always = false; /// The PDF the soak opens (`--pdf`), absolute. var pdf_path: ?[]const u8 = null; const frame_us = 16_667; @@ -779,6 +782,7 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run, if (r.diverged) |why| { if (link.put_off) totals.rejoined += 1 else { totals.divergences += 1; + Witness.failed(c, why); std.debug.print("seed {d} rtt {d} ms: client {d} diverged: {s}\n", .{ run_.seed, run_.rtt_ms, c + 1, why }); } } @@ -799,6 +803,282 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run, } } +/// The witness (a failure's report): the session's stream as its clients +/// were sent it (units and blobs, in its order, each kept once as the +/// first client's writer forwards it: no copy a client, no step: the +/// clients' pace is the run's) and every join's dump with where in that +/// stream its client began. At the run's end, only when a client diverged, +/// a replica that speculates nothing replays it from the first dump on, +/// every unit's digest compared: does the session's own tape bring a fresh +/// core to the session's digests? Where it does not, the session's step +/// read what its tape does not carry: the unit's records said, and the +/// fields named against the next dump (or the session at the end). +/// A loop inside one call that does not end (the soak's clock stands +/// still: `Soak.watch` never runs): a thread that sees no message taken for +/// `stuck_s` of the machine's clock says the last ones, has gdb print every +/// thread's stack (the soak lets any process of its own trace it: `main`'s +/// PR_SET_PTRACER), and ends the run. +const Watchdog = struct { + extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; + const stuck_s = 240; + var taken: std.atomic.Value(u64) = .init(0); + var last: [8]struct { kind: Kind = .wake, who: u16 = 0, at: u64 = 0 } = @splat(.{}); + + fn took(m: Msg) void { + const n = taken.fetchAdd(1, .monotonic); + last[n % last.len] = .{ .kind = m.kind, .who = m.who, .at = m.at }; + } + + fn said() void { + const n = taken.load(.monotonic); + std.debug.print(" the last messages taken (of {d}):", .{n}); + for (0..@min(n, last.len)) |k| { + const e = last[(n - 1 - k) % last.len]; + std.debug.print(" {t} of {d} at {d} us;", .{ e.kind, e.who, e.at }); + } + std.debug.print("\n", .{}); + } + + fn run() void { + var was = taken.load(.monotonic); + var still: u32 = 0; + while (true) { + var ts: libc.timespec = .{ .sec = 10, .nsec = 0 }; + _ = libc.nanosleep(&ts, null); + const now = taken.load(.monotonic); + if (now != was) { + was = now; + still = 0; + continue; + } + still += 10; + if (still < stuck_s) continue; + std.debug.print("watchdog: no message taken for {d} s of the machine's clock: a loop inside one call\n", .{still}); + said(); + var pid_buf: [16]u8 = undefined; + const pid = std.fmt.bufPrintSentinel(&pid_buf, "{d}", .{libc.getpid()}, 0) catch unreachable; + const argv = [_:null]?[*:0]const u8{ "gdb", "-batch", "-p", pid, "-ex", "thread apply all bt 30", null }; + const child = libc.fork(); + if (child == 0) { + _ = libc.dup2(2, 1); + _ = execvp("gdb", &argv); + libc._exit(127); + } + if (child > 0) { + var status: c_int = 0; + _ = libc.waitpid(child, &status, 0); + } + libc._exit(3); + } + } +}; + +const Witness = struct { + const Sent = struct { blob: bool, bytes: []u8 }; + const Dump = struct { c: usize, id: u16, view: u8, cols: u16, rows: u16, join_seq: u32, bytes: []u8, start: ?usize = null }; + const Failure = struct { c: usize, why: []u8, at: usize }; + var sent: std.ArrayListUnmanaged(Sent) = .empty; + var dumps: std.ArrayListUnmanaged(Dump) = .empty; + var failures: std.ArrayListUnmanaged(Failure) = .empty; + /// Each client's place in `sent` (null: none yet since its join), and + /// its join's dump. + var at: [8]?usize = @splat(null); + var dump_of: [8]usize = @splat(0); + var broken: ?[]const u8 = null; + + fn joined(c: usize, cl: *const Client, bytes: []u8, join_seq: u32) void { + dump_of[c] = dumps.items.len; + at[c] = null; + dumps.append(gpa, .{ .c = c, .id = cl.id, .view = cl.view, .cols = cl.cols, .rows = cl.rows, .join_seq = join_seq, .bytes = bytes }) catch @panic("witness: out of memory"); + } + + /// A unit's origin and number. + fn head(bytes: []const u8) u48 { + return std.mem.readInt(u48, bytes[0..6], .little); + } + + fn same(s: Sent, blob: bool, bytes: []const u8) bool { + if (s.blob != blob or s.bytes.len != bytes.len) return false; + // A unit's clock words are each client's (`Soak.stamp`). + if (!blob) return head(s.bytes) == head(bytes) and std.mem.eql(u8, s.bytes[unit_head_len..], bytes[unit_head_len..]); + return std.mem.eql(u8, s.bytes, bytes); + } + const unit_head_len = 22; + + /// Client `c`'s writer forwarded `bytes` (a unit or a blob piece). + fn forwarded(c: usize, blob: bool, bytes: []const u8) void { + // Its join is not kept (the run's end judged it). + if (dump_of[c] >= dumps.items.len) return; + const i = at[c] orelse place: { + // Its first since its join: kept already (another's writer + // forwarded it first), else the next. + var i = sent.items.len; + while (i > 0 and sent.items.len - i < 1 << 14) { + i -= 1; + if (same(sent.items[i], blob, bytes)) break :place i; + } + break :place sent.items.len; + }; + if (at[c] == null) dumps.items[dump_of[c]].start = i; + if (i == sent.items.len) { + sent.append(gpa, .{ .blob = blob, .bytes = gpa.dupe(u8, bytes) catch @panic("witness: out of memory") }) catch @panic("witness: out of memory"); + } else if (broken == null and !same(sent.items[i], blob, bytes)) broken = "a client was sent another stream than the one kept"; + at[c] = i + 1; + } + + fn failed(c: usize, why: []const u8) void { + failures.append(gpa, .{ .c = c, .why = gpa.dupe(u8, why) catch return, .at = at[c] orelse 0 }) catch {}; + } + + fn reset() void { + for (sent.items) |m| gpa.free(m.bytes); + sent.clearRetainingCapacity(); + for (dumps.items) |d| gpa.free(d.bytes); + dumps.clearRetainingCapacity(); + for (failures.items) |f| gpa.free(f.why); + failures.clearRetainingCapacity(); + at = @splat(null); + broken = null; + } + + /// A replica of dump `d`, as the soak's clients make theirs. + fn load(d: *const Dump) !*replica.Replica { + var distrusted: pardes.Addon.Distrusted = .{}; + // No client's id: every unit is another's. + const rp = try replica.Replica.initDump(gpa, std.math.maxInt(u16), d.view, d.bytes, .{ .cols = d.cols, .rows = d.rows, .distrusted = &distrusted }); + rp.guess = false; + if (bytes_kind) { + rp.t.screen_state = false; + rp.core().echo = null; + } + rp.t.local_files = true; + return rp; + } + + /// Each field of the core, its stream, its views and its panes whose + /// digest differs between `a` and `b`, named (tape.zig's digestParts', + /// by name), and each terminal's screen. + fn fieldsDiffer(a: *const pardes.Pardes, b: *const pardes.Pardes, w: *std.Io.Writer) void { + const walk = pardes.walk; + const Each = struct { + fn of(comptime T: type, x: *const T, y: *const T, prefix: []const u8, out: *std.Io.Writer) void { + const names = comptime walk.fieldNames(T); + var dx: [names.len]u64 = undefined; + var dy: [names.len]u64 = undefined; + _ = walk.fieldDigests(T, x, &dx); + _ = walk.fieldDigests(T, y, &dy); + for (names, dx, dy) |name, u, v| if (u != v) out.print("{s}{s} ", .{ prefix, name }) catch {}; + } + }; + Each.of(pardes.Pardes, a, b, "", w); + Each.of(pardes.Stream, &a.stream, &b.stream, "stream.", w); + for (&a.views, &b.views, 0..) |*x, *y, k| if (x.* != null and y.* != null) { + var buf: [24]u8 = undefined; + Each.of(pardes.Pardes.View, &x.*.?, &y.*.?, std.fmt.bufPrint(&buf, "views[{d}].", .{k}) catch "", w); + } else if ((x.* == null) != (y.* == null)) w.print("views[{d}] (one side only) ", .{k}) catch {}; + for (a.panes, b.panes, 0..) |x, y, id| { + if (x == null or y == null) { + if ((x == null) != (y == null)) w.print("pane {d} (one side only) ", .{id}) catch {}; + continue; + } + var buf: [24]u8 = undefined; + Each.of(pardes.Pane, x.?, y.?, std.fmt.bufPrint(&buf, "pane {d}.", .{id}) catch "", w); + if (x.?.terminal) |sx| if (y.?.terminal) |sy| { + const ex = &pardes.Term.emulatorOf(sx).vt; + const ey = &pardes.Term.emulatorOf(sy).vt; + w.print("[pane {d}'s screen {s}] ", .{ id, if (screenHash(ex) == screenHash(ey)) "equal" else "DIFFERS" }) catch {}; + }; + } + w.writeByte('\n') catch {}; + } + + /// At the run's end (the session's core still whole), when a client + /// diverged: the stream replayed from each dump on, as said above. + fn judge(s: *Soak) void { + if (failures.items.len == 0 and !witness_always) return; + const on = pardes.tape.on; + const trees = pardes.syntax.held_trees; + pardes.tape.on = null; + pardes.syntax.held_trees = null; + defer { + pardes.tape.on = on; + pardes.syntax.held_trees = trees; + } + var out_buf: [1 << 14]u8 = undefined; + var stderr = std.Io.File.stderr().writer(s.l.peers.io, &out_buf); + const w = &stderr.interface; + defer w.flush() catch {}; + const tag = .{ s.r.seed, s.r.rtt_ms }; + w.print("seed {d} rtt {d} ms: witness: {d} messages kept, {d} dumps{s}{s}\n", tag ++ .{ sent.items.len, dumps.items.len, if (broken != null) ": " else "", broken orelse "" }) catch {}; + for (failures.items) |f| { + const u: ?replica.Unit = if (f.at > 0 and !sent.items[f.at - 1].blob) replica.parseUnit(sent.items[f.at - 1].bytes) else null; + w.print("seed {d} rtt {d} ms: witness: client {d} failed at message {d} (unit {d}/{d}): {s}\n", tag ++ .{ f.c + 1, f.at -| 1, if (u) |x| x.origin else 0, if (u) |x| x.seq else 0, f.why }) catch {}; + } + var d: usize = 0; + while (d < dumps.items.len) { + const from = &dumps.items[d]; + const start = from.start orelse { + d += 1; + continue; + }; + const rp = load(from) catch |err| { + w.print("seed {d} rtt {d} ms: witness: dump {d} does not load: {t}\n", tag ++ .{ d, err }) catch {}; + d += 1; + continue; + }; + defer rp.deinit(); + var last0: u32 = from.join_seq; + var parted: ?usize = null; + var i = start; + const end = end: while (i < sent.items.len) : (i += 1) { + const m = sent.items[i]; + if (m.blob) { + rp.blobPiece(m.bytes); + continue; + } + const u = replica.parseUnit(m.bytes) orelse continue; + // A stretch no client was sent (none was joined): the stream + // has a gap here. + if (u.origin == 0 and u.seq != last0 + 1) break :end i; + if (u.origin == 0) last0 = u.seq; + rp.since_check = if (parted == null) 1 << 20 else 0; + rp.confirm(m.bytes); + if (rp.diverged) |why| { + if (parted == null) { + parted = i; + w.print("seed {d} rtt {d} ms: witness from dump {d} (client {d}'s, after unit 0/{d}, message {d}) PARTS at message {d}, unit {d}/{d} ({d} bytes): {s}\n its records:\n", tag ++ .{ d, from.c + 1, from.join_seq, start, i, u.origin, u.seq, u.tape.len, why }) catch {}; + pardes.tape.describe(u.tape, w); + } + // On over it, to the next dump, unchecked. + gpa.free(rp.diverged.?); + rp.diverged = null; + rp.t.diverged = null; + } + // The next dump begins here: what differs then, by field. + if (parted != null) for (dumps.items[d + 1 ..], d + 1..) |*next, k| if (next.start == i + 1) { + const there = load(next) catch break; + defer there.deinit(); + w.print(" against dump {d} (after unit 0/{d}): ", .{ k, next.join_seq }) catch {}; + fieldsDiffer(rp.core(), there.core(), w); + break :end i + 1; + }; + } else i; + if (parted == null) { + w.print("seed {d} rtt {d} ms: witness from dump {d} (client {d}'s, message {d}): messages to {d} replayed to the session's every digest{s}", tag ++ .{ d, from.c + 1, start, end, if (end == sent.items.len) "; at the end against the session: " else " (a gap: no client was joined)\n" }) catch {}; + if (end == sent.items.len) fieldsDiffer(rp.core(), s.l.core, w); + } else if (end == sent.items.len) { + w.print(" at the end against the session: ", .{}) catch {}; + fieldsDiffer(rp.core(), s.l.core, w); + } + // Next: the first dump that begins at or after where this one ended. + const next = for (dumps.items[d + 1 ..], d + 1..) |x, k| { + if (x.start) |st| if (st >= end) break k; + } else dumps.items.len; + d = next; + } + } +}; + /// When the session's shell's program prints (`.output`): a full-screen /// program, a shell's session, then the flood. const tui_at: u64 = 400_000; @@ -888,6 +1168,10 @@ const Soak = struct { far_joined: u64 = 0, far_final: bool = false, join_worst: u64 = 0, + /// The watchdog's (`watch`): what the steps and checks made came to, and + /// the soak's time it last moved. + moved: u64 = 0, + moved_at: u64 = 0, fn of(ctx: ?*anyopaque) *Soak { return @ptrCast(@alignCast(ctx.?)); @@ -1128,6 +1412,7 @@ const Soak = struct { cl.view = welcome.view.index(); cl.digest = welcome.digest; s.totals.joins += 1; + Witness.joined(c, cl, try gpa.dupe(u8, whole.items), cl.join_seq); try net.toClient(c, now, .dump, cl.gen, try whole.toOwnedSlice(gpa)); }; // A Detach typed in a client's view, or one cut off for its lag: its @@ -1220,6 +1505,7 @@ const Soak = struct { const flooding = now >= flood_at and s.flood_end == 0; switch (std.enums.fromInt(pardes.wire.ServerTag, f.tag) orelse return error.BadFrame) { .unit => { + Witness.forwarded(c, false, f.payload); s.totals.unit_bytes += f.payload.len; if (flooding) s.totals.flood_unit_bytes += f.payload.len; try net.toClient(c, now, .to_replica, cl.gen, try gpa.dupe(u8, f.payload)); @@ -1237,7 +1523,10 @@ const Soak = struct { std.mem.writeInt(u64, d[0..8], (try pardes.wire.decodeServer(f.tag, f.payload)).check, .little); try net.toClient(c, now, .checked, cl.gen, d); }, - .blob => try net.toClient(c, now, .blob, cl.gen, try gpa.dupe(u8, f.payload)), + .blob => { + Witness.forwarded(c, true, f.payload); + try net.toClient(c, now, .blob, cl.gen, try gpa.dupe(u8, f.payload)); + }, .refused => try net.toClient(c, now, .word, cl.gen, try gpa.dupe(u8, (try pardes.wire.decodeServer(f.tag, f.payload)).refused)), else => return error.UnexpectedFrame, } @@ -1295,6 +1584,7 @@ const Soak = struct { // What its boundary took is old news. _ = s.l.peers.urgent.swap(false, .acq_rel); while (true) { + try s.watch(); const next = net.q.peek() orelse return !took_output; // Every typist done, the flood over and its frames' two seconds // past: what is in flight is delivered and the run ends. The @@ -1313,6 +1603,7 @@ const Soak = struct { const m = net.q.pop().?; var kept = false; defer if (!kept and m.bytes.len > 0) gpa.free(m.bytes); + Watchdog.took(m); s.now = m.at; Draws.now = m.at; // A client's message, but an echo's and an output's `who` (a pane, @@ -1574,6 +1865,41 @@ const Soak = struct { } } + /// No step of the session's and no unit or check of a client's for + /// `stuck_us` of the soak's own clock: a loop that does not end. Every + /// side's state said, and the run failed. + fn watch(s: *Soak) !void { + var moved: u64 = s.l.peers.seq; + for (s.clients) |*cl| if (cl.r) |rp| { + moved +%= rp.stats.units +% rp.stats.checks +% rp.pending.items.len; + }; + if (moved != s.moved) { + s.moved = moved; + s.moved_at = s.now; + return; + } + if (s.now - s.moved_at < stuck_us) return; + std.debug.print("seed {d} rtt {d} ms: watchdog: nothing stepped or checked for {d} s of the soak's clock (since {d} us)\n", .{ s.r.seed, s.r.rtt_ms, stuck_us / std.time.us_per_s, s.moved_at }); + s.report(); + return error.Hung; + } + const stuck_us = 60 * std.time.us_per_s; + + /// Every side's state, for a run that hangs: the session's and each + /// client's, what each waits on and holds, and the last messages taken. + fn report(s: *Soak) void { + const ps = &s.l.peers; + const core = s.l.core; + std.debug.print(" session: unit 0/{d}, needs_frame {any}, next wake {?d} (now {d} ns), quit {any}; the net {d} in flight, the next {s}; typing {d}, own left {d}, frames left {d}, flood at {d} of {d} (ended {d}), held {any}\n", .{ ps.seq, core.needs_frame, core.nextWake(), s.now_ns, core.quit, s.net.q.count(), if (s.net.q.peek()) |n| @tagName(n.kind) else "none", s.typing, s.own_left, s.frames_left, s.program.at, s.program.bytes.len, s.flood_end, s.held != null }); + for (s.clients, 1..) |*cl, id| { + std.debug.print(" client {d} ({t}): live {d} gen {d} dialling {any} left {d} wake_at {d}", .{ id, cl.kind, cl.live, cl.gen, cl.dialling, cl.left, cl.wake_at }); + if (cl.peer) |p| std.debug.print(", its queue at the session {d} B, sending {d}/{d}, shut {any} draining {any}", .{ p.out.items.len, cl.at, cl.sending.items.len, cl.shut, cl.draining }); + if (cl.r) |rp| std.debug.print(", replica: units {d} checks {d} pending {d} applied {d} blocked {?d} since {d} copy {any} diverged {any}, link quit {any} asked {any} behind {d} ms", .{ rp.stats.units, rp.stats.checks, rp.pending.items.len, rp.applied, rp.blocked, rp.since.items.len, rp.copy.held, rp.diverged != null, cl.loop.link.quit, cl.loop.link.asked, cl.loop.link.behind / std.time.ns_per_ms }); + std.debug.print("\n", .{}); + } + Watchdog.said(); + } + /// An input of its own frontend's, in the view it shows (the first: /// tui.zig `Shell.apply` goes into `s.own`). fn own(s: *Soak, m: Msg) !void { @@ -1689,6 +2015,7 @@ const Soak = struct { if (cl.live == 0) continue; if (rp.diverged) |why| { totals.divergences += 1; + Witness.failed(id - 1, why); std.debug.print("seed {d} rtt {d} ms: client {d} diverged: {s}\n", .{ s.r.seed, s.r.rtt_ms, id, why }); } else if (!rp.quiet() or rp.digest() != want) { totals.unequal += 1; @@ -1726,11 +2053,14 @@ const Soak = struct { } } } + Witness.judge(s); } }; fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { if (trace) std.debug.print("seed {d} rtt {d} ms\n", .{ r.seed, r.rtt_ms }); + Witness.reset(); + defer Witness.reset(); var prng = std.Random.DefaultPrng.init(r.seed *% 0x9e3779b97f4a7c15 +% r.rtt_ms); const random = prng.random(); var paths: [3][256:0]u8 = undefined; @@ -3055,6 +3385,10 @@ fn floods(io: std.Io, w: *std.Io.Writer) !void { pub fn main(init: std.process.Init) !void { const args = try init.minimal.args.toSlice(init.arena.allocator()); + // A loop that does not end names itself (`Watchdog`): its gdb, a child, + // may trace this process. + _ = std.os.linux.prctl(@backingInt(std.os.linux.PR.SET_PTRACER), std.math.maxInt(usize), 0, 0, 0); + if (std.Thread.spawn(.{}, Watchdog.run, .{})) |th| th.detach() else |_| {} var seeds: u64 = 4; var first: u64 = 0; var steps: usize = 120; @@ -3077,6 +3411,10 @@ pub fn main(init: std.process.Init) !void { bytes_kind = true; continue; } + if (std.mem.eql(u8, name, "--witness")) { + witness_always = true; + continue; + } if (i + 1 >= args.len) return error.MissingValue; i += 1; const value = args[i]; |
