diff options
Diffstat (limited to 'test')
| -rw-r--r-- | test/consumer/build.zig | 77 | ||||
| -rw-r--r-- | test/consumer/lib.zig | 95 | ||||
| -rw-r--r-- | test/consumer/none.zig | 56 | ||||
| -rw-r--r-- | test/consumer/one.zig | 45 | ||||
| -rw-r--r-- | test/consumer/wasm.mjs | 113 | ||||
| -rw-r--r-- | test/daemon.py | 97 | ||||
| -rw-r--r-- | test/replicas.zig | 720 |
7 files changed, 1124 insertions, 79 deletions
diff --git a/test/consumer/build.zig b/test/consumer/build.zig index c643bfb3..45e1e2e5 100644 --- a/test/consumer/build.zig +++ b/test/consumer/build.zig @@ -1,33 +1,96 @@ //! A package that depends on pardes, as a program would (build.zig's head //! comment has its lines): pardes's `consumer-test`, which `unit-test` runs, //! runs `zig build test` here. `pardes-syntax` with the minimal grammars, -//! as a program that draws source text itself takes it; and -//! `pardes-editor` with no grammar of pardes's and one of its own, C's, -//! compiled here from the package pardes pins and handed in at run time, -//! as sketchbook's `examples/live` takes it. +//! as a program that draws source text itself takes it; with one language +//! named, for each language of pardes's manifest, read here at configure +//! time; `pardes-editor` with no grammar of pardes's and one of its own, +//! C's, compiled here from the package pardes pins and handed in at run +//! time, as sketchbook's `examples/live` takes it; and the browser's modules +//! pardes's build makes (`wasmModule`), run under node when it is there. const std = @import("std"); +const pardes = @import("pardes"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); + // A name pardes's manifest does not have ends the configure: the step + // `bad-language` below runs this build with one. + if (b.option([]const u8, "language", "configure pardes with this one language named, and stop")) |name| { + _ = b.dependency("pardes", .{ .target = target, .optimize = optimize, .languages = name }); + return; + } const syntax = b.dependency("pardes", .{ .target = target, .optimize = optimize, .grammars = .minimal }); const editor = b.dependency("pardes", .{ .target = target, .optimize = optimize, .grammars = .none, .editor = true }); // The grammar of its own: C's, from the package pardes's manifest pins // (so `--pkg-dir` at pardes's zig-pkg has it), as that package builds it. const grammar = b.dependency("ts_c", .{ .target = target, .optimize = .ReleaseFast, .@"build-shared" = false }).artifact("tree-sitter-c"); - const step = b.step("test", "colour, outline and walk a C and a Zig source through pardes's syntax, and edit a text with its editor and a grammar of this package's"); + const step = b.step("test", "colour, outline and walk a C and a Zig source through pardes's syntax, build it with one language named, edit a text with its editor and a grammar of this package's, and run a browser's modules"); // A file belongs to one module: the syntax alone, and the editor (which // has it as `.syntax`), each a test of its own. - for ([_]struct { []const u8, []const u8, *std.Build.Dependency }{ .{ "lib.zig", "pardes-syntax", syntax }, .{ "editor.zig", "pardes-editor", editor } }) |t| { + // The patch view with no grammar at all: the editor's package has + // `pardes-syntax` too. + for ([_]struct { []const u8, []const u8, *std.Build.Dependency }{ .{ "lib.zig", "pardes-syntax", syntax }, .{ "editor.zig", "pardes-editor", editor }, .{ "none.zig", "pardes-syntax", editor } }) |t| { const mod = b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path(t[0]), .imports = &.{.{ .name = t[1], .module = t[2].module(t[1]) }}, }); - if (t[2] == editor) mod.linkLibrary(grammar); + if (std.mem.eql(u8, t[1], "pardes-editor")) mod.linkLibrary(grammar); step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mod })).step); } + + // Each language a file names, from pardes's manifest: `pardes-syntax` + // with it alone (and what it needs). `test` runs two: rust, alone, and + // markdown, which brings its inline grammar. + const each = b.step("each-language", "build and test pardes-syntax with each language of its manifest named alone"); + // A browser's module a language, and the patch view's: `sizes` + // installs every one; `test` runs the patch view's and rust's. + const sizes = b.step("sizes", "install a browser's module for each language, and the patch view's, into <prefix>/bin"); + const patch = pardes.wasmModule(b, .{}); + sizes.dependOn(&b.addInstallArtifact(patch, .{}).step); + var rust: ?*std.Build.Step.Compile = null; + for (pardes.grammar_manifest.all) |g| if (g.exts.len > 0) { + const module = pardes.wasmModule(b, .{ .language = g.name }); + sizes.dependOn(&b.addInstallArtifact(module, .{}).step); + if (std.mem.eql(u8, g.name, "rust")) rust = module; + const name = b.addOptions(); + name.addOption([]const u8, "name", g.name); + const one = b.addRunArtifact(b.addTest(.{ .name = b.fmt("one-{s}", .{g.name}), .root_module = b.createModule(.{ + .target = target, + .optimize = optimize, + .root_source_file = b.path("one.zig"), + .imports = &.{ + .{ .name = "pardes-syntax", .module = b.dependency("pardes", .{ .target = target, .optimize = optimize, .languages = g.name }).module("pardes-syntax") }, + .{ .name = "language", .module = name.createModule() }, + }, + }) })); + each.dependOn(&one.step); + if (std.mem.eql(u8, g.name, "rust") or std.mem.eql(u8, g.name, "markdown")) step.dependOn(&one.step); + }; + // Each run as a page runs it, its WASI imports stubs. + if (b.findProgram(.{ .names = &.{"node"} })) |node| { + const run = b.addSystemCommand(&.{node}); + run.setName("node: the patch view's module and rust's"); + run.addFileArg(b.path("wasm.mjs")); + run.addArtifactArg(patch); + run.addArtifactArg(rust.?); + run.expectExitCode(0); + step.dependOn(&run.step); + } else { + std.debug.print("consumer-test: no node on PATH: the browser's modules are built, not run\n", .{}); + step.dependOn(&patch.step); + step.dependOn(&rust.?.step); + } + // ...and a name it does not have: the configure fails, saying so. + const bad = b.addSystemCommand(&.{ b.graph.zig_exe, "build", "-Dlanguage=klingon", "--pkg-dir", "../../zig-pkg" }); + bad.setName("a language pardes does not have fails the configure"); + bad.setCwd(b.path(".")); + bad.expectExitCode(1); + bad.addCheck(.{ .expect_stderr_match = "no language \"klingon\"" }); + bad.has_side_effects = true; + step.dependOn(&bad.step); + // What a key costs, a page count and a parse: `zig build bench -- <KiB> <keys>`. const bench = b.addExecutable(.{ .name = "bench", .root_module = b.createModule(.{ .target = target, diff --git a/test/consumer/lib.zig b/test/consumer/lib.zig index 7e297920..fa0f8aee 100644 --- a/test/consumer/lib.zig +++ b/test/consumer/lib.zig @@ -159,3 +159,98 @@ test "a diff is a language: its hunks coloured as their file's, its added and re test "every name the library has compiles outside pardes" { std.testing.refAllDecls(pardes); } + +// ---- the patch view (+Diff), without the editor ---- + +const patch_c = + \\diff --git a/main.c b/main.c + \\--- a/main.c + \\+++ b/main.c + \\@@ -2,4 +2,4 @@ int main(void) + \\ { + \\- int x = foo(1); + \\+ int x = bar(1); + \\ return x; + \\ } + \\\ No newline at end of file + \\ +; +/// main.c as the patch leaves it: what a reader hands in as its source. +const main_c = "int main(void)\n{\n int x = bar(1);\n return x;\n}"; + +/// Each byte of `text` that has `bit`, the rest as dots. +fn marked(buf: []u8, text: []const u8, styles: []const u8, bit: u8) []const u8 { + for (buf[0..text.len], text, styles) |*o, c, s| o.* = if (s & bit != 0) c else '.'; + return buf[0..text.len]; +} + +test "a diff stacked with no file to read: numbered by the diff, under git's function line, its changed words emphasised" { + const gpa = std.testing.allocator; + pardes.start(gpa); + defer pardes.stop(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const ctx: pardes.PatchCtx = .{ .arena = arena.allocator(), .colors = pardes.PatchCtx.languages }; + const p = try pardes.formatPatch(&ctx, "", patch_c); + try std.testing.expectEqualStrings("main.c:3\n int main(void)\n {\n- int x = foo(1);\n+ int x = bar(1);\n return x;\n }\n", p.text); + const Kind = pardes.PatchRow.Kind; + const want = [_]struct { Kind, ?usize, ?usize }{ + .{ .hunk, null, null }, + // the `@@`'s own words: the hunk's context + .{ .declaration, null, null }, + .{ .context, 2, 2 }, + .{ .removed, 3, null }, + .{ .added, null, 3 }, + .{ .context, 4, 4 }, + .{ .context, 5, 5 }, + }; + try std.testing.expectEqual(want.len, p.rows.len); + for (want, p.rows) |w, row| { + try std.testing.expectEqual(w[0], row.kind); + try std.testing.expectEqual(w[1], row.old); + try std.testing.expectEqual(w[2], row.new); + try std.testing.expectEqualStrings("main.c", row.path); + } + try std.testing.expectEqual(3, p.rows[0].line); + try std.testing.expectEqual("main.c:3".len, p.rows[0].location_end); + try std.testing.expect(p.rows[6].no_newline and !p.rows[5].no_newline); + var lines = std.mem.splitScalar(u8, p.text, '\n'); + var buf: [64]u8 = undefined; + for (p.rows) |row| { + const line = lines.next().?; + if (row.styles.len > 0) try std.testing.expectEqual(line.len, row.styles.len); + switch (row.kind) { + // the words a changed line changed, on both lines; each on its + // ground, its marker not on the line's own (it was paired) + .removed => try std.testing.expectEqualStrings(".............foo....", marked(&buf, line, row.styles, pardes.ground_emph)), + .added => try std.testing.expectEqualStrings(".............bar....", marked(&buf, line, row.styles, pardes.ground_emph)), + else => {}, + } + if (row.kind == .removed) try std.testing.expectEqual(pardes.ground_del, row.styles[0]); + if (row.kind == .added) try std.testing.expectEqual(pardes.ground_add, row.styles[0]); + } + // coloured as C: `return` a keyword + const ret = p.rows[5].styles[std.mem.indexOf(u8, " return x;", "return").?]; + try std.testing.expectEqual(pardes.Syn.keyword, @as(pardes.Syn, @fromBackingInt(ret & pardes.syn_bits))); +} + +test "a diff stacked with its file handed in: the declaration it stands in, from the file's own parse" { + const gpa = std.testing.allocator; + pardes.start(gpa); + defer pardes.stop(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const Given = struct { + fn source(_: *const pardes.PatchCtx, _: []const u8, path: []const u8) ?pardes.PatchSource { + return if (std.mem.eql(u8, path, "main.c")) .{ .path = path, .bytes = main_c } else null; + } + }; + const ctx: pardes.PatchCtx = .{ .arena = arena.allocator(), .source = Given.source, .declarations = pardes.PatchCtx.parsed, .colors = pardes.PatchCtx.languages }; + const p = try pardes.formatPatch(&ctx, "", patch_c); + try std.testing.expectEqualStrings("main.c:1\n int main(void)\nmain.c:3 *\n {\n- int x = foo(1);\n+ int x = bar(1);\n return x;\n }\n", p.text); + try std.testing.expectEqual(pardes.PatchRow.Kind.declaration, p.rows[0].kind); + try std.testing.expectEqual(1, p.rows[0].line); + try std.testing.expectEqual(pardes.PatchRow.Kind.declaration, p.rows[1].kind); + try std.testing.expectEqual(pardes.PatchRow.Kind.hunk, p.rows[2].kind); + try std.testing.expectEqual("main.c:3".len, p.rows[2].location_end); +} diff --git a/test/consumer/none.zig b/test/consumer/none.zig new file mode 100644 index 00000000..a389d429 --- /dev/null +++ b/test/consumer/none.zig @@ -0,0 +1,56 @@ +//! The patch view in a build with no grammar at all (`.grammars = .none`): +//! a diff of a file in a language it does not have still gets its grounds, +//! its changed words and its rows, and the colours it is not given stay +//! out. +const std = @import("std"); +const ps = @import("pardes-syntax"); + +const patch_rs = + \\diff --git a/src/lib.rs b/src/lib.rs + \\--- a/src/lib.rs + \\+++ b/src/lib.rs + \\@@ -10,3 +10,3 @@ fn total(items: &[u32]) -> u32 { + \\ let mut sum = 0; + \\- for i in items { sum += i; } + \\+ for i in items { sum += *i; } + \\ sum + \\ +; + +test "a diff with no grammar in the build: rows, grounds and changed words, no colours" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + try std.testing.expect(!ps.supportsPath("lib.rs")); + const ctx: ps.PatchCtx = .{ .arena = arena.allocator() }; + const p = try ps.formatPatch(&ctx, "", patch_rs); + try std.testing.expectEqualStrings("src/lib.rs:11\n fn total(items: &[u32]) -> u32 {\n let mut sum = 0;\n- for i in items { sum += i; }\n+ for i in items { sum += *i; }\n sum\n", p.text); + try std.testing.expectEqual(ps.PatchRow.Kind.hunk, p.rows[0].kind); + try std.testing.expectEqual(ps.PatchRow.Kind.declaration, p.rows[1].kind); + const removed = p.rows[3]; + const added = p.rows[4]; + try std.testing.expectEqual(.{ 11, null }, .{ removed.old, removed.new }); + try std.testing.expectEqual(.{ null, 11 }, .{ added.old, added.new }); + try std.testing.expectEqual(ps.ground_del, removed.styles[0]); + try std.testing.expectEqual(ps.ground_add, added.styles[0]); + // `*` added: the one word emphasised; no byte has a colour of its own + const star = std.mem.indexOfScalar(u8, "+ for i in items { sum += *i; }", '*').?; + for (added.styles, 0..) |s, i| try std.testing.expectEqual(i == star, s & ps.ground_emph != 0); + for (p.rows) |row| for (row.styles) |s| try std.testing.expectEqual(0, s & ps.syn_bits); +} + +test "with no grammar, a file handed in still places the hunk, and no declaration is made up" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const Given = struct { + fn source(_: *const ps.PatchCtx, _: []const u8, path: []const u8) ?ps.PatchSource { + return .{ .path = path, .bytes = "\n" ++ "\n" ++ "\n" ++ "\n" ++ "\n" ++ "\n" ++ "\n" ++ "\n" ++ + "fn total(items: &[u32]) -> u32 {\n let mut sum = 0;\n for i in items { sum += *i; }\n sum\n}\n" }; + } + }; + const ctx: ps.PatchCtx = .{ .arena = arena.allocator(), .source = Given.source, .declarations = ps.PatchCtx.parsed }; + const p = try ps.formatPatch(&ctx, "", patch_rs); + // found (no `@@` words then: git's guess would only contradict the + // file's own), and no grammar to read a declaration from + try std.testing.expectEqualStrings("src/lib.rs:11\n let mut sum = 0;\n- for i in items { sum += i; }\n+ for i in items { sum += *i; }\n sum\n", p.text); + for (p.rows) |row| try std.testing.expect(row.kind != .declaration); +} diff --git a/test/consumer/one.zig b/test/consumer/one.zig new file mode 100644 index 00000000..4a113842 --- /dev/null +++ b/test/consumer/one.zig @@ -0,0 +1,45 @@ +//! `pardes-syntax` built with one language named (`.languages`, build.zig +//! here: the build's loop over pardes's manifest makes one of these a +//! language): that language and what it needs (the manifest's `needs`) are +//! compiled in, and no other. +const std = @import("std"); +const ps = @import("pardes-syntax"); +const language = @import("language").name; + +test "one language named: it and what it needs are in the build, no other grammar is linked" { + const gpa = std.testing.allocator; + ps.start(gpa); + defer ps.stop(); + const g = ps.grammars; + const named = comptime named: { + @setEvalBranchQuota(10_000); + break :named g.all[g.byName(language).?]; + }; + // This test program's own bytes (a Debug build keeps its symbols): a + // name is spelled whole only in its symbol table. + const self = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, "/proc/self/exe", gpa, .unlimited); + defer gpa.free(self); + var name: [64]u8 = undefined; + inline for (g.all) |other| { + const in = comptime std.mem.eql(u8, other.name, named.name) or for (named.needs) |n| { + if (std.mem.eql(u8, n, other.name)) break true; + } else false; + // the parser itself, by its symbol in this program's symbol table: + // linked, or not in it + const symbol = try std.fmt.bufPrint(&name, "\x00tree_sitter_{s}\x00", .{other.name}); + try std.testing.expectEqual(in, std.mem.indexOf(u8, self, symbol) != null); + if (other.exts.len > 0) try std.testing.expectEqual(in, ps.supportsPath(ps.pathFor(other.name).?)); + } + + // what two of them colour: rust alone, and markdown with the inline + // grammar it brings (its bold is markdown_inline's) + for ([_]struct { []const u8, []const u8, []const u8, ps.Syn }{ + .{ "rust", "fn main() { let x = 1; }\n", "fn", .keyword }, + .{ "markdown", "# Title\n\nsome **bold** text\n", "bold", .comment }, + }) |case| if (std.mem.eql(u8, case[0], named.name)) { + const styles = try ps.highlightFileRange(gpa, ps.pathFor(language).?, case[1], 0, case[1].len); + defer gpa.free(styles); + const at = std.mem.indexOf(u8, case[1], case[2]).?; + for (styles[at..][0..case[2].len]) |s| try std.testing.expectEqual(case[3], @as(ps.Syn, @fromBackingInt(s))); + }; +} diff --git a/test/consumer/wasm.mjs b/test/consumer/wasm.mjs new file mode 100644 index 00000000..9e76af0f --- /dev/null +++ b/test/consumer/wasm.mjs @@ -0,0 +1,113 @@ +// The browser's modules pardes builds (build.zig `wasmModule`), run as a +// page runs them: `node wasm.mjs PATCH.wasm LANGUAGE.wasm`. Every WASI +// import is a stub (fd_prestat_get says there is no directory, the rest +// that they are not there), and each module prints what it imports. +import { readFileSync } from "node:fs"; + +let failed = 0; +function expect(what, got, want) { + if (JSON.stringify(got) !== JSON.stringify(want)) { + console.error(`${what}: got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`); + failed++; + } +} + +function load(file) { + const mod = new WebAssembly.Module(readFileSync(file)); + const imports = WebAssembly.Module.imports(mod); + console.log(`${file}: ${imports.length} imports: ${imports.map((i) => i.module + "." + i.name).join(" ")}`); + let memory; + const wasi = new Proxy({}, { + get: (_, name) => (...a) => { + if (name === "fd_prestat_get") return 8; // EBADF: no preopened directory + if (name === "proc_exit") throw Error(`exit ${a[0]}`); + if (name === "fd_write") { + const [, iovs, n, written] = a; + const v = new DataView(memory.buffer); + let sum = 0; + for (let i = 0; i < n; i++) { + const p = v.getUint32(iovs + 8 * i, true), l = v.getUint32(iovs + 8 * i + 4, true); + process.stderr.write(Buffer.from(memory.buffer, p, l)); + sum += l; + } + v.setUint32(written, sum, true); + return 0; + } + return 52; // ENOSYS + }, + }); + const inst = new WebAssembly.Instance(mod, { wasi_snapshot_preview1: wasi }); + memory = inst.exports.memory; + inst.exports._initialize(); + return { ex: inst.exports, mem: () => memory.buffer }; +} + +const enc = new TextEncoder(), dec = new TextDecoder(); +function put(m, text) { + const b = enc.encode(text); + const p = m.ex.reserve(b.length); + new Uint8Array(m.mem(), p, b.length).set(b); + return [p, b.length]; +} + +// patch: the diff stacked, read from the header and its 36-byte records +const kinds = ["other", "meta", "hunk", "declaration", "context", "added", "removed"]; +function patch(m, diff) { + const [p, n] = put(m, diff); + const h = m.ex.patch(p, n); + m.ex.release(p, n); + const v = new DataView(m.mem()); + const [text, textLen, styles, rows, count] = [0, 4, 8, 12, 16].map((o) => v.getUint32(h + o, true)); + const bytes = new Uint8Array(m.mem(), text); + const out = []; + for (let i = 0; i < count; i++) { + const [kind, old, nw, codeStart, off, len, pathOff, pathLen, flags] = [...Array(9)].map((_, f) => v.getUint32(rows + 36 * i + 4 * f, true)); + out.push({ + kind: kinds[kind], old, new: nw, codeStart, flags, + text: dec.decode(bytes.subarray(off, off + len)), + path: dec.decode(bytes.subarray(pathOff, pathOff + pathLen)), + styles: [...new Uint8Array(m.mem(), styles + off, len)], + }); + } + return { text: dec.decode(bytes.subarray(0, textLen)), rows: out }; +} + +const diff = "diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -10,3 +10,3 @@ fn total(items: &[u32]) -> u32 {\n let mut sum = 0;\n- for i in items { sum += i; }\n+ for i in items { sum += *i; }\n sum\n\\ No newline at end of file\n"; +for (const file of process.argv.slice(2)) { + const m = load(file); + // reserve(0) is a pointer still + const zero = m.ex.reserve(0); + expect(`${file} reserve(0)`, zero !== 0, true); + m.ex.release(zero, 0); + + const p = patch(m, diff); + expect(`${file} patch text`, p.text, "src/lib.rs:11\n fn total(items: &[u32]) -> u32 {\n let mut sum = 0;\n- for i in items { sum += i; }\n+ for i in items { sum += *i; }\n sum\n"); + expect(`${file} patch rows`, p.rows.map((r) => [r.kind, r.old, r.new, r.path, r.flags]), [ + ["hunk", 0, 0, "src/lib.rs", 0], + ["declaration", 0, 0, "src/lib.rs", 0], + ["context", 10, 10, "src/lib.rs", 0], + ["removed", 11, 0, "src/lib.rs", 0], + ["added", 0, 11, "src/lib.rs", 0], + ["context", 12, 12, "src/lib.rs", 1], + ]); + expect(`${file} hunk code start`, p.rows[0].codeStart, "src/lib.rs:11".length); + // the added line: its ground on the marker (0x80), and `*` its changed word (0x20) + const added = p.rows[4]; + expect(`${file} added styles`, added.styles.map((s, i) => (s & 0x20 ? added.text[i] : s & 0x80 ? "+" : ".")).join(""), [...added.text].map((c, i) => (i === 0 ? "+" : c === "*" ? "*" : ".")).join("")); + + if (m.ex.highlight) { + const src = 'fn main() { let s = "x"; }\n'; + const [pp, pn] = put(m, "main.rs"); + const [tp, tn] = put(m, src); + // (a call can grow the memory: its buffer is taken after it) + const at = m.ex.highlight(pp, pn, tp, tn); + const s = new Uint8Array(m.mem(), at, tn); + expect(`${file} highlight fn`, [s[0], s[1]], [1, 1]); + expect(`${file} highlight "x"`, s[src.indexOf('"')], 2); + const c = put(m, "main.c"); + const other = m.ex.highlight(c[0], c[1], tp, tn); + expect(`${file} highlight another language`, [...new Uint8Array(m.mem(), other, tn)].every((b) => b === 0), true); + } +} +if (failed) process.exit(1); +console.log("wasm: the modules run"); diff --git a/test/daemon.py b/test/daemon.py index 7a600048..2c86c04f 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -36,7 +36,8 @@ private HOME and runtime directory: the daemon killed: its sessions register again with the next; and one stopped: an Adopt waits for its answer to the hello python3 -B test/daemon.py --far <pardes> - the far clients and their blob cache alone, and a file by its hash + the far clients and their blob cache alone, one under `yes` across + a slow link, and a file by its hash python3 -B test/daemon.py --games <pardes> <lib> [seconds] the games in the clients that show them, from zig build addon-test's <prefix>/lib (libsnake, liblife, libliar) @@ -2010,6 +2011,81 @@ def far(binary): shutil.rmtree(root, ignore_errors=True) +def far_flood(binary): + """A far client (PARDES_REPLICA_FAR) across a slow link (delay_relay.py: + 200 ms each way, 20 KB/s) while the session's shell runs `yes`: once + `yes` ends it agrees with the session, and its keys after go in. It + pulls its terminal's screen (screen state), so the flood does not + queue for it: it keeps up without joining again (two runs, 2026-11-20), + and replica.behind_max_ms is not reached this way.""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='fl-', dir=os.environ.get('TMPDIR') or scratch)) + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} + env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), + XDG_CACHE_HOME=str(root / 'cache'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', + PARDES_NOTIME='1') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + notes = root / 'notes.txt' + notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300))) + started = [] + terms = [] + try: + sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + started.append(sess.pid) + sock = root / 'pardes-replica.sock' + wait_for('the replica socket', sock.exists) + wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists) + nine = Client(root / 'pardes-9p-files.sock') + pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') + nine.write(f'/pane/{pane}/exec', b'Term\n') + shell = wait_for('a shell pane', lambda: next((int(row.split()[0]) for row in nine.read('/index').splitlines() + if row.split()[1] == b'term'), None)) + wait_for('the shell\'s prompt', lambda: b'$' in nine.read(f'/pane/{shell}/body') or b'#' in nine.read(f'/pane/{shell}/body')) + relay = subprocess.Popen([sys.executable, '-B', str(Path(__file__).parent / 'delay_relay.py'), + str(root / 'relay.sock'), str(sock), '--delay', '200', '--rate', '0.02'], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + started.append(relay.pid) + wait_for('the relay', (root / 'relay.sock').exists) + check = root / 'f.check' + t = Term(30, 100) + terms.append(t) + c = t.spawn([binary, f'--attach={root / "relay.sock"}:files'], + dict(env, PARDES_REPLICA_FAR='1', PARDES_REPLICA_CHECK=str(check))) + started.append(c.pid) + wait_for('the far client\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=60) + nine.write(f'/pane/{shell}/pty/data', b'timeout 20 yes; echo yes-done\r') + wait_for('yes ended', lambda: b'yes-done' in nine.read(f'/pane/{shell}/body').replace(b'\r', b''), timeout=60) + seen = len(checks(check)) + wait_for('the far client agrees once yes ended', lambda: agreed(check, seen), timeout=120) + os.write(t.master, b'echo from-far\r') + wait_for('the far client\'s keys in the shell', lambda: b'from-far' in nine.read(f'/pane/{shell}/body'), timeout=30) + seen = len(checks(check)) + wait_for('the far client agrees after its keys', lambda: agreed(check, seen), timeout=60) + # Its keys go to the shell: its terminal hangs up instead. + c.send_signal(signal.SIGHUP) + c.wait(timeout=10) + print(f'daemon: a far client across 20 KB/s and 200 ms each way under `yes` agreed once it ended ' + f'({len(checks(check))} checks) and its keys went in') + relay.kill() + relay.wait() + exit_session(nine, pane) + sess.wait(timeout=60) + nine.socket.close() + wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10) + finally: + for term in terms: + term.close() + for pid in started + processes(root): + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + shutil.rmtree(root, ignore_errors=True) + + def by_hash(binary): """A file over the wire's 16 MiB bound opened while clients are attached (its read was one unit, dropped: the client joined again, a @@ -3347,10 +3423,20 @@ def gui_upgrades(old, new): assert client.read(f'/pane/{text}/body') == b'one\ntwo\n' assert alive(shell_pid) and ppid(shell_pid) == proc.pid and alive(sleeper) wait_for('the window drawn again', lambda: frames[0].stat().st_mtime > mark) - # The second, a client of the old build: let go and told to upgrade too. - second.p.wait(timeout=30) - said = second.err.read_bytes() - assert b'upgrade this client too' in said or b'run the same pardes at both ends' in said, said[-400:] + if knows_exec(old): + # The second, a client of a build that execs: the same process, + # on the build at its start path (upgrade_clients checks its + # view; here that it is carried and not let go). + wait_for('the second window on the new build', lambda: exe_of(second.pid) == (str(binary), True), timeout=30) + assert second.p.poll() is None + second.p.terminate() + second.p.wait(timeout=30) + else: + # The second, a client of a build before the exec: let go and + # told to upgrade too. + second.p.wait(timeout=30) + said = second.err.read_bytes() + assert b'upgrade this client too' in said or b'run the same pardes at both ends' in said, said[-400:] said = Replica(root / 'pardes-replica.sock').hello('win', semantics(new)) assert said == ('welcome', proc.pid, 'win'), said os.kill(sleeper, signal.SIGTERM) @@ -3411,6 +3497,7 @@ if __name__ == '__main__': games(sys.argv[2], sys.argv[3], float(sys.argv[4]) if len(sys.argv) > 4 else 10) elif sys.argv[1:2] == ['--far']: far(sys.argv[2]) + far_flood(sys.argv[2]) by_hash(sys.argv[2]) far_find(sys.argv[2]) elif sys.argv[1:2] == ['--far-find']: diff --git a/test/replicas.zig b/test/replicas.zig index d78e3e02..e5e719b3 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -13,8 +13,8 @@ //! are refused until one is let go. //! //! Terminals cross as screen state (core/term/screen_state.zig): the session's -//! shell pane runs a full-screen program and then a `yes` flood (`--flood` -//! MB of it) while the clients type, its output stepped by the authority +//! shell pane runs a full-screen program and then a flood (`--flood` MB of +//! `yes`, then as much of a `cat` of source text) while the clients type, its output stepped by the authority //! and sent to each replica as deltas, once a frame and before any input //! the authority steps, each replica acknowledging them over its link and //! asking for the rows it scrolls back into and does not hold. @@ -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; @@ -178,6 +181,10 @@ const Kind = enum { /// session's down it. up, blob, + /// The session's words in a client's stream (a cut's: `Peer.send`). + word, + /// Room in the far link again: its Peer's writer goes on (`Soak.write`). + drain, }; const Msg = struct { @@ -201,6 +208,8 @@ const Msg = struct { const Link = struct { last: u64 = 0, + /// When what was sent down it before has crossed (`Net.cross`). + free: u64 = 0, /// When a message sent at `now` arrives: half the RTT, jitter on top, /// and never before the one sent ahead of it (a stream keeps order). fn arrive(l: *Link, random: std.Random, now: u64, one_way: u64, jitter: u64) u64 { @@ -272,6 +281,26 @@ const Totals = struct { detach_words: u64 = 0, /// Panes of each plain kind the session opened (image, life). kind_panes: [3]u64 = @splat(0), + /// The far client (`throttle_*`): its joins from a dump, the time between + /// two from the flood's start on, and from the flood's end to the first + /// frame of its final screen (us); the most the session's queue for it + /// held (bytes); the clients the session cut off. + far_joins: u64 = 0, + far_gaps: std.ArrayListUnmanaged(u64) = .empty, + far_final: std.ArrayListUnmanaged(u64) = .empty, + queue_max: u64 = 0, + cut: u64 = 0, + /// How far behind the session each fell at most (Link.behind, ns), and + /// how often it let its link go for it: the far client, and the others. + far_behind: u64 = 0, + far_lags: u64 = 0, + near_behind: u64 = 0, + near_lags: u64 = 0, + /// What a join costs the replicas already there, ns of this process's + /// clock: the session's join step (its reloads and its dump), and each + /// client's unit that reloaded its terminals. + join_session_ns: std.ArrayListUnmanaged(u64) = .empty, + join_client_ns: std.ArrayListUnmanaged(u64) = .empty, fn add(t: *Totals, s: *const replica.Stats) !void { t.inputs += s.inputs; @@ -307,7 +336,7 @@ const Totals = struct { /// search (`/`, a pattern, Enter), a sweep of B1 over the PDF and its /// wheel; a yank to the system clipboard and a paste from it; now and /// then a client's Detach. -fn nextEvent(random: std.Random, buf: *[64]u8, aim: Aim, looks: []const []const u8, script: *Script) pardes.Event { +fn nextEvent(random: std.Random, buf: *[64]u8, aim: Aim, looks: []const []const u8, script: *Script, far: bool) pardes.Event { const typed = "abcdefghijklmnopqrstuvwxyz0123456789 -_=+,:;()"; const normal = "hjklwbe0$xpuyoOiaAIdcv.nN%sC"; if (script.at < script.n) { @@ -351,8 +380,9 @@ fn nextEvent(random: std.Random, buf: *[64]u8, aim: Aim, looks: []const []const 10 => "Tab 8", 11 => "Life", // Its link ended by the session (the session's own view's, - // its terminal's: none here). - 12 => if (random.uintLessThan(u8, 4) == 0) "Detach" else "Undo", + // its terminal's: none here). Not the far client's: the scene + // waits for its screen after the flood. + 12 => if (random.uintLessThan(u8, 4) == 0 and !far) "Detach" else "Undo", // The system clipboard, the client's own frontend's (client.zig // `asks`): a yank of the selection to it, a paste from it. 13 => "ClipYank", @@ -509,6 +539,17 @@ const Client = struct { distrusted: pardes.Addon.Distrusted = .{}, /// What stopped its inputs as last judged (`judgeStops`). stops: @FieldType(replica.Stats, "stops") = @splat(.{}), + /// Its Peer's writer's (`Soak.write`): the batch swapped out of the + /// session's queue for it (the Peers' allocator's), how much of it went + /// down the link, whether a cut's words end it, a wake asked for room; + /// how much of the queue carries the soak's clock (`Soak.stamp`). + sending: std.ArrayListUnmanaged(u8) = .empty, + at: usize = 0, + last: bool = false, + draining: bool = false, + marked: usize = 0, + /// The session's unit its last join's dump came after. + join_seq: u32 = 0, /// Where it is (`clients[c]`), the net its wakes go through, and the /// soak's time now. c: usize = 0, @@ -614,6 +655,17 @@ const Net = struct { jitter: u64, up: [8]Link = @splat(.{}), down: [8]Link = @splat(.{}), + /// The far client, whose link is `throttle_*`'s. + throttled: ?usize = null, + + /// When `bytes` sent at `now` down or up client `c`'s link `l` arrive: + /// the far one's cross at its rate as the far stream's zstd at `level` + /// makes them, after what was sent before them, then its delay. + fn cross(net: *Net, l: *Link, c: usize, now: u64, bytes: []const u8, level: c_int) u64 { + if (net.throttled != @as(?usize, c)) return l.arrive(net.random, now, net.one_way, net.jitter); + l.free = @max(now, l.free) + zstdLen(bytes, level) * std.time.us_per_s / throttle_rate; + return l.arrive(net.random, l.free, throttle_one_way, throttle_one_way / 20); + } fn send(net: *Net, m: Msg) !void { var mm = m; @@ -624,10 +676,32 @@ const Net = struct { /// Down client `c`'s link (the session's stream to it), `bytes` its. fn toClient(net: *Net, c: usize, now: u64, kind: Kind, gen: u32, bytes: []u8) !void { - try net.send(.{ .at = net.down[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = kind, .who = @intCast(c + 1), .bytes = bytes, .gen = gen }); + try net.send(.{ .at = net.cross(&net.down[c], c, now, bytes, if (kind == .dump) 6 else 3), .n = 0, .kind = kind, .who = @intCast(c + 1), .bytes = bytes, .gen = gen }); } }; +/// P32's far case: a link of 1 Mbit/s and 200 ms each way, what it carries +/// counted as the far stream's zstd makes it (core/replica.zig `zstd`), the +/// third client's (it joins before the flood); at most `throttle_window` of it ahead of +/// what has crossed (its sockets' and the route's buffers), the rest in the +/// session's queue for it, as a writer blocked on its socket leaves it. +const throttle_rate: u64 = 125_000; +const throttle_one_way: u64 = 200_000; +const throttle_window: u64 = 64 << 10; + +extern fn ZSTD_compressBound(n: usize) usize; +extern fn ZSTD_compress(dst: [*]u8, cap: usize, src: [*]const u8, n: usize, level: c_int) usize; +extern fn ZSTD_isError(code: usize) c_uint; + +/// `bytes` through zstd at `level`, alone: the far stream's (3, and 6 for a +/// join's), which a message shares with those before it. +fn zstdLen(bytes: []const u8, level: c_int) u64 { + const room = gpa.alloc(u8, ZSTD_compressBound(bytes.len)) catch return bytes.len; + defer gpa.free(room); + const n = ZSTD_compress(room.ptr, room.len, bytes.ptr, bytes.len, level); + return if (ZSTD_isError(n) != 0) bytes.len else n; +} + /// What client `c` wrote to its socket since (its inputs and their stamps, /// its terminal messages, a check asked, its bye), read off the session's /// end, a frame a message up its link: the session's Peer takes each as it @@ -642,7 +716,7 @@ fn drain(cl: *Client, c: usize, net: *Net, now: u64) !void { } var at: usize = 0; while (try pardes.wire.framed(cl.got.items[at..])) |f| : (at += f.total) { - try net.send(.{ .at = net.up[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = .up, .who = @intCast(c + 1), .bytes = try gpa.dupe(u8, cl.got.items[at..][0..f.total]), .gen = cl.live }); + try net.send(.{ .at = net.cross(&net.up[c], c, now, cl.got.items[at..][0..f.total], 3), .n = 0, .kind = .up, .who = @intCast(c + 1), .bytes = try gpa.dupe(u8, cl.got.items[at..][0..f.total]), .gen = cl.live }); } std.mem.copyForwards(u8, cl.got.items[0 .. cl.got.items.len - at], cl.got.items[at..]); cl.got.shrinkRetainingCapacity(cl.got.items.len - at); @@ -699,19 +773,23 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run, const r = cl.r.?; const link = &cl.loop.link; // Its link ended by the session (a Detach), it says nothing more. - if (!link.gone) replica.bye(link.fd, .{ .again = r.diverged != null }); + if (!link.gone) replica.bye(link.fd, .{ .again = r.diverged != null or link.lagged != 0 }); try drain(cl, c, net, now); cl.live = 0; + if (link.lagged != 0) { + if (net.throttled == @as(?usize, c)) totals.far_lags += 1 else totals.near_lags += 1; + } 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 }); } } if (link.rejoins()) { cl.back = r.view; cl.dialling = true; - return net.send(.{ .at = net.up[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); + return net.send(.{ .at = net.cross(&net.up[c], c, now, &.{}, 3), .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); } try totals.add(&r.stats); r.deinit(); @@ -725,6 +803,289 @@ 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. + /// The kinds the witness's replica distrusts: it keeps a pointer to + /// them for its life (a local here was a stack slot gone by its first + /// kind's call: an index of 0xAA..., the screen-state soak's panic). + var distrusted: pardes.Addon.Distrusted = .{}; + + fn load(d: *const Dump) !*replica.Replica { + 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; + // Streaming: a positional writer starts at offset 0, and over a log + // file each judgement wrote over the run's first lines. + var stderr = std.Io.File.stderr().writerStreaming(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; @@ -756,7 +1117,9 @@ const Soak = struct { /// What the shell's program prints (`.output`). tui: []const u8, shell_session: []const u8, - yes: []const u8, + /// The flood: `yes`, then a `cat` (its first `yes_len` bytes `yes`). + flood: []const u8, + yes_len: usize, l: *SessionLoop = undefined, /// What failed inside the loop (its wait returns nothing): the run's. err: ?anyerror = null, @@ -805,9 +1168,17 @@ const Soak = struct { /// The temporary file and the shared memory object an image was shown /// by (`images`): gone once the session read them. media: *const Media = undefined, - /// A Peer's queue, swapped out as its writer swaps it (the Peers' - /// allocator's). - sending: std.ArrayListUnmanaged(u8) = .empty, + /// The session's unit with the flood's last bytes; the far client's + /// last join, and whether it has shown the final screen; a join's step + /// at worst. + flood_seq: u32 = 0, + 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.?)); @@ -914,13 +1285,13 @@ const Soak = struct { cl.loop.link.check = null; cl.loop.link.deinit(gpa); } + cl.sending.deinit(s.l.peers.gpa); } while (s.net.q.pop()) |m| if (m.bytes.len > 0) gpa.free(m.bytes); if (s.held) |m| if (m.bytes.len > 0) gpa.free(m.bytes); for (s.echo.items) |e| gpa.free(e.bytes); s.echo.deinit(gpa); s.versions.deinit(gpa); - s.sending.deinit(s.l.peers.gpa); } /// The tty's own boot (a raw shell, a text pane under it), then three @@ -1034,11 +1405,21 @@ const Soak = struct { cl.peer = peer; cl.shut = false; cl.read_done = false; + cl.join_seq = ps.seq; + cl.sending.clearRetainingCapacity(); + cl.at = 0; + cl.last = false; + cl.marked = 0; + // What the join cost the session's step (Peers.join's measure). + s.join_worst = @max(s.join_worst, ps.join_ns); + try s.totals.join_session_ns.append(gpa, ps.join_ns); + ps.join_ns = 0; cl.gen += 1; cl.id = welcome.client; cl.view = welcome.view.index(); cl.digest = welcome.digest; s.totals.joins += 1; + if (bytes_kind) Witness.joined(c, cl, try gpa.dupe(u8, whole.items), cl.join_seq); // never given the screen deltas, it checks no screen-state run 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 @@ -1048,49 +1429,19 @@ const Soak = struct { cl.shut = true; }; s.detach_view = null; - const flooding = now >= flood_at and s.flood_end == 0; + // The unit with the flood's last bytes: what the far client's final + // screen shows. + if (s.flood_end != 0 and s.flood_seq == 0) s.flood_seq = ps.seq; for (s.clients, 0..) |*cl, c| if (cl.peer) |peer| { - if (peer.cut) cl.shut = true; - const io = ps.io; - peer.lock.lockUncancelable(io); - std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &s.sending); - peer.lock.unlock(io); - defer s.sending.clearRetainingCapacity(); if (cl.shut) { - if (!cl.read_done) { - cl.read_done = true; - ps.post(.{ .gone = peer }); - try net.toClient(c, now, .gone, cl.gen, &.{}); - } + // What was queued for it is let go with its link. + peer.out.clearRetainingCapacity(); + try s.shut(cl, c); continue; } - var at: usize = 0; - while (try pardes.wire.framed(s.sending.items[at..])) |f| : (at += f.total) { - const tag = std.enums.fromInt(pardes.wire.ServerTag, f.tag) orelse return error.BadFrame; - switch (tag) { - .unit => { - 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)); - }, - .screen => { - if (f.payload[5] == 1) { - s.totals.deltas += 1; - s.totals.delta_bytes += f.payload.len; - if (flooding) s.totals.flood_delta_bytes += f.payload.len; - } else s.totals.filled_bytes += f.payload.len; - try net.toClient(c, now, .screen_down, cl.gen, try gpa.dupe(u8, f.payload)); - }, - .check => { - const d = try gpa.alloc(u8, 8); - 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)), - else => return error.UnexpectedFrame, - } - } - if (at != s.sending.items.len) return error.TornFrame; + s.stamp(cl, peer); + if (net.throttled == @as(?usize, c)) s.totals.queue_max = @max(s.totals.queue_max, peer.out.items.len); + try s.write(cl, c); }; // The kinds' panes it has opened, each counted once. for (core.panes) |slot| if (slot) |pane| if (pane.addon) |k| if (pane.serial > s.kinds_seen) { @@ -1105,6 +1456,102 @@ const Soak = struct { } } + /// The units the session queued for client `cl` since, their heads + /// carrying the soak's clock, the session's here (its host's `now`): + /// what the client's lag is measured by. Its replica guesses no clock + /// from them (`joined`: in process, both read one). + fn stamp(s: *Soak, cl: *Client, peer: *replica.Peer) void { + const out = peer.out.items; + // A cut (Peer.send, past its limit) empties the queue for its words. + var at = @min(cl.marked, out.len); + while (pardes.wire.framed(out[at..]) catch null) |f| : (at += f.total) { + if (f.tag != @backingInt(pardes.wire.ServerTag.unit)) continue; + const head = at + f.total - f.payload.len; + std.mem.writeInt(i64, out[head + 14 ..][0..8], @intCast(s.now * std.time.ns_per_us), .little); + } + cl.marked = at; + } + + /// Client `c`'s Peer's writer (Peer.writeLoop's): the session's queue + /// for it swapped out a batch at a time and handed down its link, a + /// frame a message. The far link takes no more than `throttle_window` + /// ahead of what has crossed: the rest waits in the queue, as it does + /// for a writer blocked on its socket, until room comes (`.drain`). A + /// cut's words end a batch, and its link after them. + fn write(s: *Soak, cl: *Client, c: usize) !void { + const peer = cl.peer orelse return; + const net = s.net; + const window_us = throttle_window * std.time.us_per_s / throttle_rate; + while (true) { + if (cl.at == cl.sending.items.len) { + cl.sending.clearRetainingCapacity(); + cl.at = 0; + if (cl.last) return s.shut(cl, c); + const io = s.l.peers.io; + peer.lock.lockUncancelable(io); + std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &cl.sending); + cl.last = peer.cut; + peer.lock.unlock(io); + cl.marked = 0; + if (cl.sending.items.len == 0) return; + } + if (net.throttled == @as(?usize, c) and net.down[c].free > s.now + window_us) { + if (!cl.draining) try net.send(.{ .at = net.down[c].free - window_us, .n = 0, .kind = .drain, .who = @intCast(c + 1), .bytes = &.{} }); + cl.draining = true; + return; + } + const f = (try pardes.wire.framed(cl.sending.items[cl.at..])) orelse return error.TornFrame; + cl.at += f.total; + try s.forward(cl, c, f); + } + } + + /// One frame of client `c`'s stream, down its link. + fn forward(s: *Soak, cl: *Client, c: usize, f: pardes.wire.Framed) !void { + const net = s.net; + const now = s.now; + 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)); + }, + .screen => { + if (f.payload[5] == 1) { + s.totals.deltas += 1; + s.totals.delta_bytes += f.payload.len; + if (flooding) s.totals.flood_delta_bytes += f.payload.len; + } else s.totals.filled_bytes += f.payload.len; + try net.toClient(c, now, .screen_down, cl.gen, try gpa.dupe(u8, f.payload)); + }, + .check => { + const d = try gpa.alloc(u8, 8); + 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 => { + 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, + } + } + + /// Client `c`'s link ended at the session's side (a Detach typed in its + /// view, or the words of a cut sent): it hears its end and nothing after, + /// and its reader's end is said (the next boundary lets it go). + fn shut(s: *Soak, cl: *Client, c: usize) !void { + cl.shut = true; + cl.last = false; + if (cl.read_done) return; + cl.read_done = true; + s.l.peers.post(.{ .gone = cl.peer.? }); + try s.net.toClient(c, s.now, .gone, cl.gen, &.{}); + } + /// Each terminal at its version as the session's screen shows it now /// (after a flush: `Peers.flushed`). fn flushed(ctx: *anyopaque, core: *pardes.Pardes, screens: *replica.Screens) void { @@ -1144,6 +1591,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 @@ -1162,6 +1610,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, @@ -1172,7 +1621,7 @@ const Soak = struct { // tape is stepped in it between its steps (tape.enter's check), // and no rollback epoch's trees are held. const in_client = switch (m.kind) { - .refused, .dump, .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone => true, + .refused, .dump, .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone, .word => true, .draw => Draws.jobs.items.len > 0 and Draws.jobs.items[0].draw != null and Draws.jobs.items[0].draw != @as(?*const pardes.Pardes, core), else => false, }; @@ -1211,15 +1660,17 @@ const Soak = struct { if (s.program.at == s.program.bytes.len) { s.program = .{ .bytes = switch (m.who) { 0 => s.tui, - 1 => s.yes, + 1 => s.flood, else => s.shell_session, } }; } const k = @min(s.program.bytes.len - s.program.at, if (m.who == 1) @as(usize, 4096) else 700); const chunk = s.program.bytes[s.program.at..][0..k]; s.program.at += k; + // `yes` a read every 450 us, the `cat` a read every 4 ms + // (1 MB/s: the far link falls behind, many seconds long). if (s.program.at < s.program.bytes.len) - try net.send(.{ .at = m.at + if (m.who == 1) @as(u64, 450) else 3_000, .n = 0, .kind = .output, .who = m.who, .bytes = &.{} }) + try net.send(.{ .at = m.at + if (m.who != 1) @as(u64, 3_000) else if (s.program.at < s.yes_len) @as(u64, 450) else 4_000, .n = 0, .kind = .output, .who = m.who, .bytes = &.{} }) else if (m.who == 1) s.flood_end = m.at; core.update(.{ .output = .{ .pane = .at(s.shell), .bytes = chunk } }); took_output = true; @@ -1240,6 +1691,12 @@ const Soak = struct { return false; } }, + // Room in the far link: its Peer's writer goes on. + .drain => { + cl.draining = false; + try s.write(cl, c); + if (s.l.peers.urgent.swap(false, .acq_rel)) return false; + }, // A client's connection, handed over by the daemon (tui.zig // `.replica`): joined at the session's next step boundary, // on a socket pair of its own. @@ -1322,7 +1779,12 @@ const Soak = struct { cl.r = null; } cl.tries += 1; - if (cl.left > 0 and cl.tries < 40) try net.send(.{ .at = net.up[c].arrive(s.random, m.at + 500_000, net.one_way, net.jitter), .n = 0, .kind = .dial, .who = m.who, .bytes = &.{} }) else { + // The far client refused before its screen after the + // flood (a join again for its lag finds its view taken: + // a join with no room lets an away one go): said, so + // that "it left" says why. + if (net.throttled == @as(?usize, c) and !s.far_final and cl.tries == 1) std.debug.print("seed {d} rtt {d} ms: the far client refused (every view taken), {d} keys left, try {d}\n", .{ s.r.seed, s.r.rtt_ms, cl.left, cl.tries }); + if (cl.left > 0 and cl.tries < 40) try net.send(.{ .at = net.cross(&net.up[c], c, m.at + 500_000, &.{}, 3), .n = 0, .kind = .dial, .who = m.who, .bytes = &.{} }) else { // Given up on: its keys are never typed. cl.dialling = false; if (cl.left > 0) s.typing -= 1; @@ -1330,7 +1792,7 @@ const Soak = struct { } }, .dump => try s.joined(cl, c, m), - .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone => { + .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone, .word => { if (m.kind == .input and cl.left == 0) continue; const rp = cl.r orelse if (m.kind == .input and cl.dialling) { try net.send(.{ .at = m.at + 50_000, .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }); @@ -1349,7 +1811,7 @@ const Soak = struct { switch (m.kind) { .input => { var buf: [64]u8 = undefined; - const ev = nextEvent(s.random, &buf, s.aim, s.looks, &cl.script); + const ev = nextEvent(s.random, &buf, s.aim, s.looks, &cl.script, net.throttled == @as(?usize, c)); cl.loop.input(ev); cl.left -= 1; if (cl.left > 0) try net.send(.{ .at = m.at + typistGap(s.random), .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }) else { @@ -1358,7 +1820,21 @@ const Soak = struct { if (c == 0) try net.send(.{ .at = m.at + 300_000, .n = 0, .kind = .quit, .who = m.who, .bytes = &.{} }); } }, - .to_replica => cl.loop.take(.{ .unit = try std.heap.c_allocator.dupe(u8, m.bytes) }), + .to_replica => { + if (net.throttled == @as(?usize, c) and !s.far_final and s.flood_seq != 0) if (replica.parseUnit(m.bytes)) |u| if (u.origin == 0 and u.seq >= s.flood_seq) { + s.far_final = true; + try s.totals.far_final.append(gpa, m.at - s.flood_end); + }; + // A join's reloads on a replica there before it: + // what its unit cost, on this process's clock. + const reloads = pardes.Term.reloads.n; + const t0 = monoNs(); + cl.loop.take(.{ .unit = try std.heap.c_allocator.dupe(u8, m.bytes) }); + if (pardes.Term.reloads.n != reloads) try s.totals.join_client_ns.append(gpa, monoNs() - t0); + const behind = if (net.throttled == @as(?usize, c)) &s.totals.far_behind else &s.totals.near_behind; + behind.* = @max(behind.*, cl.loop.link.behind); + }, + .word => cl.loop.take(.{ .refused = try std.heap.c_allocator.dupe(u8, m.bytes) }), .blob => cl.loop.take(.{ .blob = try std.heap.c_allocator.dupe(u8, m.bytes) }), .screen_down => { const pane = m.bytes[0]; @@ -1401,13 +1877,48 @@ 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 { const core = s.l.core; s.clock(); var buf: [64]u8 = undefined; - const ev = nextEvent(s.random, &buf, s.aim, s.looks, &s.own_script); + const ev = nextEvent(s.random, &buf, s.aim, s.looks, &s.own_script, false); core.toView(.at(0)); core.update(ev); s.own_left -= 1; @@ -1428,6 +1939,18 @@ const Soak = struct { } const rp = try replica.Replica.initDump(gpa, cl.id, cl.view, m.bytes, .{ .cols = cl.cols, .rows = cl.rows, .distrusted = &cl.distrusted }); cl.r = rp; + // In process: its clock reads are the session's machine's, and the + // units' heads carry the soak's clock (`stamp`). + rp.guess = false; + if (s.net.throttled == @as(?usize, c)) { + s.totals.far_joins += 1; + if (m.at >= flood_at and s.far_joined != 0) try s.totals.far_gaps.append(gpa, m.at - s.far_joined); + s.far_joined = m.at; + if (!s.far_final and s.flood_seq != 0 and cl.join_seq >= s.flood_seq) { + s.far_final = true; + try s.totals.far_final.append(gpa, m.at - s.flood_end); + } + } // Its terminals its own emulators, fed what the units carry. if (bytes_kind) { rp.t.screen_state = false; @@ -1470,7 +1993,9 @@ const Soak = struct { totals.flood_us += s.flood_end -| flood_at; for (s.flood_deltas[0..s.clients.len]) |d| totals.flood_deltas += d; const want = pardes.tape.digestOf(core); - if (bytes_kind) std.debug.print("seed {d} rtt {d} ms: a join's step at worst {d} us (the session's reloads and its dump), the last dump {d} KB ({d} KB of state)\n", .{ s.r.seed, s.r.rtt_ms, s.l.peers.join_ns / 1000, s.l.peers.dump_bytes >> 10, s.l.peers.state_bytes >> 10 }); + totals.cut += s.l.peers.cut; + if (bytes_kind) std.debug.print("seed {d} rtt {d} ms: a join's step at worst {d} us (the session's reloads and its dump), the last dump {d} KB ({d} KB of state)\n", .{ s.r.seed, s.r.rtt_ms, s.join_worst / 1000, s.l.peers.dump_bytes >> 10, s.l.peers.state_bytes >> 10 }); + if (s.net.throttled) |c| if (!s.far_final) std.debug.print("seed {d} rtt {d} ms: the far client never showed the screen after the flood ({s})\n", .{ s.r.seed, s.r.rtt_ms, if (s.clients[c].r == null) "it left" else "it is joined" }); if (bytes_kind) for (kitty_oks, s.kitty_answers) |ok, n| if (n != 1) { totals.unequal += 1; std.debug.print("seed {d} rtt {d} ms: the program's kitty {f} was answered {d} times on the session's pty\n", .{ s.r.seed, s.r.rtt_ms, std.ascii.hexEscape(ok, .lower), n }); @@ -1502,6 +2027,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; @@ -1539,11 +2065,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; @@ -1579,7 +2108,7 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { nlooks += 1; }; - var net: Net = .{ .random = random, .one_way = r.rtt_ms * 1000 / 2, .jitter = r.rtt_ms * 1000 / 20 }; + var net: Net = .{ .random = random, .one_way = r.rtt_ms * 1000 / 2, .jitter = r.rtt_ms * 1000 / 20, .throttled = if (r.clients >= 3) 2 else null }; defer net.q.deinit(gpa); pardes.Kind.drawer = .{ .ctx = null, .go = Draws.go }; Draws.net = &net; @@ -1597,7 +2126,7 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { // What the shell's program prints: a full-screen program, a shell's // session (prompts, titles, directories, a clear now and then), then a - // flood of `yes`, read 4 KB at a time as a pty gives it. + // flood of `yes` and of a `cat`, read 4 KB at a time as a pty gives it. const tui = try screen_state.tuiStream(gpa); defer gpa.free(tui); const session_only = try screen_state.shellStream(gpa); @@ -1617,6 +2146,8 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { defer gpa.free(yes_only); const yes = try std.mem.concat(gpa, u8, &.{ yes_only, shown }); defer gpa.free(yes); + const flood = try catAfter(yes, yes.len); + defer gpa.free(flood); var soak: Soak = .{ .r = r, @@ -1628,7 +2159,8 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { .with_pdf = with_pdf, .tui = tui, .shell_session = shell_session, - .yes = yes, + .flood = flood, + .yes_len = yes.len, .own_left = r.steps, .typing = r.clients + 1, .media = &media, @@ -1717,6 +2249,26 @@ fn images(dir: []const u8, seed: u64, media: *Media) ![]u8 { return out.toOwnedSlice(gpa); } +/// `before`, then `n` bytes of what a `cat` of source text prints through a +/// pty: this file's lines, CR LF after each, again and again. +fn catAfter(before: []const u8, n: usize) ![]u8 { + var out: std.ArrayListUnmanaged(u8) = .empty; + errdefer out.deinit(gpa); + try out.appendSlice(gpa, before); + while (out.items.len < before.len + n) { + var lines = std.mem.splitScalar(u8, @embedFile("replicas.zig"), '\n'); + while (lines.next()) |line| try out.print(gpa, "{s}\r\n", .{line}); + } + out.shrinkRetainingCapacity(before.len + n); + return out.toOwnedSlice(gpa); +} + +fn monoNs() u64 { + var ts: libc.timespec = undefined; + _ = libc.clock_gettime(.MONOTONIC, &ts); + return @as(u64, @intCast(ts.sec)) * std.time.ns_per_s + @as(u64, @intCast(ts.nsec)); +} + /// A typist: keys 50-200 ms apart, a pause now and then. fn typistGap(random: std.Random) u64 { return if (random.uintLessThan(u8, 12) == 0) random.intRangeAtMost(u64, 300_000, 1_500_000) else random.intRangeAtMost(u64, 50_000, 200_000); @@ -2562,7 +3114,7 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { .screen_up => { if (try screens.take(a.core, peer, m.bytes)) |answer| try push(&queue, &n, .{ .at = down[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_down, .who = 1, .bytes = answer }); }, - .output, .own, .dial, .dump, .refused, .check_up, .checked, .bye_up, .wake, .quit, .gone, .draw, .up, .blob => {}, + .output, .own, .dial, .dump, .refused, .check_up, .checked, .bye_up, .wake, .quit, .gone, .draw, .up, .blob, .word, .drain => {}, } } const s = rp.echo.stats; @@ -2661,6 +3213,14 @@ fn echoMain(seeds: u64, first: u64, rtts: []const u64) !bool { } +fn secs(us: u64) f64 { + return @as(f64, @floatFromInt(us)) / std.time.us_per_s; +} + +fn msOf(ns: u64) f64 { + return @as(f64, @floatFromInt(ns)) / std.time.ns_per_ms; +} + fn pct(samples: []u64, p: usize) u64 { if (samples.len == 0) return 0; std.mem.sort(u64, samples, {}, std.sort.asc(u64)); @@ -2837,6 +3397,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; @@ -2859,6 +3423,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]; @@ -2914,7 +3482,7 @@ pub fn main(init: std.process.Init) !void { // files (runtime/session.zig opens them), never the user's. var runtime_buf: [300]u8 = undefined; if (setenv("XDG_RUNTIME_DIR", try std.fmt.bufPrintSentinel(&runtime_buf, "{s}", .{dir}, 0), 1) != 0) return error.NoRuntimeDir; - std.debug.print("{d} seeds x {d} inputs from the session's own frontend and each of {d} clients (terminals and windows by turns, joined from a dump, at most {d} at once), a TUI then {d} MB of yes in the shell; costs in us (frame {d})\n", .{ seeds, steps, clients, pardes.views.max - 1, flood_mb, frame_us }); + std.debug.print("{d} seeds x {d} inputs from the session's own frontend and each of {d} clients (terminals and windows by turns, joined from a dump, at most {d} at once), a TUI then {d} MB of yes and as much of a cat in the shell; costs in us (frame {d})\n", .{ seeds, steps, clients, pardes.views.max - 1, flood_mb, frame_us }); std.debug.print(" rtt inputs at-once stopped units fast rollback(mis+foreign) rate rebase spec p50/p99 copy p50/p99 (KB) rollback p50/p99 diverged unequal\n", .{}); var term_lines: std.ArrayList(u8) = .empty; defer term_lines.deinit(gpa); @@ -2922,6 +3490,8 @@ pub fn main(init: std.process.Init) !void { defer join_lines.deinit(gpa); var stop_lines: std.ArrayList(u8) = .empty; defer stop_lines.deinit(gpa); + var far_lines: std.ArrayList(u8) = .empty; + defer far_lines.deinit(gpa); for (rtts) |rtt| { var t: Totals = .{}; pardes.Term.reloads = .{}; @@ -2958,6 +3528,20 @@ pub fn main(init: std.process.Init) !void { for (t.stops) |st| if (st.n > 0) try stop_lines.print(gpa, "{s}:{d} ", .{ st.name, st.n }); try stop_lines.append(gpa, '\n'); try join_lines.print(gpa, "{d:>4} {d:>5} {d:>7} {d:>8} {d:>8} {d:>6} {d:>5}/{d:<5} {d:>5}/{d:<6} {d:>7} {d:>5}/{d}/{d}\n", .{ rtt, t.joins, t.refused, t.rejoined, t.detached, t.detach_words, t.agree, t.differ, t.checks, t.units, t.resizes, t.kind_panes[0], t.kind_panes[1], t.kind_panes[2] }); + try far_lines.print(gpa, "{d:>4} {d:>5} {d:>4} {d:>6.1}/{d:<6.1} {d:>6.1}/{d:<6.1} {d:>8} {d:>3} {d:>6.1}/{d:<6.1} {d:>6.1}/{d:<6.1} ({d}) {d:>6.0}/{d:<6.0} {d}\n", .{ + rtt, t.far_joins, t.far_lags, + secs(pct(t.far_gaps.items, 50)), secs(pct(t.far_gaps.items, 100)), + secs(pct(t.far_final.items, 50)), secs(pct(t.far_final.items, 100)), + t.queue_max >> 10, t.cut, + msOf(pct(t.join_session_ns.items, 50)), msOf(pct(t.join_session_ns.items, 100)), + msOf(pct(t.join_client_ns.items, 50)), msOf(pct(t.join_client_ns.items, 100)), + t.join_client_ns.items.len, + msOf(t.far_behind), msOf(t.near_behind), + t.near_lags, + }); + // The far client shows the final screen in every run, and the near + // ones never fall behind with it. + if ((t.far_final.items.len < seeds and clients >= 3) or t.near_lags > 0) failed = true; if (t.divergences > 0 or t.unequal > 0 or t.screens_wrong > 0 or t.differ > 0 or t.unlisted > 0) failed = true; } std.debug.print("terminals: deltas a replica applied a second under the flood; a peer's bytes a second under the flood (deltas, units); encode a frame of the flood for every peer, apply a delta (us); rows fetched, KB of rows sent before the step that read them; resets; deltas checked/wrong\n", .{}); @@ -2966,6 +3550,8 @@ pub fn main(init: std.process.Init) !void { std.debug.print(" rtt joins refused rejoined detached detach agree/differ checks/units resizes kinds\n{s}", .{join_lines.items}); std.debug.print("stops: the wakes the clients' loops asked, the frames they drew, the yanks, pastes and links their frontends did (y/p/l), and what stopped their inputs (a stop counted again as its input is applied again), by name; those at a name replica.may_wait does not list fail the run\n", .{}); std.debug.print(" rtt unlisted wakes draws y/p/l stops\n{s}", .{stop_lines.items}); + std.debug.print("far: the third client's link 1 Mbit/s and 200 ms each way (zstd's bytes): its joins from a dump, of them for its lag (Link.behind past replica.behind_max_ms), s between two from the flood's start (p50/max), s from the flood's end to its final screen (p50/max: a run that never shows it fails), the session's queue for it at most, clients cut off; a join's cost to the replicas there before it, ms on this process's clock (p50/max): the session's step (reloads and dump), a client's unit (reloads), how many; ms behind the session at most (Link.behind), the far client and the others, and the others' joins for it (0, or the run fails)\n", .{}); + std.debug.print(" rtt joins lags refresh s final s queue KB cut session ms client ms behind far/near ms\n{s}", .{far_lines.items}); if (failed) std.process.exit(1); } |
