diff options
Diffstat (limited to 'core/replica.zig')
| -rw-r--r-- | core/replica.zig | 826 |
1 files changed, 798 insertions, 28 deletions
diff --git a/core/replica.zig b/core/replica.zig index c68848f2..a52061f4 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -40,8 +40,10 @@ const checked = builtin.mode == .debug or builtin.mode == .safe; const head_len = 6; // origin or client: u16le, seq: u32le /// A `stamp` frame (wire.zig): its header and the two clocks. const stamp_len = wire.header_len + 16; -/// Confirmed units fast-pathed under one copy before it is taken afresh: -/// a rollback replays them all. +/// Confirmed units kept under one copy before it is let go, at the next +/// unit that leaves nothing applied on top (free: it is the confirmed +/// state); a rollback replays them all, so with inputs applied on top all +/// the while it is put back at twice as many. const rebase_after = 32; /// A client compares its core's digest with the session's at most once in /// this many confirmed units (a unit that carries one, its state the @@ -568,6 +570,8 @@ pub const Stats = struct { /// the authority did not share), or another's unit first. mispredicted: u32 = 0, foreign: u32 = 0, + /// The copy put back at `rebase_after` kept units with inputs applied + /// on top: the kept units replayed, the inputs applied again. rebases: u32 = 0, units: u32 = 0, /// Its digest compared with the session's (a unit's, or quiet). @@ -905,7 +909,7 @@ pub const Replica = struct { // nothing ends on again (`neutral`); none, not known. r.last_digest.clearRetainingCapacity(); if (lastDigest(u.tape)) |d| r.last_digest.appendSlice(r.gpa, d) catch {}; - if (r.pending.items[0].terminal and r.applied > 1) { + if (r.pending.items[0].terminal and (r.applied > 1 or !r.t.screen_state)) { // Right, but what it did read a terminal: replayed later (a // rollback's `since`) it would read the deltas that came // after it. So it is taken now, over the emulator its step @@ -959,7 +963,12 @@ pub const Replica = struct { r.last_digest.clearRetainingCapacity(); if (ends) |d| r.last_digest.appendSlice(r.gpa, d) catch {}; } - if (r.applied > 0 and u.origin != r.id and ends != null and std.mem.eql(u8, ends.?, r.last_digest.items)) { + // A terminal's output is never taken so (the one rule): what it + // writes outside the copy is applied once, at its place, and much + // of it no digest covers (a colour set, a mode). + if (r.applied > 0 and u.origin != r.id and ends != null and std.mem.eql(u8, ends.?, r.last_digest.items) and + (r.t.screen_state or !tape.feedsTerminal(u.tape))) + { // Nothing a digest covers moved: what was applied on top is // what the session will apply on top of it. Replayed when the // copy is next put back. @@ -992,6 +1001,7 @@ pub const Replica = struct { // replayed by a rollback were, if at all, as they came). const check = ends != null and r.checkDue(); r.t.checks = check; + const writes = Term.writes; const replayed = tape.replayUnit(&r.t, u.tape); r.t.checks = false; if (replayed) |why| { @@ -1015,10 +1025,15 @@ pub const Replica = struct { // or freed here, and is not put back with the copy: a rollback // replaying the unit again would close a terminal freed already (the // soak, a `Del` of the shell). Let go with the copy. + // The one rule: a unit that wrote an emulator (a terminal's output, + // a grid reflowed, a view moved, one reloaded at a join) wrote what + // no copy holds: kept, a rollback would replay it into what it + // wrote already (the bytes fed twice). It goes with the copy: the + // state is the confirmed one, nothing being on top. const c = r.core(); for (c.retired_panes.current, c.retired_panes.previous) |x, y| retiring = retiring or x != null or y != null; for (c.panes, serials) |slot, n| retiring = retiring or (if (slot) |pane| pane.serial else 0) != n; - if (retiring) { + if (retiring or (!r.t.screen_state and Term.writes != writes)) { r.copy.release(); rollback.Epoch.select(null); return r.clearSince(); @@ -1035,22 +1050,23 @@ pub const Replica = struct { if (r.diverged == null) r.diverged = r.gpa.dupe(u8, why) catch return; } - /// A unit kept to replay when the copy is next put back; past - /// `rebase_after` of them, that is now (`toConfirmed`). + /// A unit kept to replay when the copy is next put back (`rebase_after`). fn keepSince(r: *Replica, unit: []const u8) void { const kept = r.gpa.dupe(u8, unit) catch return r.fail("out of memory"); r.since.append(r.gpa, kept) catch return r.fail("out of memory"); - if (r.since.items.len >= rebase_after) { - r.stats.rebases += 1; - // Nothing on top: it is the confirmed state already. - if (r.applied == 0) { - r.copy.release(); - rollback.Epoch.select(null); - return r.clearSince(); - } - r.toConfirmed(); - r.dirty = true; + if (r.since.items.len < rebase_after) return; + // Nothing on top: it is the confirmed state already. + if (r.applied == 0) { + r.copy.release(); + rollback.Epoch.select(null); + return r.clearSince(); } + // An input applied on top (the session's pump unit before its own + // unit, the next to come): let go then, not replayed whole now. + if (r.since.items.len < 2 * rebase_after) return; + r.stats.rebases += 1; + r.toConfirmed(); + r.dirty = true; } fn clearSince(r: *Replica) void { @@ -1139,7 +1155,9 @@ pub const Replica = struct { const keyboard = if (c.panes[c.view().active]) |pane| pane.terminal != null else false; c.update(in.event); c.step(); - p.terminal = r.t.screen_state and (keyboard or r.t.touched); + // Under bytes: it owes an emulator a write it skipped (a grid's + // size), replayed when confirmed. + p.terminal = if (r.t.screen_state) keyboard or r.t.touched else r.t.touched; const clean = tape.endSpeculation(&r.t); const dt = nowNs() - t0; // Where a blob was written, should one be: the input that did. @@ -1215,7 +1233,6 @@ pub const Replica = struct { r.retiring = for (c.retired_panes.current, c.retired_panes.previous) |x, y| { if (x != null or y != null) break true; } else false; - if (!r.t.screen_state) return; for (r.core().panes, &r.views) |slot, *v| v.* = if (slot) |pane| if (pane.terminal) |state| pardes.Term.grid(state).view else null else null; } @@ -1230,7 +1247,6 @@ pub const Replica = struct { } fn putViews(r: *Replica) void { - if (!r.t.screen_state) return; for (r.core().panes, r.views) |slot, at| if (slot) |pane| if (pane.terminal) |state| pardes.Term.viewTo(state, at); } @@ -2055,6 +2071,10 @@ pub const Peers = struct { /// After each flush of a client's terminals, told: the soak's record /// of each terminal as each version left it (test/replicas.zig). flushed: ?struct { ctx: *anyopaque, f: *const fn (*anyopaque, *Pardes, *Screens) void } = null, + /// Its clients' terminals cross as the pty's bytes in its units, each + /// client's emulator its own (P29, P32), not as screen state: the + /// soak's (test/replicas.zig `--bytes`), until the switch. + bytes: bool = false, pub const Note = union(enum) { join: Joining, input: Msg, screen: Msg, gone: *Peer, check: *Peer, joined: *Peer }; /// A connection to join, and the view it joins again for, if it does. @@ -2175,6 +2195,14 @@ pub const Peers = struct { ps.screensOut(core, .flush); } + /// What its steps recorded passed a unit's bound (`tape.unit_max`): a + /// unit of its own now, between two inputs of the pump (Tape.cut). + fn cutUnit(ctx: *anyopaque) void { + const ps: *Peers = @ptrCast(@alignCast(ctx)); + ps.seq += 1; + ps.unit(0, ps.seq); + } + const ScreensOut = enum { flush, fill }; /// What each client is owed of the terminals (`Screens.flush`), or the @@ -2186,6 +2214,7 @@ pub const Peers = struct { } fn screensTo(ps: *Peers, core: *Pardes, peer: *Peer, comptime what: ScreensOut) void { + if (ps.bytes) return; defer { for (ps.msgs.items) |m| ps.gpa.free(m); ps.msgs.clearRetainingCapacity(); @@ -2219,8 +2248,9 @@ pub const Peers = struct { ps.t.unit_digests = true; // Terminals cross as screen state: a unit carries no pty bytes, // and its digest is a word (PARDES_REPLICA_TRACE: one a field). - ps.t.screen_state = true; + ps.t.screen_state = !ps.bytes; ps.t.whole_digest = std.c.getenv("PARDES_REPLICA_TRACE") == null; + ps.t.cut = .{ .ctx = ps, .f = cutUnit }; ps.screens = .init(ps.gpa); tape.on = &ps.t; core.tape = &ps.t; @@ -3241,13 +3271,13 @@ pub const Link = struct { var buf: [1024]u8 = undefined; const e = &c.r.echo.stats; var w: std.Io.Writer = .fixed(&buf); - w.print("inputs {d} at_once {d} stopped {d} units {d} fast {d} neutral {d} mispredicted {d} foreign {d} visible {d} rtt_us {d} spec_us {d}/{d} copy_us {d}/{d} rollback_us {d}/{d} join_ms {d} blobs {d} from_memory {d} from_disk {d} sent_kb {d} echo {d}/{d} confirmed {d} missed {d} draws {d} again {d}", .{ + w.print("inputs {d} at_once {d} stopped {d} units {d} fast {d} neutral {d} mispredicted {d} foreign {d} visible {d} rtt_us {d} spec_us {d}/{d} copy_us {d}/{d} rollback_us {d}/{d} join_ms {d} blobs {d} from_memory {d} from_disk {d} sent_kb {d} echo {d}/{d} confirmed {d} missed {d} draws {d} again {d} rebases {d} copies {d} checks {d}", .{ st.inputs, st.speculated, st.stopped, st.units, st.fast, c.r.neutral, st.mispredicted, st.foreign, c.visible, c.r.rtt_ns / 1000, pctOf(st.spec_ns.items, 50) / 1000, pctOf(st.spec_ns.items, 99) / 1000, pctOf(st.copy_ns.items, 50) / 1000, pctOf(st.copy_ns.items, 99) / 1000, pctOf(st.rollback_ns.items, 50) / 1000, pctOf(st.rollback_ns.items, 99) / 1000, c.join_ms, c.join.blobs, c.join.from_memory, c.join.from_disk, c.join.sent_bytes >> 10, e.predicted, e.predicted + e.unpredicted, e.confirmed, e.mispredicted, - c.draws, c.again, + c.draws, c.again, st.rebases, st.copies, st.checks, }) catch return; // What stopped its inputs, last: a word a pair before it. w.writeAll(" stops ") catch return; @@ -3678,6 +3708,56 @@ test "the copy taken for an input of its own stays once the input is confirmed: try std.testing.expectEqual(@as(u32, 1), r.stats.foreign); } +test "the session's pump units that moved nothing, kept under a key applied on top, reach the kept list's bound: it is let go at the confirm that leaves nothing applied, never replayed whole" { + // The live pair's order (core/replica.zig Peers.boundary): before it + // steps a client's key the session sends its pump's unit, which moved + // nothing; the client takes it with the key applied on top (`neutral`, + // kept), then the key's own unit (fast, kept). Two kept a key: which + // of them is the bound's is the arrivals' parity, and a pump's unit + // while idle turns it. + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + defer a.deinit(); + const r = try Replica.init(gpa, 1, try a.unit(0, 0), false); + defer r.deinit(); + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| gpa.free(m); + sent.deinit(gpa); + } + freshSecond(); + // A first key, confirmed: the copy held, one unit kept (the parity + // that puts the bound on a pump's unit). + try key(r, 'j', &sent); + r.confirm(try a.take(sent.items[0])); + for (1..rebase_after) |i| { + try key(r, if (i % 2 == 0) 'j' else 'k', &sent); + a.pump(); + r.confirm((try a.pending()).?); + r.confirm(try a.take(sent.items[i])); + r.settle(); + try std.testing.expect(r.since.items.len <= rebase_after); + } + try std.testing.expectEqual(@as(u32, rebase_after - 1), r.neutral); + try std.testing.expectEqual(@as(u32, 0), r.stats.rebases); + try agrees(a, r); + // Keys applied on top all the while (one ahead of the session): the + // list is put back and replayed at twice the bound, not let grow. + try key(r, 'j', &sent); + for (0..3 * rebase_after) |i| { + try key(r, 'k', &sent); + a.pump(); + r.confirm((try a.pending()).?); + r.confirm(try a.take(sent.items[rebase_after + i])); + r.settle(); + try std.testing.expect(r.since.items.len <= 2 * rebase_after); + } + try std.testing.expect(r.stats.rebases >= 1); + r.confirm(try a.take(sent.items[sent.items.len - 1])); + r.settle(); + try agrees(a, r); +} + test "a rollback over a Tab it applied measures tabs as its core has them again" { // A tab's width is the core's (settings.tab, handed to every width // function), which the copy holds: once the process's (config.tab_now), @@ -4139,6 +4219,214 @@ test "a unit that closes or tears down a terminal is never kept over a copy take try std.testing.expectEqual(a.core.store.closed.items.len, r.core().store.closed.items.len); } +/// The emulators of a session's and a replica's terminals as a dump keeps +/// them (what pardes keeps beside each, its whole snapshot): the same +/// bytes, or a test fails. +fn sameTerminals(a: *Authority, r: *Replica) !void { + const gpa = std.testing.allocator; + for (a.core.panes, r.core().panes) |x, y| { + const theirs = (x orelse continue).terminal orelse continue; + const mine = (y orelse return error.NoPane).terminal orelse return error.NoTerminal; + var w1: std.Io.Writer.Allocating = .init(gpa); + defer w1.deinit(); + var w2: std.Io.Writer.Allocating = .init(gpa); + defer w2.deinit(); + try theirs.dumpWrite(gpa, &w1.writer); + try mine.dumpWrite(gpa, &w2.writer); + try std.testing.expectEqualSlices(u8, w1.written(), w2.written()); + } +} + +/// A session and a replica of the bytes kind (its terminals fed the pty's +/// bytes the session's units carry), the session's view on its text pane, +/// and the shell's slot. +const BytesPair = struct { + a: *Authority, + r: *Replica, + shell: pardes.Pane.Id, + + fn init() !BytesPair { + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), false); + errdefer a.deinit(); + const r = try Replica.init(gpa, 1, try a.unit(0, 0), false); + var shell: ?pardes.Pane.Id = null; + for (a.core.panes, 0..) |slot, id| if (slot) |pane| { + if (pane.isTerminal()) shell = .at(id) else if (pane.file != null) a.core.view().active = @intCast(id); + }; + const pair: BytesPair = .{ .a = a, .r = r, .shell = shell orelse return error.NoShell }; + r.confirm(try a.local(.{ .focus = true })); + return pair; + } + + fn deinit(b: BytesPair) void { + b.r.deinit(); + b.a.deinit(); + } + + /// The session's program prints `bytes`, a unit of its own the replica takes. + fn output(b: BytesPair, bytes: []const u8) !void { + b.a.output(.{ .output = .{ .pane = b.shell, .bytes = bytes } }); + b.r.confirm((try b.a.pending()).?); + b.r.settle(); + } + + /// The client types a key over the text, and the session's own key + /// comes first: a rollback, which replays what was kept since the copy. + fn rollback(b: BytesPair) !void { + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| std.testing.allocator.free(m); + sent.deinit(std.testing.allocator); + } + try key(b.r, 'l', &sent); + try std.testing.expectEqual(@as(usize, 1), b.r.applied); + b.r.confirm(try b.a.local(.{ .key = .{ .cp = 'j', .text = "j" } })); + b.r.settle(); + b.r.confirm(try b.a.take(sent.items[0])); + b.r.settle(); + } +}; + +test "bytes: a session's output taken over a copy held ahead is fed once: a rollback does not feed it again" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const b = try BytesPair.init(); + defer b.deinit(); + b.r.ready(); + try std.testing.expect(b.r.copy.held); + try b.output("one line of the program's\r\n"); + try b.rollback(); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); +} + +test "bytes: what a terminal's emulator gains while a copy is held is its own: a rollback frees none of it" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const b = try BytesPair.init(); + defer b.deinit(); + b.r.ready(); + // Pages and their side tables the emulator had not: thousands of rows, + // a colour and a link a word. + var line: [128]u8 = undefined; + for (0..3000) |i| b.a.output(.{ .output = .{ .pane = b.shell, .bytes = try std.fmt.bufPrint(&line, "\x1b[3{d}m{d}\x1b]8;;https://example.com/{d}\x1b\\ link\x1b]8;;\x1b\\\x1b[0m\r\n", .{ i % 8, i, i }) } }); + b.r.confirm((try b.a.pending()).?); + try b.rollback(); + try b.output("after\r\n"); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); +} + +test "bytes: a session's output that moves nothing the digest covers (a colour set) is never taken as moving nothing: it is fed, at its place" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const b = try BytesPair.init(); + defer b.deinit(); + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| std.testing.allocator.free(m); + sent.deinit(std.testing.allocator); + } + // A key of its own applied on top, the session's colour comes, then the + // key is confirmed, and the session's next output is in that colour. + try key(b.r, 'l', &sent); + try std.testing.expectEqual(@as(usize, 1), b.r.applied); + try b.output("\x1b[31m"); + b.r.confirm(try b.a.take(sent.items[0])); + b.r.settle(); + try b.output("red\r\n"); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); +} + +test "bytes: a mouse motion a speculation told a terminal's program is told again when its input is replayed: the cell last told is the pane's, put back with it" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const b = try BytesPair.init(); + defer b.deinit(); + // The program hears every motion, in SGR form. + try b.output("\x1b[?1003h\x1b[?1006h"); + const at = b.a.core.view().rects[b.shell.index()]; + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| gpa.free(m); + sent.deinit(gpa); + } + // Its speculation encodes the motion (the cell noted) and stops at the + // pty's write; the session's unit for it is replayed. + try sent.append(gpa, try gpa.dupe(u8, try b.r.input(.{ .mouse = .{ .button = .none, .kind = .motion, .col = at.x + 3, .row = at.y + at.h / 2 } }))); + b.r.confirm(try b.a.take(sent.items[0])); + b.r.settle(); + try agrees(b.a, b.r); +} + +test "bytes: a client joins from a dump with its terminals whole, and every side, the session too, reloads each terminal in the step that opens its view: their hashes agree, and all go on as one" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const b = try BytesPair.init(); + defer b.deinit(); + // History with colours and links, a sequence left open at the cut. + var line: [128]u8 = undefined; + for (0..400) |i| try b.output(try std.fmt.bufPrint(&line, "\x1b[3{d}m{d}\x1b]8;;https://example.com/{d}\x1b\\ link\x1b]8;;\x1b\\\x1b[0m\r\n", .{ i % 8, i, i })); + try b.output("half a colour: \x1b[38;2;10;20"); + const reloads = pardes.Term.writes; + const joined = (try b.a.join(2, null)).?; + defer gpa.free(joined.dump); + b.r.confirm(joined.unit); + try std.testing.expect(b.r.diverged == null); + try std.testing.expect(pardes.Term.writes != reloads); + const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); + defer late.deinit(); + late.t.screen_state = false; + late.core().echo = null; + try std.testing.expectEqual(joined.digest, late.digest()); + b.a.output(.{ .output = .{ .pane = b.shell, .bytes = ";30mthe rest of it\x1b[0m\r\n" } }); + const rest = (try b.a.pending()).?; + b.r.confirm(rest); + late.confirm(rest); + late.settle(); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); + try agrees(b.a, late); + try sameTerminals(b.a, late); +} + +test "bytes: a session's output past a unit's bound is cut into units under it, between two reads" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const b = try BytesPair.init(); + defer b.deinit(); + const Cuts = struct { + a: *Authority, + units: std.ArrayListUnmanaged([]u8) = .empty, + fn cut(ctx: *anyopaque) void { + const c: *@This() = @ptrCast(@alignCast(ctx)); + c.a.batched = 0; + c.a.seq += 1; + const u = c.a.unit(0, c.a.seq) catch unreachable; + c.units.append(std.testing.allocator, std.testing.allocator.dupe(u8, u) catch unreachable) catch unreachable; + } + }; + var cuts: Cuts = .{ .a = b.a }; + defer { + for (cuts.units.items) |u| gpa.free(u); + cuts.units.deinit(gpa); + } + b.a.t.cut = .{ .ctx = &cuts, .f = Cuts.cut }; + defer b.a.t.cut = null; + // A pump's worth of reads, 64 KiB each, 3 MiB in all. + var read: [64 * 1024]u8 = undefined; + for (&read, 0..) |*c, i| c.* = if (i % 80 == 79) '\n' else @intCast('a' + i % 26); + for (0..48) |_| b.a.output(.{ .output = .{ .pane = b.shell, .bytes = &read } }); + try std.testing.expect(cuts.units.items.len >= 2); + for (cuts.units.items) |u| { + try std.testing.expect(u.len <= tape.unit_max + read.len + 4096); + b.r.confirm(u); + } + if (try b.a.pending()) |u| b.r.confirm(u); + b.r.settle(); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); +} + test "a replica joined from the session's dump replays the units after it" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); @@ -5342,7 +5630,6 @@ const may_wait = [_]Wait{ .{ .what = "Dump", .on = .any, .stop = "write_dump", .why = "a dump written" }, .{ .what = "Upgrade", .on = .any, .stop = "upgrade", .why = "the session execs itself" }, .{ .what = "Detach", .on = .any, .stop = "detach", .why = "the session lets its frontend go" }, - .{ .what = "focus lost and found", .on = .any, .stop = "newer_build", .why = "a window found again asks whether a newer build is installed: the session's disk" }, // What the session alone holds: its closed panes, Recent and History // (every session of its user writes them), the config and theme files. .{ .what = "Restore", .on = .any, .stop = "the authority's own state", .why = "the session's dumps" }, @@ -5354,10 +5641,7 @@ const may_wait = [_]Wait{ .{ .what = "DumpConfig", .on = .any, .stop = "the authority's own state", .why = "the config file written" }, .{ .what = "ThemeFile *", .on = .any, .stop = "the authority's own state", .why = "a theme file, the session's" }, .{ .what = "DumpThemes", .on = .any, .stop = "the authority's own state", .why = "the theme files written" }, - // A search's rows: the session's worker or its loop writes them, and - // whether it has a worker is not the client's to know (12a); a - // +Preview's text is read from the session's disk. - .{ .what = "Search *", .on = .any, .stop = "search", .why = "a search's rows, the session's worker's" }, + // A +Preview's text is read from the session's disk. .{ .what = "Search *", .on = .any, .stop = "preview", .why = "a +Preview's file, from the session's disk" }, // A kind's own state on the session (a PDF's document): asking it. .{ .what = "*", .on = .addon, .stop = "a kind's search", .why = "a search in a kind's pane: its own state, the session's" }, @@ -5884,3 +6168,489 @@ test "an idle client's check answered covers the units that came while it was as c.take(.{ .checked = digestOf(a) }); try std.testing.expect(!c.asked and c.changed); } + +// A window's keyboard found again asked the session's host whether a newer +// pardes is installed, in the core's focus step: a client's refocus waited +// a round trip for a question about the session's binary that its own +// window has nothing to do with. Each process's build is its own frontend's +// to look at, at its own focus-in (upgrade.noticeNewer). +test "a far client's window found again is instant: its refocus asks the session's host nothing, and the session's unit confirms it" { + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, FullHost.host(), false); + defer a.deinit(); + const r = try joinedFresh(a); + defer r.deinit(); + for ([_]bool{ false, true }) |focused| { + const msg = try gpa.dupe(u8, try r.input(.{ .focus = focused })); + defer gpa.free(msg); + try std.testing.expectEqual(@as(usize, 1), r.applied); + r.confirm(try a.take(msg)); + r.settle(); + try agrees(a, r); + } + try std.testing.expectEqual(@as(u32, 0), r.stats.stopped); + try std.testing.expectEqual(@as(u32, 2), r.stats.fast); +} + +/// Kind `ops`'s code in the client for its pane `id`, as a client that +/// has its library runs it (initDump: Addon.plainOps, dump.plainHere). +fn runsHere(r: *Replica, id: usize, ops: *const pardes.Kind.Ops) !void { + const was = Stepping.begin(&r.t, &r.epoch); + defer was.end(); + const c = r.core(); + const slot = c.panes[id].?.addon.?; + c.kinds.ops[c.kinds.byName(slot.nameOf()).?] = ops; + c.panes[id].?.addon = try pardes.dump.plainHere(c, id, slot, ops); +} + +/// A plain kind that takes the mouse (normal mode has its keys). +const Pointed = struct { + const pa = pardes.Kind.c; + fn mouse(_: ?*anyopaque, _: [*c]const pa.pa_mouse) callconv(.c) c_int { + return 1; + } + const words = [_]pa.pa_word{std.mem.zeroInit(pa.pa_word, .{ .name = "Pointed", .opens = 1, .doc = "a pane that takes the mouse" })}; + const ops = std.mem.zeroInit(pardes.Kind.Ops, .{ + .head = std.mem.zeroInit(pa.pa_head, .{ .size = @sizeOf(pa.pa_head), .abi = pardes.Kind.abi, .name = "pointed".* ++ @as([9]u8, @splat(0)), .version = 1, .exts = "", .flags = pa.PA_PLAIN, .words = &words, .nwords = 1 }), + .open = Still.open, + .paint = Still.paint, + .mouse = mouse, + }); +}; + +// A press grabs a kind's pane (the drag and release after it are the +// kind's wherever they land); a step between can leave that pane too +// short for a row of body, and the drag's row clamped into an empty range +// tripped std.math.clamp's assertion (the soak, once, at rtt 207, in a +// client's speculation). +test "a far client's drag in a kind's pane it grabbed, the pane since too short for a row of body: the kind is told its edge, at once and as on the session" { + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + defer a.deinit(); + var words: [64]pardes.Kind.LoadedWord = undefined; + const pointed = pardes.Kind.loadedOf(&Pointed.ops, "/x/pointed.so", @splat(8), &words); + _ = try a.local(.{ .addon = .{ .op = .load, .pane = .at(0), .kind = &pointed } }); + _ = try a.local(.{ .command = "Pointed" }); + const kid = a.core.view().active; + const r = try joinedFresh(a); + defer r.deinit(); + try runsHere(r, kid, &Pointed.ops); + const rect = r.core().view().rects[kid]; + const col = rect.x + 4; + const row = rect.y + r.core().panes[kid].?.tag_rows + 1; + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| gpa.free(m); + sent.deinit(gpa); + } + for ([_]pardes.Event{ + .{ .mouse = .{ .button = .left, .kind = .press, .col = col, .row = row } }, + .{ .resize = .{ .cols = 80, .rows = 4 } }, + .{ .mouse = .{ .button = .left, .kind = .drag, .col = col, .row = 30 } }, + .{ .mouse = .{ .button = .left, .kind = .release, .col = col, .row = 30 } }, + }) |ev| { + try sent.append(gpa, try gpa.dupe(u8, try r.input(ev))); + } + try std.testing.expectEqual(@as(u16, 1), r.core().view().rects[kid].h); + try std.testing.expectEqual(@as(u32, 0), r.stats.stopped); + for (sent.items) |m| { + r.confirm(try a.take(m)); + r.settle(); + } + try std.testing.expectEqual(@as(u32, 0), r.stats.mispredicted); + try agrees(a, r); +} + +// A draw's token is its slot's count of draws, which the rollback copy +// holds with the slot: a frame drawn under a speculation asks token T, the +// rollback takes the count back, and the next frame's draw (of the state +// the replay came to) is given T again. Its answer and the discarded one's +// both come to job_done as T, in the order the workers finish. +test "a far client's frame drawn under a speculation that rolls back asks a picture whose token the next draw is never given again: the kind keeps the picture of the state it shows" { + // A plain kind whose picture is a draw of its count (api.draw from its + // paint, when the picture asked for is of another count), its answer kept + // for the token it asked last, once: a kind with one draw outstanding. + // What it shows is this process's (a kind's own memory, never its block). + const Drawn = struct { + const pa = pardes.Kind.c; + var want: u32 = 0; + var asked: ?u32 = null; + var shown: ?u32 = null; + fn open(_: [*c]const u8, _: [*c]const u8, _: u64) callconv(.c) ?*anyopaque { + const n: *u32 = @ptrCast(@alignCast(pardes.Kind.api.alloc.?(4))); + n.* = 0; + return n; + } + fn paint(st: ?*anyopaque, _: [*c]const pa.pa_window, _: [*c]pa.pa_paint) callconv(.c) void { + const n: *const u32 = @ptrCast(@alignCast(st.?)); + if (asked == n.*) return; + asked = n.*; + want = pardes.Kind.api.draw.?(n, 4); + } + fn press(st: ?*anyopaque, _: [*c]const pa.pa_key) callconv(.c) c_int { + const n: *u32 = @ptrCast(@alignCast(st.?)); + n.* = n.* * 2 + 1; + return 1; + } + fn jobRun(in: [*c]const u8, n: u32, out: [*c]pa.pa_out) callconv(.c) u32 { + const o: [*]u8 = @ptrCast(out.*.alloc.?(out, n) orelse return 0); + @memcpy(o[0..n], in[0..n]); + return n; + } + fn jobDone(_: ?*anyopaque, token: u32, out: [*c]const u8, n: u32) callconv(.c) void { + if (token != want or n != 4) return; + want = 0; + shown = std.mem.readInt(u32, out[0..4], .little); + } + const words = [_]pa.pa_word{std.mem.zeroInit(pa.pa_word, .{ .name = "Drawn", .opens = 1, .doc = "a picture of a count" })}; + const ops = std.mem.zeroInit(pardes.Kind.Ops, .{ + .head = std.mem.zeroInit(pa.pa_head, .{ .size = @sizeOf(pa.pa_head), .abi = pardes.Kind.abi, .name = "drawn".* ++ @as([11]u8, @splat(0)), .version = 1, .exts = "", .flags = pa.PA_PLAIN, .words = &words, .nwords = 1 }), + .open = open, + .paint = paint, + .key = press, + .job_run = jobRun, + .job_done = jobDone, + }); + }; + + // A frontend's workers for draws, run when the test says, each landing + // when it says (host_io.KindJob: run on a worker, landed on the loop). + const HeldDraws = struct { + var held: [4]*@import("dev").host_io.KindJob = undefined; + var n: usize = 0; + fn go(_: ?*anyopaque, j: *@import("dev").host_io.KindJob) bool { + j.run(); + held[n] = j; + n += 1; + return true; + } + }; + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + defer a.deinit(); + var words: [64]pardes.Kind.LoadedWord = undefined; + const drawn = pardes.Kind.loadedOf(&Drawn.ops, "/x/drawn.so", @splat(9), &words); + _ = try a.local(.{ .addon = .{ .op = .load, .pane = .at(0), .kind = &drawn } }); + _ = try a.local(.{ .command = "Drawn" }); + const kid = a.core.view().active; + const r = try joinedFresh(a); + defer r.deinit(); + try runsHere(r, kid, &Drawn.ops); + Drawn.want = 0; + Drawn.asked = null; + Drawn.shown = null; + HeldDraws.n = 0; + const was = pardes.Kind.drawer; + pardes.Kind.drawer = .{ .ctx = null, .go = HeldDraws.go }; + defer pardes.Kind.drawer = was; + const none: pardes.views.Present = .{ .ctx = null, .f = null }; + // Its own key: 0 -> 1, drawn (a picture of 1 asked). + const msg = try gpa.dupe(u8, try r.input(.{ .key = .{ .cp = 'x', .text = "x" } })); + defer gpa.free(msg); + _ = r.draw(none); + try std.testing.expectEqual(@as(?u32, 1), Drawn.asked); + // The session's own key first: rolled back, its own applied again on + // top (0 -> 1 -> 3), drawn (a picture of 3 asked). + r.confirm(try a.own(.{ .key = .{ .cp = 'x', .text = "x" } })); + r.settle(); + _ = r.draw(none); + try std.testing.expectEqual(@as(?u32, 3), Drawn.asked); + try std.testing.expectEqual(@as(usize, 2), HeldDraws.n); + // The discarded picture's worker done first, then the other's; a frame. + for (HeldDraws.held[0..2]) |j| pardes.Kind.landDraw(r.core(), j); + _ = r.draw(none); + try std.testing.expectEqual(@as(?u32, 3), Drawn.shown); + r.confirm(try a.take(msg)); + r.settle(); + try agrees(a, r); +} + +// A program that asked for focus events is told of a click into its shell +// by the session's step (Core.reportFocus): a client's own step writes +// nothing. Where the shell's queue is backed up (a 9P write past what the +// effects ring holds, parked until the session's next pump), the session's +// report parks behind it, into `pending_write`, which is digested, where +// the client's speculation skips the write. It cannot differ: a client's +// step settles as the session's does, draining the queue, and what is +// parked is a write into the shell, which stops it (the client holds the +// same queue: the unit that parked it is the session's, which it replays). +test "a far client's click into a shell whose queue is backed up: the session's focus report queues behind what is parked, and the client ends as the session does" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const Told = struct { + var bytes: usize = 0; + var tail: [3]u8 = @splat(0); + fn write(_: ?*anyopaque, _: pardes.Pane.Id, b: []const u8) void { + bytes += b.len; + if (b.len >= 3) @memcpy(&tail, b[b.len - 3 ..]); + } + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .pty_write = write }; + }; + const a = try Authority.init(gpa, .{ .cols = 120, .rows = 40, .boot = .tty }, .{ .vtable = &Told.vtable }, true); + defer a.deinit(); + const shell: u8 = for (a.core.panes, 0..) |slot, id| { + if (slot) |pane| if (pane.isTerminal()) break @intCast(id); + } else return error.NoShell; + a.output(.{ .output = .{ .pane = .at(shell), .bytes = "\x1b[?1004h$ " } }); + _ = (try a.pending()).?; + _ = try a.local(.{ .command = "New" }); + var screens: Screens = .init(gpa); + defer screens.deinit(a.core); + const peer = try screens.addPeer(); + const r = try joinedFresh(a); + defer r.deinit(); + try deliver(a, &screens, peer, r, .flush); + r.settle(); + // A 9P write into the shell, past the ring: the rest parked, on both. + const big = try gpa.alloc(u8, pardes.memory.limits.effect_cap * pardes.effect_write_cap + 100); + defer gpa.free(big); + @memset(big, 'x'); + { + const was = Stepping.begin(&a.t, null); + defer was.end(); + _ = a.core.serveFs(.{ .tag = 1, .op = .write, .node = pardes.ctlfs.Node.of(a.core.panes[shell].?.serial, .pty_data), .data = big }); + } + a.seq += 1; + r.confirm(try a.unit(0, a.seq)); + r.settle(); + try std.testing.expect(a.core.pending_write[shell] != null and r.core().pending_write[shell] != null); + Told.bytes = 0; + const rect = r.core().view().rects[shell]; + const row = rect.y + r.core().panes[shell].?.tag_rows + 1; + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| gpa.free(m); + sent.deinit(gpa); + } + r.stats.stops = @splat(.{}); + for ([_]pardes.Mouse.Kind{ .press, .release }) |kind| try sent.append(gpa, try gpa.dupe(u8, try r.input(.{ .mouse = .{ .button = .left, .kind = kind, .col = rect.x + 2, .row = row } }))); + // The client's own step drains the queue it holds as the session's + // does: what is parked is a write into the shell, so it stops there, + // and waits for the session's step, focus report and all. + try std.testing.expectEqual(@as(usize, 0), r.applied); + for (r.stats.stops) |st| if (st.n > 0) try std.testing.expectEqualStrings("pty_write", st.name); + for (sent.items) |m| { + try deliver(a, &screens, peer, r, .flush); + const u = try gpa.dupe(u8, try a.take(m)); + defer gpa.free(u); + try deliver(a, &screens, peer, r, .fill); + r.confirm(u); + r.settle(); + } + // The program had what was parked, then the focus. + try std.testing.expectEqual(big.len + 3, Told.bytes); + try std.testing.expectEqualStrings("\x1b[I", &Told.tail); + try std.testing.expectEqual(@as(usize, shell), r.core().view().active); + try std.testing.expectEqual(@as(u32, 0), r.stats.mispredicted); + try agrees(a, r); +} + +// A `/` in a file groups its rows under the declarations they are in once +// a parse of the text exists (Query.ownerDecls): the pane's context, a +// worker's answer, or the locations cache's (a Diff's). Both were kept out +// of the dump as made again from the text, so a client joined since had +// neither, and its replay of the session's next row asked a parse the +// session never asked: the context is dumped now, the cache's no longer read. +test "a client joined from a dump makes a `/` query's rows as the session does, though only the session has the owner's declarations from a worker's parse" { + // A session's host whose parses and searches run on a worker (a tty's, + // Stream.start), their batches posted to an inbox; `land` hands them to + // the core as the session's inputs, as its loop does. + const WorkerSearch = struct { + const Inbox = @import("dev").host_io.Inbox; + var q: Inbox = undefined; + var core: ?*Pardes = null; + fn search(_: ?*anyopaque, gen: u32) void { + pardes.Stream.start(std.testing.io, std.testing.allocator, core.?, gen, &q, Inbox.pushSearch); + } + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .search = search }; + fn init(a: *Authority) void { + q = .{ .gpa = std.testing.allocator, .lsp_allocator = std.testing.allocator, .io = std.testing.io }; + core = a.core; + } + // The batches posted until the parse asked has answered (a second's + // wait at most), each a unit the replica takes. + fn land(a: *Authority, r: ?*Replica) !void { + var waited: u32 = 0; + while (a.core.stream.parse != null) : (waited += 1) { + if (waited == 1000) return error.Timeout; + var batch: Inbox.Batch = .{}; + q.takeInto(&batch); + for (batch.slice()) |m| switch (m) { + .search => |b| { + const u = try a.local(.{ .search = b }); + if (r) |c| { + c.confirm(u); + c.settle(); + } + b.deinit(std.testing.allocator); + }, + else => m.deinit(std.testing.allocator, std.testing.allocator), + }; + if (a.core.stream.parse != null) { + const rest: std.c.timespec = .{ .sec = 0, .nsec = std.time.ns_per_ms }; + _ = std.c.nanosleep(&rest, null); + } + } + } + }; + if (comptime !pardes.syntax.enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, .{ .vtable = &WorkerSearch.vtable }, false); + defer a.deinit(); + WorkerSearch.init(a); + defer WorkerSearch.q.deinit(); + // The session's own `/`: its parse asked of the worker, its answer an + // input (the rows grouped once it lands). + _ = try a.local(.{ .command = "Search /pub" }); + try WorkerSearch.land(a, null); + // A client joined now, and a key typed into the query: both its rows. + const r = try joinedNow(a, 1, 0); + defer r.deinit(); + try std.testing.expectEqual(digestOf(a), r.digest()); + try std.testing.expectEqual(a.core.panes[0].?.file.?.context.declarations.len, r.core().panes[0].?.file.?.context.declarations.len); + const u = try gpa.dupe(u8, try a.local(.{ .key = .{ .cp = 'l', .text = "l" } })); + defer gpa.free(u); + r.confirm(u); + r.settle(); + try agrees(a, r); +} + +// A text's places show as ticks on its rail (Places.addTicks), made again +// only when `gen` moves (buildTicks), by a frame or by a step's rail click +// (tickHit), whichever asks first; a dump keeps neither. A frame's ticks +// that a click read after the places changed under them would land it +// elsewhere on a core that drew than on one that did not. +test "a client joined from a dump lands a click on a rail's tick as the session does, the session's ticks drawn before the places changed" { + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host(), false); + defer a.deinit(); + _ = try a.local(.{ .command = "Search /pub" }); + const owner: usize = 0; + try std.testing.expect(a.core.panes[owner].?.places.hits.items.len > 1); + // The session draws: its ticks, of `/pub`'s places. + { + const was = Stepping.begin(&a.t, null); + defer was.end(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + _ = try a.core.render(arena.allocator()); + } + const ticks_gen = a.core.panes[owner].?.places.ticks_gen; + try std.testing.expectEqual(a.core.panes[owner].?.places.gen, ticks_gen); + const r = try joinedFresh(a); + defer r.deinit(); + // Its places changed (`/publ`), then a click on each row of the rail. + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| gpa.free(m); + sent.deinit(gpa); + } + try sent.append(gpa, try gpa.dupe(u8, try r.input(.{ .key = .{ .cp = 'l', .text = "l" } }))); + const rect = r.core().view().rects[owner]; + const pane = r.core().panes[owner].?; + for (rect.y + pane.tag_rows..rect.y + rect.h) |row| for ([_]pardes.Mouse.Kind{ .press, .release }) |kind| { + try sent.append(gpa, try gpa.dupe(u8, try r.input(.{ .mouse = .{ .button = .left, .kind = kind, .col = rect.x, .row = @intCast(row) } }))); + }; + try std.testing.expect(a.core.panes[owner].?.places.ticks_gen == ticks_gen); + for (sent.items) |m| { + r.confirm(try a.take(m)); + r.settle(); + } + // (The key may be mispredicted: a step's places are a frame's time's + // worth, `tape.over`, the session's verdict, and its drawn caches let + // it find more in that time than the client's speculation did.) + try agrees(a, r); + try std.testing.expectEqual(a.core.panes[owner].?.places.current, r.core().panes[owner].?.places.current); +} + +// `search` stopped every client's step that asked for one, because a host +// with no worker wrote the rows outside any record: then no client had them, +// stopped or not (a replay answers the entry from the tape and runs no +// host). Its rows are inputs now, as a worker's are, and a step that asks +// the session's host for a search goes on. +test "a far client's step that asks for a search goes on at once, and a session whose host searches on its loop gives every client its rows" { + // A session's host with no worker for a search (a frontend before its + // threads, or one whose worker could not be had: Stream.start): it runs + // the search on its loop, in its `search` entry. + const LoopSearch = struct { + var core: ?*Pardes = null; + fn search(_: ?*anyopaque, gen: u32) void { + pardes.Stream.runHere(core.?, gen, true); + } + fn now(_: ?*anyopaque) u64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts); + return @intCast(ts.sec * std.time.ns_per_s + ts.nsec); + } + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .search = search, .now = now }; + }; + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "a.zig", .data = "const needle = 1;\nfn f() void {}\n// a needle\n" }); + var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var path_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "{s}/a.zig", .{dir}); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = path }, .{ .vtable = &LoopSearch.vtable }, false); + defer a.deinit(); + LoopSearch.core = a.core; + const r = try joinedFresh(a); + defer r.deinit(); + // A `/` in a file asks the session's host for its parse. + const msg = try gpa.dupe(u8, try r.input(.{ .command = "Search /ne" })); + defer gpa.free(msg); + try std.testing.expectEqual(@as(u32, 0), r.stats.stopped); + r.confirm(try a.take(msg)); + r.settle(); + try agrees(a, r); + // A Grep the session's loop runs when the typing pauses: its rows. + r.confirm(try a.local(.{ .key = .{ .cp = pardes.Key.escape } })); + r.confirm(try a.local(.{ .command = "Search Grep needle" })); + r.settle(); + var ticks: u32 = 0; + while (a.core.stream.state == .waiting) : (ticks += 1) { + if (ticks == 200) return error.Timeout; + const rest: std.c.timespec = .{ .sec = 0, .nsec = 10 * std.time.ns_per_ms }; + _ = std.c.nanosleep(&rest, null); + r.confirm(try a.local(.tick)); + r.settle(); + } + try std.testing.expect(a.core.stream.state == .done); + try agrees(a, r); +} + +// PARDES_NOTIME (the tests' `--:--:--` clock) is read by `Message.stamp`, +// which only a host calls: between steps, or in its own entry during one. +// The stamped text crosses as the setMessage the host makes, so a client +// whose environment says otherwise replays the session's text. +test "a far client's replay of a message its session's host stamped takes the session's text, whatever its own PARDES_NOTIME says" { + const gpa = std.testing.allocator; + const Stamping = struct { + var core: ?*Pardes = null; + fn yank(_: ?*anyopaque, _: []const u8) void { + var buf: [64]u8 = undefined; + const c = core.?; + c.setMessage(.at(c.view().active), pardes.Messages.Message.stamp(&buf, "yanked", "x")); + } + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .set_clipboard = yank }; + }; + const Shell = @import("dev").host_io.Shell; + const was = if (std.c.getenv("PARDES_NOTIME")) |v| try gpa.dupeSentinel(u8, std.mem.span(v), 0) else null; + defer if (was) |v| gpa.free(v); + defer _ = if (was) |v| Shell.setenv("PARDES_NOTIME", v, 1) else @import("dev").host_io.testUnsetenv("PARDES_NOTIME"); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &Stamping.vtable }, false); + defer a.deinit(); + Stamping.core = a.core; + const r = try joinedFresh(a); + defer r.deinit(); + // The session's machine says `--:--:--`; the client's the time of day. + _ = Shell.setenv("PARDES_NOTIME", "1", 1); + const u = try gpa.dupe(u8, try a.own(.{ .command = "ClipYank" })); + defer gpa.free(u); + _ = @import("dev").host_io.testUnsetenv("PARDES_NOTIME"); + r.confirm(u); + r.settle(); + try agrees(a, r); + try std.testing.expect(try shows(r.core(), "--:--:-- yanked x")); +} |
