//! A session's replicas (docs/next-daemon.md, phase 5 part A): the authority //! orders every input and records what its core consumed (core/tape.zig); //! each replica runs a core of its own, applies its own inputs at once, and //! takes the authority's stream as the truth. //! //! A replica's state is the confirmed position plus its own pending inputs, //! applied on top (a speculation, recorded as the authority would record //! it). For each unit of the authority's stream, in order: //! - its own pending head, recorded the same (inputs, host calls and //! answers): the head goes, nothing is redone (the fast path); //! - else the rollback copy is put back (core/rollback.zig), the confirmed //! units since it are replayed, then this one, and the pending inputs //! are applied again. //! A speculation that reaches a host call or a syscall (a Host function, //! a `tape.site`) or an emulator (the authority's) stops: the copy is put //! back and the input waits for the authority's answer, one RTT late but //! never wrong. Clock and environment reads (`tape.value`) are made here, //! and the comparison catches a guess the authority did not share. //! //! No transport: messages are bytes in and out. A client's input is its //! id, a sequence number and the event as wire.zig frames it; a //! unit is the input's origin (0 for the authority's own: a pty's output, a //! tick), its sequence number and the authority's tape of it. const std = @import("std"); const builtin = @import("builtin"); const pardes = @import("root.zig"); const tape = @import("tape.zig"); const rollback = @import("rollback.zig"); const walk = @import("walk.zig"); const wire = @import("wire"); const daemon = @import("runtime").daemon; const writeAll = daemon.writeAll; const c_heap = @import("c_heap"); const Term = pardes.Term; const Echo = @import("echo.zig").Echo; const Allocator = std.mem.Allocator; const Pardes = pardes.Pardes; 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 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 /// confirmed one), and once quiet (`Link.quietCheck`): a full digest is a /// walk of the whole core, an edit's worth of work. const check_every = 32; fn header(buf: []u8, who: u16, seq: u32) void { std.mem.writeInt(u16, buf[0..2], who, .little); std.mem.writeInt(u32, buf[2..6], seq, .little); } /// A unit's head: its origin and seq, then the authority's clocks when it /// was made (realtime and monotonic, ns), which a replica's guesses of the /// session's clock start from. const unit_head = head_len + 16; pub const Unit = struct { origin: u16, seq: u32, real_ns: i64 = 0, mono_ns: i64 = 0, tape: []const u8 }; fn clockNs(id: std.c.clockid_t) i64 { var ts: std.c.timespec = undefined; if (std.c.clock_gettime(id, &ts) != 0) return 0; return @as(i64, ts.sec) * std.time.ns_per_s + ts.nsec; } fn unitHeader(buf: []u8, origin: u16, seq: u32) void { header(buf, origin, seq); std.mem.writeInt(i64, buf[6..14], clockNs(.REALTIME), .little); std.mem.writeInt(i64, buf[14..22], clockNs(.MONOTONIC), .little); } pub const Input = struct { client: u16, seq: u32, event: pardes.Event, stamp: ?[2]i64 = null }; /// A client's input message: its head, a `stamp` frame (when its client /// guessed the session's clocks), and its event's frame, which the event /// borrows. pub fn parseInput(msg: []const u8) ?Input { if (msg.len < head_len) return null; var rest = msg[head_len..]; var f = (wire.framed(rest) catch return null) orelse return null; var stamp: ?[2]i64 = null; if (f.tag == @backingInt(wire.ClientTag.stamp)) { stamp = (wire.decodeClient(f.tag, f.payload) catch return null).stamp; rest = rest[f.total..]; f = (wire.framed(rest) catch return null) orelse return null; } const ev = switch (wire.decodeClient(f.tag, f.payload) catch return null) { .event => |ev| ev, else => return null, }; return .{ .client = std.mem.readInt(u16, msg[0..2], .little), .seq = std.mem.readInt(u32, msg[2..6], .little), .event = ev, .stamp = stamp }; } /// An input's stamp as the authority takes it: the client's guess of its /// clocks, so the guess its speculation recorded is the step's own; none /// from a client a second or more off (a stall, a bad round trip), whose /// step reads the clocks here. fn stampOf(in: Input) ?tape.Guess { const s = in.stamp orelse return null; if (@abs(s[0] - clockNs(.REALTIME)) >= std.time.ns_per_s or @abs(s[1] - clockNs(.MONOTONIC)) >= std.time.ns_per_s) return null; return .{ .real_ns = s[0], .mono_ns = s[1], .gmtoff = gmtoff() }; } /// The core whose tape is `t`, stepped: tape.on is process-wide, and so /// are syntax.zig's held trees, so one process can step several. const Stepping = struct { tape: ?*tape.Tape, trees: ?*pardes.syntax.HeldTrees, fn begin(t: *tape.Tape, epoch: ?*rollback.Epoch) Stepping { const was: Stepping = .{ .tape = tape.on, .trees = pardes.syntax.held_trees }; tape.on = t; rollback.Epoch.select(epoch); return was; } fn end(was: Stepping) void { tape.on = was.tape; pardes.syntax.held_trees = was.trees; } }; const nowNs = pardes.FrameStats.nowNs; /// With PARDES_REPLICA_TRACE, a line on stderr, each of `tapes` described /// after it. fn trace(gpa: Allocator, comptime fmt: []const u8, args: anytype, tapes: []const []const u8) void { if (std.c.getenv("PARDES_REPLICA_TRACE") == null) return; var w: std.Io.Writer.Allocating = .init(gpa); defer w.deinit(); w.writer.print(fmt, args) catch {}; for (tapes) |t| tape.describe(t, &w.writer); std.debug.print("{s}", .{w.written()}); } /// The `p`th percentile of `samples` (sorted here); 100 is the worst. fn pctOf(samples: []u64, p: usize) u64 { if (samples.len == 0) return 0; std.mem.sort(u64, samples, {}, std.sort.asc(u64)); return samples[@min(samples.len - 1, samples.len * p / 100)]; } // ---- the authority ---- pub const Authority = struct { gpa: Allocator, t: tape.Tape, core: *Pardes, host: pardes.Host, out: std.ArrayListUnmanaged(u8) = .empty, seq: u32 = 0, /// Each client's view (core/views.zig): its own layout, focus and /// cursors over the session's text. The first client has the session's. view_of: [64]Pardes.View.Id = @splat(.at(0)), /// Steps of its own taken since the last unit (`output`): one unit, /// `pending`, sent before the next input it steps and at a frame. batched: u32 = 0, /// A session booted with `opts`; `unit` is its first, which a replica /// is made from. pub fn init(gpa: Allocator, options: pardes.Options, host: pardes.Host) !*Authority { // A replay gives its core every allocator (tape.zig), and a digest // tells an allocator from none. var opts = options; opts.image_allocator = opts.image_allocator orelse gpa; opts.tree_sitter_allocator = opts.tree_sitter_allocator orelse gpa; opts.frame_allocator = opts.frame_allocator orelse gpa; const a = try gpa.create(Authority); errdefer gpa.destroy(a); a.* = .{ .gpa = gpa, .t = tape.memory(gpa), .core = undefined, .host = host }; errdefer tape.release(&a.t); // A digest at a unit's end, as the session's (Peers.unit). a.t.no_digest = true; opts.tape = &a.t; const was = Stepping.begin(&a.t, null); defer was.end(); a.core = try Pardes.init(gpa, opts); a.core.host = host; a.core.pump(host) catch {}; return a; } pub fn deinit(a: *Authority) void { const was = Stepping.begin(&a.t, null); a.core.deinit(); was.end(); tape.release(&a.t); a.out.deinit(a.gpa); a.gpa.destroy(a); } /// What was recorded since the last unit, as one (the boot's, a setup's /// done straight on the core). pub fn unit(a: *Authority, origin: u16, seq: u32) ![]const u8 { const was = Stepping.begin(&a.t, null); tape.recordDigest(&a.t); was.end(); a.out.clearRetainingCapacity(); try a.out.appendNTimes(a.gpa, 0, unit_head); unitHeader(a.out.items, origin, seq); try a.out.appendSlice(a.gpa, a.t.buf.items); a.t.buf.clearRetainingCapacity(); return a.out.items; } /// An input of the authority's own (a pty's output, a tick, a setup's /// command), recorded into the unit being made. pub fn apply(a: *Authority, ev: pardes.Event) void { const was = Stepping.begin(&a.t, null); a.core.update(ev); a.core.pump(a.host) catch {}; was.end(); } /// One of the authority's own inputs, as its unit. pub fn local(a: *Authority, ev: pardes.Event) ![]const u8 { std.debug.assert(a.batched == 0); // `pending` first: units keep the order steps took a.apply(ev); a.seq += 1; return a.unit(0, a.seq); } /// An input of its own frontend's, in the view that frontend shows /// (the first: tui.zig `Shell.handle` goes into `s.own`), as its unit. pub fn own(a: *Authority, ev: pardes.Event) ![]const u8 { std.debug.assert(a.batched == 0); const was = Stepping.begin(&a.t, null); a.core.toView(.at(0)); was.end(); return a.local(ev); } /// A step of its own (a pty's output) into the open batch: under a /// flood a replica gets a unit a frame, not one a read (each unit of the /// authority's rolls back a replica's pending inputs), and its digest /// once a unit. pub fn output(a: *Authority, ev: pardes.Event) void { a.apply(ev); a.batched += 1; } /// A pass of its host's loop with no input (a frame's wake): its pump /// alone, its clock advanced and what is due ticked, into the open /// batch. pub fn pump(a: *Authority) void { const was = Stepping.begin(&a.t, null); a.core.pump(a.host) catch {}; was.end(); a.batched += 1; } /// The open batch as a unit, or null: what the host sends before it /// steps any other input, and once a frame. pub fn pending(a: *Authority) !?[]const u8 { if (a.batched == 0) return null; a.batched = 0; a.seq += 1; return try a.unit(0, a.seq); } /// A view of its own for `client`, as its unit; which it is. pub fn openView(a: *Authority, client: u16) !struct { view: u8, unit: []const u8 } { std.debug.assert(a.batched == 0); const was = Stepping.begin(&a.t, null); const k = a.core.openView() orelse { was.end(); return error.TooManyViews; }; a.core.pump(a.host) catch {}; was.end(); a.view_of[client] = k; a.seq += 1; return .{ .view = k.index(), .unit = try a.unit(0, a.seq) }; } /// A client joining as `Peers.join` takes one: its view kept for it /// (`back`, after a divergence) or a new one, null when every view is /// taken (refused); the unit that says so to the others (valid until the /// next call), and the dump it loads, its blobs in place (`gpa`'s), with /// the digest it checks its load by. pub fn join(a: *Authority, client: u16, back: ?u8) !?struct { view: u8, unit: []const u8, dump: []u8, digest: u64 } { std.debug.assert(a.batched == 0); const was = Stepping.begin(&a.t, null); defer was.end(); const again = if (back) |v| a.core.rejoinView(.at(v)) else false; const k = (if (again) back else if (a.core.openView()) |o| o.index() else null) orelse return null; a.core.undrawn |= @as(u8, 1) << @intCast(k); a.view_of[client] = .at(k); a.seq += 1; const u = try a.unit(0, a.seq); var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; defer blobs.deinit(a.core.gpa); const dumped = try pardes.dump.dumpJoin(a.core, &blobs); const state = dumped.bytes; defer a.core.gpa.free(state); tape.resync(&a.t); var whole: std.ArrayListUnmanaged(u8) = .empty; errdefer whole.deinit(a.gpa); var pos: usize = 0; for (blobs.items) |b| { try whole.appendSlice(a.gpa, state[pos..b.at]); try whole.appendSlice(a.gpa, b.bytes); pos = b.at; } try whole.appendSlice(a.gpa, state[pos..]); return .{ .view = k, .unit = u, .dump = try whole.toOwnedSlice(a.gpa), .digest = dumped.digest }; } /// Client `client` gone as `Peers.leave` lets one go: its view kept for /// it (`again`: it joins again for it) or closed; the unit. pub fn leave(a: *Authority, client: u16, again: bool) ![]const u8 { std.debug.assert(a.batched == 0); const was = Stepping.begin(&a.t, null); const k = a.view_of[client]; a.core.undrawn &= ~(@as(u8, 1) << @intCast(k.index())); if (again) a.core.awayView(k) else a.core.closeView(k); was.end(); a.seq += 1; return a.unit(0, a.seq); } /// Client `client`'s view gone (its link ended), as its unit. pub fn closeView(a: *Authority, client: u16) ![]const u8 { std.debug.assert(a.batched == 0); const was = Stepping.begin(&a.t, null); a.core.closeView(a.view_of[client]); was.end(); a.seq += 1; return a.unit(0, a.seq); } /// One client's input, applied in the order it came, in its view: the /// unit every replica takes. pub fn take(a: *Authority, msg: []const u8) ![]const u8 { std.debug.assert(a.batched == 0); const in = parseInput(msg) orelse return error.BadInput; const was = Stepping.begin(&a.t, null); a.core.toView(a.view_of[in.client]); a.t.stamp = stampOf(in); a.core.update(in.event); a.core.step(); a.t.stamp = null; was.end(); return a.unit(in.client, in.seq); } }; // ---- a replica ---- pub const Stats = struct { inputs: u32 = 0, /// Applied at once and clean. speculated: u32 = 0, /// Stopped at a host call, a syscall or an emulator: waits one RTT. stopped: u32 = 0, /// The authority's unit was the pending head, recorded the same. fast: u32 = 0, /// The copy put back: the head recorded otherwise (a guess of the clock /// 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). checks: u32 = 0, /// The samples below kept: an in-process harness's replica, or a /// client's with PARDES_REPLICA_STATS. Without, nothing is: a client /// runs for days, and they grew a word an input and a delta. samples: bool = false, /// Nanoseconds: one speculative apply, a copy taken, a rollback (the /// copy put back, the confirmed units replayed, the pending reapplied). spec_ns: std.ArrayListUnmanaged(u64) = .empty, copy_ns: std.ArrayListUnmanaged(u64) = .empty, rollback_ns: std.ArrayListUnmanaged(u64) = .empty, copy_bytes: u64 = 0, copies: u32 = 0, /// What stopped them (`Tape.poisoned_by`), a count a name. stops: [16]Stop = @splat(.{}), const Stop = struct { name: []const u8 = "", n: u32 = 0 }; fn stop(s: *Stats, name: []const u8) void { for (&s.stops) |*st| if (st.n == 0 or std.mem.eql(u8, st.name, name)) { st.name = name; st.n += 1; return; }; } /// `name:n,...` (spaces as dashes), or `-`. fn writeStops(s: *const Stats, w: *std.Io.Writer) !void { var any = false; for (s.stops) |st| if (st.n > 0) { if (any) try w.writeByte(','); any = true; for (st.name) |ch| try w.writeByte(if (ch == ' ') '-' else ch); try w.print(":{d}", .{st.n}); }; if (!any) try w.writeByte('-'); } pub fn deinit(s: *Stats, gpa: Allocator) void { s.spec_ns.deinit(gpa); s.copy_ns.deinit(gpa); s.rollback_ns.deinit(gpa); } }; /// `outside`: how far its speculation moved its core's count of writes /// outside the rollback copy (Pardes.outside): not 0, it owes an emulator /// a write (a grid's size), which only its replay makes. const Pending = struct { seq: u32, msg: []u8, spec: ?[]u8 = null, sent_ns: u64 = 0, outside: u64 = 0, guess: ?tape.Guess = null }; pub fn parseUnit(msg: []const u8) ?Unit { if (msg.len < unit_head) return null; return .{ .origin = std.mem.readInt(u16, msg[0..2], .little), .seq = std.mem.readInt(u32, msg[2..6], .little), .real_ns = std.mem.readInt(i64, msg[6..14], .little), .mono_ns = std.mem.readInt(i64, msg[14..22], .little), .tape = msg[unit_head..], }; } pub const Replica = struct { gpa: Allocator, id: u16, /// Its own view of the session (Authority.openView's). view: u8 = 0, /// The core's allocator; its tapes and the engine's own lists are not. epoch: rollback.Epoch = .{}, t: tape.Tape, copy: rollback.Copy = .{}, pending: std.ArrayListUnmanaged(Pending) = .empty, /// pending[0..applied] are applied on top of the confirmed position. applied: usize = 0, /// The pending input that waits for the authority (it stopped at a host /// call, or is the view's), and those after it with it. blocked: ?u32 = null, /// Confirmed units since the copy was taken, replayed over it when it /// is put back: a unit of another's that came while the client was /// idle (`ready`), one of its own fast-pathed, one that moved nothing /// (`neutral`). Each read the terminals as they are now: a delta lets /// them go first (`screen`). since: std.ArrayListUnmanaged([]u8) = .empty, /// Pending inputs to apply again (after a rollback). dirty: bool = false, next_seq: u32 = 1, stats: Stats = .{}, diverged: ?[]const u8 = null, out: std.ArrayListUnmanaged(u8) = .empty, /// Nanoseconds of the rollback being made, until its reapply. recovering: ?u64 = null, /// The digest the last confirmed unit ended on (its last record's /// bytes): a unit of another's that ends on it again (the session's /// pump that took this replica's input in, and moved nothing) leaves /// the speculation on top as it was. last_digest: std.ArrayListUnmanaged(u8) = .empty, /// Units of another's taken so, no rollback made. neutral: u32 = 0, /// Confirmed units since its digest was last compared (`check_every`). since_check: u32 = 0, /// What it shows changed since the host last drew it: a unit replayed /// on it, a rollback (a unit that confirmed what it applied, or moved /// nothing, changes nothing to draw). moved: bool = false, /// A client of a session elsewhere (`initDump`): the session's clock is /// guessed, never read here -- its last unit's reading, plus the time /// since it came, plus a round trip (the input reaches the session that /// much later). In process, both read one clock. guess: bool = false, stamp: struct { real_ns: i64 = 0, mono_ns: i64 = 0, at_ns: u64 = 0 } = .{}, rtt_ns: u64 = 0, gmtoff: i32 = 0, /// Its panes' serials as the copy was taken, and whether one was being /// torn down then (`panesMoved`). serials: [pardes.MAX_PANES]u32 = @splat(0), retiring: bool = false, /// A record's bytes by hash coming in pieces (`blobPiece`), and how /// many of them came. incoming: ?tape.Big = null, incoming_got: usize = 0, /// A far client's blobs on disk (its Have's), where a file it is sent /// goes for its next join. cache: ?Cache = null, io: std.Io = undefined, /// Its predicted echo (core/term/echo.zig), drawn over its core's terminals: /// fed by its keys and its units here, and by `echoFrame`. echo: Echo = .{}, /// A replica of the session whose first unit is `first`, its terminals /// fed the pty's bytes the units carry. In process, its timing samples /// kept for the harness that reads them; no predicted echo (a joined /// client's has one: `made`). pub fn init(gpa: Allocator, id: u16, first: []const u8) !*Replica { const r = try gpa.create(Replica); r.* = .{ .gpa = gpa, .id = id, .t = tape.memory(gpa), .stats = .{ .samples = true } }; r.t.core_gpa = r.epoch.allocator(); r.t.checks = false; r.confirm(first); if (r.t.core == null) { r.deinit(); return error.NoCore; } return r; } /// A replica of a session elsewhere, as its walker dump (core/dump.zig) /// is: what a client of a socket joins with. `opts` are this process's /// (a replica's own allocators and names); its core's allocator is the /// rollback epoch's, its `image_allocator` too (a kind's slot whose /// state is not plain: a speculation that closes one frees it into the /// epoch, put off, as any). ponytail: a picture's pixels (`Kind.heap`) /// freed while a copy is held are not put off; a rollback over one shows /// an image a frame late at worst... or reads freed pixels, which no test /// session has. pub fn initDump(gpa: Allocator, id: u16, view: u8, bytes: []const u8, opts: pardes.Options) !*Replica { return made(gpa, id, view, opts, bytes, null); } /// A pair's first client's replica (Options.pair): its core made here /// from the options the session is made from, its file read here (a /// near client's read of its own machine), the view the session's join /// opens for it opened (`Peers.viewFor`): the session's core at its /// join, which the welcome confirms by its digest (`confirmBoot`). Its /// id the session's first client's. pub fn initBoot(gpa: Allocator, opts: pardes.Options) !*Replica { return made(gpa, 1, null, opts, null, null); } /// `initDump`'s, or with no dump `initBoot`'s; why a dump was refused /// in `why` when given (its loader's words). fn made(gpa: Allocator, id: u16, view: ?u8, opts: pardes.Options, dump: ?[]const u8, why: ?*std.ArrayList(u8)) !*Replica { const r = try gpa.create(Replica); r.* = .{ .gpa = gpa, .id = id, .view = view orelse 0, .t = tape.memory(gpa), .guess = true }; r.t.skips_render = true; r.t.checks = false; errdefer { tape.release(&r.t); r.epoch.deinit(); gpa.destroy(r); } const epoch = r.epoch.allocator(); r.t.core_gpa = epoch; var o = opts; o.frame_allocator = epoch; o.tree_sitter_allocator = epoch; o.image_allocator = epoch; // The session's closed panes and Recent are the authority's. o.state = .off; // Its emulators off the epoch, as `terminal.create` makes a screen // replica's: deltas write them while a copy is held. pardes.dump.terminal_gpa = pardes.panes.emulator_gpa; defer pardes.dump.terminal_gpa = null; // The loader's words, the epoch's: why a refusal is copied out. var words: std.ArrayList(u8) = .empty; defer words.deinit(epoch); const c = if (dump) |bytes| pardes.dump.load(epoch, o, bytes, &words) catch |err| { if (why) |w| w.appendSlice(gpa, words.items) catch {}; return err; } else boot: { // The addons the session's start finds (runtime/session.zig). o.addons = pardes.Addon.scan(); // On no tape, as the session's start is (one recording to a // file aside): what it reads of the machine (the directory, the // shell, the file) it reads as the session does, not as a // replica's step would. const c = init: { const was = Stepping.begin(&tape.none, &r.epoch); defer was.end(); break :init try pardes.Pardes.init(epoch, o); }; // Its view opened on its own tape, as the session's join opens // it on the one its clients are sent: its terminals, screen // state, not reloaded there either. tape.adoptCore(&r.t, c); const was = Stepping.begin(&r.t, &r.epoch); defer was.end(); r.view = Peers.viewFor(c, null, true) orelse return error.NoView; break :boot c; }; // It runs a plain kind's code of its own (Addon.plainOps), loaded // at its first pane, each opened here from its record; another's // panes show a line. c.kinds.ops = @splat(null); for (c.panes, 0..) |pslot, at| if (pslot) |pane| if (pane.addon) |s| if (c.kinds.byName(s.nameOf())) |k| { if (c.kinds.ops[k] == null) c.kinds.ops[k] = pardes.Addon.plainOps(&c.kinds.kinds[k], o.distrusted); // Refused (its file not here): the line saying it does not run here. if (c.kinds.ops[k]) |ops| pane.addon = pardes.dump.plainHere(c, at, s, ops) catch s; }; // What loading queued (a watch, a theme asked for) is the // authority's errand, done there already: the session was dumped // between steps, with nothing queued. c.effects_len = 0; c.effects_head = 0; c.in_len = 0; c.in_head = 0; tape.adoptCore(&r.t, c); // Its keys into a terminal drawn at once (core/term/echo.zig). c.echo = &r.echo; return r; } pub fn deinit(r: *Replica) void { if (r.t.core) |c| { const was = Stepping.begin(&r.t, &r.epoch); // The state it ends on is whole as it is: the copy let go, its // put-off frees done (a held copy across an input of its own, a // rejoin's old replica). if (r.copy.held) r.copy.release(); c.deinit(); was.end(); } if (r.incoming) |b| r.gpa.free(b.bytes); r.copy.deinit(); for (r.pending.items) |p| r.freePending(p); r.pending.deinit(r.gpa); for (r.since.items) |u| r.gpa.free(u); r.since.deinit(r.gpa); r.out.deinit(r.gpa); r.last_digest.deinit(r.gpa); r.stats.deinit(r.gpa); tape.release(&r.t); if (r.diverged) |why| r.gpa.free(why); r.epoch.deinit(); r.gpa.destroy(r); } pub fn core(r: *const Replica) *Pardes { return r.t.core.?; } fn freePending(r: *Replica, p: Pending) void { r.gpa.free(p.msg); if (p.spec) |s| r.gpa.free(s); } /// The replica's own input: applied at once when it can be, and the /// message for the authority returned (valid until the next call). pub fn input(r: *Replica, ev: pardes.Event) ![]const u8 { const msg = try r.pend(ev); r.applyPended(ev); return msg; } /// An input's first half: stamped, numbered and pending, its message /// for the authority returned (valid until the next call), which a /// client sends before it applies it (`applyPended`, Link.input): the /// session starts its step while the client speculates. pub fn pend(r: *Replica, ev: pardes.Event) ![]const u8 { r.stats.inputs += 1; const seq = r.next_seq; r.next_seq += 1; // Its time, as the session's clocks will read when it steps it (a // round trip on from the last unit's, the clocks here in process): // the step's clock reads, here and there (`stampOf`). const g: tape.Guess = if (r.guess) guess: { const since: i64 = @intCast(nowNs() -| r.stamp.at_ns + r.rtt_ns); break :guess .{ .real_ns = r.stamp.real_ns + since, .mono_ns = r.stamp.mono_ns + since, .gmtoff = r.gmtoff }; } else .{ .real_ns = clockNs(.REALTIME), .mono_ns = clockNs(.MONOTONIC), .gmtoff = gmtoff() }; const room = try r.gpa.alloc(u8, head_len + stamp_len + wire.clientBound(.{ .event = ev })); defer r.gpa.free(room); _ = try wire.encodeClient(room[head_len..][0..stamp_len], .{ .stamp = .{ g.real_ns, g.mono_ns } }); const n = (try wire.encodeClient(room[head_len + stamp_len ..], .{ .event = ev })).len; header(room, r.id, seq); const msg = try r.gpa.dupe(u8, room[0 .. head_len + stamp_len + n]); try r.pending.append(r.gpa, .{ .seq = seq, .msg = msg, .sent_ns = nowNs(), .guess = g }); r.dirty = true; r.out.clearRetainingCapacity(); try r.out.appendSlice(r.gpa, msg); return r.out.items; } /// An input's second half (`pend`'s, the last): applied at once when it /// can be, its echo predicted. pub fn applyPended(r: *Replica, ev: pardes.Event) void { r.settle(); if (r.diverged == null and r.core().echo != null) r.echo.typed(r.core(), r.view, ev, r.next_seq - 1, r.applied == r.pending.items.len); } /// One unit of the authority's stream, in its order. pub fn confirm(r: *Replica, msg: []const u8) void { if (r.diverged != null) return; const u = parseUnit(msg) orelse return r.fail("a unit too short to read"); r.stats.units += 1; r.since_check +|= 1; if (u.origin == r.id) if (r.t.core) |c| r.echo.confirmed(c, u.seq); // THE ONE QUESTION of a unit: did applying it write state outside // the rollback copy (an emulator: Pardes.outside, the count of those // writes, moved over its apply, read off the core that applied it)? // Such a unit is applied once, to the confirmed core, never kept to // replay over a copy; and its emulators' new state is what the // predicted echo is judged against. var moved = false; defer if (r.diverged == null and moved) if (r.t.core) |c| if (c.echo != null) r.echo.fed(c); // A copy taken ahead (`ready`), nothing on top: it stays the point a // rollback goes back to, the unit replayed on it and kept in `since`, // not let go and taken again (a megabyte walked) for each unit of // the session's that comes while the client is idle. const ahead = r.applied == 0 and r.copy.held; if (r.guess) { r.stamp = .{ .real_ns = u.real_ns, .mono_ns = u.mono_ns, .at_ns = nowNs() }; if (u.origin == r.id) for (r.pending.items) |p| if (p.seq == u.seq) { // Sent to confirmed: what reaching the session takes, and back. if (p.sent_ns != 0) r.rtt_ns = nowNs() -| p.sent_ns; break; }; } const was = Stepping.begin(&r.t, &r.epoch); defer was.end(); if (u.origin == r.id and r.pending.items.len > 0 and r.pending.items[0].seq == u.seq and r.applied > 0 and tape.sameRecords(r.pending.items[0].spec.?, u.tape)) { r.stats.fast += 1; // The state it ends on, which a unit of another's that moves // 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 {}; // Its speculation's own count (`Pending.outside`: the fast // path's premise, the same records, makes it this unit's): it // owes an emulator a write (a grid's size), which a speculation // never makes: kept, the write would be missing; replayed later // (a rollback's `since`), made then. So it is taken now, on the // confirmed core, and the ones on top applied again over it. moved = r.pending.items[0].outside != 0; if (moved) { r.toConfirmed(); if (tape.replayUnit(&r.t, u.tape)) |why| return r.fail(why); r.freePending(r.pending.orderedRemove(0)); r.dirty = true; return; } r.freePending(r.pending.orderedRemove(0)); r.applied -= 1; if (r.applied == 0) { // Nothing speculative on top any more: the state is the // confirmed one, which its digest says, when it carries one // and a check is due. A step of its own that read what the // session's did not (a frame's, a derived field's) shows at // the next check, or quiet (`Link.quietCheck`). if (r.checkDue()) if (lastDigest(u.tape)) |d| { r.t.checks = true; r.t.check(d); r.t.checks = false; r.since_check = 0; r.stats.checks += 1; if (r.t.diverged) |why| { trace(r.gpa, "replica {d}: its input {d} came to another state than the session's: {s}\n", .{ r.id, u.seq, why }, &.{u.tape}); return r.fail(why); } }; // The copy stays the point a rollback goes back to, this // input kept to replay over it as a unit of the session's // that comes while idle is: a step writes some bytes of the // megabyte the copy is, walked once in `rebase_after` units, // not once a key. Not once a pane opened, closed or was torn // down since the copy (what it holds outside the copy was // made or freed: `ahead`'s rule). if (!r.panesMoved()) return r.keepSince(u.tape); r.copy.release(); rollback.Epoch.select(null); r.clearSince(); return; } return r.keepSince(u.tape); } const ends = lastDigest(u.tape); // None: where it ended is not known, and the next unit is not // taken as moving nothing from it. defer { r.last_digest.clearRetainingCapacity(); if (ends) |d| r.last_digest.appendSlice(r.gpa, d) catch {}; } // The one question needs no read here: the session's digest after // the unit holds its count of writes outside the copy, so a unit that // wrote an emulator (a terminal's output, a colour set no other // digested field shows, a join's reloads) never ends where it began. if (r.applied > 0 and u.origin != r.id and ends != null and std.mem.eql(u8, ends.?, r.last_digest.items)) { // 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. r.neutral += 1; return r.keepSince(u.tape); } if (r.applied > 0) { if (u.origin == r.id) r.stats.mispredicted += 1 else r.stats.foreign += 1; if (u.origin == r.id and std.c.getenv("PARDES_REPLICA_TRACE") != null) { trace(r.gpa, "replica {d}: its input {d} was recorded otherwise; it guessed:\n", .{ r.id, u.seq }, &.{r.pending.items[0].spec.?}); trace(r.gpa, "and the authority recorded:\n", .{}, &.{u.tape}); } r.recovering = nowNs(); r.toConfirmed(); if (r.diverged != null) return; } // What the unit opens or closes outside the copy (`keepSince` below). var serials: [pardes.MAX_PANES]u32 = undefined; var retiring = false; if (ahead) { const c = r.core(); for (c.panes, &serials) |slot, *n| n.* = if (slot) |pane| pane.serial else 0; for (c.retired_panes.current, c.retired_panes.previous) |x, y| retiring = retiring or x != null or y != null; } // Its digest compared when one is due (the units kept since and // replayed by a rollback were, if at all, as they came). const check = ends != null and r.checkDue(); r.t.checks = check; const outside = if (r.t.core) |c| c.outside.n else 0; const replayed = tape.replayUnit(&r.t, u.tape); r.t.checks = false; if (replayed) |why| { trace(r.gpa, "replica {d}: the unit of {d}/{d} diverged: {s}\n", .{ r.id, u.origin, u.seq, why }, &.{u.tape}); return r.fail(why); } // What it shows moved only when the unit's steps asked for a frame, // as the session's own frontend draws (Pardes.pump): a pump that // read its clock and stepped none, a 9P request that changed no // pane (the close after a ctl write: its frame was drawn again), // draw nothing. Read after the replay: before it, it is what the // units before asked (and a first unit has no core yet). if (r.core().needs_frame) r.moved = true; moved = r.core().outside.n != outside; if (check) { r.since_check = 0; r.stats.checks += 1; } if (u.origin == r.id) { if (r.pending.items.len == 0 or r.pending.items[0].seq != u.seq) return r.fail("the authority confirmed an input this replica did not send next"); if (r.blocked == u.seq) r.blocked = null; r.freePending(r.pending.orderedRemove(0)); } r.dirty = true; if (!ahead) return; // A pane opened, closed, or torn down (two syncs after it closed, // `reapPanes`): what it holds outside the copy (a terminal's // emulator, a picture's pixels, the store's record of it) was made // 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 question: a unit that wrote an emulator (a terminal's // output, a grid reflowed, one opened, closed or 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 or moved) { r.copy.release(); rollback.Epoch.select(null); return r.clearSince(); } r.keepSince(u.tape); } /// Its digest is due a comparison (`check_every`; every unit traced). fn checkDue(r: *const Replica) bool { return r.since_check >= check_every or std.c.getenv("PARDES_REPLICA_TRACE") != null; } fn fail(r: *Replica, why: []const u8) void { 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 (`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) 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 { for (r.since.items) |u| r.gpa.free(u); r.since.clearRetainingCapacity(); } /// Back to the confirmed position: the copy put back, the units fast- /// pathed since replayed. fn toConfirmed(r: *Replica) void { const held = r.copy.held; if (held) { const whole = r.copy.restore(); rollback.Epoch.select(null); if (!whole) return r.fail("out of memory for a rollback"); // The frame its host drew is of the memory put back: drawn again. r.moved = true; } r.applied = 0; for (r.since.items) |u| if (tape.replayUnit(&r.t, u)) |why| { trace(r.gpa, "replica {d}: a unit kept since the copy came to another state replayed again: {s}\n", .{ r.id, why }, &.{u}); return r.fail(why); }; r.clearSince(); for (r.pending.items) |*p| if (p.spec) |s| { r.gpa.free(s); p.spec = null; }; } /// The pending inputs applied again, as far as they go. pub fn settle(r: *Replica) void { if (!r.dirty or r.diverged != null) return; r.dirty = false; const was = Stepping.begin(&r.t, &r.epoch); defer was.end(); while (r.applied < r.pending.items.len and r.blocked != r.pending.items[r.applied].seq) if (!r.speculate()) break; if (r.recovering) |t0| { if (r.stats.samples) r.stats.rollback_ns.append(r.gpa, nowNs() - t0) catch {}; r.recovering = null; } } /// pending[applied] applied on top: whether it was. fn speculate(r: *Replica) bool { const p = &r.pending.items[r.applied]; // Every kind, a view's own (a resize, the pointer) too: each client // has its own view, and what reaches the authority's (a pty's size, // the pointer over a sliding pane) stops it as any host call does. const in = parseInput(p.msg) orelse return false; const c = r.core(); if (!r.copy.held) { const t0 = nowNs(); r.copy.take(&r.epoch, c) catch return false; r.keepSerials(); rollback.Epoch.select(&r.epoch); if (r.stats.samples) r.stats.copy_ns.append(r.gpa, nowNs() - t0) catch {}; r.stats.copy_bytes += r.copy.savedBytes(); r.stats.copies += 1; } var terminals: [pardes.MAX_PANES]u64 = undefined; if (checked) terminalDigests(c, &terminals); const t0 = nowNs(); tape.beginSpeculation(&r.t); // The time it was sent with, every time it is applied. r.t.guess = p.guess; const outside = c.outside.n; c.toView(.at(r.view)); // Input into a terminal: what reaches its program (a key in tty // mode, a paste, a mouse report) is a pty write, the authority's, // and stops here (core/echo.zig predicts its echo). The rest // (pardes's own keys over it, the wheel) reads its emulator, fed // the same bytes in the same order as the session's: it is applied. c.update(in.event); c.step(); // What it owes outside the copy (an emulator's grid: Term.resize // counts the write a speculation skips): replayed when confirmed. p.outside = c.outside.n -% outside; const clean = tape.endSpeculation(&r.t); const dt = nowNs() - t0; // Where a blob was written, should one be: the input that did. if (checked and std.c.getenv("PARDES_REPLICA_TRACE") != null) r.copy.check(); if (!clean) { // Undone, and the earlier ones applied again on the confirmed // position: this one waits for the authority. r.stats.stopped += 1; r.stats.stop(r.t.poisoned_by); if (std.c.getenv("PARDES_REPLICA_TRACE") != null) std.debug.print("replica {d}: its input {d} ({t}) stopped at a host call ({s}): it waits\n", .{ r.id, p.seq, in.event, r.t.poisoned_by }); r.blocked = p.seq; const upto = r.applied; r.toConfirmed(); while (r.applied < upto) if (!r.speculate()) break; if (r.applied == 0 and r.copy.held) { r.copy.release(); rollback.Epoch.select(null); } return false; } if (checked) { var after: [pardes.MAX_PANES]u64 = undefined; terminalDigests(c, &after); if (!std.mem.eql(u64, &terminals, &after)) { for (terminals, after, 0..) |x, y, id| if (x != y) std.debug.print("replica {d}: its input {d} ({any}) wrote terminal {d}\n", .{ r.id, p.seq, in.event, id }); @panic("replica: a speculation wrote a terminal's emulator"); } } r.stats.speculated += 1; if (r.stats.samples) r.stats.spec_ns.append(r.gpa, dt) catch {}; p.spec = r.gpa.dupe(u8, r.t.buf.items) catch return false; r.t.buf.clearRetainingCapacity(); r.applied += 1; return true; } /// Its client's, once a frame before it draws: a predicted echo the /// screen has not shown in time goes, and keys deferred behind one not /// predicted are predicted once its doing is on the screen. Whether what /// the overlay draws changed since the last call (by a key, a unit, a /// delta or this: `echo.changed`). pub fn echoFrame(r: *Replica) bool { return r.echo.frame(r.core()); } /// Nothing pending and nothing applied: the replica is the authority's /// confirmed state, which `digest` says (a copy taken ahead, `ready`, /// has nothing on top of it). pub fn quiet(r: *const Replica) bool { return r.pending.items.len == 0 and r.applied == 0; } /// The copy taken now, while nothing is pending (the host is idle, its /// frame drawn), so that the next input of its own is applied at once /// without taking it: a copy is a megabyte saved. Let go when a unit /// comes first. pub fn ready(r: *Replica) void { if (r.copy.held or r.pending.items.len > 0 or r.diverged != null) return; const c = r.core(); const t0 = nowNs(); rollback.Epoch.select(&r.epoch); defer rollback.Epoch.select(null); r.copy.take(&r.epoch, c) catch return; r.keepSerials(); if (r.stats.samples) r.stats.copy_ns.append(r.gpa, nowNs() - t0) catch {}; r.stats.copy_bytes += r.copy.savedBytes(); r.stats.copies += 1; } fn keepSerials(r: *Replica) void { const c = r.core(); for (c.panes, &r.serials) |slot, *n| n.* = if (slot) |pane| pane.serial else 0; r.retiring = for (c.retired_panes.current, c.retired_panes.previous) |x, y| { if (x != null or y != null) break true; } else false; } /// Whether a pane opened, closed or is torn down since the copy was /// taken (`keepSerials`). fn panesMoved(r: *const Replica) bool { const c = r.core(); if (r.retiring) return true; for (c.retired_panes.current, c.retired_panes.previous) |x, y| if (x != null or y != null) return true; for (c.panes, r.serials) |slot, n| if ((if (slot) |pane| pane.serial else 0) != n) return true; return false; } /// Whether its core loaded from the dump is the session as it was /// dumped, by the welcome's `digest`. pub fn loaded(r: *Replica, want: u64) bool { return r.digest() == want; } /// Its own view drawn and presented through `present`, between steps /// (views.drawOne): nothing the digest covers moves. The epoch's trees /// held while a copy is (a render can make or drop a syntax tree). pub fn draw(r: *Replica, present: pardes.views.Present) bool { rollback.Epoch.select(&r.epoch); defer rollback.Epoch.select(null); // A client's replica (`skips_render`) is never watched in its // replay, which so never clears `needs_frame`: the frame its steps // asked for is this one. One in process replays its session's own // drawing (Pardes.pump), which reads and clears it as the session's. const c = r.core(); const needs = c.needs_frame and !r.t.skips_render; defer c.needs_frame = needs; return pardes.views.drawOne(c, r.view, present) catch true; } /// A piece of a record's bytes by hash (Peer.blob): whole and checked /// against its hash, kept for the unit that names it (tape.keepFile), /// and a file's, a far client's, on disk (`cache`) for its next join. pub fn blobPiece(r: *Replica, msg: []const u8) void { if (msg.len < 49) return r.fail("a short piece of a record by hash"); const total = std.math.cast(usize, std.mem.readInt(u64, msg[32..40], .little)) orelse return r.fail("a record by hash too long"); const at = std.mem.readInt(u64, msg[40..48], .little); if (at == 0) { if (r.incoming) |b| r.gpa.free(b.bytes); r.incoming = .{ .hash = msg[0..32].*, .bytes = r.gpa.alloc(u8, total) catch return r.fail("out of memory for a record by hash"), .path = msg[48] != 0 }; r.incoming_got = 0; } const b = r.incoming orelse return r.fail("a piece of a record by hash out of order"); const piece = msg[49..]; if (at != r.incoming_got or b.bytes.len != total or piece.len > total - at) return r.fail("a piece of a record by hash out of order"); @memcpy(b.bytes[at..][0..piece.len], piece); r.incoming_got += piece.len; if (r.incoming_got < total) return; r.incoming = null; if ((b.path and b.bytes.len < 9) or !std.mem.eql(u8, &tape.Big.hashOf(b.bytes, b.path), &b.hash)) { r.gpa.free(b.bytes); return r.fail("a record by hash came other than its hash"); } if (b.path) if (r.cache) |c| if (b.bytes.len - 9 <= c.cap) c.put(r.io, &.{.{ .hash = b.hash, .bytes = b.bytes[9..] }}, &.{}); tape.keepFile(&r.t, b); } pub fn digest(r: *Replica) u64 { const was = Stepping.begin(&r.t, &r.epoch); defer was.end(); return tape.digestOf(r.core()); } }; /// The bytes of a unit's last digest record: the state it ended on; null /// for one that says what the host wrote or which host it is (a replica's /// core takes those only by replaying the unit). fn lastDigest(bytes: []const u8) ?[]const u8 { var r: walk.Reader = .{ .bytes = bytes }; var last: ?[]const u8 = null; while (true) { const head = r.take(5) catch return last; const payload = r.take(std.mem.bytesToValue(u32, head[1..5])) catch return last; if (head[0] == tape.digest_kind) last = payload; if (head[0] == tape.set_kind) return null; } } fn terminalDigests(p: *const Pardes, out: *[pardes.MAX_PANES]u64) void { for (p.panes, out) |slot, *d| { d.* = 0; const pane = slot orelse continue; const state = pane.terminal orelse continue; var h = walk.Hasher.init(0); state.digest(&h); d.* = h.final(); } } // ---- over a socket (docs/next-daemon.md, "Phase 5 part B notes") ---- // // The session's half: each client handed over by the daemon (daemon.zig) is // a Peer, with a view of its own, a thread reading its inputs and one // writing what it is sent. The recorder is on while any is. At each step // boundary of the session's loop (`Peers.boundary`, after a pump): // - the pump's unit goes to every client; // - a client that came is joined: its view opened, the session dumped // (core/dump.zig) and sent ahead of every unit after; // - each input that came is a unit of its own: its view, the input, a // `step` (what the client's own core applied at once); // - a client gone takes its view with it. // A client's link only ever holds bytes queued for it: the session's step // never waits on one. One that lets `lag_max` pile up is cut off. const libc = std.c; const log = std.log.scoped(.replica); /// What a client may leave unread, past its join's dump, before it is cut /// off: minutes of typing, a screenful of a flood's deltas many times over. const lag_max: usize = 64 << 20; const dump_piece = 1 << 20; /// A blob in a far join's list (wire.zig `blobs`): its place in the state /// (u64le), its length (u64le) and its BLAKE3 hash. const blob_entry = 48; const Tm = extern struct { sec: c_int, min: c_int, hour: c_int, mday: c_int, mon: c_int, year: c_int, wday: c_int, yday: c_int, isdst: c_int, gmtoff: c_long, zone: ?[*:0]const u8 }; extern "c" fn localtime_r(t: *const libc.time_t, tm: *Tm) ?*Tm; /// This zone's offset from UTC now, seconds. fn gmtoff() i32 { var ts: libc.timespec = undefined; _ = libc.clock_gettime(.REALTIME, &ts); const secs: libc.time_t = ts.sec; var tm: Tm = undefined; return if (localtime_r(&secs, &tm) != null) @intCast(tm.gmtoff) else 0; } /// `bytes` as dump pieces (1 MiB at most each). fn writePieces(fd: c_int, bytes: []const u8) bool { var at: usize = 0; while (at < bytes.len) : (at += dump_piece) { const piece = bytes[at..@min(bytes.len, at + dump_piece)]; const head = wire.header(@backingInt(wire.ServerTag.dump), piece.len); if (!writeAll(fd, &head) or !writeAll(fd, piece)) return false; } return true; } // ---- zstd (libzstd, vendored: build.zig) ---- /// A far client's stream from its welcome on (`Peer.farJoin`): its join in /// one frame at level 6 over an 8 MiB window, since an undo snapshot is a /// near copy of its file's text, a file's length before or after it (the /// join's numbers: Phase 6's content cache and zstd notes); what follows in /// a frame at level 3 over 1 MiB. Each envelope (wire.zig `zstd`) is a /// flush of at most `piece` of input, so that a reader unpacks one whole. const zstd = struct { const CCtx = opaque {}; const DCtx = opaque {}; const In = extern struct { src: ?*const anyopaque, size: usize, pos: usize }; const Out = extern struct { dst: ?*anyopaque, size: usize, pos: usize }; const Mem = extern struct { alloc: *const fn (?*anyopaque, usize) callconv(.c) ?*anyopaque, free: *const fn (?*anyopaque, ?*anyopaque) callconv(.c) void, ctx: ?*anyopaque = null, }; extern fn ZSTD_createCCtx_advanced(mem: Mem) ?*CCtx; extern fn ZSTD_freeCCtx(c: ?*CCtx) usize; extern fn ZSTD_CCtx_setParameter(c: *CCtx, param: c_int, value: c_int) usize; extern fn ZSTD_compressStream2(c: *CCtx, out: *Out, in: *In, op: c_int) usize; extern fn ZSTD_createDCtx_advanced(mem: Mem) ?*DCtx; extern fn ZSTD_freeDCtx(d: ?*DCtx) usize; extern fn ZSTD_decompressStream(d: *DCtx, out: *Out, in: *In) usize; extern fn ZSTD_isError(code: usize) c_uint; const level_param = 100; const window_param = 101; const Op = enum(c_int) { more = 0, flush = 1, end = 2 }; const piece = 1 << 20; /// What zstd allocates is a Zig allocator's (c_heap): a test's own. var gpa: Allocator = std.heap.c_allocator; const heap = c_heap.Heap(&gpa); fn alloc(_: ?*anyopaque, n: usize) callconv(.c) ?*anyopaque { return heap.malloc(n); } fn free(_: ?*anyopaque, p: ?*anyopaque) callconv(.c) void { heap.free(p); } const mem: Mem = .{ .alloc = alloc, .free = free }; fn compressor(level: c_int, window_log: c_int) ?*CCtx { const c = ZSTD_createCCtx_advanced(mem) orelse return null; if (ZSTD_isError(ZSTD_CCtx_setParameter(c, level_param, level)) != 0 or ZSTD_isError(ZSTD_CCtx_setParameter(c, window_param, window_log)) != 0) { _ = ZSTD_freeCCtx(c); return null; } return c; } }; fn readSome(fd: c_int, buf: []u8) usize { while (true) { const n = libc.read(fd, buf.ptr, buf.len); if (n < 0 and libc.errno(n) == .INTR) continue; return if (n <= 0) 0 else @intCast(n); } } /// What a stream's reader holds of it, read and not yet taken: a dump's /// reader leaves the units read with its last piece to the stream's. pub const Framer = struct { buf: std.ArrayListUnmanaged(u8) = .empty, len: usize = 0, /// What zstd envelopes (wire.zig `zstd`) unpacked to, its messages not /// taken yet, and the stream's decompressor: a far client's. inner: std.ArrayListUnmanaged(u8) = .empty, z: ?*zstd.DCtx = null, bad: bool = false, pub fn deinit(f: *Framer, gpa: Allocator) void { f.buf.deinit(gpa); f.inner.deinit(gpa); if (f.z) |z| _ = zstd.ZSTD_freeDCtx(z); f.z = null; } /// The length a message past the wire's bound said it had, when that /// is where `run` stopped: an error to name, never a hangup (17.3). pub fn overlong(fr: *const Framer) ?u32 { for ([_][]const u8{ fr.buf.items[0..fr.len], fr.inner.items }) |b| if (wire.framed(b)) |_| {} else |_| return std.mem.readInt(u32, b[1..5], .little); return null; } /// Framed messages off `fd` (wire.zig) handed to `take` until /// the stream ends, `take` says stop, or a message is malformed. An /// envelope's are handed on as if they had come bare. fn run(fr: *Framer, gpa: Allocator, fd: c_int, ctx: anytype, comptime take: fn (@TypeOf(ctx), u8, []const u8) bool) void { if (fr.bad or !fr.drain(ctx, take)) return; while (true) { var at: usize = 0; var stop = false; while (!stop) { const f = (wire.framed(fr.buf.items[at..fr.len]) catch break) orelse break; at += f.total; if (f.tag == @backingInt(wire.ServerTag.zstd)) { fr.bad = !fr.unpack(gpa, f.payload); stop = fr.bad or !fr.drain(ctx, take); } else stop = !take(ctx, f.tag, f.payload); } if (at > 0) { std.mem.copyForwards(u8, fr.buf.items[0 .. fr.len - at], fr.buf.items[at..fr.len]); fr.len -= at; } if (stop) return; if (wire.framed(fr.buf.items[0..fr.len])) |_| {} else |_| return; // Room for what the head says is coming, or 64 KiB more. const want = if (fr.len >= wire.header_len) wire.header_len + @as(usize, std.mem.readInt(u32, fr.buf.items[1..5], .little)) else 0; const room = @max(want, fr.len + (64 << 10)); if (fr.buf.items.len < room) fr.buf.resize(gpa, room) catch return; const n = readSome(fd, fr.buf.items[fr.len..]); if (n == 0) return; fr.len += n; } } /// A join's welcome a link's reader stopped at (`readLink`), first again /// for the join's reader, what was read past it after it; the stream it /// ends lets its decompressor go (the join's is a frame of its own). fn putBack(fr: *Framer, gpa: Allocator, msg: []const u8) bool { if (fr.buf.items.len < fr.len + msg.len) fr.buf.resize(gpa, fr.len + msg.len) catch return false; std.mem.copyBackwards(u8, fr.buf.items[msg.len..][0..fr.len], fr.buf.items[0..fr.len]); @memcpy(fr.buf.items[0..msg.len], msg); fr.len += msg.len; fr.inner.clearRetainingCapacity(); if (fr.z) |z| _ = zstd.ZSTD_freeDCtx(z); fr.z = null; return true; } /// An envelope's bytes onto `inner`. Its writer flushed at most /// `zstd.piece` of input into it, so it unpacks to no more than that. fn unpack(fr: *Framer, gpa: Allocator, payload: []const u8) bool { if (fr.z == null) fr.z = zstd.ZSTD_createDCtx_advanced(zstd.mem); const z = fr.z orelse return false; var in: zstd.In = .{ .src = payload.ptr, .size = payload.len, .pos = 0 }; while (true) { fr.inner.ensureUnusedCapacity(gpa, 256 << 10) catch return false; const spare = fr.inner.unusedCapacitySlice(); var out: zstd.Out = .{ .dst = spare.ptr, .size = spare.len, .pos = 0 }; if (zstd.ZSTD_isError(zstd.ZSTD_decompressStream(z, &out, &in)) != 0) return false; fr.inner.items.len += out.pos; if (in.pos == in.size and out.pos < out.size) return true; } } /// The whole messages in `inner` handed to `take`; false when it says /// stop (what is left waits for the next run) or one is malformed. fn drain(fr: *Framer, ctx: anytype, comptime take: fn (@TypeOf(ctx), u8, []const u8) bool) bool { var at: usize = 0; var stop = false; while (!stop) { const f = (wire.framed(fr.inner.items[at..]) catch { fr.bad = true; return false; }) orelse break; at += f.total; stop = !take(ctx, f.tag, f.payload); } if (at > 0) { const rest = fr.inner.items.len - at; std.mem.copyForwards(u8, fr.inner.items[0..rest], fr.inner.items[at..]); fr.inner.items.len = rest; } return !stop; } }; pub const Peer = struct { peers: *Peers, fd: c_int, id: u16, view: Pardes.View.Id, /// Its process (its socket's peer), for `--ps`; 0 not known. pid: libc.pid_t = 0, /// Its bye said it joins again for its view: its hello comes next on /// this link (`Peers.joinAgain`), or the link's end (a client of another /// build gone to exec this one's: `sameBuild`), its view kept for it then /// (views.away), not closed. Its reader's, read after its end. again: bool = false, /// ...or that its window was closed (Peers.closed). close: bool = false, /// It said a bye: none, and the session let it go with no word of its /// own (`closing`, `cut`), is a client that died (killed: P48). bye: bool = false, /// A pair's first client (`Joining.own`): the terminal its session /// keeps is its (`Peers.pair_left`). pair: bool = false, /// Inputs read (each one's seq, as the client numbered them). seq: u32 = 0, /// The `stamp` frame its next input came with (its reader's). stamp: [stamp_len]u8 = undefined, stamped: bool = false, reader: ?std.Thread = null, writer: ?std.Thread = null, lock: std.Io.Mutex = .init, cond: std.Io.Condition = .init, /// What it is sent, not written yet, and what the writer writes now. out: std.ArrayListUnmanaged(u8) = .empty, sending: std.ArrayListUnmanaged(u8) = .empty, /// What may wait in `out` before it is cut off (a test's less). limit: usize = lag_max, closing: bool = false, /// Cut off (`send`): the words why, then nothing until its client's /// hello again on this link (`Peers.joinAgain`); its view is kept for it /// (views.away) if the link ends first, as for a bye's `again`. cut: bool = false, /// Its joins on this link the session has dumped (`Peers.join`, /// `Peers.joinAgain`), and how many its writer has written whole: one not /// written is the writer's next (`writeLoop`). Under `lock`. gen: u32 = 1, written: u32 = 0, /// Its client's join again for its view, come before this link's end /// was heard: judged once it is let go (`Peers.join`, `letGo`). rejoin: ?Peers.Joining = null, /// Its writer has ended (what it was sent, written). done: std.atomic.Value(bool) = .init(false), /// Its join, which its writer writes before what it is sent: the /// welcome, then the dump with the session's blobs put back where they /// go, pinned until written (memory.zig `pin`). The core's allocator's. welcome: [wire.hello_max + 64]u8 = undefined, welcome_len: usize = 0, dump: []u8 = &.{}, blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty, dump_gpa: Allocator = undefined, /// Its first word after its hello: whether it is far (through ssh), its /// blobs asked for by hash and its stream in zstd (`farJoin`). far: ?bool = null, /// A pair's client's word before that: the digest of the core it made /// itself (`boot`); the session's at the join (`digest`) the same, its /// dump is not sent. boot: ?u64 = null, digest: u64 = 0, /// A far client's answer to its join's list: the blobs it lacks. want: ?[]u8 = null, /// A far client's stream's compressor, and an envelope's worth of its /// output; the input since the last envelope. z: ?*zstd.CCtx = null, zout: std.ArrayListUnmanaged(u8) = .empty, zin: usize = 0, fn writeJoin(peer: *Peer) bool { // Again over this link: the old stream's frame ended and its // compressor let go; the join's is a frame of its own. if (peer.z) |z| { if (!peer.zWrite(&.{}, .end)) return false; _ = zstd.ZSTD_freeCCtx(z); peer.z = null; peer.zout.clearRetainingCapacity(); peer.zin = 0; } if (!writeAll(peer.fd, peer.welcome[0..peer.welcome_len])) return false; const io = peer.peers.io; peer.lock.lockUncancelable(io); while (peer.far == null and !peer.closing) peer.cond.waitUncancelable(io, &peer.lock); const far = peer.far; // A pair's word on its first join alone. const boot = peer.boot; peer.boot = null; peer.lock.unlock(io); if (far orelse return false) { if (!peer.farJoin()) return false; } else if (boot != peer.digest) { // (Its client made this core itself, a pair's: nothing to send.) var pos: usize = 0; for (peer.blobs.items) |b| { if (!writePieces(peer.fd, peer.dump[pos..b.at]) or !writePieces(peer.fd, b.bytes)) return false; pos = b.at; } if (!writePieces(peer.fd, peer.dump[pos..])) return false; } return true; } /// A far client's join, in one zstd frame: the list of the dump's blobs /// (each one's place in the state, its length and its BLAKE3 hash), the /// state, then the blobs it says it lacks; what follows the join goes /// in a cheaper frame. The hashing is this thread's, never the step's. /// ponytail: a blob is hashed again at every far join, 3.6 GB/s; a /// session's join after its first could keep them. fn farJoin(peer: *Peer) bool { const gpa = peer.peers.gpa; peer.z = zstd.compressor(6, 23) orelse return false; var list: std.ArrayListUnmanaged(u8) = .empty; defer list.deinit(gpa); for (peer.blobs.items) |b| { // Gone meanwhile: its leave waits for this thread in the // session's step, so the hashing stops here. if (peer.letting()) return false; var entry: [blob_entry]u8 = undefined; std.mem.writeInt(u64, entry[0..8], b.at, .little); std.mem.writeInt(u64, entry[8..16], b.bytes.len, .little); std.crypto.hash.Blake3.hash(b.bytes, entry[16..48], .{}); list.appendSlice(gpa, &entry) catch return false; if (list.items.len + blob_entry > dump_piece) { if (!peer.zMessage(.blobs, list.items)) return false; list.clearRetainingCapacity(); } } if (list.items.len > 0 and !peer.zMessage(.blobs, list.items)) return false; if (!peer.zPieces(peer.dump) or !peer.zWrite(&.{}, .flush)) return false; if (peer.blobs.items.len > 0) { const io = peer.peers.io; peer.lock.lockUncancelable(io); while (peer.want == null and !peer.closing) peer.cond.waitUncancelable(io, &peer.lock); const want = peer.want; peer.lock.unlock(io); const bits = want orelse return false; if (bits.len != (peer.blobs.items.len + 7) / 8) return false; for (peer.blobs.items, 0..) |b, i| if (bits[i / 8] >> @intCast(i % 8) & 1 != 0) { if (!peer.zPieces(b.bytes)) return false; }; // This join's answer, used: a join again over this link asks its own. peer.lock.lockUncancelable(io); peer.want = null; peer.lock.unlock(io); peer.peers.gpa.free(bits); } if (!peer.zWrite(&.{}, .end)) return false; _ = zstd.ZSTD_freeCCtx(peer.z); peer.z = zstd.compressor(3, 20); return peer.z != null; } /// Whether it is being let go. One cut off is still sent its join /// whole, then the words why (`send`): it joins again after them. fn letting(peer: *Peer) bool { const io = peer.peers.io; peer.lock.lockUncancelable(io); defer peer.lock.unlock(io); return peer.closing; } /// One message into its stream's compressor. fn zMessage(peer: *Peer, tag: wire.ServerTag, payload: []const u8) bool { const head = wire.header(@backingInt(tag), payload.len); return peer.zWrite(&head, .more) and peer.zWrite(payload, .more); } /// `bytes` as dump pieces (1 MiB at most each), into the compressor. fn zPieces(peer: *Peer, bytes: []const u8) bool { var at: usize = 0; while (at < bytes.len) : (at += dump_piece) { if (!peer.zMessage(.dump, bytes[at..@min(bytes.len, at + dump_piece)])) return false; } return true; } /// `bytes` into its stream's compressor, and what comes out written as /// envelopes: one at each `zstd.piece` of input, and one now if `op` /// says flush or end (the frame's). fn zWrite(peer: *Peer, bytes: []const u8, op: zstd.Op) bool { const z = peer.z orelse return false; var rest = bytes; while (true) { const n = @min(rest.len, zstd.piece - peer.zin); const full = peer.zin + n == zstd.piece; const now: zstd.Op = if (n < rest.len or (full and op == .more)) .flush else op; var in: zstd.In = .{ .src = rest.ptr, .size = n, .pos = 0 }; while (true) { peer.zout.ensureUnusedCapacity(peer.peers.gpa, 128 << 10) catch return false; const spare = peer.zout.unusedCapacitySlice(); var out: zstd.Out = .{ .dst = spare.ptr, .size = spare.len, .pos = 0 }; const left = zstd.ZSTD_compressStream2(z, &out, &in, @backingInt(now)); if (zstd.ZSTD_isError(left) != 0) return false; peer.zout.items.len += out.pos; if (if (now == .more) in.pos == in.size else left == 0) break; } peer.zin += n; if (now != .more) { const head = wire.header(@backingInt(wire.ServerTag.zstd), peer.zout.items.len); if (!writeAll(peer.fd, &head) or !writeAll(peer.fd, peer.zout.items)) return false; peer.zout.clearRetainingCapacity(); peer.zin = 0; } rest = rest[n..]; if (rest.len == 0) return true; } } /// `parts` queued for it, in order; never waits. A client whose queue /// passes its limit is cut off: what waits for it is let go and the /// words why queued in its place, and nothing after them: it says its /// goodbye and its hello again on this link and is dumped there, for /// its view (`Peers.joinAgain`). fn send(peer: *Peer, parts: []const []const u8) void { const io = peer.peers.io; peer.lock.lockUncancelable(io); defer peer.lock.unlock(io); if (peer.cut or peer.closing) return; // The wire's bound, as the message goes (17.3): one past it would // be the link's end at the reader. const len = std.mem.readInt(u32, parts[0][1..5], .little); if (len > wire.max_payload) { log.err("a {d} MB message to client {d}, over the {d} MiB bound: dropped", .{ len >> 20, peer.id, wire.max_payload >> 20 }); if (checked) std.debug.panic("a {d}-byte message to client {d}, over the wire's bound", .{ len, peer.id }); return; } var n: usize = peer.out.items.len; for (parts) |p| n += p.len; if (n > peer.limit) { log.info("client {d} is {d} MB behind: cut off", .{ peer.id, n >> 20 }); peer.peers.cut += 1; peer.cut = true; peer.out.clearRetainingCapacity(); var words: [48]u8 = undefined; var msg: [64]u8 = undefined; const word = wire.encodeServer(&msg, .{ .refused = std.fmt.bufPrint(&words, "{d} MB behind the session", .{n >> 20}) catch unreachable }) catch unreachable; peer.out.appendSlice(peer.peers.gpa, word) catch { _ = libc.shutdown(peer.fd, 2); }; peer.cond.signal(io); return; } for (parts) |p| peer.out.appendSlice(peer.peers.gpa, p) catch { peer.cut = true; _ = libc.shutdown(peer.fd, 2); break; }; peer.cond.signal(io); } /// A record's bytes by hash (tape.Big) queued for it in pieces, before /// the unit that names them: for a far client, and for one on this /// machine unless they are a file it reads itself (tape.zig `byHash`). /// Never cut off for them: a big file is no lag. fn blob(peer: *Peer, b: tape.Big) void { const io = peer.peers.io; peer.lock.lockUncancelable(io); defer peer.lock.unlock(io); if (peer.cut or peer.closing or (b.path and peer.far == false)) return; var at: usize = 0; while (at < b.bytes.len) : (at += dump_piece) { const piece = b.bytes[at..@min(b.bytes.len, at + dump_piece)]; var meta: [49]u8 = undefined; meta[0..32].* = b.hash; std.mem.writeInt(u64, meta[32..40], b.bytes.len, .little); std.mem.writeInt(u64, meta[40..48], at, .little); meta[48] = @intFromBool(b.path); const head = wire.header(@backingInt(wire.ServerTag.blob), meta.len + piece.len); for ([_][]const u8{ &head, &meta, piece }) |part| peer.out.appendSlice(peer.peers.gpa, part) catch { peer.cut = true; _ = libc.shutdown(peer.fd, 2); return; }; } peer.cond.signal(io); } /// Its last message: queued, and its writer ends once it is written. fn last(peer: *Peer, words: []const u8) void { const io = peer.peers.io; peer.send(&.{words}); peer.lock.lockUncancelable(io); peer.closing = true; peer.cond.signal(io); peer.lock.unlock(io); } /// Its join, then what it is sent; a join again over this link /// (`Peers.joinAgain`) next whenever one is dumped, what was queued before /// it let go. Ends once it is let go and has written what it holds. fn writeLoop(peer: *Peer) void { const io = peer.peers.io; defer peer.done.store(true, .release); while (true) { peer.lock.lockUncancelable(io); while (peer.out.items.len == 0 and !peer.closing and peer.written == peer.gen) peer.cond.waitUncancelable(io, &peer.lock); const gen = peer.gen; const joining = peer.written != gen; if (!joining and peer.out.items.len == 0) { peer.lock.unlock(io); return; } if (!joining) std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &peer.sending); peer.lock.unlock(io); const ok = if (joining) peer.writeJoin() else peer.writeOut(); if (!ok) { _ = libc.shutdown(peer.fd, 2); return; } if (!joining) continue; peer.lock.lockUncancelable(io); peer.written = gen; peer.lock.unlock(io); // Its pins let go at the next boundary. peer.peers.post(.{ .joined = .{ .peer = peer, .gen = gen } }); } } /// What it was sent (`sending`), a MiB at most a write and at a /// message's end: a join due again over this link waits for no more of /// the stream it leaves than that, the rest let go. fn writeOut(peer: *Peer) bool { defer peer.sending.clearRetainingCapacity(); const all = peer.sending.items; var at: usize = 0; while (at < all.len) { var end = at; while (wire.framed(all[end..]) catch null) |f| { if (end > at and end + f.total - at > dump_piece) break; end += f.total; } if (end == at) end = all.len; if (!(if (peer.z != null) peer.zWrite(all[at..end], .flush) else writeAll(peer.fd, all[at..end]))) return false; at = end; if (at < all.len and peer.joinDue()) return true; } return true; } fn joinDue(peer: *Peer) bool { const io = peer.peers.io; peer.lock.lockUncancelable(io); defer peer.lock.unlock(io); return peer.written != peer.gen; } pub fn take(peer: *Peer, tag: u8, payload: []const u8) bool { const t = std.enums.fromInt(wire.ClientTag, tag) orelse return false; switch (t) { // Its hello again on this link, its goodbye saying it joins // again just before (runtime/client.zig `run`): the session's // state dumped for it here (`Peers.joinAgain`), its inputs numbered // afresh. A hello anywhere else ends the link. .hello => { if (!peer.bye or !peer.again) return false; _ = wire.decodeClient(tag, payload) catch return false; peer.again = false; peer.close = false; peer.bye = false; peer.seq = 0; peer.stamped = false; peer.peers.post(.{ .again = peer }); return true; }, // Read on after one that says it joins again: its hello. .bye => { const b = (wire.decodeClient(tag, payload) catch return false).bye; peer.again = b.again; peer.close = b.close; peer.bye = true; return b.again; }, .ping => { var out: [16]u8 = undefined; const v = (wire.decodeClient(tag, payload) catch return false).ping; const pong = wire.encodeServer(&out, .{ .pong = v }) catch return false; peer.send(&.{pong}); return true; }, .check => { peer.peers.post(.{ .check = peer }); return true; }, // What its join's writer waits for (`writeJoin`, `farJoin`); a // pair's boot comes before its far. .far, .want, .boot => { const io = peer.peers.io; const msg = wire.decodeClient(tag, payload) catch return false; const bits = if (msg == .want) peer.peers.gpa.dupe(u8, msg.want) catch return false else null; peer.lock.lockUncancelable(io); defer peer.lock.unlock(io); if (bits) |b| { if (peer.want != null) { peer.peers.gpa.free(b); return false; } peer.want = b; } else if (msg == .boot) { peer.boot = msg.boot; } else peer.far = msg.far; peer.cond.signal(io); return true; }, // Its next input's time, kept for it (this thread's alone). .stamp => { const s = (wire.decodeClient(tag, payload) catch return false).stamp; _ = wire.encodeClient(&peer.stamp, .{ .stamp = s }) catch return false; peer.stamped = true; return true; }, else => {}, } peer.seq += 1; const stamp: []const u8 = if (peer.stamped) &peer.stamp else &.{}; peer.stamped = false; const msg = peer.peers.gpa.alloc(u8, head_len + stamp.len + wire.header_len + payload.len) catch return false; header(msg, peer.id, peer.seq); @memcpy(msg[head_len..][0..stamp.len], stamp); const at = head_len + stamp.len; msg[at] = tag; std.mem.writeInt(u32, msg[at + 1 ..][0..4], @intCast(payload.len), .little); @memcpy(msg[at + wire.header_len ..], payload); if (parseInput(msg) == null) { peer.peers.gpa.free(msg); return false; } peer.peers.post(.{ .input = .{ .peer = peer, .msg = msg } }); return true; } fn readLoop(peer: *Peer) void { // The framer goes before `gone`, after which the peer may be freed. var fr: Framer = .{}; fr.run(peer.peers.gpa, peer.fd, peer, take); if (fr.overlong()) |n| log.err("client {d} sent a {d} MB message, over the {d} MiB bound: let go", .{ peer.id, n >> 20, wire.max_payload >> 20 }); fr.deinit(peer.peers.gpa); peer.peers.post(.{ .gone = peer }); } }; /// The session's clients, for `dying`. var live_peers: ?*Peers = null; /// The process is panicking: each client's link shut first, so that it /// hears the end now, not when the trace is written (seconds, symbolized). pub fn dying() void { const ps = live_peers orelse return; for (ps.list) |slot| if (slot) |peer| { _ = libc.shutdown(peer.fd, 2); }; } /// Whether the other end of socket `fd` has hung up (shut, or closed). fn hungUp(fd: c_int) bool { const rdhup = if (@hasDecl(libc.POLL, "RDHUP")) libc.POLL.RDHUP else 0; var p = [1]libc.pollfd{.{ .fd = fd, .events = libc.POLL.IN | rdhup, .revents = 0 }}; return libc.poll(&p, 1, 0) == 1 and p[0].revents & (libc.POLL.HUP | rdhup) != 0; } /// The process at the other end of unix socket `fd` (Linux's SO_PEERCRED), /// or 0: a client's through ssh is ssh's. fn peerPid(fd: c_int) libc.pid_t { if (comptime builtin.os.tag != .linux) return 0; const Cred = extern struct { pid: libc.pid_t, uid: libc.uid_t, gid: libc.gid_t }; var cred: Cred = undefined; var len: libc.socklen_t = @sizeOf(Cred); if (libc.getsockopt(fd, libc.SOL.SOCKET, libc.SO.PEERCRED, &cred, &len) != 0) return 0; return cred.pid; } pub const Peers = struct { gpa: Allocator = std.heap.c_allocator, io: std.Io = undefined, /// This session's name and pid, for a welcome. name: []const u8 = "", t: tape.Tape = undefined, recording: bool = false, list: [pardes.views.max]?*Peer = @splat(null), next_id: u16 = 1, seq: u32 = 0, lock: std.Io.Mutex = .init, inbox: std.ArrayListUnmanaged(Note) = .empty, /// The batch `boundary` takes, and the note it is at: a client let go /// there (`letGo`) takes its notes after that one out too. taken: std.ArrayListUnmanaged(Note) = .empty, taking: usize = 0, /// A reader posted: the loop's one test a step while nothing is attached. mail: std.atomic.Value(bool) = .init(false), /// ...and what it posted was a client's input or a join, which the /// session steps at once; a terminal's acknowledgement waits for the /// session's next frame, as its output does (tui.zig `waitInput`). urgent: std.atomic.Value(bool) = .init(false), /// Wakes the session's loop (its wait for input) from a reader. wake_ctx: ?*anyopaque = null, wake: ?*const fn (?*anyopaque) void = null, /// No frontend of its own (the host says): with no client either, the /// session is unattended. detached: bool = false, /// A Restore let every client go (`restoring`): the restored core's one /// view (views.only) is the first to join again's. restored: bool = false, /// Its last client left with a close (its window closed, its terminal /// hung up) and the session is a pair's not kept (daemon.sessionState): it /// ends there (runtime/session.zig). closed: bool = false, /// Its pair's first client left (P48): with no word at all (killed), /// true; its session's frontend puts the user's terminal back then, /// and lets it go either way (tui.zig `Own.sent`), and clears this. pair_left: ?bool = null, /// Its pair's first client's terminal or window found again (a focus /// in): the session asks whether a newer build is installed, as its own /// frontend asks at its own (runtime/session.zig), and clears this. pair_focused: bool = false, /// An Upgrade told its clients so (`refuseAll`): a connection handed /// over before its exec is told the same, never closed by the exec /// unanswered. Its exec failed: the next boundary takes joins again. upgrading: std.atomic.Value(bool) = .init(false), /// The worst a join cost the session's step, and the last one's dump. join_ns: u64 = 0, each_join: std.ArrayListUnmanaged(u64) = .empty, dump_bytes: usize = 0, /// ...of it the state the step dumped (the rest, blobs, the writer's). state_bytes: usize = 0, /// What each client input cost the session (its step, its unit sent), /// and each boundary (its pump's unit sent, what came taken in), ns: /// PARDES_REPLICA_STATS writes them at the session's end, and only then /// are these and `each_join` kept (`samples`): a session runs for days. samples: bool = false, input_ns: std.ArrayListUnmanaged(u64) = .empty, boundary_ns: std.ArrayListUnmanaged(u64) = .empty, cut: u32 = 0, /// Joins again over a client's own link (`joinAgain`): no dial, no daemon. again_here: u32 = 0, head: [unit_head]u8 = undefined, /// False: its clients' links are in this process's memory, a thread /// for none of them (the soak's, test/replicas.zig): what a client's /// writer would write (its join, then `out`) and its reader read /// (`Peer.take`, then `.gone` posted) are its driver's to do. threads: bool = true, pub const Note = union(enum) { join: Joining, input: Msg, gone: *Peer, check: *Peer, joined: Written, again: *Peer }; /// A join its writer wrote whole: the `gen`-th on its link (`Peer.gen`). pub const Written = struct { peer: *Peer, gen: u32 }; /// A connection to join, and the view it joins again for, if it does. pub const Joining = daemon.Joining; pub const Msg = struct { peer: *Peer, msg: []u8 }; pub fn count(ps: *const Peers) usize { var n: usize = 0; for (ps.list) |slot| n += @intFromBool(slot != null); return n; } /// The time the session's pump reads after its wait, when that wait /// took a client's post and nothing else (`only_mail`, the shell's word /// for its wait): the core's clock as it stands, so the pump's unit /// moves nothing a client's speculation stands on; null otherwise (the /// shell's clock). Held only while a post waits (`mail`): a wait that /// ran out took none, and the pump after it is the one its deadline /// asked for (a window's wait that ran out was held, 2026-11-24: a /// deadline never met, the session stepped a millisecond for ever). pub fn heldNow(ps: *const Peers, core: *const Pardes, only_mail: bool) ?u64 { return if (only_mail and ps.recording and ps.mail.load(.acquire) and core.clock.started) core.clock.now_ns else null; } pub fn post(ps: *Peers, note: Note) void { ps.lock.lockUncancelable(ps.io); if (note == .join and ps.upgrading.load(.monotonic)) { ps.lock.unlock(ps.io); return daemon.refuseReplica(note.join.fd, upgrading); } ps.inbox.append(ps.gpa, note) catch { ps.lock.unlock(ps.io); switch (note) { .join => |j| _ = libc.close(j.fd), .input => |in| ps.gpa.free(in.msg), // Never dumped again: its link ended, as the session lets it go. .again => |peer| _ = libc.shutdown(peer.fd, 2), .gone, .check, .joined => {}, } return; }; ps.mail.store(true, .release); ps.urgent.store(true, .release); ps.lock.unlock(ps.io); if (ps.wake) |w| w(ps.wake_ctx); } /// A replica's connection the daemon handed over (its hello taken /// there), and the view its hello says it had: joined at the next step /// boundary. Any thread. pub fn handed(ps: *Peers, fd: c_int, view: ?u8) void { ps.post(.{ .join = .{ .fd = fd, .view = view } }); } /// What was recorded since the last unit, to every client as one, its /// digest at its end. fn unit(ps: *Peers, origin: u16, seq: u32) void { if (ps.t.buf.items.len == 0) return; tape.recordDigest(&ps.t); const bytes = ps.t.buf.items; unitHeader(&ps.head, origin, seq); trace(ps.gpa, "session: unit {d}/{d}, {d} bytes, to {d} clients:\n", .{ origin, seq, bytes.len, ps.count() }, &.{bytes}); // Its records by hash first (tape.by_hash_min: a file read), each // whole before the unit that names it. for (ps.t.big.items) |b| { for (ps.list) |slot| if (slot) |peer| peer.blob(b); ps.gpa.free(b.bytes); } ps.t.big.clearRetainingCapacity(); const head = wire.header(@backingInt(wire.ServerTag.unit), unit_head + bytes.len); for (ps.list) |slot| if (slot) |peer| peer.send(&.{ &head, &ps.head, bytes }); ps.t.buf.clearRetainingCapacity(); } /// After each of the session's pumps: its unit sent, the clients that /// came joined, their inputs taken in, the ones gone let go. pub fn boundary(ps: *Peers, core: *Pardes) void { if (ps.upgrading.load(.monotonic)) ps.upgrading.store(false, .monotonic); if (!ps.recording and !ps.mail.load(.acquire)) return; const t0 = nowNs(); defer if (ps.recording and ps.samples) ps.boundary_ns.append(ps.gpa, nowNs() - t0) catch {}; if (ps.recording) { ps.seq += 1; ps.unit(0, ps.seq); } if (!ps.mail.load(.acquire)) return; ps.lock.lockUncancelable(ps.io); std.mem.swap(std.ArrayListUnmanaged(Note), &ps.inbox, &ps.taken); ps.mail.store(false, .release); ps.lock.unlock(ps.io); ps.taking = 0; while (ps.taking < ps.taken.items.len) : (ps.taking += 1) switch (ps.taken.items[ps.taking]) { .join => |j| ps.join(core, j), .input => |in| { ps.input(core, in.peer, in.msg); ps.gpa.free(in.msg); }, .gone => |peer| ps.leave(core, peer), // One dumped again over its link since holds that join's pins. .joined => |w| if (w.gen == w.peer.gen) released(w.peer), .again => |peer| ps.joinAgain(core, peer), .check => |peer| { var out: [16]u8 = undefined; peer.send(&.{wire.encodeServer(&out, .{ .check = tape.digestOf(core) }) catch unreachable}); }, }; ps.taken.clearRetainingCapacity(); } fn input(ps: *Peers, core: *Pardes, peer: *Peer, msg: []const u8) void { const in = parseInput(msg) orelse return; const t0 = nowNs(); defer if (ps.samples) ps.input_ns.append(ps.gpa, nowNs() - t0) catch {}; core.toView(peer.view); if (peer.pair and in.event == .focus and in.event.focus) ps.pair_focused = true; ps.t.stamp = stampOf(in); core.update(in.event); core.step(); ps.t.stamp = null; ps.unit(peer.id, in.seq); } /// 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); } /// A client on `joining.fd` joined: a dump of the session now, its /// threads started. At a step boundary (`boundary`), or a session's /// first client before its first effects (runtime/session.zig). pub fn join(ps: *Peers, core: *Pardes, joining: Joining) void { // A join for a view whose client's link has hung up is that client // joining again (runtime/client.zig `run`: its bye, its link shut, // then its dial): its goodbye comes on that link and this join // through the daemon, in no order between them. Held until that // link is let go, its view kept for it by then; a view whose link // is up is another client's. if (joining.view) |v| for (ps.list) |slot| if (slot) |p| if (p.view.index() == v and p.rejoin == null and hungUp(p.fd)) { p.rejoin = joining; return; }; const fd = joining.fd; const t0 = nowNs(); defer { ps.join_ns = @max(ps.join_ns, nowNs() - t0); if (ps.samples) ps.each_join.append(ps.gpa, nowNs() - t0) catch {}; } const slot = for (&ps.list) |*s| { if (s.* == null) break s; } else return daemon.refuseReplica(fd, "that session has as many clients as it takes"); live_peers = ps; if (!ps.recording) { // A session recording to a file (PARDES_RECORD) has its tape. if (tape.on != null) return daemon.refuseReplica(fd, "that session records a tape of its own (PARDES_RECORD)"); ps.t = tape.memory(ps.gpa); ps.t.unit_digests = true; // A unit's digest is a word (PARDES_REPLICA_TRACE: one a field). ps.t.whole_digest = std.c.getenv("PARDES_REPLICA_TRACE") == null; ps.t.cut = .{ .ctx = ps, .f = cutUnit }; tape.on = &ps.t; core.tape = &ps.t; ps.recording = true; ps.samples = std.c.getenv("PARDES_REPLICA_STATS") != null; } // A join with no room lets go a view kept past its bound by the // core's clock (Core.openView), which a wake by mail alone, as this // join's, does not move (tui.zig `clockNow`): moved now, on the tape. if (@popCount(core.views_open) == pardes.views.max) if (core.host.call(.now, .{})) |now| core.advance(now); // A pair's first client, or the first back after a Restore with no // client and no view kept for one: the view the session has is the // joiner's. Any other attach (a detached session's too) opens one. const own = joining.own or (ps.restored and ps.count() == 0 and core.views_away == 0); ps.restored = false; const k = viewFor(core, joining.view, own) orelse { core.unattended = ps.count() == 0 and ps.detached; if (ps.count() == 0) ps.stop(core); const full = "that session has as many views as it takes"; var left: u64 = 0; for (0..pardes.views.max) |i| if (pardes.views.isAway(core, @intCast(i))) { const n = (core.views[i].?.away_ns + pardes.views.away_kept_ns) -| core.clock.now_ns; left = if (left == 0) n else @min(left, n); }; var why: [128]u8 = undefined; return daemon.refuseReplica(fd, if (left == 0) full else std.fmt.bufPrint(&why, full ++ " (one is kept {d} s more for a client joining again)", .{(left + std.time.ns_per_s - 1) / std.time.ns_per_s}) catch full); }; var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; const got = ps.dumped(core, &blobs) catch |err| { core.undrawn &= ~(@as(u8, 1) << @intCast(k)); core.closeView(.at(k)); ps.unit(0, ps.seq); if (ps.count() == 0) ps.stop(core); var why: [96]u8 = undefined; return daemon.refuseReplica(fd, std.fmt.bufPrint(&why, "that session could not be dumped: {t}", .{err}) catch "that session could not be dumped"); }; const bytes = got.bytes; const peer = ps.gpa.create(Peer) catch { for (blobs.items) |b| pardes.memory.unpin(b.bytes); blobs.deinit(core.gpa); core.gpa.free(bytes); return daemon.refuseReplica(fd, "out of memory"); }; peer.* = .{ .peers = ps, .fd = fd, .id = ps.next_id, .view = .at(k), .dump_gpa = core.gpa, .pair = joining.own }; ps.next_id +%= 1; if (ps.next_id == 0) ps.next_id = 1; ps.welcome(peer, bytes, got.digest, blobs); if (ps.threads) peer.writer = std.Thread.spawn(.{}, Peer.writeLoop, .{peer}) catch null; if (ps.threads) peer.reader = std.Thread.spawn(.{}, Peer.readLoop, .{peer}) catch null; if (ps.threads and (peer.writer == null or peer.reader == null)) { ps.letGo(peer); core.undrawn &= ~(@as(u8, 1) << @intCast(k)); core.closeView(.at(k)); ps.unit(0, ps.seq); return; } slot.* = peer; peer.pid = peerPid(fd); ps.tellClients(); log.info("client {d} joined '{s}' as view {d}: a {d} KB dump ({d} KB of state) in {d} us", .{ peer.id, ps.name, k, ps.dump_bytes >> 10, ps.state_bytes >> 10, (nowNs() - t0) / 1000 }); if (std.c.getenv("PARDES_REPLICA_TRACE") != null) std.debug.print("session: client {d} joined after unit {d}\n", .{ peer.id, ps.seq }); } /// What was recorded sent as a unit, then the session's mutable state /// dumped for a join; its blobs (file texts, undo, registers) left out, /// pinned, and streamed by the client's writer thread: the step pays for /// the state, not for the text. The joiner's core is the dump's: the host /// this tape wraps, and what the host wrote in the core, are said again /// at the next input. With the session's digest taken with the dump /// (`dumpJoin`: one moment). fn dumped(ps: *Peers, core: *Pardes, blobs: *std.ArrayListUnmanaged(walk.Deferred)) !struct { bytes: []u8, digest: u64 } { ps.seq += 1; ps.unit(0, ps.seq); const got = pardes.dump.dumpJoin(core, blobs) catch |err| { blobs.deinit(core.gpa); return err; }; var whole = got.bytes.len; for (blobs.items) |b| { pardes.memory.pin(b.bytes); whole += b.bytes.len; } ps.dump_bytes = whole; ps.state_bytes = got.bytes.len; tape.resync(&ps.t); return .{ .bytes = got.bytes, .digest = got.digest }; } /// `peer`'s join made of the dump `bytes`: its welcome, with the /// session's `digest` as dumped for the joiner to check its load by (a /// pair's client, its own boot: `writeJoin`). fn welcome(ps: *Peers, peer: *Peer, bytes: []u8, digest: u64, blobs: std.ArrayListUnmanaged(walk.Deferred)) void { peer.dump = bytes; peer.blobs = blobs; peer.digest = digest; peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = @intCast(libc.getpid()), .session = ps.name[0..@min(ps.name.len, wire.max_name)], .client = peer.id, .view = peer.view, .dump_len = ps.dump_bytes, .gmtoff = gmtoff(), .digest = peer.digest, .semantics = wire.semantics, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len; } /// Its client's goodbye and hello again on its link (`Peer.take`: it /// diverged, fell behind, or was cut off): the session's state dumped /// for it there, for its view, away a moment and its own again in one /// step (one connection, in order: no other client can take it /// meanwhile), what was queued for it before let go, its writer's next /// a join (`writeLoop`). The daemon is not asked. Its last join not /// written whole yet (no client's road), its link let go meanwhile, or /// no dump: its link ends (it dials again, `replica.join`). fn joinAgain(ps: *Peers, core: *Pardes, peer: *Peer) void { if (!ps.dumpAgain(core, peer)) _ = libc.shutdown(peer.fd, 2); } /// `joinAgain`'s dump; false when its link is to end. fn dumpAgain(ps: *Peers, core: *Pardes, peer: *Peer) bool { const io = ps.io; peer.lock.lockUncancelable(io); const ok = !peer.closing and peer.written == peer.gen; peer.lock.unlock(io); if (!ok) return false; const t0 = nowNs(); defer { ps.join_ns = @max(ps.join_ns, nowNs() - t0); if (ps.samples) ps.each_join.append(ps.gpa, nowNs() - t0) catch {}; } // The last join's pins, if its note has not come yet (it is written). released(peer); // Its view away a moment and its own again, as a client that left // and joined for it (`leave`, `join`): every side's terminals // reloaded in that step (Core.rejoinView), as the dump's are. core.awayView(peer.view); peer.view = .at(viewFor(core, peer.view.index(), false) orelse return false); var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; const got = ps.dumped(core, &blobs) catch return false; peer.lock.lockUncancelable(io); ps.welcome(peer, got.bytes, got.digest, blobs); peer.out.clearRetainingCapacity(); peer.cut = false; peer.gen += 1; peer.cond.signal(io); peer.lock.unlock(io); ps.again_here += 1; log.info("client {d} joined '{s}' again on its link as view {d}: a {d} KB dump ({d} KB of state) in {d} us", .{ peer.id, ps.name, peer.view.index(), ps.dump_bytes >> 10, ps.state_bytes >> 10, (nowNs() - t0) / 1000 }); return true; } /// A joiner's view in `core`: the one kept for it since it left /// (views.away), or one new; someone looks at the session now (its /// messages go by keys, not the clock), and that view is its own /// process's to draw. The session's join and a pair's client's own boot /// (`Replica.initBoot`) alike, so that the two cores are the same: what /// was queued before the join (a pair's session's first effects, its /// boot shell's spawn among them) is performed after it, on the tape /// its client is sent, not by the view's settle, as a client that made /// its core itself performs none of them. /// `own`: the live view is the joiner's, in a session nobody looks at /// (a pair's first client, Options.pair; the first back after a /// Restore): not one beside it nobody looks at, which would size its /// terminals (Pardes.sizes). /// ponytail: a divergence's redial that came before its old link's end /// (posted by that link's reader, microseconds after the bye; the /// redial is a dial and the daemon's hand-over later) finds its view /// not kept yet, and takes a new one. fn viewFor(core: *Pardes, back: ?u8, own: bool) ?u8 { const held = core.gpa.alloc(pardes.Effect, core.effects_len) catch return null; defer core.gpa.free(held); for (held, 0..) |*e, i| e.* = core.effects[(core.effects_head + i) % core.effects.len]; core.effects_len = 0; defer queueFirst(core, held); core.unattended = false; const k = if (own) core.live else (if (back) |v| (if (core.rejoinView(.at(v))) v else null) else null) orelse (core.openView() orelse return null).index(); core.undrawn |= @as(u8, 1) << @intCast(k); return k; } /// `held` queued again ahead of what is queued now, in its order. fn queueFirst(core: *Pardes, held: []const pardes.Effect) void { const cap = core.effects.len; const n = @min(held.len, cap - core.effects_len); const head = (core.effects_head + cap - n) % cap; for (held[0..n], 0..) |e, i| core.effects[(head + i) % cap] = e; core.effects_head = head; core.effects_len += n; } fn leave(ps: *Peers, core: *Pardes, peer: *Peer) void { for (&ps.list) |*slot| if (slot.* == peer) { slot.* = null; }; log.info("client {d} left '{s}'", .{ peer.id, ps.name }); ps.tellClients(); core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view.index())); // Cut off, it joins again after the words why (`send`); its reader // has ended and no other thread sets `cut` now. ps.closeViewOf(core, peer, peer.again or peer.cut); if (ps.count() == 0) core.unattended = ps.detached; if (ps.count() == 0 and peer.close and daemon.sessionState() == .pair) ps.closed = true; if (peer.pair) ps.pair_left = !peer.bye and !peer.closing and !peer.cut; ps.seq += 1; ps.unit(0, ps.seq); ps.letGo(peer); if (ps.count() == 0) ps.stop(core); } /// A gone client's view closed (its slot let go already), or kept for /// it (`again`: it joins again for it, views.away): the last one of a /// session no one else watches leaves the session its layout, for a /// client that comes after to find. fn closeViewOf(ps: *Peers, core: *Pardes, peer: *Peer, again: bool) void { if (again) core.awayView(peer.view) else if (ps.count() == 0 and ps.detached) core.leaveView(peer.view) else core.closeView(peer.view); } /// Its threads ended and joined, its link closed. fn letGo(ps: *Peers, peer: *Peer) void { const io = ps.io; peer.lock.lockUncancelable(io); peer.closing = true; peer.cond.signal(io); peer.lock.unlock(io); _ = libc.shutdown(peer.fd, 2); if (peer.writer) |w| w.join(); if (peer.reader) |r| r.join(); released(peer); _ = libc.close(peer.fd); peer.out.deinit(ps.gpa); peer.sending.deinit(ps.gpa); if (peer.want) |b| ps.gpa.free(b); if (peer.z) |z| _ = zstd.ZSTD_freeCCtx(z); peer.zout.deinit(ps.gpa); // What it posted and is not taken yet is nobody's: its reader's // after it was let go (its end), and its writer's last (`.joined`) // in the next batch or after this note in the one taken now. ps.lock.lockUncancelable(io); ps.dropNotes(&ps.inbox, 0, peer); ps.lock.unlock(io); ps.dropNotes(&ps.taken, ps.taking + 1, peer); if (peer.rejoin) |j| ps.post(.{ .join = j }); ps.gpa.destroy(peer); } /// `peer`'s notes in `list` from `from` on taken out, in order (an /// input's bytes freed). fn dropNotes(ps: *Peers, list: *std.ArrayListUnmanaged(Note), from: usize, peer: *const Peer) void { var i = from; while (i < list.items.len) { const mine = switch (list.items[i]) { .input => |in| in.peer == peer, .gone, .check, .again => |p| p == peer, .joined => |w| w.peer == peer, .join => false, }; if (!mine) { i += 1; continue; } if (list.items[i] == .input) ps.gpa.free(list.items[i].input.msg); _ = list.orderedRemove(i); } } /// Every client told the session is upgrading and let go, its view with /// it: an Upgrade's exec is next (tui.zig `upgradeNow`). What each was /// sent goes first, for up to 200 ms; a client then dials the session /// again. So is a connection handed over and not joined yet, or until /// the exec (`upgrading`): the exec would close it unanswered, and its /// client would take that for the session's end. pub fn refuseAll(ps: *Peers, core: *Pardes) void { ps.lock.lockUncancelable(ps.io); ps.upgrading.store(true, .monotonic); var i: usize = 0; while (i < ps.inbox.items.len) { if (ps.inbox.items[i] == .join) daemon.refuseReplica(ps.inbox.orderedRemove(i).join.fd, upgrading) else i += 1; } ps.lock.unlock(ps.io); if (ps.count() == 0) return; var out: [600]u8 = undefined; const words = wire.encodeServer(&out, .{ .refused = upgrading }) catch unreachable; // the words fit for (ps.list) |slot| if (slot) |peer| peer.last(words); ps.flushed200(); // Each joins again for its view, kept in the dump (views.away). ps.drop(core, true); } /// Every client told the session is restoring a dump and let go: each /// joins again at once (host_io.restoreCore), as at an Upgrade, not /// asking the daemon whether a link cut with no word was its /// session's end (`cutListed`). pub fn restoring(ps: *Peers, core: *Pardes) void { var out: [600]u8 = undefined; const words = wire.encodeServer(&out, .{ .refused = restore_words }) catch unreachable; // the words fit for (ps.list) |slot| if (slot) |peer| peer.last(words); ps.flushed200(); // One dialling again already (handed over meanwhile) joins the // restored core at the next boundary, not hung up on: its redial // would wait 100 ms for the next dial. var again: std.ArrayListUnmanaged(Joining) = .empty; defer again.deinit(ps.gpa); ps.lock.lockUncancelable(ps.io); var i: usize = 0; while (i < ps.inbox.items.len) { if (ps.inbox.items[i] != .join) { i += 1; continue; } again.append(ps.gpa, ps.inbox.items[i].join) catch break; _ = ps.inbox.orderedRemove(i); } ps.lock.unlock(ps.io); for (ps.list) |slot| if (slot) |p| if (p.rejoin) |j| { again.append(ps.gpa, j) catch continue; p.rejoin = null; }; ps.drop(core, false); ps.restored = true; for (again.items) |j| ps.post(.{ .join = j }); } /// What each client was sent goes first, for up to 200 ms. fn flushed200(ps: *Peers) void { const until = nowNs() + 200 * std.time.ns_per_ms; while (nowNs() < until) { const busy = for (ps.list) |slot| { if (slot) |peer| if (!peer.done.load(.acquire)) break true; } else false; if (!busy) break; const ts: libc.timespec = .{ .sec = 0, .nsec = 2 * std.time.ns_per_ms }; _ = libc.nanosleep(&ts, null); } } /// A join's dump and pins let go: written, or its client gone. fn released(peer: *Peer) void { for (peer.blobs.items) |b| pardes.memory.unpin(b.bytes); peer.blobs.deinit(peer.dump_gpa); peer.blobs = .empty; if (peer.dump.len > 0) peer.dump_gpa.free(peer.dump); peer.dump = &.{}; } /// The daemon told the clients there are now (`pardes --ps`). fn tellClients(ps: *const Peers) void { var pids: [pardes.views.max]libc.pid_t = undefined; var n: usize = 0; for (ps.list) |slot| if (slot) |peer| { pids[n] = peer.pid; n += 1; }; daemon.clients(pids[0..n]); } /// Detach typed in client view `k`'s: told it left the session running /// (`left`), its last word; the client goes, and its reader says so. pub fn detach(ps: *Peers, k: u8) bool { for (ps.list) |slot| if (slot) |peer| if (peer.view.index() == k) { daemon.keepSession(); var out: [wire.max_name + 8]u8 = undefined; peer.last(wire.encodeServer(&out, .{ .left = ps.name[0..@min(ps.name.len, wire.max_name)] }) catch unreachable); return true; }; return false; } /// The session ends with `code`: every client told so (`ended`), its /// last word, before the links are let go (`dropAll`). pub fn ended(ps: *Peers, code: u8) void { var out: [16]u8 = undefined; const words = wire.encodeServer(&out, .{ .ended = code }) catch unreachable; for (ps.list) |slot| if (slot) |peer| peer.last(words); ps.flushed200(); } fn stop(ps: *Peers, core: *Pardes) void { if (!ps.recording) return; tape.on = null; core.tape = core.opts.tape orelse &tape.none; tape.release(&ps.t); ps.recording = false; } /// Every client let go (the session's end, a Restore): each sees its /// link end. pub fn dropAll(ps: *Peers, core: *Pardes) void { ps.drop(core, false); } /// ...each view kept for its client if `again` (an Upgrade's). fn drop(ps: *Peers, core: *Pardes, again: bool) void { for (&ps.list) |*slot| if (slot.*) |peer| { slot.* = null; core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view.index())); ps.closeViewOf(core, peer, again); ps.letGo(peer); }; ps.tellClients(); ps.stop(core); ps.lock.lockUncancelable(ps.io); for (ps.inbox.items) |note| switch (note) { .join => |j| _ = libc.close(j.fd), .input => |in| ps.gpa.free(in.msg), .gone, .check, .joined, .again => {}, }; ps.inbox.clearRetainingCapacity(); ps.lock.unlock(ps.io); core.unattended = ps.detached; } pub fn deinit(ps: *Peers) void { if (std.c.getenv("PARDES_REPLICA_STATS")) |path| if (ps.input_ns.items.len > 0) ps.writeStats(std.mem.span(path)); ps.inbox.deinit(ps.gpa); ps.taken.deinit(ps.gpa); ps.input_ns.deinit(ps.gpa); ps.boundary_ns.deinit(ps.gpa); ps.each_join.deinit(ps.gpa); } fn writeStats(ps: *Peers, path: []const u8) void { var buf: [400]u8 = undefined; const line = std.fmt.bufPrint(&buf, "session inputs {d} input_us {d}/{d}/{d} boundaries {d} boundary_us {d}/{d}/{d} join_us {d} dump_kb {d} state_kb {d} cut {d} again {d}\n", .{ ps.input_ns.items.len, pctOf(ps.input_ns.items, 50) / 1000, pctOf(ps.input_ns.items, 99) / 1000, pctOf(ps.input_ns.items, 100) / 1000, ps.boundary_ns.items.len, pctOf(ps.boundary_ns.items, 50) / 1000, pctOf(ps.boundary_ns.items, 99) / 1000, pctOf(ps.boundary_ns.items, 100) / 1000, ps.join_ns / 1000, ps.dump_bytes >> 10, ps.state_bytes >> 10, ps.cut, ps.again_here, }) catch return; var z: [4096]u8 = undefined; const pz = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return; const fd = libc.open(pz, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644)); if (fd < 0) return; _ = libc.write(fd, line.ptr, line.len); var each: [400]u8 = undefined; var w: std.Io.Writer = .fixed(&each); w.writeAll("session joins_us") catch {}; for (ps.each_join.items) |ns| w.print(" {d}", .{ns / 1000}) catch {}; w.writeAll("\n") catch {}; _ = libc.write(fd, w.buffered().ptr, w.buffered().len); _ = libc.close(fd); } }; // ---- the client's half ---- pub const Joined = struct { fd: c_int, pid: u32, client: u16, view: u8, gmtoff: i32, dump: []u8, /// The session's digest as dumped (`Replica.loaded`). digest: u64 = 0, /// Its build's (wire.semantics): the daemon judged the hello by what it /// last heard, which an upgrade under way may not have said yet. semantics: u64 = 0, /// What was read past the dump: the stream's (`readLink`). rest: Framer = .{}, /// A far join's blobs that came over the link, for `Have.store` (the C /// heap's), and how it went: its blobs, those it held already (from the /// core it left, from disk) and the bytes of the ones it was sent. got: []Got = &.{}, blobs: u32 = 0, from_memory: u32 = 0, from_disk: u32 = 0, sent_bytes: u64 = 0, /// How long its dial and load took, ms (`join`). ms: u64 = 0, /// Its replica is its own boot, the welcome not read yet (`ownBoot`, /// `confirmBoot`). booted: bool = false, }; /// A blob a far join was sent: where it is in the dump, and its hash. pub const Got = struct { pos: usize, len: usize, hash: [32]u8 }; /// Connected to the replica socket at `path`, its hello said for /// `session`, welcomed, and the dump read whole: what a client joins with. /// A far client (`have`) is sent its dump's blobs by hash first, and asks /// for those it holds nowhere. Errors are said in `why`. `view`: the one /// it had, joining again for it. pub fn dial(gpa: Allocator, path: []const u8, session: []const u8, why: []u8, have: ?*Have, view: ?u8) ?Joined { const fd = libc.socket(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0); if (fd < 0) return said(why, "no socket", .{}); var addr: libc.sockaddr.un = .{ .path = @splat(0) }; if (path.len >= addr.path.len) { _ = libc.close(fd); return said(why, "the socket's path is too long: {s}", .{path}); } @memcpy(addr.path[0..path.len], path); if (libc.connect(fd, @ptrCast(&addr), @sizeOf(libc.sockaddr.un)) != 0) { _ = libc.close(fd); return said(why, "nothing answers at {s}", .{path}); } return joinOn(gpa, fd, session, why, have, view, null, .{}); } /// `dial`'s, on a connection made: the hello, then the join, read on from /// `rest` (what its reader read already). The connection is closed if the /// join fails. No session named: no hello said here: a pair's /// (Options.pair), whose session took it as its first client, or one /// joining again over its link, its hello said there (`comeBack`). `boot`: /// a pair's client that made its core itself and said so (`boot`): /// nothing said here, and its welcome's digest the same, no dump comes. fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Have, view: ?u8, boot_digest: ?u64, rest: Framer) ?Joined { var out: [wire.hello_max + 16]u8 = undefined; const hello = if (session) |name| wire.encodeClient(&out, .{ .hello = .{ .session = name, .view = view } }) catch { _ = libc.close(fd); return said(why, "that session's name is too long", .{}); } else out[0..0]; // Its first word, in the same write: whether it is far. const far = wire.encodeClient(out[hello.len..], .{ .far = have != null }) catch unreachable; var j: Joined = .{ .fd = fd, .pid = 0, .client = 0, .view = 0, .gmtoff = 0, .dump = &.{}, .rest = rest }; const Read = struct { j: *Joined, gpa: Allocator, why: []u8, have: ?*Have, boot: ?u64, failed: ?[]const u8 = null, welcomed: bool = false, done: bool = false, /// The join's list of blobs (`blob_entry` each), as it comes. list: std.ArrayListUnmanaged(u8) = .empty, /// Where what comes fills the dump, in order (each a place and a /// length): the state's runs between the blobs, then each blob /// asked for. A blob listed twice is copied once the dump is whole. runs: std.ArrayListUnmanaged([2]usize) = .empty, run: usize = 0, run_at: usize = 0, dups: std.ArrayListUnmanaged([3]usize) = .empty, fn deinit(r: *@This()) void { r.list.deinit(r.gpa); r.runs.deinit(r.gpa); r.dups.deinit(r.gpa); } fn fail(r: *@This(), words: []const u8) bool { r.failed = words; return false; } fn take(r: *@This(), tag: u8, payload: []const u8) bool { const msg = wire.decodeServer(tag, payload) catch return r.fail("the session's answer was not understood"); switch (msg) { .welcome => |w| { r.j.pid = w.pid; r.j.client = w.client; r.j.view = w.view.index(); r.j.gmtoff = w.gmtoff; r.j.digest = w.digest; r.j.semantics = w.semantics; if (r.boot == w.digest) { r.done = true; return false; } r.j.dump = r.gpa.alloc(u8, @intCast(w.dump_len)) catch return r.fail("out of memory for the session's dump"); r.welcomed = true; r.j.blobs = if (r.have != null) w.blobs else 0; // A near client's dump comes whole, and a far one's // without blobs is its state. if (r.j.blobs == 0) r.runs.append(r.gpa, .{ 0, r.j.dump.len }) catch return r.fail("out of memory for the session's dump"); r.done = w.dump_len == 0; return !r.done; }, .refused => |words| { r.failed = std.fmt.bufPrint(r.why, "{s}\x00", .{words}) catch "refused"; return false; }, .blobs => |entries| { const whole = @as(usize, r.j.blobs) * blob_entry; if (r.runs.items.len > 0 or r.list.items.len + entries.len > whole) return r.fail("the session sent more of its blobs' list than it said"); r.list.appendSlice(r.gpa, entries) catch return r.fail("out of memory for the session's blobs' list"); if (r.list.items.len == whole) return r.lacking(); return true; }, .dump => |piece| { if (r.runs.items.len == 0) return r.fail("the session sent its dump before its blobs' list"); var p = piece; while (p.len > 0) { if (r.run == r.runs.items.len) return r.fail("the session sent more dump than it said"); const run = r.runs.items[r.run]; const n = @min(p.len, run[1] - r.run_at); @memcpy(r.j.dump[run[0] + r.run_at ..][0..n], p[0..n]); r.run_at += n; p = p[n..]; if (r.run_at == run[1]) { r.run += 1; r.run_at = 0; } } if (r.run < r.runs.items.len) return true; for (r.dups.items) |d| @memcpy(r.j.dump[d[0]..][0..d[2]], r.j.dump[d[1]..][0..d[2]]); r.done = true; return false; }, // What the stream it leaves still brings, joining again over // its link (`loadAgain`): let go until the welcome. .unit, .blob, .check, .pong => return !r.welcomed or r.fail("the session sent a unit before its dump"), else => return r.fail("the session sent a unit before its dump"), } } /// The list whole: each blob put in place from what the client /// holds (`Have.find`), or asked for, and the runs to fill made. fn lacking(r: *@This()) bool { const h = r.have.?; const dump = r.j.dump; const n: usize = r.j.blobs; const bits = r.gpa.alloc(u8, (n + 7) / 8) catch return r.fail("out of memory for the session's blobs' list"); defer r.gpa.free(bits); @memset(bits, 0); var got: std.ArrayListUnmanaged(Got) = .empty; defer got.deinit(std.heap.c_allocator); var firsts: std.AutoHashMapUnmanaged([32]u8, [2]usize) = .empty; defer firsts.deinit(r.gpa); var shift: usize = 0; var end: usize = 0; for (0..n) |i| { const e = r.list.items[i * blob_entry ..][0..blob_entry]; const len = std.math.cast(usize, std.mem.readInt(u64, e[8..16], .little)) orelse return r.fail("the session's list of blobs is malformed"); const pos = std.math.add(usize, std.math.cast(usize, std.mem.readInt(u64, e[0..8], .little)) orelse maxInt, shift) catch maxInt; if (pos < end or pos > dump.len or len > dump.len - pos) return r.fail("the session's list of blobs is malformed"); shift += len; if (pos > end) r.runs.append(r.gpa, .{ end, pos - end }) catch return r.fail("out of memory for the session's blobs' list"); end = pos + len; const hash = e[16..48]; const first = firsts.getOrPut(r.gpa, hash.*) catch return r.fail("out of memory for the session's blobs' list"); if (first.found_existing and first.value_ptr[1] == len) { r.dups.append(r.gpa, .{ pos, first.value_ptr[0], len }) catch return r.fail("out of memory for the session's blobs' list"); continue; } first.value_ptr.* = .{ pos, len }; if (h.find(hash, dump[pos..][0..len])) |where| switch (where) { .memory => r.j.from_memory += 1, .disk => r.j.from_disk += 1, } else { bits[i / 8] |= @as(u8, 1) << @intCast(i % 8); got.append(std.heap.c_allocator, .{ .pos = pos, .len = len, .hash = hash.* }) catch return r.fail("out of memory for the session's blobs' list"); r.j.sent_bytes += len; } } if (dump.len > end) r.runs.append(r.gpa, .{ end, dump.len - end }) catch return r.fail("out of memory for the session's blobs' list"); for (got.items) |g| r.runs.append(r.gpa, .{ g.pos, g.len }) catch return r.fail("out of memory for the session's blobs' list"); const head = wire.header(@backingInt(wire.ClientTag.want), bits.len); if (!writeAll(r.j.fd, &head) or !writeAll(r.j.fd, bits)) return r.fail("the session hung up"); r.j.got = got.toOwnedSlice(std.heap.c_allocator) catch return r.fail("out of memory for the session's blobs' list"); return true; } const maxInt = std.math.maxInt(usize); }; if (boot_digest == null and !writeAll(fd, out[0 .. hello.len + far.len])) { j.rest.deinit(gpa); _ = libc.close(fd); return said(why, "the session hung up", .{}); } var r: Read = .{ .j = &j, .gpa = gpa, .why = why, .have = have, .boot = boot_digest }; defer r.deinit(); j.rest.run(gpa, fd, &r, Read.take); if (r.failed != null or !r.done) { j.rest.deinit(gpa); if (j.dump.len > 0) gpa.free(j.dump); std.heap.c_allocator.free(j.got); _ = libc.close(fd); const text = r.failed orelse "the session hung up before the dump was whole"; if (text.ptr == why.ptr) return null; return said(why, "{s}", .{text}); } return j; } // ---- a far client's blobs ---- /// What a far client holds of a join's blobs already, by content (`dial`): /// the cache on disk, and on a rejoin the blobs of the core it leaves. pub const Have = struct { io: std.Io, cache: ?Cache = null, /// The blobs a join found on disk: the most recently used once stored. hits: std.ArrayListUnmanaged([32]u8) = .empty, /// The core it leaves (`leaving`), each blob hashed once when one of its /// length is looked for. ponytail: a scan a lookup, fine to some /// thousands of blobs; a map by length would take over past that. old: std.ArrayListUnmanaged([]const u8) = .empty, old_hash: std.ArrayListUnmanaged(?[32]u8) = .empty, /// The thread writing the last join's blobs to disk (`store`). storing: ?std.Thread = null, pub fn init(io: std.Io) Have { return .{ .io = io, .cache = Cache.open(io) }; } pub fn deinit(h: *Have) void { h.wait(); h.left(); h.old.deinit(std.heap.c_allocator); h.old_hash.deinit(std.heap.c_allocator); h.hits.deinit(std.heap.c_allocator); } fn wait(h: *Have) void { if (h.storing) |t| t.join(); h.storing = null; } /// `core`'s blobs, looked at by the next join until `left`: a rejoin /// takes what it held, by content, before the core goes. pub fn leaving(h: *Have, core: *const Pardes) void { h.left(); walk.blobs(Pardes, core, &h.old); h.old_hash.appendNTimes(std.heap.c_allocator, null, h.old.items.len) catch h.old.clearRetainingCapacity(); } pub fn left(h: *Have) void { h.old.clearRetainingCapacity(); h.old_hash.clearRetainingCapacity(); } pub const Where = enum { memory, disk }; /// The blob of `hash` put in `out` (its length), from the core it /// leaves or the cache; null when it holds it nowhere. fn find(h: *Have, hash: *const [32]u8, out: []u8) ?Where { for (h.old.items, h.old_hash.items) |b, *word| { if (b.len != out.len) continue; if (word.* == null) { var d: [32]u8 = undefined; std.crypto.hash.Blake3.hash(b, &d, .{}); word.* = d; } if (!std.mem.eql(u8, &word.*.?, hash)) continue; @memcpy(out, b); return .memory; } if (h.cache) |*c| if (c.get(h.io, hash, out)) { h.hits.append(std.heap.c_allocator, hash.*) catch {}; return .disk; }; return null; } /// The blobs a join was sent, written to the cache on a thread of their /// own (with those it found there, made the most recently used), which /// frees the dump (`gpa`'s) and the lists after: the first frame waits /// for none of it. pub fn store(h: *Have, gpa: Allocator, j: *Joined) void { const dump = j.dump; const got = j.got; j.dump = &.{}; j.got = &.{}; h.wait(); var hits = h.hits; h.hits = .empty; const Store = struct { fn run(c: Cache, io: std.Io, a: Allocator, bytes: []u8, list: []Got, found: std.ArrayListUnmanaged([32]u8)) void { var seen = found; defer { a.free(bytes); std.heap.c_allocator.free(list); seen.deinit(std.heap.c_allocator); } var blobs: std.ArrayListUnmanaged(walk.Blob) = .empty; defer blobs.deinit(std.heap.c_allocator); var put: u64 = 0; for (list) |g| { if (put + g.len > c.cap) continue; put += g.len; blobs.append(std.heap.c_allocator, .{ .hash = g.hash, .bytes = bytes[g.pos..][0..g.len] }) catch return; } c.put(io, blobs.items, seen.items); } }; const c = h.cache orelse { gpa.free(dump); std.heap.c_allocator.free(got); hits.deinit(std.heap.c_allocator); return; }; h.storing = std.Thread.spawn(.{}, Store.run, .{ c, h.io, gpa, dump, got, hits }) catch { Store.run(c, h.io, gpa, dump, got, hits); return; }; } /// `core`'s blobs the cache lacks, written there: what this client made /// since it joined (an edit's text, its undo), for its next start; then /// the cache trimmed under its cap, at this client's end. pub fn keep(h: *Have, core: *const Pardes) void { h.wait(); const c = h.cache orelse return; var all: std.ArrayListUnmanaged([]const u8) = .empty; defer all.deinit(std.heap.c_allocator); walk.blobs(Pardes, core, &all); var missing: std.ArrayListUnmanaged(walk.Blob) = .empty; defer missing.deinit(std.heap.c_allocator); var put: u64 = 0; for (all.items) |b| { var d: [32]u8 = undefined; std.crypto.hash.Blake3.hash(b, &d, .{}); if (put + b.len > c.cap or c.has(h.io, &d, b.len)) continue; put += b.len; missing.append(std.heap.c_allocator, .{ .bytes = b, .hash = d }) catch return; } c.put(h.io, missing.items, h.hits.items); h.hits.clearRetainingCapacity(); c.trim(h.io); } }; /// A far client's blobs on disk (Db.zig): cache.xitdb, by BLAKE3 hash. pub const Cache = pardes.Db.Cache; fn said(why: []u8, comptime fmt: []const u8, args: anytype) ?Joined { _ = std.fmt.bufPrint(why, fmt ++ "\x00", args) catch {}; return null; } /// A message `Replica.input` made, to the session: the event's frame (its /// client and seq are the connection's). pub fn sendInput(fd: c_int, msg: []const u8) bool { return writeAll(fd, msg[head_len..]); } /// Asks the session's digest, answered in stream order. pub fn askCheck(fd: c_int) bool { var out: [16]u8 = undefined; return writeAll(fd, wire.encodeClient(&out, .check) catch unreachable); } /// The client's last word: `again`, it joins again for its view at once; /// `close`, its window was closed. pub fn bye(fd: c_int, how: @FieldType(wire.ClientMsg, "bye")) void { var out: [16]u8 = undefined; if (wire.encodeClient(&out, .{ .bye = how })) |b| _ = writeAll(fd, b) else |_| {} } /// Its goodbye that says it joins again and its hello for `view`, said on /// its link in one write: the session dumps its state for it there /// (`Peers.joinAgain`); its first word after them is the join's (`joinOn`). /// False: the link is gone. pub fn comeBack(fd: c_int, session: []const u8, view: u8) bool { var out: [wire.hello_max + 16]u8 = undefined; const said_bye = wire.encodeClient(&out, .{ .bye = .{ .again = true } }) catch unreachable; // fits const hello = wire.encodeClient(out[said_bye.len..], .{ .hello = .{ .session = session[0..@min(session.len, wire.max_name)], .view = view } }) catch unreachable; // fits return writeAll(fd, out[0 .. said_bye.len + hello.len]); } /// What the session streams a client after its dump, as its frontend's loop /// takes it: a unit's bytes and a refusal's words on the C heap, the loop's /// to free. pub const Said = union(enum) { unit: []u8, checked: u64, refused: []u8, blob: []u8, ended: u8, left }; /// The session's stream off `fd`, each message handed to `post` until the /// link ends (a refusal ends it too); `post` says whether it took it (one /// it did not is freed here). Once `link` comes back over it (`Link.back`): /// what the stream it leaves still brings is let go, a last word is the /// link's own (`Link.take`; a cut's words are followed by the welcome), and /// the session's welcome there ends it, put back for the join's reader /// (`join`). pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, link: *Link, ctx: anytype, comptime post: fn (@TypeOf(ctx), Said) bool) void { const Reading = struct { ctx: @TypeOf(ctx), link: *Link, welcome: [wire.hello_max + 64]u8 = undefined, welcome_len: usize = 0, fn take(x: *@This(), tag: u8, payload: []const u8) bool { const t = std.enums.fromInt(wire.ServerTag, tag) orelse return false; const back = x.link.back.load(.acquire); if (t == .welcome and back) { if (wire.header_len + payload.len > x.welcome.len) return false; x.welcome[0..wire.header_len].* = wire.header(tag, payload.len); @memcpy(x.welcome[wire.header_len..][0..payload.len], payload); x.welcome_len = wire.header_len + payload.len; return false; } const msg: Said = switch (t) { .unit => if (back) return true else .{ .unit = std.heap.c_allocator.dupe(u8, payload) catch return false }, .blob => if (back) return true else .{ .blob = std.heap.c_allocator.dupe(u8, payload) catch return false }, .check => if (back) return true else .{ .checked = (wire.decodeServer(tag, payload) catch return false).check }, .refused => .{ .refused = std.heap.c_allocator.dupe(u8, (wire.decodeServer(tag, payload) catch return false).refused) catch return false }, .ended => .{ .ended = (wire.decodeServer(tag, payload) catch return false).ended }, .left => .left, .pong, .welcome, .dump, .blobs, .zstd => return true, }; return x.said(msg); } fn said(x: *@This(), msg: Said) bool { if (x.link.back.load(.acquire)) { x.link.take(msg); return msg == .refused; } if (!post(x.ctx, msg)) switch (msg) { .unit, .refused, .blob => |b| std.heap.c_allocator.free(b), .checked, .ended, .left => {}, }; // A last word ends the stream. return msg == .unit or msg == .checked or msg == .blob; } }; var x: Reading = .{ .ctx = ctx, .link = link }; rest.run(gpa, fd, &x, Reading.take); if (x.welcome_len > 0) { if (!rest.putBack(gpa, x.welcome[0..x.welcome_len])) rest.bad = true; return; } // A message past the wire's bound: said, never a hangup. const n = rest.overlong() orelse return; const words = std.fmt.allocPrint(std.heap.c_allocator, "the session sent a {d} MB message, over the {d} MiB bound", .{ n >> 20, wire.max_payload >> 20 }) catch return; _ = x.said(.{ .refused = words }); } /// A join's failure that is its session's end, whenever it came (the /// session or its daemon gone, or hung up before the dump was whole): a /// client joining again then goes as at a hang-up (`.gone`), in the same /// words, never as a join that failed. pub fn ended(why: []const u8) bool { const words = std.mem.sliceTo(why, 0); for ([_][]const u8{ "the session hung up", "nothing answers at ", "no session called " }) |w| if (std.mem.startsWith(u8, words, w)) return true; return false; } /// What an Upgrade tells its clients (`Peers.refuseAll`): each dials again. pub const upgrading = "the session is upgrading to another build of pardes"; /// What a Restore tells its clients (`Peers.restoring`): each joins again, /// saying nothing (the own frontend's Restore shows nothing either). pub const restore_words = "the session is restoring a dump"; /// A link cut with no last word (`why` its hang-up) whose session its /// daemon lists still: an Upgrade's exec cut it, a dump on the way past the /// clients' flush (`Peers.refuseAll`), whichever build the session is, not /// the session's end, which the daemon sees as its link's: so the client /// joins again as one told `upgrading` does, whatever the flush's bound let /// through. Near, this machine's daemon is asked; far, the dial again is /// the asking (the far daemon's "no session called" ends it: `redial`). pub fn cutListed(why: []const u8, session: []const u8, far: bool) bool { if (!std.mem.startsWith(u8, std.mem.sliceTo(why, 0), "the session hung up")) return false; if (far) return true; var buf: [8192]u8 = undefined; const list = daemon.ask("list", &buf) orelse return false; var lines = std.mem.tokenizeScalar(u8, list, '\n'); while (lines.next()) |line| { if (!std.mem.startsWith(u8, line, "session ")) continue; if (std.mem.eql(u8, line[(std.mem.lastIndexOfScalar(u8, line, ' ') orelse continue) + 1 ..], session)) return true; } return false; } /// The words a client goes with when its session runs another build now. const upgrade_words = "session upgraded to a newer pardes: upgrade this client too"; /// A join's failure that is its session's running another build now: a /// client whose own start path holds a newer one execs that instead /// (runtime/client.zig). pub fn otherBuild(why: []const u8) bool { return std.mem.endsWith(u8, std.mem.sliceTo(why, 0), upgrade_words); } /// A replica client's join, the terminal's and the window's alike (their /// `runClient`): the session at `path` dialled (or, first, the one on its /// pair, `o.pair`), its build checked to be this /// one's, and its dump loaded into a replica checked against the session /// as it was dumped. Or, `old` given, joined again for old's view: over /// old's link when its hello was said there (`here`: `comeBack`), the join /// read on from what its reader left (`j.rest`); else, or that link ending /// first, dialled again once it has ended (`redial`); the core it leaves /// held meanwhile so that its blobs are not sent again (`Have.leaving`), /// and let go before the new one loads. The dump is let go, a far join's to /// the thread that keeps the blobs it was sent (`Have.store`), and how long /// it all took is `j.ms`. Null, and why in `why`. pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o: pardes.Options, have: ?*Have, why: *[600]u8, old: ?*Replica, here: bool) ?*Replica { if (old == null) if (o.pair) |fd| return ownBoot(gpa, j, fd, o, why); if (old) |prev| if (have) |h| h.leaving(prev.core()); const t0 = nowNs(); if (old) |prev| { const view = j.view; const over = if (here) over: { const rest = j.rest; j.rest = .{}; break :over joinOn(gpa, j.fd, null, why, have, null, null, rest); } else null; if (here and over == null) log.info("its link ended before the session's welcome there ({s}): dialled again", .{std.mem.sliceTo(why, 0)}); const back = if (over) |got| sameBuild(gpa, got, why, true) else null; j.* = back orelse redial(gpa, path, session, why, have, prev.diverged == null, view) orelse { if (ended(why)) return null; var words: [600]u8 = undefined; const said_ = std.mem.sliceTo(why, 0); @memcpy(words[0..said_.len], said_); _ = std.fmt.bufPrint(why, "could not join again: {s}\x00", .{words[0..said_.len]}) catch {}; return null; }; if (have) |h| h.left(); prev.deinit(); } else j.* = (if (o.join_view) |v| redial(gpa, path, session, why, have, true, v) else sameBuild(gpa, (dial(gpa, path, session, why, have, null) orelse // Handed to the session as it upgraded, or cut by its exec with // its dump on the way: it is there again soon. if (std.mem.eql(u8, std.mem.sliceTo(why, 0), upgrading) or cutListed(why, session, have != null)) redial(gpa, path, session, why, have, true, null) else null) orelse return null, why, false)) orelse return null; defer { if (have) |h| h.store(gpa, j) else gpa.free(j.dump); j.dump = &.{}; } return fromDump(gpa, j, o, have, why, t0, session); } /// The replica of the dump `j` brought, its load checked by the session's /// digest (its emulators' among it), and what it takes of `j`. One that /// does not load as the session names the fields that differ (the digest a /// field at a time each join's dump ends with: `loadDiffers`) in the log /// and asks once more over its link (`loadAgain`); a second that does not /// either, or a link that cannot ask, is given up, the fields named in /// `why`. Null, and why in `why`. fn fromDump(gpa: Allocator, j: *Joined, o: pardes.Options, have: ?*Have, why: []u8, t0: u64, session: []const u8) ?*Replica { var twice = false; while (true) { var refused: std.ArrayList(u8) = .empty; defer refused.deinit(gpa); const r = Replica.made(gpa, j.client, j.view, o, j.dump, &refused) catch |err| { // The loader's first words name the field it refused. const first = refused.items[0..@min(400, std.mem.indexOfScalar(u8, refused.items, '\n') orelse refused.items.len)]; _ = std.fmt.bufPrint(why, "the session's dump would not load: {t}{s}{s}\x00", .{ err, if (first.len > 0) ": " else "", first }) catch {}; return null; }; if (r.loaded(j.digest)) { takeJoined(r, j, have, t0); return r; } var named: [400]u8 = undefined; const fields = loadDiffers(r, j.dump, &named); r.deinit(); log.warn("client {d}: the session's dump loaded as another session{s}: {s}", .{ j.client, if (twice) " twice" else "", fields }); _ = said(why, "the session's dump loaded as another session{s}: {s}differs", .{ if (twice) " twice" else "", fields }); if (twice or !loadAgain(gpa, j, have, why, session)) return null; twice = true; } } /// Its link asks for the session's state once more: the dump it had let /// go, the join read on that link into `j`. False when the link is gone /// (`why` and `j` kept) or the join ended first (why in `why`). fn loadAgain(gpa: Allocator, j: *Joined, have: ?*Have, why: []u8, session: []const u8) bool { if (!comeBack(j.fd, session, j.view)) return false; if (have) |h| h.store(gpa, j) else gpa.free(j.dump); j.dump = &.{}; const rest = j.rest; j.rest = .{}; j.* = joinOn(gpa, j.fd, null, why, have, null, null, rest) orelse return false; return true; } /// The fields a replica loaded from the join's dump `bytes` has other than /// the session as it dumped them (the digest a field at a time the dump /// ends with: dump.joinParts), named in `out`. pub fn loadDiffers(r: *Replica, bytes: []const u8, out: []u8) []const u8 { const want = pardes.dump.joinParts(r.gpa, bytes) orelse return "(the dump names no field) "; defer r.gpa.free(want); var arena: std.heap.ArenaAllocator = .init(r.gpa); defer arena.deinit(); const got = arena.allocator().create(tape.Parts) catch return ""; const was = Stepping.begin(&r.t, &r.epoch); const parts = tape.digestParts(r.core(), got); was.end(); const fields = tape.partsDiffer(parts, want, arena.allocator()); return std.fmt.bufPrint(out, "{s}", .{fields[0..@min(fields.len, out.len)]}) catch out; } /// What a replica joined by `j` takes of it, and of the environment. fn takeJoined(r: *Replica, j: *Joined, have: ?*Have, t0: u64) void { // PARDES_NO_ECHO: no predicted echo (the gates' baseline). if (std.c.getenv("PARDES_NO_ECHO") != null) r.echo.on = false; // PARDES_REPLICA_STATS: its timing samples kept, for its line. r.stats.samples = std.c.getenv("PARDES_REPLICA_STATS") != null; r.gmtoff = j.gmtoff; // On the session's machine: a file read sent by hash is read here; // far, it goes to the disk for the next join. r.t.local_files = have == null; if (have) |h| { r.cache = h.cache; r.io = h.io; } j.ms = (nowNs() - t0) / std.time.ns_per_ms; } /// A pair's first join (Options.pair): its own core made (`Replica.initBoot`) /// and its digest said before its `far`, nothing waited for: the welcome is /// read once its first frame is drawn (`confirmBoot`). Its welcome's words /// meanwhile are what the session's first join gives: its first client's /// id, this process's time zone (the same machine), this build. fn ownBoot(gpa: Allocator, j: *Joined, fd: c_int, o: pardes.Options, why: *[600]u8) ?*Replica { const t0 = nowNs(); const r = Replica.initBoot(gpa, o) catch |err| { _ = std.fmt.bufPrint(why, "this client could not start the session's file itself: {t}\x00", .{err}) catch {}; return null; }; const digest = r.digest(); var out: [64]u8 = undefined; const said_boot = wire.encodeClient(&out, .{ .boot = digest }) catch unreachable; const said_far = wire.encodeClient(out[said_boot.len..], .{ .far = false }) catch unreachable; if (!writeAll(fd, out[0 .. said_boot.len + said_far.len])) { r.deinit(); _ = std.fmt.bufPrint(why, "the session hung up\x00", .{}) catch {}; return null; } j.* = .{ .fd = fd, .pid = 0, .client = r.id, .view = r.view, .gmtoff = gmtoff(), .dump = &.{}, .digest = digest, .semantics = wire.semantics, .booted = true }; takeJoined(r, j, null, t0); return r; } /// A pair's first client's welcome (`ownBoot`), read once its first frame is /// drawn: the session's core at its join the one this client made itself /// (the same digest), `r` goes on and nothing more comes; or not (the file /// changed between the two reads, anything else a start reads otherwise): /// the dump the session sent instead, loaded, `r` let go, and the dump's /// replica returned in its place. Null, and why in `why`, when the session /// hung up or runs another build, or its dump would not load. pub fn confirmBoot(gpa: Allocator, j: *Joined, r: *Replica, o: pardes.Options, why: *[600]u8) ?*Replica { const t0 = nowNs(); const digest = j.digest; j.* = sameBuild(gpa, joinOn(gpa, j.fd, null, why, null, null, digest, .{}) orelse return null, why, false) orelse return null; if (j.dump.len == 0) { r.id = j.client; r.view = j.view; return r; } defer { gpa.free(j.dump); j.dump = &.{}; } const loaded = fromDump(gpa, j, o, null, why, t0, "") orelse return null; r.deinit(); return loaded; } /// `j`, when its session runs this build; else its link let go, and why in /// `why`: the daemon judged the hello by what the session last said, which /// an upgrade under way may not have said yet. `again`: it was a rejoin for /// the view the session kept, which the welcome gave it: kept again for it /// (its bye's `again`), for the build at its start path, exec'd, to come /// back to (client.zig `execAgain`); closed, it came back in a new view, /// its own lost (1 in 4 Upgrades on one CPU, 2026-11-22). fn sameBuild(gpa: Allocator, j: Joined, why: []u8, again: bool) ?Joined { if (j.semantics == wire.semantics) return j; bye(j.fd, .{ .again = again }); _ = libc.close(j.fd); var jj = j; jj.rest.deinit(gpa); gpa.free(j.dump); _ = std.fmt.bufPrint(why, "{s}\x00", .{upgrade_words}) catch {}; return null; } /// The session again, after a divergence or an upgrade: an upgrade's /// takes the time its exec and load take, and its daemon's, so it is /// dialled every 100 ms for 20 s. Null, and why in `why`. The session's /// own word that it is upgrading (`Peers.refuseAll`, until its exec) is /// not a try: it is there, writing its dump for as long as that takes (a /// 24 s write let every client go for good, 2026-11-22). /// `patient`: after an Upgrade's `refused` alone, while the session is /// away a moment; after a divergence a session that will not answer is /// gone, and the client says so at once (it froze 20 s, 2026-10-30). /// `view`: the one it had, which the session kept for it (views.away); /// none for a first join that met an Upgrade. fn redial(gpa: Allocator, path: []const u8, session: []const u8, why: *[600]u8, have: ?*Have, patient: bool, view: ?u8) ?Joined { var tries: u32 = 0; while (true) { why.* = @splat(0); if (dial(gpa, path, session, why, have, view)) |j| return sameBuild(gpa, j, why, view != null); // Another build, or another protocol (the daemon moved with its // session): no dial again will do. const words = std.mem.sliceTo(why, 0); if (std.mem.indexOf(u8, words, "runs another build") != null or std.mem.indexOf(u8, words, "run the same pardes at both ends") != null) { _ = std.fmt.bufPrint(why, "{s}\x00", .{upgrade_words}) catch {}; return null; } // Its daemon lists no such session: it is gone, not away a moment // (an Upgrade keeps it listed throughout). if (std.mem.startsWith(u8, words, "no session called ")) return null; if (!std.mem.eql(u8, words, upgrading)) { if (!patient or tries > 200) return null; tries += 1; } const ts: libc.timespec = .{ .sec = 0, .nsec = 100 * std.time.ns_per_ms }; _ = libc.nanosleep(&ts, null); } } /// How far behind its session a client may fall before it lets its link go /// and joins again from a dump (P32 (b)): near and far alike. pub const behind_max_ms = 2_000; /// A replica client's link to its session, the terminal's (tui.zig /// `runClient`) and the window's (gui.zig `runClient`): its replica, its socket, /// what the session said, and what it checks. Drawing is the frontend's. pub const Link = struct { r: *Replica, fd: c_int, quit: bool = false, /// ...because its window was closed: said in its bye. close: bool = false, /// The session hung up. gone: bool = false, /// Something to draw: an input applied, a unit taken. dirty: bool = true, /// The last frame was held for the frontend's answer (a terminal's /// FrameAck, a window's skipped image). owed: bool = false, /// Once quiet a while after a change, the session's digest is asked /// (`quietCheck`): another than this replica's is a divergence, and it /// joins again. PARDES_REPLICA_CHECK=: whether they agree is /// written there too, a line a check. check: ?[:0]const u8 = null, changed: bool = false, asked: bool = false, /// When its own last input was, and its last check asked (`quietCheck` /// waits a while after each). input_ns: u64 = 0, asked_ns: u64 = 0, /// The clock those read, when not the machine's: a simulation's (the /// soak's, test/replicas.zig), as `Echo.now` is. now: ?u64 = null, /// How many of its own inputs the session recorded otherwise when it /// last drew: a frame after one that draws something is a rollback that /// may have been seen (counted so: an upper bound, the frame shows the /// inputs after it too). mispredicted: u32 = 0, visible: u32 = 0, /// What the session said as it let this client go (the C heap's). refused: ?[]u8 = null, /// Its last word: it ended, with this code; or this client left it. ended: ?u8 = null, left: bool = false, /// A line over its frame, until its next key (`notify`): why it joined /// again. The client's own, never the session's core. notice_buf: [240]u8 = undefined, notice_len: usize = 0, /// PARDES_TEST_DIVERGE=: once quiet after its n-th unit, its core /// is put off the session's (a digested counter moved), the next unit's /// digest finds it, and it joins again (test/daemon.py). test_diverge: u32 = 0, /// Put off so in this join: its checks are not written (they differ). put_off: bool = false, /// How its last join went (Joined's counts), and how long its dial and /// load took (PARDES_REPLICA_STATS). join: struct { blobs: u32 = 0, from_memory: u32 = 0, from_disk: u32 = 0, sent_bytes: u64 = 0 } = .{}, join_ms: u64 = 0, /// Its view's yanks, pastes and links (Pardes.View.yanks) its /// frontend has done: from the joined dump's, so a join does none /// again (client.zig `asks`). yanks: u32 = 0, pastes: u32 = 0, links: u32 = 0, /// Frames it drew whole (`drawn`), and the last one presented again /// moved on (its own motion), for PARDES_REPLICA_STATS. draws: u32 = 0, again: u32 = 0, /// How far behind the session it is, ns: each unit's head carries the /// session's monotonic clock as it was made; against this client's own, /// less the smallest difference seen (the clocks' offset and the link's /// quickest crossing). This machine's clock, the link's alone: no step /// reads it and no digest holds it (`lags`). behind: u64 = 0, least: ?i64 = null, /// No unit taken since it joined (`lags`). fresh: bool = true, /// How far behind it was as it let its link go (`rejoins` says so). lagged: u64 = 0, /// Its link crosses machines (a `Have`: ssh's forward, a relay): fallen /// behind, it dials again (`backHere`). far: bool = false, /// A pair's first join, its own boot not confirmed yet: its inputs /// kept here, not sent (`release`; client.zig `confirm`). held: ?std.ArrayListUnmanaged(u8) = null, /// It comes back over this link (`backHere`, `comeBack`): its reader lets /// the stream it leaves go and stops at the session's welcome there /// (`readLink`). Set by the client's loop, read by its link's reader. back: std.atomic.Value(bool) = .init(false), fn time(c: *const Link) u64 { return c.now orelse nowNs(); } /// The test knobs the environment sets (PARDES_REPLICA_CHECK, /// PARDES_TEST_DIVERGE). pub fn fromEnv(c: *Link, gpa: Allocator, env: *const std.process.Environ.Map) !void { if (env.get("PARDES_REPLICA_CHECK")) |file| c.check = try gpa.dupeSentinel(u8, file, 0); if (env.get("PARDES_TEST_DIVERGE")) |n| c.test_diverge = std.fmt.parseInt(u32, n, 10) catch 0; } pub fn deinit(c: *Link, gpa: Allocator) void { if (c.check) |file| gpa.free(file); if (c.refused) |words| std.heap.c_allocator.free(words); } /// Join `j`'s link, from its start, and how that join went. pub fn reset(c: *Link, r: *Replica, j: *const Joined) void { c.r = r; c.fd = j.fd; c.join = .{ .blobs = j.blobs, .from_memory = j.from_memory, .from_disk = j.from_disk, .sent_bytes = j.sent_bytes }; c.join_ms = j.ms; c.quit = false; c.gone = false; c.dirty = true; c.owed = false; c.changed = false; c.asked = false; c.mispredicted = 0; c.put_off = false; c.behind = 0; c.fresh = true; c.back.store(false, .release); if (r.core().views[r.view]) |v| { c.yanks = v.yanks; c.pastes = v.pastes; c.links = v.links; } } /// What was held (`held`) sent, or, its replica not the one they were /// pended on (`send` false), dropped. pub fn release(c: *Link, gpa: Allocator, send: bool) void { var h = c.held orelse return; c.held = null; defer h.deinit(gpa); if (send and !writeAll(c.fd, h.items)) c.cut(); } pub fn notify(c: *Link, comptime fmt: []const u8, args: anytype) void { const text = std.fmt.bufPrint(&c.notice_buf, fmt, args) catch c.notice_buf[0..]; for (text) |*b| if (b.* < 0x20 or b.* > 0x7e) { b.* = '?'; }; c.notice_len = text.len; } pub fn notice(c: *const Link) []const u8 { return c.notice_buf[0..c.notice_len]; } /// The frontend's input: applied at once, and sent to the session. pub fn input(c: *Link, ev: pardes.Event) void { // Its notice read: a key of its own puts it away. if (c.notice_len > 0 and (ev == .key or ev == .paste)) c.notice_len = 0; c.input_ns = c.time(); // Sent first: the session steps it while this replica speculates. const msg = c.r.pend(ev) catch return; if (c.held) |*h| { h.appendSlice(c.r.gpa, msg[head_len..]) catch c.cut(); } else if (!sendInput(c.fd, msg)) c.cut(); c.r.applyPended(ev); c.dirty = true; } /// What the session streamed, in its order; the bytes are let go. pub fn take(c: *Link, msg: Said) void { switch (msg) { .unit => |bytes| { defer std.heap.c_allocator.free(bytes); if (c.quit or c.lags(bytes)) return; c.r.confirm(bytes); if (c.test_diverge != 0 and c.r.stats.units >= c.test_diverge and c.r.quiet()) { c.test_diverge = 0; c.put_off = true; c.r.core().next_serial +%= 1000; } if (c.r.moved) c.dirty = true; c.r.moved = false; // One while a check is asked is the answer's: it comes // after it in the stream and its digest covers it. if (!c.asked) c.changed = true; }, .blob => |bytes| { defer std.heap.c_allocator.free(bytes); c.r.blobPiece(bytes); }, .checked => |d| c.checked(d), .refused => |words| { if (c.refused) |old| std.heap.c_allocator.free(old); c.refused = words; c.quit = true; }, .ended => |code| { c.ended = code; c.quit = true; }, .left => { c.left = true; c.quit = true; }, } if (c.r.diverged != null) c.quit = true; } /// Its own view drawn, by the frontend (`drew` is whether anything was /// written to it): a rollback it may have shown counted. pub fn drawn(c: *Link, drew: bool) void { if (c.r.stats.mispredicted > c.mispredicted) { c.mispredicted = c.r.stats.mispredicted; if (drew) c.visible += 1; } c.dirty = false; c.draws += 1; // What moved before this frame is in it: not drawn again at the // next unit (a stopped input's rollback, under its own frame). c.r.moved = false; } /// The session's unit `bytes`, taken now: how far behind it is. Past /// `behind_max_ms` it lets its link go (true), to join again from a dump. /// The first unit after a join past it is taken as the link now (a /// session's clock stood still while its machine slept; a dump that took /// longer than the bound to come), never a let-go again at once. fn lags(c: *Link, bytes: []const u8) bool { const u = parseUnit(bytes) orelse return false; const d = @as(i64, @intCast(c.time())) - u.mono_ns; const max = behind_max_ms * std.time.ns_per_ms; if (c.fresh and d - (c.least orelse d) > max) c.least = d; c.fresh = false; c.least = @min(c.least orelse d, d); c.behind = @intCast(d - c.least.?); if (c.behind <= max) return false; c.lagged = c.behind; c.quit = true; return true; } /// A write to the session failed: it hung up (it cut this client off, /// lagging), as its reader will say. fn cut(c: *Link) void { c.quit = true; c.gone = true; } /// Each pass of the frontend's loop: quiet (nothing of its own /// pending) 300 ms after its last input and its last check, and /// changed since, the session's digest is asked once, answered in /// stream order after the units before it (a session that pumps on, a /// window's test feed, sends a unit a frame; the check's own wakes it /// once). The wake it wants, ms. pub fn quietCheck(c: *Link) ?u32 { if (!c.changed or c.asked or !c.r.quiet()) return null; const quiet_ns = 300 * std.time.ns_per_ms; const since = c.time() -| @max(c.input_ns, c.asked_ns); if (since < quiet_ns) return @intCast((quiet_ns - since) / std.time.ns_per_ms + 1); c.changed = false; c.asked = askCheck(c.fd); if (!c.asked) c.cut(); c.asked_ns = c.time(); return null; } /// The session's digest against this replica's, if it is quiet still: /// another is a divergence (the replica joins again). fn checked(c: *Link, theirs: u64) void { c.asked = false; // Not quiet now, the answer is let go: it covers nothing, and the // next quiet asks again. Nor once its link is let go: a lag's let-go // drops the units after it (`lags`), and the core is behind them. if (c.quit or !c.r.quiet() or c.r.diverged != null) { c.changed = true; return; } const mine = c.r.digest(); c.r.stats.checks += 1; c.r.since_check = 0; if (mine != theirs) { c.r.fail("its digest, quiet, is not the session's"); c.quit = true; } const path = c.check orelse return; if (c.put_off) return; var buf: [96]u8 = undefined; const line = (if (mine == theirs) std.fmt.bufPrint(&buf, "agree {x:0>16}\n", .{mine}) else std.fmt.bufPrint(&buf, "differ {x:0>16} {x:0>16}\n", .{ mine, theirs })) catch return; appendTo(path, line); } /// PARDES_REPLICA_STATS=: how its inputs and the session's units /// went, a line at its end (test/daemon.py, the gates). pub fn writeStats(c: *Link, path: []const u8) void { const st = &c.r.stats; 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} 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, st.rebases, st.copies, st.checks, }) catch return; // What stopped its inputs, last: a word a pair before it. w.writeAll(" stops ") catch return; st.writeStops(&w) catch return; w.writeByte('\n') catch return; var z: [4096]u8 = undefined; appendTo(std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return, w.buffered()); } /// Its loop ended with its link up and a reason to take the session's /// state again (it diverged, fell behind, or the session's words came: /// a cut's keep the link, an Upgrade's and a Restore's end it, which the /// join there finds): its goodbye and hello are said on it (`comeBack`). /// One that is gone, or a last word, is not. /// THE SECOND ROAD: a far client that fell behind dials again (a new /// connection; the one it leaves is shut): over its own link it would /// first read through all that link holds for it, which a relay or a /// forward buffers without bound (test/daemon.py `far_flood`: 49-68 s /// to agree after the flood against 22.7 s by a dial). Bounded flight /// (the session never more than a window past what its client has /// taken) replaces it, and this line goes. pub fn backHere(c: *const Link) bool { if (c.far and c.lagged != 0) return false; return !c.gone and c.ended == null and !c.left and (c.r.diverged != null or c.lagged != 0 or c.refused != null); } /// The link ended: whether the client joins again, and why in its /// notice (it diverged, it fell too far behind, or the session let it /// go: to upgrade, or cut off). pub fn rejoins(c: *Link) bool { if (c.r.diverged) |reason| { c.notify("joined again: this client diverged from the session ({s})", .{reason}); return true; } if (c.lagged != 0) { c.notify("joined again: {d}.{d} s behind", .{ c.lagged / std.time.ns_per_s, c.lagged / (std.time.ns_per_s / 10) % 10 }); c.lagged = 0; return true; } if (c.refused) |words| { if (!std.mem.eql(u8, words, restore_words)) c.notify("joined again: {s}", .{words}); std.heap.c_allocator.free(words); c.refused = null; return true; } return false; } }; fn appendTo(path: [:0]const u8, line: []const u8) void { const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644)); if (fd < 0) return; _ = libc.write(fd, line.ptr, line.len); _ = libc.close(fd); } pub fn digestOf(a: *Authority) u64 { const was = Stepping.begin(&a.t, null); defer was.end(); return tape.digestOf(a.core); } const TestHost = struct { fn watched(_: ?*anyopaque) bool { return false; } const vtable: pardes.Host.VTable = .{ .watched = watched }; fn host() pardes.Host { return .{ .vtable = &vtable }; } }; /// A host with ptys whose pump polls for a frame, as a client's does. const PtyHost = struct { fn resized(_: ?*anyopaque, _: pardes.Pane.Id, _: pardes.PtySize) void {} fn poll(_: ?*anyopaque) void {} const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .pty_resize = resized, .poll_frame = poll }; fn host() pardes.Host { return .{ .vtable = &vtable }; } }; /// A kind as a library brings one, its state not plain (no PA_PLAIN): a /// counter its keys move, painted as `count N`. const Counter = struct { const pa = pardes.Kind.c; fn open(_: [*c]const u8, _: [*c]const u8, _: u64) callconv(.c) ?*anyopaque { return pardes.Kind.api.alloc.?(4); } fn paint(st: ?*anyopaque, win: [*c]const pa.pa_window, _: [*c]pa.pa_paint) callconv(.c) void { const n: *u32 = @ptrCast(@alignCast(st.?)); var line: [16]u8 = undefined; const text = std.fmt.bufPrint(&line, "count {d}", .{n.*}) catch unreachable; for (text, 0..) |ch, i| win.*.cells[i] = std.mem.zeroInit(pa.pa_cell, .{ .text = .{ ch, 0, 0, 0, 0, 0, 0, 0 }, .len = 1, .flags = pa.PA_PAINTED, .fg = pa.PA_DEFAULT, .bg = pa.PA_DEFAULT }); } fn press(st: ?*anyopaque, _: [*c]const pa.pa_key) callconv(.c) c_int { const n: *u32 = @ptrCast(@alignCast(st.?)); n.* += 1; return 1; } const words = [_]pa.pa_word{std.mem.zeroInit(pa.pa_word, .{ .name = "Counter", .opens = 1, .doc = "a counter" })}; 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 = "counter".* ++ @as([9]u8, @splat(0)), .version = 1, .exts = "", .words = &words, .nwords = 1 }), .open = open, .paint = paint, .key = press, }); }; /// An edit's file time is the clock's second, which a replica guesses: a /// second's turn between a key and the authority's take of it is a fair /// misprediction (11 runs in 40 of a loaded Debug window build's test /// below). The tests that count fast confirmations start early in a second. fn freshSecond() void { while (true) { var ts: std.c.timespec = undefined; if (std.c.clock_gettime(.REALTIME, &ts) != 0 or ts.nsec < 50 * std.time.ns_per_ms) return; const rest: std.c.timespec = .{ .sec = 0, .nsec = std.time.ns_per_s - ts.nsec }; _ = std.c.nanosleep(&rest, null); } } fn key(r: *Replica, cp: u21, sent: *std.ArrayListUnmanaged([]u8)) !void { const text = [_]u8{@intCast(cp & 0x7f)}; const msg = try r.input(.{ .key = .{ .cp = cp, .text = if (cp < 0x80 and cp >= 0x20) &text else "" } }); try sent.append(std.testing.allocator, try std.testing.allocator.dupe(u8, msg)); } /// The blob cache of a test, in its own directory (never the user's). fn testCache(tmp: *std.testing.TmpDir, buf: *[4200]u8, cap: u64) !Cache { 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)]; return Cache.of(try std.fmt.bufPrint(buf, "{s}/" ++ Cache.name, .{dir}), cap); } /// A far join over a socket pair, the session's writer and reader threads /// against the client's `joinOn`, as the daemon hands a connection over: /// its hello read off first. fn farJoinOnce(ps: *Peers, core: *Pardes, have: ?*Have) !Joined { var fds: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; const state = (pardes.dump.dumpJoin(core, &blobs) catch |err| { _ = libc.close(fds[0]); _ = libc.close(fds[1]); return err; }).bytes; var whole = state.len; for (blobs.items) |b| whole += b.bytes.len; const peer = try ps.gpa.create(Peer); peer.* = .{ .peers = ps, .fd = fds[0], .id = 1, .view = .at(0), .dump = state, .blobs = blobs, .dump_gpa = core.gpa }; peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = 1, .session = "t", .dump_len = whole, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len; const Serve = struct { fn run(p: *Peer) void { var hello: [wire.header_len + 14]u8 = undefined; var got: usize = 0; while (got < hello.len) { const n = libc.read(p.fd, hello[got..].ptr, hello.len - got); if (n <= 0) return p.peers.post(.{ .gone = p }); got += @intCast(n); } p.readLoop(); } }; peer.writer = try std.Thread.spawn(.{}, Peer.writeLoop, .{peer}); peer.reader = try std.Thread.spawn(.{}, Serve.run, .{peer}); defer ps.letGo(peer); var why: [300]u8 = @splat(0); return joinOn(std.testing.allocator, fds[1], "t", &why, have, null, null, .{}) orelse { std.debug.print("the join failed: {s}\n", .{std.mem.sliceTo(&why, 0)}); return error.JoinFailed; }; } fn endJoin(j: *Joined, have: ?*Have) void { _ = libc.close(j.fd); j.rest.deinit(std.testing.allocator); if (have) |h| { h.store(std.testing.allocator, j); h.wait(); } else { std.testing.allocator.free(j.dump); std.heap.c_allocator.free(j.got); } } /// A replica joined from the session's dump as it is now, between units, /// as `Peers.join` sends it: its state, its blobs put back where they go. fn joinedNow(a: *Authority, id: u16, view: u8) !*Replica { const gpa = std.testing.allocator; // What was recorded goes first, as a join sends it (Peers.dumped): // left on the tape, the joiner's first unit replayed it over the dump // it loaded (a session's `init` first: a core made afresh). a.seq += 1; _ = try a.unit(0, a.seq); const was = Stepping.begin(&a.t, null); var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; defer blobs.deinit(a.core.gpa); const state = (try pardes.dump.dumpJoin(a.core, &blobs)).bytes; defer a.core.gpa.free(state); tape.resync(&a.t); was.end(); var whole: std.ArrayListUnmanaged(u8) = .empty; defer whole.deinit(gpa); var pos: usize = 0; for (blobs.items) |b| { try whole.appendSlice(gpa, state[pos..b.at]); try whole.appendSlice(gpa, b.bytes); pos = b.at; } try whole.appendSlice(gpa, state[pos..]); return Replica.initDump(gpa, id, view, whole.items, .{ .cols = 80, .rows = 24 }); } fn agrees(a: *Authority, r: *Replica) !void { if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); try std.testing.expect(r.diverged == null); try std.testing.expect(r.quiet()); try std.testing.expectEqual(digestOf(a), r.digest()); } fn inputOf(buf: []u8, client: u16, seq: u32, ev: pardes.Event) ![]const u8 { const n = (try wire.encodeClient(buf[head_len..], .{ .event = ev })).len; header(buf, client, seq); return buf[0 .. head_len + n]; } /// An input of a replica's in the session's order, as `Peers.input` takes /// it: the step, then its unit to every replica. fn takeAll(a: *Authority, rs: []const *Replica, msg: []const u8) !void { const gpa = std.testing.allocator; const u = try gpa.dupe(u8, try a.take(msg)); defer gpa.free(u); for (rs) |r| { r.confirm(u); r.settle(); } } fn sendAs(r: *Replica, a: *Authority, rs: []const *Replica, ev: pardes.Event) !void { const msg = try std.testing.allocator.dupe(u8, try r.input(ev)); defer std.testing.allocator.free(msg); try takeAll(a, rs, msg); } fn shows(p: *Pardes, text: []const u8) !bool { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const s = try p.render(arena.allocator()); var row: [512]u8 = undefined; for (0..s.rows) |y| { var n: usize = 0; for (0..s.cols) |x| { const g = s.at(@intCast(x), @intCast(y)).grapheme(); if (n + g.len > row.len) break; @memcpy(row[n..][0..g.len], g); n += g.len; } if (std.mem.indexOf(u8, row[0..n], text) != null) return true; } return false; } test "a client joined from a dump keeps the session's jump list through a step: two entries the same but for their place's undefined bytes are one entry on both" { // The release soak's parting (the witness: `views[3].jumps`): a text's // entry has `.place = .{}`, bytes undefined: a session's are its // stack's (here 0x11 and 0x22, the two a release build left), a // client's what its load left; the step drops the gone entry between // the two and makes them one where they compare the same. const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const v = a.core.view(); const serial = a.core.panes[v.active].?.serial; var at: pardes.Jump.Loc = .{ .pane = @intCast(v.active), .serial = serial, .line = 1, .col = 1 }; var again = at; @memset(&at.place.bytes, 0x11); @memset(&again.place.bytes, 0x22); v.jumps.list[0] = at; v.jumps.list[1] = .{ .pane = 5, .serial = 999, .line = 1, .col = 1 }; v.jumps.list[2] = again; v.jumps.list[3] = .{ .pane = @intCast(v.active), .serial = serial, .line = 150, .col = 1 }; v.jumps.n, v.jumps.cur = .{ 4, 3 }; const r = try joinedNow(a, 1, 0); defer r.deinit(); r.confirm(try a.local(.{ .key = .{ .cp = 'l', .text = "l" } })); try agrees(a, r); try std.testing.expectEqual(@as(usize, 2), r.core().view().jumps.n); } test "a message past the wire's bound is named, never read as the link's end" { var fds: [2]c_int = undefined; try std.testing.expectEqual(0, libc.pipe(&fds)); const head = wire.header(@backingInt(wire.ServerTag.unit), wire.max_payload + 1); _ = libc.write(fds[1], &head, head.len); _ = libc.close(fds[1]); var fr: Framer = .{}; defer fr.deinit(std.testing.allocator); fr.run(std.testing.allocator, fds[0], {}, struct { fn take(_: void, _: u8, _: []const u8) bool { return true; } }.take); _ = libc.close(fds[0]); try std.testing.expectEqual(wire.max_payload + 1, fr.overlong().?); } test "a client joining again after a divergence is told at once that its session is gone" { var why: [600]u8 = undefined; const t0 = nowNs(); try std.testing.expect(redial(std.testing.allocator, "/nonexistent/pardes-replica.sock", "gone", &why, null, false, 1) == null); try std.testing.expect(nowNs() - t0 < 100 * std.time.ns_per_ms); try std.testing.expect(ended(&why)); // Its session ending as it joins: hung up before the dump was whole, // its end too, said as the end it is. var fds: [2]c_int = undefined; try std.testing.expectEqual(0, libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM, 0, &fds)); _ = libc.close(fds[1]); try std.testing.expect(joinOn(std.testing.allocator, fds[0], "gone", &why, null, 1, null, .{}) == null); try std.testing.expect(ended(&why)); } test "an Upgrade tells a client handed to the session and not joined yet that it is upgrading, as it tells its clients; one handed after it is told so at once: each dials again" { var ps: Peers = .{ .gpa = std.testing.allocator, .io = std.testing.io }; defer ps.deinit(); var fds: [2][2]c_int = undefined; for (&fds) |*f| try std.testing.expectEqual(0, libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM, 0, f)); // Handed by the daemon, waiting for the next step boundary; then the // Upgrade's word to the clients (no client joined: count() is 0), and // a hand-over after it, before the exec. ps.handed(fds[0][0], null); ps.refuseAll(undefined); ps.handed(fds[1][0], null); try std.testing.expectEqual(0, ps.inbox.items.len); for (fds) |f| { defer _ = libc.close(f[1]); var buf: [600]u8 = undefined; const n = libc.read(f[1], &buf, buf.len); try std.testing.expect(n > wire.header_len); const msg = try wire.decodeServer(buf[0], buf[wire.header_len..@intCast(n)]); try std.testing.expectEqualStrings(upgrading, msg.refused); try std.testing.expectEqual(0, libc.read(f[1], &buf, buf.len)); } // Its exec failed: the session goes on, and takes joins again. ps.boundary(undefined); ps.handed(-1, null); try std.testing.expectEqual(1, ps.inbox.items.len); } test "a replica's own keys apply at once, confirm on the fast path, and end at the authority's digest" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); try std.testing.expectEqual(digestOf(a), r.digest()); var sent: std.ArrayListUnmanaged([]u8) = .empty; defer { for (sent.items) |m| gpa.free(m); sent.deinit(gpa); } freshSecond(); for ("oabc") |k| try key(r, k, &sent); try key(r, pardes.Key.escape, &sent); try std.testing.expectEqual(@as(usize, 5), r.applied); for (sent.items) |m| { r.confirm(try a.take(m)); r.settle(); } if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); try std.testing.expect(r.diverged == null); try std.testing.expectEqual(@as(u32, 5), r.stats.fast); try std.testing.expect(r.quiet()); try std.testing.expectEqual(digestOf(a), r.digest()); } test "an input's time is its client's: an edit's second confirms on the fast path though the authority takes it in the next" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); var sent: std.ArrayListUnmanaged([]u8) = .empty; defer { for (sent.items) |m| gpa.free(m); sent.deinit(gpa); } try key(r, 'o', &sent); for (sent.items) |m| { r.confirm(try a.take(m)); r.settle(); } // Typed 30 ms before a second's turn, taken 30 ms after it: the edit's // file time is the clock's second, read in the step. while (true) { var ts: std.c.timespec = undefined; _ = std.c.clock_gettime(.REALTIME, &ts); if (ts.nsec >= 970 * std.time.ns_per_ms) break; const rest: std.c.timespec = .{ .sec = 0, .nsec = 970 * std.time.ns_per_ms - ts.nsec }; _ = std.c.nanosleep(&rest, null); } try key(r, 'x', &sent); try std.testing.expectEqual(@as(usize, 1), r.applied); const late: std.c.timespec = .{ .sec = 0, .nsec = 60 * std.time.ns_per_ms }; _ = std.c.nanosleep(&late, null); r.confirm(try a.take(sent.items[1])); r.settle(); try std.testing.expect(r.diverged == null and r.quiet()); try std.testing.expectEqual(@as(u32, 2), r.stats.fast); try std.testing.expectEqual(@as(u32, 0), r.stats.mispredicted); try std.testing.expectEqual(digestOf(a), r.digest()); } test "another client's input first: a replica rolls back, replays it and applies its own again" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const first = try gpa.dupe(u8, try a.unit(0, 0)); defer gpa.free(first); const r1 = try Replica.init(gpa, 1, first); defer r1.deinit(); const r2 = try Replica.init(gpa, 2, first); defer r2.deinit(); var s1: std.ArrayListUnmanaged([]u8) = .empty; var s2: std.ArrayListUnmanaged([]u8) = .empty; defer { for (s1.items) |m| gpa.free(m); for (s2.items) |m| gpa.free(m); s1.deinit(gpa); s2.deinit(gpa); } freshSecond(); for ("oone") |k| try key(r1, k, &s1); for ("Otwo") |k| try key(r2, k, &s2); // The authority hears r2 first, then r1; both hear the units in that // order. for ([_]*std.ArrayListUnmanaged([]u8){ &s2, &s1 }) |list| for (list.items) |m| { const u = try gpa.dupe(u8, try a.take(m)); defer gpa.free(u); r1.confirm(u); r1.settle(); r2.confirm(u); r2.settle(); }; for ([_]*Replica{ r1, r2 }) |r| { if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); try std.testing.expect(r.diverged == null); try std.testing.expect(r.quiet()); try std.testing.expectEqual(digestOf(a), r.digest()); } try std.testing.expect(r1.stats.foreign >= 1); try std.testing.expectEqual(@as(u32, 4), r2.stats.fast); } test "the copy taken for an input of its own stays once the input is confirmed: the next takes none, and a rollback replays the first over it" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const first = try gpa.dupe(u8, try a.unit(0, 0)); defer gpa.free(first); const r = try Replica.init(gpa, 1, first); defer r.deinit(); var sent: std.ArrayListUnmanaged([]u8) = .empty; defer { for (sent.items) |m| gpa.free(m); sent.deinit(gpa); } freshSecond(); try key(r, 'j', &sent); const copies = r.stats.copies; r.confirm(try a.take(sent.items[0])); try std.testing.expect(r.copy.held); try std.testing.expectEqual(@as(usize, 1), r.since.items.len); try key(r, 'j', &sent); try std.testing.expectEqual(copies, r.stats.copies); // The session's own key first: back to the copy, the first replayed. r.confirm(try a.local(.{ .key = .{ .cp = 'l', .text = "l" } })); r.settle(); r.confirm(try a.take(sent.items[1])); r.settle(); try agrees(a, r); try std.testing.expectEqual(@as(u32, 1), r.stats.foreign); } test "a client marks its view moved for a unit of the session's whose steps asked for a frame, and not for one whose steps asked none" { // The own frontend's rule (Pardes.pump): a unit that only read the // clock, or a ctl write's close, draws nothing; a client presented it // again (the corpus's pet: one picture twice). const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); // A client as a dial joins it: it draws none of its replay. const r = try joinedNow(a, 1, 0); defer r.deinit(); _ = r.draw(.{ .ctx = null, .f = null }); r.moved = false; r.confirm(try a.local(.{ .key = .{ .cp = 'l', .text = "l" } })); try std.testing.expect(r.moved); _ = r.draw(.{ .ctx = null, .f = null }); r.moved = false; a.pump(); r.confirm((try a.pending()).?); try std.testing.expect(!r.moved); try agrees(a, r); } 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()); defer a.deinit(); const r = try Replica.init(gpa, 1, try a.unit(0, 0)); 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), // a Tab undone left it, and the next replayed step measured the files' // tabs otherwise (the soak, five clients). const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const first = try gpa.dupe(u8, try a.unit(0, 0)); defer gpa.free(first); const r = try Replica.init(gpa, 1, first); defer r.deinit(); const was = r.core().settings.tab; const msg = try gpa.dupe(u8, try r.input(.{ .command = "Tab 2" })); defer gpa.free(msg); try std.testing.expectEqual(@as(usize, 1), r.applied); try std.testing.expectEqual(@as(u16, 2), r.core().settings.tab); // The session's own key first: back to the confirmed position. r.confirm(try a.local(.{ .key = .{ .cp = 'l', .text = "l" } })); try std.testing.expectEqual(was, r.core().settings.tab); r.settle(); r.confirm(try a.take(msg)); r.settle(); try agrees(a, r); } test "a closed terminal brought back on a screen-state replica: its emulator on the C heap, never the rollback epoch's" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host()); defer a.deinit(); const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.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.core.view().active = shell; r.confirm(try a.local(.{ .command = "Del" })); try std.testing.expectEqual(@as(usize, 1), a.core.store.closed.items.len); var line: [32]u8 = undefined; r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look @p{d}", .{a.core.store.closed.items[0].serial}) })); try std.testing.expect(r.diverged == null); const back = for (r.core().panes) |slot| { if (slot) |pane| if (pane.terminal) |state| break state; } else return error.NotBack; // Its deltas write it while a copy is held, and its screen replica's // blobs are freed with the C heap's (`deinit`): the epoch's, a rollback // freed what they held and the exit freed them behind its back (H21). try std.testing.expect(r.epoch.owns(@intFromPtr(back)) == null); } test "a view that sized a terminal closing leaves nothing queued: the others' replicas copy, type and agree" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, TestHost.host()); defer a.deinit(); const first = try gpa.dupe(u8, try a.unit(0, 0)); defer gpa.free(first); const r1 = try Replica.init(gpa, 1, first); defer r1.deinit(); const r2 = try Replica.init(gpa, 2, first); defer r2.deinit(); a.core.view().active = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break id; } else return error.NoShell; const opened = try a.openView(2); r2.view = opened.view; for ([_]*Replica{ r1, r2 }) |r| r.confirm(opened.unit); var sent: std.ArrayListUnmanaged([]u8) = .empty; defer { for (sent.items) |m| gpa.free(m); sent.deinit(gpa); } // The second client, at another size, types into the terminal: its // view sizes it. Then it goes (H10, 2026-10-30: the first aborted). try sent.append(gpa, try gpa.dupe(u8, try r2.input(.{ .resize = .{ .cols = 50, .rows = 20 } }))); try key(r2, 'x', &sent); for (sent.items) |m| { const u = try gpa.dupe(u8, try a.take(m)); defer gpa.free(u); r1.confirm(u); r1.settle(); } r1.confirm(try a.closeView(2)); try std.testing.expectEqual(@as(usize, 0), a.core.effects_len); try std.testing.expectEqual(@as(usize, 0), r1.core().effects_len); r1.ready(); try std.testing.expect(r1.copy.held); for (sent.items) |m| gpa.free(m); sent.clearRetainingCapacity(); try key(r1, 'y', &sent); r1.confirm(try a.take(sent.items[0])); r1.settle(); if (r1.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); try std.testing.expect(r1.diverged == null and r1.quiet()); try std.testing.expectEqual(digestOf(a), r1.digest()); } test "a unit that closes or tears down a terminal is never kept over a copy taken ahead: a rollback would close its emulator again" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host()); defer a.deinit(); const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); const text = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.file != null) break id; } else return error.NoTextPane; a.core.view().active = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break id; } else return error.NoShell; // The session closes its shell, and its next steps tear it down, while // the client is idle (a copy taken ahead each time). r.ready(); r.confirm(try a.local(.{ .command = "Del" })); a.core.view().active = text; for (0..3) |_| { r.ready(); r.confirm(try a.local(.{ .key = .{ .cp = 'j', .text = "j" } })); } // The client types, and the session's key comes first: a rollback. var sent: std.ArrayListUnmanaged([]u8) = .empty; defer { for (sent.items) |m| gpa.free(m); sent.deinit(gpa); } r.ready(); try key(r, 'l', &sent); r.confirm(try a.local(.{ .key = .{ .cp = 'o', .text = "o" } })); r.settle(); r.confirm(try a.take(sent.items[0])); r.settle(); if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); try std.testing.expect(r.diverged == null and r.quiet()); try std.testing.expectEqual(digestOf(a), r.digest()); // The shell closed once here as there (the store's record of it is made // as it closes, on the host's heap, which no copy puts back). 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()); errdefer a.deinit(); const r = try Replica.init(gpa, 1, try a.unit(0, 0)); 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: a session's reflow of a terminal's grid over a copy held ahead is the count's to decide: the copy goes, and a rollback does not reflow the grid again" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const b = try BytesPair.init(); defer b.deinit(); try b.output("a line long enough to wrap once the grid is narrower than it is now, and then some more\r\n"); b.r.ready(); try std.testing.expect(b.r.copy.held); // The unit carries no output: its sync reflows the grid, which no record // names; the core that applied it counted the write. const before = b.r.core().outside.n; b.r.confirm(try b.a.own(.{ .resize = .{ .cols = 40, .rows = 20 } })); b.r.settle(); try std.testing.expect(b.r.core().outside.n != before); try std.testing.expect(!b.r.copy.held); try b.rollback(); try agrees(b.a, b.r); try sameTerminals(b.a, b.r); } test "the count of writes outside the copy is digested: a session's emulator written where its client's is not (a colour set, which no other digested field shows) is a digest that names `outside`" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const b = try BytesPair.init(); defer b.deinit(); try std.testing.expectEqualStrings("", try partsApart(b.a, b.r, arena.allocator())); // A write of one side's emulator that no unit carries, as a stray one // would be: the count alone says it. const pane = b.a.core.panes[b.shell.index()].?; _ = pardes.Term.feed(&b.a.core.outside, pane.terminal.?, "\x1b[31m", &.{}, &.{}, &.{}, &.{}); try std.testing.expectEqualStrings("outside ", try partsApart(b.a, b.r, arena.allocator())); } test "bytes: a terminal's rows read before an idle client's copy are the copy's: a rollback puts them back, neither dropped nor freed twice" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const b = try BytesPair.init(); defer b.deinit(); try b.output("a line of the program's\r\nand another\r\n"); // Its rows read between steps (a draw's), then the copy taken while it // idles (`ready`): the rows are what the core holds at the copy. const pane = b.r.core().panes[b.shell.index()].?; _ = try pardes.edit.shellRows(b.r.core(), pane); const cached = b.r.core().shell_rows.text_alloc.ptr; b.r.ready(); try std.testing.expect(b.r.copy.held); // A key of the client's on top, the session's own key first: the copy // put back, the rows with it (not left orphaned in the epoch). try b.rollback(); try std.testing.expectEqual(cached, b.r.core().shell_rows.text_alloc.ptr); try agrees(b.a, b.r); try b.output("after\r\n"); _ = try pardes.edit.shellRows(b.r.core(), pane); try agrees(b.a, b.r); } test "bytes: a client's key that reads a terminal's rows, the session's output before it in the session's order: the output rolls it back, its read is made again over the fed rows, and the input is kept on the fast path with the session's reading" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const b = try BytesPair.init(); defer b.deinit(); try b.output("l1\r\nl2\r\nl3\r\n"); // The shell's pane focused and out of its tty mode (^B): a cursor over // its rows. const id = b.shell.index(); const rect = b.a.core.view().rects[id]; for ([_]pardes.Event{ .{ .mouse = .{ .button = .left, .kind = .press, .col = rect.x + 2, .row = rect.y + 1 } }, .{ .mouse = .{ .button = .left, .kind = .release, .col = rect.x + 2, .row = rect.y + 1 } }, .{ .key = .{ .cp = 'b', .ctrl = true } }, }) |ev| { b.r.confirm(try b.a.own(ev)); b.r.settle(); } try agrees(b.a, b.r); // G: to the last of its rows, which it reads (edit.shellRows). const last = try gpa.dupe(u8, try b.r.input(.{ .key = .{ .cp = 'G', .text = "G" } })); defer gpa.free(last); try std.testing.expectEqual(@as(usize, 1), b.r.applied); const read_before = b.r.core().panes[id].?.body.cur_row; // The program prints two lines before the session takes the G: the // emulator fed (its count moved, so never a neutral unit), the G // undone and read again over the rows as fed. b.a.output(.{ .output = .{ .pane = b.shell, .bytes = "l4\r\nl5\r\n" } }); b.r.confirm((try b.a.pending()).?); b.r.settle(); try std.testing.expectEqual(@as(usize, 1), b.r.applied); try std.testing.expect(b.r.core().panes[id].?.body.cur_row > read_before); const fast = b.r.stats.fast; b.r.confirm(try b.a.take(last)); b.r.settle(); try std.testing.expectEqual(fast + 1, b.r.stats.fast); try agrees(b.a, b.r); try std.testing.expectEqual(b.a.core.panes[id].?.body.cur_row, b.r.core().panes[id].?.body.cur_row); } 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 terminal's view is the same row on every side through a reflow and a rollback: a view on a wrapped line's second row, joined into the row above by the session's widening, is the same row after its narrowing on every side" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const b = try BytesPair.init(); defer b.deinit(); const id = b.shell.index(); // Lines a row and a half long, the view on the first's second row (put // there alike on both sides: no step of either moved it). const cols = pardes.Term.grid(b.a.core.panes[id].?.terminal).cols; var line: [512]u8 = undefined; const text = line[0 .. cols + cols / 2]; @memset(text, 'x'); b.a.output(.{ .output = .{ .pane = b.shell, .bytes = "\x1bc" } }); for (0..40) |_| { b.a.output(.{ .output = .{ .pane = b.shell, .bytes = text } }); b.a.output(.{ .output = .{ .pane = b.shell, .bytes = "\r\n" } }); } b.r.confirm((try b.a.pending()).?); b.r.settle(); for ([_]*Pardes{ b.a.core, b.r.core() }) |core| core.panes[id].?.scrolled_to = 1; // The session's frontend widens: the line one row, the view at row 0. b.r.confirm(try b.a.own(.{ .resize = .{ .cols = 200, .rows = 24 } })); b.r.settle(); try agrees(b.a, b.r); try std.testing.expectEqual(@as(?usize, 0), b.a.core.panes[id].?.scrolled_to); // A key of the client's on top, the session's first: the copy put back. try b.rollback(); try agrees(b.a, b.r); // The session narrows again: every side's view the same row. b.r.confirm(try b.a.own(.{ .resize = .{ .cols = 80, .rows = 24 } })); b.r.settle(); try agrees(b.a, b.r); } /// Where view `k` stands in terminal pane `id`'s history (Pane.scrolled_to): /// the pane's own field while `k` is live, its share's else. fn placeIn(p: *const Pardes, k: u8, id: usize) ?usize { const pane = p.panes[id].?; return if (p.live == k) pane.scrolled_to else pane.pv[k].scrolled_to; } test "bytes: a client's wheel over a terminal is its own view's: applied at once, the session's view on the output and following it, the client's on its row through output and a rollback" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const b = try BytesPair.init(); defer b.deinit(); const id = b.shell.index(); var line: [32]u8 = undefined; for (0..100) |i| b.a.output(.{ .output = .{ .pane = b.shell, .bytes = try std.fmt.bufPrint(&line, "line-{d}\r\n", .{i}) } }); b.r.confirm((try b.a.pending()).?); b.r.settle(); // The client in a view of its own, laid out by a step of its own. const opened = try b.a.openView(1); b.r.view = opened.view; b.r.confirm(opened.unit); b.r.settle(); const focus = try gpa.dupe(u8, try b.r.input(.{ .focus = true })); defer gpa.free(focus); b.r.confirm(try b.a.take(focus)); b.r.settle(); const rect = b.a.core.views[b.r.view].?.rects[id]; const wheel = try gpa.dupe(u8, try b.r.input(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = rect.x + 2, .row = rect.y + rect.h -| 1 } })); defer gpa.free(wheel); // Applied at once, nothing of it outside the copy: the session's own // view (the replica's core holds it too) is where it was. try std.testing.expectEqual(@as(usize, 1), b.r.applied); const back = placeIn(b.r.core(), b.r.view, id).?; try std.testing.expectEqual(@as(?usize, null), placeIn(b.r.core(), 0, id)); b.r.confirm(try b.a.take(wheel)); b.r.settle(); try agrees(b.a, b.r); // The program prints: the view on the output follows, the client's stays. try b.output("more-1\r\nmore-2\r\n"); try agrees(b.a, b.r); for ([_]*Pardes{ b.a.core, b.r.core() }) |core| { try std.testing.expectEqual(@as(?usize, null), placeIn(core, 0, id)); try std.testing.expectEqual(@as(?usize, back), placeIn(core, b.r.view, id)); } // A wheel of the client's on top, the session's own key first: the // copy put back, the wheel applied again over it. const again = try gpa.dupe(u8, try b.r.input(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = rect.x + 2, .row = rect.y + rect.h -| 1 } })); defer gpa.free(again); b.r.confirm(try b.a.local(.{ .key = .{ .cp = 'j', .text = "j" } })); b.r.settle(); b.r.confirm(try b.a.take(again)); b.r.settle(); try agrees(b.a, b.r); try std.testing.expect(placeIn(b.r.core(), b.r.view, id).? < back); } test "a view's top is a line and a row of its block: a client's wheel into a line wrapped over rows moves it a row a notch, the session agrees through a rollback, and a dump keeps the row" { const gpa = std.testing.allocator; var text: std.ArrayList(u8) = .empty; defer text.deinit(gpa); // Line 3 is 60 words: four rows at this width. for (0..40) |i| if (i == 3) { for (0..60) |w| try text.print(gpa, "w{d:0>3} ", .{w}); try text.append(gpa, '\n'); } else try text.print(gpa, "line {d}\n", .{i}); const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const was = Stepping.begin(&a.t, null); _ = try a.core.setTestFile(text.items); was.end(); _ = try a.unit(0, 0); const id = a.core.view().active; // A client joined from the session's dump: the text is in it. const r = try joinedNow(a, 1, 0); defer r.deinit(); const rect = a.core.view().rects[id]; const notch: pardes.Event = .{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = rect.x + 10, .row = rect.y + 5 } }; // Three notches to line 3's first row, two into its block. for (0..5) |_| { const m = try gpa.dupe(u8, try r.input(notch)); defer gpa.free(m); r.confirm(try a.take(m)); r.settle(); try agrees(a, r); } for ([_]*Pardes{ a.core, r.core() }) |core| { try std.testing.expectEqual(@as(usize, 3), core.panes[id].?.file.?.scroll); try std.testing.expectEqual(@as(u32, 2), core.panes[id].?.file.?.scroll_row); } // A notch of the client's on top of the session's own key (one that // leaves the view be): the copy put back, the notch applied over it. const again = try gpa.dupe(u8, try r.input(notch)); defer gpa.free(again); r.confirm(try a.local(.{ .key = .{ .cp = pardes.Key.escape } })); r.settle(); r.confirm(try a.take(again)); r.settle(); try agrees(a, r); try std.testing.expectEqual(@as(u32, 3), r.core().panes[id].?.file.?.scroll_row); // A client joining over the view scrolled into the block has the row. const late = try joinedNow(a, 2, 0); defer late.deinit(); try agrees(a, late); try std.testing.expectEqual(@as(u32, 3), late.core().panes[id].?.file.?.scroll_row); // The client's view keys, each after the session drew (its geometry // made for the frame; the client's is not): what a key reads of the // body's rows is made of the state alone (the soak's divergence at a // Ctrl-b, before File.shownRows laid the geometry out first). var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); for ([_]pardes.Key{ .{ .cp = 'b', .ctrl = true }, .{ .cp = 'f', .ctrl = true }, .{ .cp = 'd', .ctrl = true }, .{ .cp = 'u', .ctrl = true }, .{ .cp = 'e', .ctrl = true } }) |k| { for (0..3) |_| { { const drew = Stepping.begin(&a.t, null); defer drew.end(); _ = try a.core.render(arena.allocator()); } const m = try gpa.dupe(u8, try r.input(.{ .key = k })); defer gpa.free(m); r.confirm(try a.take(m)); r.settle(); try agrees(a, r); } } // A session's dump keeps the row. const bytes = try pardes.dump.dumpBytes(a.core); defer gpa.free(bytes); const loaded = try pardes.dump.load(gpa, .{ .cols = 80, .rows = 24 }, bytes, null); defer loaded.deinit(); try std.testing.expectEqual(walk.digest(Pardes, a.core), walk.digest(Pardes, loaded)); try std.testing.expectEqual(a.core.panes[id].?.file.?.scroll_row, loaded.panes[id].?.file.?.scroll_row); } test "a text's views under random orders of the session's and a client's keys, wheels and draws, keys of the session's between a client's and its confirm (rollbacks): every side agrees (an explorer of a view's rows)" { const gpa = std.testing.allocator; var text: std.ArrayList(u8) = .empty; defer text.deinit(gpa); // Lines of one row and of several (wrapped at 80 columns). for (0..120) |i| if (i % 7 == 3) { for (0..20 + i % 40) |w| try text.print(gpa, "w{d:0>3} ", .{w}); try text.append(gpa, '\n'); } else try text.print(gpa, "line {d}\n", .{i}); const keys = [_]pardes.Key{ .{ .cp = 'j', .text = "j" }, .{ .cp = 'k', .text = "k" }, .{ .cp = 'w', .text = "w" }, .{ .cp = 'b', .text = "b" }, .{ .cp = 'b', .ctrl = true }, .{ .cp = 'f', .ctrl = true }, .{ .cp = 'd', .ctrl = true }, .{ .cp = 'u', .ctrl = true }, .{ .cp = 'G', .text = "G" }, .{ .cp = 'z', .text = "z" }, .{ .cp = 't', .text = "t" }, .{ .cp = 'i', .text = "i" }, .{ .cp = 'x', .text = "x" }, .{ .cp = pardes.Key.escape }, .{ .cp = '/', .text = "/" }, .{ .cp = pardes.Key.enter }, }; for (0..view_orders) |seed| { const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const was = Stepping.begin(&a.t, null); _ = try a.core.setTestFile(text.items); was.end(); _ = try a.unit(0, 0); const id = a.core.view().active; const r = try joinedNow(a, 1, 0); defer r.deinit(); const opened = try a.openView(1); r.view = opened.view; r.confirm(opened.unit); r.settle(); try agrees(a, r); var prng: std.Random.DefaultPrng = .init(seed); const rand = prng.random(); var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); for (0..150) |_| { const rect = a.core.views[r.view].?.rects[id]; const at = .{ .col = rect.x + 10, .row = rect.y + rect.h / 2 }; const ev: pardes.Event = switch (rand.uintLessThan(u8, 10)) { 0 => .{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = at.col, .row = at.row } }, 1 => .{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = at.col, .row = at.row } }, else => .{ .key = keys[rand.uintLessThan(usize, keys.len)] }, }; if (rand.boolean()) { const drew = Stepping.begin(&a.t, null); defer drew.end(); _ = arena.reset(.retain_capacity); _ = try a.core.render(arena.allocator()); } if (rand.uintLessThan(u8, 4) == 0) _ = r.draw(.{ .ctx = null, .f = null }); if (rand.uintLessThan(u8, 3) == 0) { // The session's own key, then nothing of the client's. r.confirm(try a.local(.{ .key = keys[rand.uintLessThan(usize, keys.len)] })); r.settle(); } else { const m = try gpa.dupe(u8, try r.input(ev)); defer gpa.free(m); // Sometimes the session's own key first: the client's // applied at once is rolled back and replayed. if (rand.uintLessThan(u8, 3) == 0) { r.confirm(try a.local(.{ .key = keys[rand.uintLessThan(usize, keys.len)] })); r.settle(); } r.confirm(try a.take(m)); r.settle(); } agrees(a, r) catch |err| { std.debug.print("seed {d}: diverged\n", .{seed}); return err; }; } } } /// Seeds of the explorer below a run of the suite takes; 3,000 were run /// once (reports/pardes-term-join-10.md). const view_orders = 30; test "bytes: terminal views under random orders of the session's output, each view's wheels, keys and resizes, a copy taken ahead and rollbacks, the history at its cap: every side agrees (an explorer)" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const Ev = pardes.Event; const K = pardes.Key; var seed: u64 = 0; while (seed < view_orders) : (seed += 1) { const b = try BytesPair.init(); defer b.deinit(); var prng: std.Random.DefaultPrng = .init(seed); const rnd = prng.random(); var sent: std.ArrayListUnmanaged([]u8) = .empty; var units: std.ArrayListUnmanaged([]u8) = .empty; var trail: std.ArrayListUnmanaged(u8) = .empty; defer { for (sent.items) |m| gpa.free(m); sent.deinit(gpa); for (units.items) |m| gpa.free(m); units.deinit(gpa); trail.deinit(gpa); } var line: [64]u8 = undefined; // The history at its cap: the emulator's byte limit at its least, // on both sides alike, then flooded past it. for ([_]*Pardes{ b.a.core, b.r.core() }) |core| pardes.Term.emulatorOf(core.panes[b.shell.index()].?.terminal.?).vt.screens.active.pages.setMaxBytes(1); var n_out: usize = 0; while (n_out < 6000) : (n_out += 1) b.a.output(.{ .output = .{ .pane = b.shell, .bytes = try std.fmt.bufPrint(&line, "line {d}\r\n", .{n_out}) } }); b.r.confirm((try b.a.pending()).?); b.r.settle(); // The session's view at or near the history's top, on both sides. const top = rnd.uintLessThan(usize, 4); for ([_]*Pardes{ b.a.core, b.r.core() }) |core| core.panes[b.shell.index()].?.scrolled_to = top; b.a.core.view().active = b.shell.index(); b.r.confirm(try b.a.own(.{ .focus = true })); const opened = try b.a.openView(1); b.r.view = opened.view; b.r.confirm(opened.unit); b.r.settle(); for (0..150) |_| { const who = rnd.uintLessThan(u8, 10); if (who < 2) { // the session's own pty, or its taking a client's input if (rnd.boolean()) { try trail.print(gpa, "So ", .{}); for (0..rnd.intRangeAtMost(usize, 1, 600)) |_| { b.a.output(.{ .output = .{ .pane = b.shell, .bytes = try std.fmt.bufPrint(&line, "line {d}\r\n", .{n_out}) } }); n_out += 1; } try units.append(gpa, try gpa.dupe(u8, (try b.a.pending()).?)); } else if (sent.items.len > 0) { try trail.print(gpa, "St ", .{}); const m = sent.orderedRemove(0); defer gpa.free(m); try units.append(gpa, try gpa.dupe(u8, try b.a.take(m))); } continue; } if (who < 5) { if (rnd.uintLessThan(u8, 4) == 0) { try trail.print(gpa, "Rr ", .{}); b.r.ready(); } else if (units.items.len > 0) { try trail.print(gpa, "R ", .{}); const u = units.orderedRemove(0); defer gpa.free(u); b.r.confirm(u); b.r.settle(); } continue; } // an input, the session's frontend's (view 0) or the client's const client = who >= 7; const k: u8 = if (client) b.r.view else 0; const rect = b.a.core.views[k].?.rects[b.shell.index()]; const ev: Ev, const name: []const u8 = switch (rnd.uintLessThan(u8, 20)) { 14 => .{ .{ .key = .{ .cp = 'g', .text = "g" } }, "g" }, 15 => .{ .{ .key = .{ .cp = 'G', .text = "G" } }, "G" }, 16 => .{ .{ .key = .{ .cp = 'n', .text = "n" } }, "n" }, 17 => .{ .{ .key = .{ .cp = 'N', .text = "N" } }, "N" }, 18 => .{ .{ .key = .{ .cp = '/', .text = "/" } }, "/" }, 19 => .{ .{ .paste = "line 1" }, "p" }, 0, 1, 2, 3 => .{ .{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = rect.x + 2, .row = rect.y + rect.h -| 1 } }, "wu" }, 4, 5 => .{ .{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = rect.x + 2, .row = rect.y + rect.h -| 1 } }, "wd" }, 6 => .{ .{ .key = .{ .cp = 'b', .ctrl = true } }, "^b" }, 7 => .{ .{ .key = .{ .cp = 'j', .text = "j" } }, "j" }, 8 => .{ .{ .key = .{ .cp = 'k', .text = "k" } }, "k" }, 9 => .{ .{ .key = .{ .cp = 'u', .ctrl = true } }, "^u" }, 10 => .{ .{ .key = .{ .cp = 'd', .ctrl = true } }, "^d" }, 11 => .{ .{ .key = .{ .cp = K.escape } }, "esc" }, 13 => .{ .{ .key = .{ .cp = K.enter } }, "ent" }, 12 => .{ .{ .resize = .{ .cols = rnd.intRangeAtMost(u16, 60, 90), .rows = rnd.intRangeAtMost(u16, 6, 14) } }, "rs" }, else => .{ .{ .mouse = .{ .button = .left, .kind = .press, .col = rect.x + 2, .row = rect.y + rect.h -| 1 } }, "cl" }, }; try trail.print(gpa, "{s}{s} ", .{ if (client) "C" else "S", name }); if (client) { try sent.append(gpa, try gpa.dupe(u8, try b.r.input(ev))); } else { try units.append(gpa, try gpa.dupe(u8, try b.a.own(ev))); if (ev == .mouse) try units.append(gpa, try gpa.dupe(u8, try b.a.own(.{ .mouse = .{ .button = .left, .kind = .release, .col = ev.mouse.col, .row = ev.mouse.row } }))); } if (b.r.diverged) |why| { std.debug.print("seed {d}: diverged {s}: {s}\n", .{ seed, why, trail.items }); return error.TestExpectedEqual; } if (sent.items.len == 0 and units.items.len == 0 and b.r.quiet() and digestOf(b.a) != b.r.digest()) { std.debug.print("seed {d}: digests differ: {s}\n", .{ seed, trail.items }); return error.TestExpectedEqual; } } } } 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 = b.r.core().outside.n; 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(b.r.core().outside.n != reloads); const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); defer late.deinit(); 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 "a session's first client on the socket it starts with (Options.pair), joined there with no hello before the session's first effects: the boot shell's spawn and first bytes reach it and the digests agree" { try firstOnPair(false); } test "bytes: a session's first client on its pair, taken before its first effects, has the boot shell's first bytes with no reload at all (its view is the session's, none opened for it); a client after them makes every side reload" { try firstOnPair(true); } test "a pair's client makes its own core from the session's options, its file read itself: the welcome confirms it by the digest and no dump is sent" { try ownBootAgainst(false); } test "a pair's client's own core, the file edited between the session's read and its own: the dump is sent, loaded in its place, and the client shows the session's file" { try ownBootAgainst(true); } test "a Restore tells its clients so before it lets them go (each joins again, saying nothing), and one handed over meanwhile is joined to the restored core at the next boundary, not hung up on" { const gpa = std.testing.allocator; var fds: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; defer _ = libc.close(fds[1]); var late: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &late) != 0) return error.NoSocket; defer _ = libc.close(late[1]); const core = try Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); defer core.deinit(); core.host = TestHost.host(); var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .name = "restore", .detached = true }; defer ps.deinit(); defer live_peers = null; defer ps.dropAll(core); ps.join(core, .{ .fd = fds[0] }); var why: [600]u8 = @splat(0); var j = joinOn(gpa, fds[1], null, &why, null, null, null, .{}) orelse return error.JoinFailed; gpa.free(j.dump); defer j.rest.deinit(gpa); // A client dialling again, handed over before the Restore lets the first go. ps.handed(late[0], null); ps.restoring(core); const Last = struct { words: ?[]u8 = null, fn post(l: *@This(), msg: Said) bool { switch (msg) { .refused => |w| l.words = w, .unit, .blob => |b| std.heap.c_allocator.free(b), .checked, .ended, .left => {}, } return true; } }; var last: Last = .{}; // Its stream as a client that does not come back takes it. var no_link: Link = .{ .r = undefined, .fd = fds[1] }; readLink(gpa, fds[1], &j.rest, &no_link, &last, Last.post); const words = last.words orelse return error.NoLastWord; defer std.heap.c_allocator.free(words); try std.testing.expectEqualStrings(restore_words, words); try std.testing.expectEqual(1, ps.inbox.items.len); } test "a detached session's first attach opens a view of its own beside the session's; the first back after a Restore takes the session's" { const gpa = std.testing.allocator; const core = try Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); defer core.deinit(); core.host = TestHost.host(); var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .name = "attach", .detached = true }; defer ps.deinit(); defer live_peers = null; defer ps.dropAll(core); const session_view = core.live; var fds: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; defer _ = libc.close(fds[1]); ps.join(core, .{ .fd = fds[0] }); const first = for (ps.list) |slot| { if (slot) |peer| break peer; } else return error.NotJoined; try std.testing.expect(first.view.index() != session_view); try std.testing.expect(pardes.views.isOpen(core, session_view)); ps.restoring(core); var again: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &again) != 0) return error.NoSocket; defer _ = libc.close(again[1]); ps.join(core, .{ .fd = again[0] }); const back = for (ps.list) |slot| { if (slot) |peer| break peer; } else return error.NotJoined; try std.testing.expectEqual(core.live, back.view.index()); try std.testing.expectEqual(1, pardes.views.count(core)); } /// A session's first client on its pair making its core itself /// (`ownBoot`), the file it opens `edited` after the session read it. fn ownBootAgainst(edited: bool) !void { const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); 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.txt", .{dir}); try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "a.txt", .data = "the session's start\n" }); var fds: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; const opts: pardes.Options = .{ .cols = 80, .rows = 24, .file = path }; const core = try Pardes.init(gpa, opts); defer core.deinit(); core.host = TestHost.host(); var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .name = "pair", .detached = true }; defer ps.deinit(); defer live_peers = null; defer ps.dropAll(core); ps.join(core, .{ .fd = fds[0], .own = true }); // Edited after the session read it, before its client does. if (edited) try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "a.txt", .data = "edited between\n" }); var o = opts; o.pair = fds[1]; var j: Joined = undefined; var why: [600]u8 = @splat(0); const booted = join(gpa, &j, "", "", o, null, &why, null, false) orelse return error.JoinFailed; const r = confirmBoot(gpa, &j, booted, o, &why) orelse { std.debug.print("the welcome: {s}\n", .{std.mem.sliceTo(&why, 0)}); return error.JoinFailed; }; defer r.deinit(); defer { _ = libc.close(j.fd); j.rest.deinit(gpa); } try std.testing.expectEqual(!edited, r == booted); try std.testing.expectEqual(tape.digestOf(core), r.digest()); // The session's one view is its client's: none beside it, nobody's, // sizes its terminals. try std.testing.expectEqual(@as(u8, 1), core.views_open); try std.testing.expectEqual(@as(u8, 0), r.view); // What the client shows is the session's file as the session read it. try std.testing.expectEqualStrings("the session's start\n", r.core().panes[0].?.file.?.content); } /// A session's first client on a socket pair (runtime/session.zig's, then /// the client's first join on its end), the session's first effects after: /// its boot shell spawned, its first bytes output; the client quiet and /// checked. `by_dump`: the client joined by the session's dump, as any /// client loads one (`fromDump`); else it makes its own core (Options.pair, /// `confirmBoot`). fn firstOnPair(by_dump: bool) !void { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const Spawns = struct { fn spawn(ctx: ?*anyopaque, _: pardes.Pane.Id, _: []const u8, _: pardes.PtySize) void { const n: *u32 = @ptrCast(@alignCast(ctx.?)); n.* += 1; } const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .spawn = spawn }; }; var spawns: u32 = 0; var fds: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; const opts: pardes.Options = .{ .cols = 80, .rows = 24, .boot = .tty }; const core = try Pardes.init(gpa, opts); defer core.deinit(); core.host = .{ .ctx = &spawns, .vtable = &Spawns.vtable }; var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .name = "pair", .detached = true }; defer ps.deinit(); defer live_peers = null; defer ps.dropAll(core); const reloads = pardes.Term.reloads.n; ps.join(core, .{ .fd = fds[0], .own = true }); var j: Joined = undefined; var why: [600]u8 = @splat(0); const r = if (by_dump) r: { // Joined by its dump as any client loads one (`fromDump`). j = joinOn(gpa, fds[1], null, &why, null, null, null, .{}) orelse return error.JoinFailed; defer gpa.free(j.dump); break :r fromDump(gpa, &j, opts, null, &why, nowNs(), "") orelse { std.debug.print("the join: {s}\n", .{std.mem.sliceTo(&why, 0)}); return error.JoinFailed; }; } else r: { var o = opts; o.pair = fds[1]; // Its own core, from the same options, before any byte of the // session's; the welcome then says it is the session's: no dump. const booted = join(gpa, &j, "", "", o, null, &why, null, false) orelse { std.debug.print("the join failed: {s}\n", .{std.mem.sliceTo(&why, 0)}); return error.JoinFailed; }; try std.testing.expect(j.booted); const r = confirmBoot(gpa, &j, booted, o, &why) orelse { std.debug.print("the welcome: {s}\n", .{std.mem.sliceTo(&why, 0)}); return error.JoinFailed; }; try std.testing.expect(r == booted); try std.testing.expectEqual(@as(usize, 0), j.dump.len); break :r r; }; defer r.deinit(); defer { _ = libc.close(j.fd); j.rest.deinit(gpa); } try std.testing.expect(r.loaded(j.digest)); // The first effects, the boot shell's spawn among them; its first bytes. while (core.nextEffect()) |e| core.perform(e); try std.testing.expectEqual(@as(u32, 1), spawns); const shell: u8 = for (core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break @intCast(id); } else return error.NoShell; core.update(.{ .output = .{ .pane = .at(shell), .bytes = "first$ " } }); ps.boundary(core); // Its check, answered after every unit before it. try std.testing.expect(askCheck(j.fd)); while (!ps.mail.load(.acquire)) std.Thread.yield() catch {}; ps.boundary(core); const Take = struct { r: *Replica, fd: c_int, digest: ?u64 = null, fn take(t: *@This(), tag: u8, payload: []const u8) bool { switch (std.enums.fromInt(wire.ServerTag, tag) orelse return false) { .unit => t.r.confirm(payload), .check => { t.digest = (wire.decodeServer(tag, payload) catch return false).check; return false; }, else => {}, } return true; } }; var take: Take = .{ .r = r, .fd = j.fd }; j.rest.run(gpa, j.fd, &take, Take.take); r.settle(); if (r.diverged) |w| std.debug.print("diverged: {s}\n", .{w}); try std.testing.expect(r.diverged == null); try std.testing.expectEqual(take.digest.?, r.digest()); // No reload at the join: the session's view is its first client's, none // opened for it (Peers.viewFor); the client loaded the terminal from the // dump and replayed every byte since. try std.testing.expectEqual(reloads, pardes.Term.reloads.n); var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const rows = try pardes.Term.viewport(r.core().panes[shell].?.terminal.?, arena.allocator(), false, r.core().panes[shell].?.scrolled_to); try std.testing.expect(std.mem.indexOf(u8, rows[0], "first$") != null); if (!by_dump) return; // One that comes after the shell's bytes: every side reloads. var late: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &late) != 0) return error.NoSocket; defer _ = libc.close(late[1]); ps.join(core, .{ .fd = late[0] }); try std.testing.expectEqual(reloads + 1, pardes.Term.reloads.n); } test "bytes: a join refused for want of a view reloads nothing on any side: a client with a key on top stays the session's" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const b = try BytesPair.init(); defer b.deinit(); try b.output("a line of the program's\r\n"); // Every view taken: the session's, then three clients'. for (2..pardes.views.max + 1) |client| b.r.confirm((try b.a.openView(@intCast(client))).unit); try b.output("and one since the last join\r\n"); var sent: std.ArrayListUnmanaged([]u8) = .empty; defer { for (sent.items) |m| gpa.free(m); sent.deinit(gpa); } // A key of its own on top; a fifth client refused, in the unit of the // pump the others take next; the key confirmed; the program prints on. try key(b.r, 'l', &sent); try std.testing.expectEqual(@as(usize, 1), b.r.applied); const before = pardes.Term.reloads.n; try std.testing.expect(try b.a.join(pardes.views.max + 1, null) == null); try std.testing.expectEqual(before, pardes.Term.reloads.n); b.a.pump(); b.r.confirm((try b.a.pending()).?); b.r.confirm(try b.a.take(sent.items[0])); b.r.settle(); try b.output("and on\r\n"); try std.testing.expectEqual(before, pardes.Term.reloads.n); try agrees(b.a, b.r); try sameTerminals(b.a, b.r); } test "bytes: a join reloads only the terminals written since their last reload: one idle since the last join is reloaded on no side, and through a prune of both every side holds the session's terminals, the joiner too" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const b = try BytesPair.init(); defer b.deinit(); b.r.confirm(try b.a.local(.{ .command = "Term" })); b.r.settle(); const second: pardes.Pane.Id = for (b.a.core.panes, 0..) |slot, id| { if (id != b.shell.index() and (slot orelse continue).terminal != null) break .at(id); } else return error.NoTerminal; const both = [_]pardes.Pane.Id{ b.shell, second }; // Both written, and a join reloads both. for (both) |id| b.a.output(.{ .output = .{ .pane = id, .bytes = "written\r\n" } }); b.r.confirm((try b.a.pending()).?); const first = (try b.a.join(2, null)).?; gpa.free(first.dump); b.r.confirm(first.unit); // The shell alone written since: the next join reloads it alone, on // every side; the joiner loads the other's snapshot as it was. try b.output("the shell's\r\n"); const before = pardes.Term.reloads.n; const joined = (try b.a.join(3, null)).?; defer gpa.free(joined.dump); try std.testing.expectEqual(1, pardes.Term.reloads.n - before); b.r.confirm(joined.unit); try std.testing.expectEqual(2, pardes.Term.reloads.n - before); const late = try Replica.initDump(gpa, 3, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); defer late.deinit(); late.core().echo = null; try std.testing.expectEqual(joined.digest, late.digest()); // Output into both until each has pruned its history (whole pages, by // the history of its pages), a unit every few reads. var read: std.ArrayListUnmanaged(u8) = .empty; defer read.deinit(gpa); const lines = 40_000; var n: usize = 0; while (n < lines) : (n += 100) { read.clearRetainingCapacity(); for (n..n + 100) |i| try read.print(gpa, "\x1b[3{d}m{d}\x1b[0m line\r\n", .{ i % 8, i }); for (both) |id| b.a.output(.{ .output = .{ .pane = id, .bytes = read.items } }); if (n % 2000 == 1900) { const u = (try b.a.pending()).?; b.r.confirm(u); late.confirm(u); } } if (try b.a.pending()) |u| { b.r.confirm(u); late.confirm(u); } for (both) |id| try std.testing.expect(pardes.Term.grid(b.a.core.panes[id.index()].?.terminal).total < lines); try agrees(b.a, b.r); try sameTerminals(b.a, b.r); try agrees(b.a, late); try sameTerminals(b.a, late); // And a join after: both written, both reloaded, every hash compared. const left = try b.a.leave(2, false); b.r.confirm(left); late.confirm(left); const third = (try b.a.join(4, null)).?; gpa.free(third.dump); b.r.confirm(third.unit); late.confirm(third.unit); try agrees(b.a, b.r); try agrees(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 "bytes: a kitty image shown by a file, a temporary file or shared memory is the session's read, and the replica is handed its bytes: the same image, the cursor moved past it, the temporary file and the shared memory gone once, a missing file refused alike" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const shm = struct { extern "c" fn shm_open(name: [*:0]const u8, flag: c_int, mode: std.c.mode_t) c_int; extern "c" fn shm_unlink(name: [*:0]const u8) c_int; extern "c" fn ftruncate(fd: c_int, len: i64) c_int; }; // ghostty warns of the missing file, on the session alone. const level = std.testing.log_level; std.testing.log_level = .err; defer std.testing.log_level = level; const b = try BytesPair.init(); defer b.deinit(); const pixels: [12]u8 = @splat(0x7f); // 2 by 2, RGB const pid = std.c.getpid(); var names: [4][80]u8 = undefined; const file = try std.fmt.bufPrintSentinel(&names[0], "/tmp/pardes-replica-{d}-file.rgb", .{pid}, 0); const temp = try std.fmt.bufPrintSentinel(&names[1], "/tmp/tty-graphics-protocol-pardes-replica-{d}.rgb", .{pid}, 0); const object = try std.fmt.bufPrintSentinel(&names[2], "/pardes-replica-{d}", .{pid}, 0); const missing = try std.fmt.bufPrintSentinel(&names[3], "/tmp/pardes-replica-{d}-missing.rgb", .{pid}, 0); for ([_][:0]const u8{ file, temp }) |path| { const fd = std.c.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(std.c.mode_t, 0o600)); try std.testing.expect(fd >= 0); defer _ = std.c.close(fd); try std.testing.expectEqual(@as(isize, pixels.len), std.c.write(fd, &pixels, pixels.len)); } defer for ([_][:0]const u8{ file, temp }) |path| { _ = std.c.unlink(path); }; { const fd = shm.shm_open(object, @bitCast(std.c.O{ .ACCMODE = .RDWR, .CREAT = true, .TRUNC = true }), 0o600); try std.testing.expect(fd >= 0); defer _ = std.c.close(fd); try std.testing.expectEqual(@as(c_int, 0), shm.ftruncate(fd, pixels.len)); try std.testing.expectEqual(@as(isize, pixels.len), std.c.write(fd, &pixels, pixels.len)); } defer _ = shm.shm_unlink(object); const enc = std.base64.standard.Encoder; var line: [256]u8 = undefined; var b64: [128]u8 = undefined; for ([_][:0]const u8{ file, temp, object, missing }, "ftsf", 7..) |path, medium, id| try b.output(try std.fmt.bufPrint(&line, "\x1b_Ga=T,t={c},i={d},f=24,s=2,v=2;{s}\x1b\\ shown\r\n", .{ medium, id, enc.encode(&b64, path) })); try agrees(b.a, b.r); try sameTerminals(b.a, b.r); try std.testing.expect(std.c.access(file, std.c.F_OK) == 0); try std.testing.expect(std.c.access(temp, std.c.F_OK) != 0); try std.testing.expect(shm.shm_open(object, @bitCast(std.c.O{ .ACCMODE = .RDONLY }), 0) < 0); } test "a join's dump whose length says more than its buffer holds is refused, the field named, never loaded" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); // A column tag's room for one range, that range written as a dump // writes its numbers, then how many it uses: one. const tag = &a.core.view().col_tags[0]; tag.sels = try a.core.gpa.alloc(pardes.panes.Text.SelRange, 1); tag.sels[0] = .{ .row = 0x1234567, .col = 0x2345678, .arow = 0x3456789, .acol = 0x456789a, .sticky = 0x56789ab }; tag.nsel = 1; const was = Stepping.begin(&a.t, null); const dumped = try pardes.dump.byteDump(a.core); tape.resync(&a.t); was.end(); defer a.core.gpa.free(dumped); const range = std.mem.sliceAsBytes(&[_]i32{ 0x1234567, 0x2345678, 0x3456789, 0x456789a, 0x56789ab }); const at = (std.mem.indexOf(u8, dumped, range) orelse return error.NoRange) + range.len; try std.testing.expectEqual(@as(u16, 1), std.mem.readInt(u16, dumped[at..][0..2], .little)); // As a damaged dump has it: seven, in the room for one. std.mem.writeInt(u16, dumped[at..][0..2], 7, .little); var j: Joined = .{ .fd = -1, .pid = 0, .client = 1, .view = 0, .gmtoff = 0, .dump = dumped }; var why: [600]u8 = @splat(0); try std.testing.expect(fromDump(gpa, &j, .{ .cols = 80, .rows = 24 }, null, &why, 0, "") == null); const words = std.mem.sliceTo(&why, 0); try std.testing.expect(std.mem.startsWith(u8, words, "the session's dump would not load: BadDump: ")); try std.testing.expect(std.mem.indexOf(u8, words, "nsel says 7, past the 1 its buffer holds") != null); } 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()); defer a.deinit(); _ = try a.local(.{ .key = .{ .cp = 'j', .text = "j" } }); const was = Stepping.begin(&a.t, null); const bytes = try pardes.dump.dumpBytes(a.core); tape.resync(&a.t); was.end(); defer a.core.gpa.free(bytes); const r = try Replica.initDump(gpa, 1, 0, bytes, .{ .cols = 80, .rows = 24 }); defer r.deinit(); try std.testing.expectEqual(digestOf(a), r.digest()); r.confirm(try a.local(.{ .key = .{ .cp = 'j', .text = "j" } })); if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); try std.testing.expect(r.diverged == null); var sent: std.ArrayListUnmanaged([]u8) = .empty; defer { for (sent.items) |m| gpa.free(m); sent.deinit(gpa); } for ("oab") |k| try key(r, k, &sent); try key(r, pardes.Key.escape, &sent); for (sent.items) |m| { r.confirm(try a.take(m)); r.settle(); } if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); try std.testing.expect(r.diverged == null); try std.testing.expect(r.quiet()); try std.testing.expectEqual(digestOf(a), r.digest()); } test "a replica joined from a dump replays a step that opens a file's pane and says it has no room for it: its /log, empty, is not the session's" { const gpa = std.testing.allocator; // No rows for a second pane: the Look's pane of a kind is made, the // placement says it has no room (a message in the step that made the // pane, which was not in /log yet), and the pane goes. const a = try Authority.init(gpa, .{ .cols = 80, .rows = 5, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); var words: [64]pardes.Kind.LoadedWord = undefined; const zon = pardes.Kind.loadedOf(&Zon.ops, "/x/zon.so", @splat(9), &words); _ = try a.local(.{ .addon = .{ .op = .load, .pane = .at(0), .kind = &zon } }); const r = try joinedNow(a, 1, 0); defer r.deinit(); try std.testing.expectEqual(digestOf(a), r.digest()); var whole: [libc.PATH_MAX]u8 = undefined; var look: [libc.PATH_MAX + 8]u8 = undefined; const path = std.mem.span(libc.realpath("build.zig.zon", &whole) orelse return error.SkipZigTest); r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&look, "Look {s}", .{path}) })); if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); try std.testing.expect(r.diverged == null); try std.testing.expectEqual(digestOf(a), r.digest()); } /// A kind of `.zon` files, for a replica's Look of one (a picture's, /// as a kind's pane is made). const Zon = struct { const pa = pardes.Kind.c; fn open(_: [*c]const u8, _: [*c]const u8, _: u64) callconv(.c) ?*anyopaque { return pardes.Kind.api.alloc.?(4); } fn paint(_: ?*anyopaque, _: [*c]const pa.pa_window, _: [*c]pa.pa_paint) callconv(.c) void {} 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 = "zon".* ++ @as([13]u8, @splat(0)), .version = 1, .exts = ".zon" }), .open = open, .paint = paint, }); }; test "a replica joined from a themed dump paints its taglines in the restored theme" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host()); defer a.deinit(); _ = try a.local(.{ .command = "Theme rose_pine_moon" }); const was = Stepping.begin(&a.t, null); const bytes = try pardes.dump.dumpBytes(a.core); tape.resync(&a.t); was.end(); defer a.core.gpa.free(bytes); const r = try Replica.initDump(gpa, 1, 0, bytes, .{ .cols = 80, .rows = 24 }); defer r.deinit(); const expected = a.core.chrome().tag[0]; try std.testing.expectEqualStrings("rose_pine_moon", r.core().theme().name); try std.testing.expectEqual(expected, r.core().chrome().tag[0]); _ = r.draw(.{ .ctx = null, .f = null }); try std.testing.expectEqual(expected.ground, r.core().surface.chrome.tag_bg); try std.testing.expectEqual(expected.text, r.core().surface.chrome.tag_fg); try std.testing.expectEqual(digestOf(a), r.digest()); // A later theme is an ordinary confirmed unit, its chrome set at once. r.confirm(try a.local(.{ .command = "Theme monokai_pro_classic" })); r.settle(); _ = r.draw(.{ .ctx = null, .f = null }); const changed = a.core.chrome().tag[0]; try std.testing.expect(!std.meta.eql(changed, expected)); try std.testing.expectEqual(changed.ground, r.core().surface.chrome.tag_bg); try std.testing.expectEqual(changed.text, r.core().surface.chrome.tag_fg); try std.testing.expect(r.diverged == null); try std.testing.expectEqual(digestOf(a), r.digest()); } test "a host's Adopt and a terminal reader's failure are inputs: a replica makes the same pane" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, opened by a key const gpa = std.testing.allocator; // Its terminals as screen state, as a session's for its clients are. const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const was = Stepping.begin(&a.t, null); const bytes = try pardes.dump.dumpBytes(a.core); tape.resync(&a.t); was.end(); defer a.core.gpa.free(bytes); const r = try Replica.initDump(gpa, 1, 0, bytes, .{ .cols = 80, .rows = 24 }); defer r.deinit(); // What tui.zig's and gui.zig's adoptShell and a failed reader do between // steps: they wrote the core straight, and every client joined again. const host = Stepping.begin(&a.t, null); const id = a.core.adoptShell().?.index(); try std.testing.expect(a.core.panes[id].?.isTerminal() and !a.core.panes[id].?.greet); a.core.readerFailed(.at(id), error.InputOutput); a.core.pump(a.host) catch {}; host.end(); a.seq += 1; r.confirm(try a.unit(0, a.seq)); if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); try std.testing.expect(r.diverged == null); try std.testing.expectEqual(digestOf(a), r.digest()); } test "a join's dump, its blobs put back where they go, is the session's dump" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const text = try gpa.alloc(u8, 20000); defer gpa.free(text); @memset(text, 'x'); _ = try a.local(.{ .key = .{ .cp = 'i', .text = "i" } }); _ = try a.local(.{ .paste = text }); _ = try a.local(.{ .key = .{ .cp = pardes.Key.escape, .text = "" } }); const was = Stepping.begin(&a.t, null); defer was.end(); const whole = try pardes.dump.byteDump(a.core); defer a.core.gpa.free(whole); var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; defer blobs.deinit(a.core.gpa); const state = (try pardes.dump.dumpJoin(a.core, &blobs)).bytes; defer a.core.gpa.free(state); try std.testing.expect(blobs.items.len > 0); try std.testing.expect(state.len + 20000 <= whole.len); var joined: std.ArrayListUnmanaged(u8) = .empty; defer joined.deinit(gpa); var pos: usize = 0; for (blobs.items) |b| { try joined.appendSlice(gpa, state[pos..b.at]); try joined.appendSlice(gpa, b.bytes); pos = b.at; } try joined.appendSlice(gpa, state[pos..]); try std.testing.expectEqualSlices(u8, whole, joined.items); } test "a cached blob is hashed again as it is read: one kept cut short, corrupted, planted or longer is a miss, and goes" { const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var path: [4200]u8 = undefined; const c = try testCache(&tmp, &path, 1 << 20); var text: [6000]u8 = undefined; for (&text, 0..) |*b, i| b.* = @truncate(i *% 31 +% i / 7); var hash: [32]u8 = undefined; std.crypto.hash.Blake3.hash(&text, &hash, .{}); var out: [6000]u8 = undefined; try std.testing.expect(!c.get(io, &hash, &out)); var corrupted = text; corrupted[4000] ^= 0x20; const planted: [6000]u8 = @splat('x'); var longer: [6001]u8 = undefined; @memcpy(longer[0..6000], &text); longer[6000] = '\n'; // Each kept under the text's hash, as a torn write or another hand // would leave it: read, it is a miss, and gone. for ([_][]const u8{ text[0..3000], &corrupted, &planted, &longer }) |bad| { c.put(io, &.{.{ .hash = hash, .bytes = bad }}, &.{}); try std.testing.expect(c.has(io, &hash, bad.len)); @memset(&out, 0); try std.testing.expect(!c.get(io, &hash, &out)); try std.testing.expect(!c.has(io, &hash, bad.len)); } // ...and put right, it is read again. c.put(io, &.{.{ .hash = hash, .bytes = &text }}, &.{}); try std.testing.expect(c.get(io, &hash, &out)); try std.testing.expectEqualSlices(u8, &text, &out); } test "the blob cache stays under its cap, the least recently used going first and one past the cap alone without them, the file compacted" { const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var path: [4200]u8 = undefined; const c = try testCache(&tmp, &path, 3 * 5000); var blobs: [4][5000]u8 = undefined; var hashes: [4][32]u8 = undefined; for (&blobs, &hashes, 0..) |*b, *h, k| { @memset(b, @intCast('a' + k)); std.crypto.hash.Blake3.hash(b, h, .{}); } for (0..3) |k| c.put(io, &.{.{ .hash = hashes[k], .bytes = &blobs[k] }}, &.{}); // The oldest read: it is the newest now. var out: [5000]u8 = undefined; try std.testing.expect(c.get(io, &hashes[0], &out)); c.put(io, &.{}, &.{hashes[0]}); // Under the cap: nothing goes. c.trim(io); for (hashes[0..3]) |*h| try std.testing.expect(c.has(io, h, 5000)); // One more is past it: the least recently used goes. c.put(io, &.{.{ .hash = hashes[3], .bytes = &blobs[3] }}, &.{}); const before = (try std.Io.Dir.cwd().statFile(io, c.path(), .{})).size; c.trim(io); try std.testing.expect(c.has(io, &hashes[0], 5000)); try std.testing.expect(!c.has(io, &hashes[1], 5000)); try std.testing.expect(c.has(io, &hashes[2], 5000) and c.has(io, &hashes[3], 5000)); try std.testing.expect((try std.Io.Dir.cwd().statFile(io, c.path(), .{})).size < before); // The newest past the cap alone (an edited big file's text): it goes, // and the older ones, which fit, stay. const big: [4 * 5000]u8 = @splat('z'); var big_hash: [32]u8 = undefined; std.crypto.hash.Blake3.hash(&big, &big_hash, .{}); c.put(io, &.{.{ .hash = big_hash, .bytes = &big }}, &.{}); c.trim(io); try std.testing.expect(!c.has(io, &big_hash, big.len)); for ([_]usize{ 0, 2, 3 }) |k| try std.testing.expect(c.has(io, &hashes[k], 5000)); // Room for nothing: everything goes. Cache.of(c.path(), 0).trim(io); for (&hashes) |*h| try std.testing.expect(!c.has(io, h, 5000)); } test "a blob cache that is no database is started afresh" { const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var path: [4200]u8 = undefined; const c = try testCache(&tmp, &path, 1 << 20); try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = c.path(), .data = "xit but not a database, cut short" }); const text: [5000]u8 = @splat('t'); var hash: [32]u8 = undefined; std.crypto.hash.Blake3.hash(&text, &hash, .{}); var out: [5000]u8 = undefined; try std.testing.expect(!c.get(io, &hash, &out)); c.put(io, &.{.{ .hash = hash, .bytes = &text }}, &.{}); try std.testing.expect(c.get(io, &hash, &out)); } test "a far join is sent each blob once: joined again with them on disk or in the core it leaves, the state alone; a cached file gone bad, that blob again" { const gpa = std.testing.allocator; const io = std.testing.io; zstd.gpa = gpa; defer zstd.gpa = std.heap.c_allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const text = try gpa.alloc(u8, 30000); defer gpa.free(text); for (text, 0..) |*b, i| b.* = if (i % 61 == 60) '\n' else @intCast('a' + (i * 7 + i / 13) % 26); _ = try a.local(.{ .key = .{ .cp = 'i', .text = "i" } }); _ = try a.local(.{ .paste = text }); _ = try a.local(.{ .key = .{ .cp = pardes.Key.escape, .text = "" } }); _ = try a.local(.{ .key = .{ .cp = 'o', .text = "o" } }); _ = try a.local(.{ .paste = text[0..9000] }); _ = try a.local(.{ .key = .{ .cp = pardes.Key.escape, .text = "" } }); // Two blobs more than the text: 70 lines deleted (the undo's), the 80 // after them yanked (the register's). for ("gg70xd80xy") |c| _ = try a.local(.{ .key = .{ .cp = c, .text = &.{c} } }); const was = Stepping.begin(&a.t, null); defer was.end(); const whole = try pardes.dump.byteDump(a.core); defer a.core.gpa.free(whole); // What the session's list will say: its blobs, those of one text once. var listed: std.ArrayListUnmanaged(walk.Deferred) = .empty; defer listed.deinit(a.core.gpa); a.core.gpa.free((try pardes.dump.dumpJoin(a.core, &listed)).bytes); var distinct: std.AutoHashMapUnmanaged([32]u8, usize) = .empty; defer distinct.deinit(gpa); var distinct_bytes: u64 = 0; var biggest: [32]u8 = undefined; var biggest_len: usize = 0; for (listed.items) |b| { var d: [32]u8 = undefined; std.crypto.hash.Blake3.hash(b.bytes, &d, .{}); if ((try distinct.getOrPut(gpa, d)).found_existing) continue; distinct_bytes += b.bytes.len; if (b.bytes.len > biggest_len) { biggest = d; biggest_len = b.bytes.len; } } try std.testing.expect(distinct.count() >= 3); var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var path: [4200]u8 = undefined; var have: Have = .{ .io = io, .cache = try testCache(&tmp, &path, 64 << 20) }; defer { have.cache = null; have.deinit(); } var ps: Peers = .{ .gpa = gpa, .io = io }; defer ps.deinit(); // A near client: the dump whole, as before. var j = try farJoinOnce(&ps, a.core, null); try std.testing.expectEqualSlices(u8, whole, j.dump); try std.testing.expectEqual(@as(u32, 0), j.blobs); endJoin(&j, null); // The first far join: every blob sent, once. j = try farJoinOnce(&ps, a.core, &have); try std.testing.expectEqualSlices(u8, whole, j.dump); try std.testing.expectEqual(listed.items.len, j.blobs); try std.testing.expectEqual(@as(u32, 0), j.from_disk + j.from_memory); try std.testing.expectEqual(distinct_bytes, j.sent_bytes); endJoin(&j, &have); // Again: all of them on disk. j = try farJoinOnce(&ps, a.core, &have); try std.testing.expectEqualSlices(u8, whole, j.dump); try std.testing.expectEqual(distinct.count(), j.from_disk); try std.testing.expectEqual(@as(u64, 0), j.sent_bytes); endJoin(&j, &have); // The biggest kept wrong (read back once as another length, it goes; // then junk under its hash): it alone is sent again. const junk = try gpa.alloc(u8, biggest_len); defer gpa.free(junk); @memset(junk, 'z'); try std.testing.expect(!have.cache.?.get(io, &biggest, junk[0 .. biggest_len - 1])); have.cache.?.put(io, &.{.{ .hash = biggest, .bytes = junk }}, &.{}); j = try farJoinOnce(&ps, a.core, &have); try std.testing.expectEqualSlices(u8, whole, j.dump); try std.testing.expectEqual(distinct.count() - 1, j.from_disk); try std.testing.expectEqual(@as(u64, biggest_len), j.sent_bytes); endJoin(&j, &have); // A rejoin, no disk: what the core it leaves holds. const cache = have.cache; have.cache = null; have.leaving(a.core); j = try farJoinOnce(&ps, a.core, &have); have.left(); have.cache = cache; try std.testing.expectEqualSlices(u8, whole, j.dump); try std.testing.expectEqual(distinct.count(), j.from_memory); try std.testing.expectEqual(@as(u64, 0), j.sent_bytes); endJoin(&j, &have); } test "a replica joined after a pane closed: the session's jump to it, its Panes and Recent rows, asked by either" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); // About a jump opening a pane: `Jumps new-pane` (SPEC §6.6). a.core.settings.jumps = .@"new-pane"; // A file looked at and closed: a jump to it, Recent's, a closed pane. var cwd: [std.Io.Dir.max_path_bytes]u8 = undefined; var line: [std.Io.Dir.max_path_bytes + 32]u8 = undefined; const dir = std.mem.span(@as([*:0]u8, @ptrCast(std.c.getcwd(&cwd, cwd.len) orelse return error.NoCwd))); _ = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/build.zig.zon", .{dir}) }); _ = try a.local(.{ .command = "Del" }); try std.testing.expectEqual(@as(usize, 1), a.core.store.closed.items.len); try std.testing.expect(a.core.view().jumps.n > 1); // What another window of the user's wrote to the store, which the // session read (src/variants_test.zig's case, the variant hunt's). a.core.recent.opened(a.core.recentGpa(), try std.fmt.bufPrint(&line, "{s}/build.zig", .{dir})); const r = try joinedNow(a, 1, 0); defer r.deinit(); try std.testing.expectEqual(digestOf(a), r.digest()); r.confirm(try a.local(.{ .key = .{ .cp = 'j', .text = "j" } })); r.confirm(try a.local(.{ .command = "Search Panes" })); r.confirm(try a.local(.{ .command = "Search Recent" })); try agrees(a, r); // The replica's own: it waits for the session's rows. for ([_][]const u8{ "Search Panes", "Search Recent" }) |asked| { const msg = try gpa.dupe(u8, try r.input(.{ .command = asked })); defer gpa.free(msg); r.confirm(try a.take(msg)); r.settle(); } try agrees(a, r); // The closed pane brought back by the replica's Look at it: the // session's record of it, off the tape. { const closed = try std.fmt.bufPrint(&line, "Look @p{d}", .{a.core.store.closed.items[0].serial}); const msg = try gpa.dupe(u8, try r.input(.{ .command = closed })); defer gpa.free(msg); r.confirm(try a.take(msg)); r.settle(); try std.testing.expectEqual(@as(usize, 0), a.core.store.closed.items.len); try agrees(a, r); r.confirm(try a.local(.{ .command = "Del" })); } // A jump back onto the closed file: opened again, from Recent. for (0..3) |_| { const msg = try gpa.dupe(u8, try r.input(.{ .key = .{ .cp = 'o', .ctrl = true } })); defer gpa.free(msg); r.confirm(try a.take(msg)); r.settle(); } try agrees(a, r); } test "a replica's Del of a file its session's Recent knows asks the host what the session asked" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); var cwd: [std.Io.Dir.max_path_bytes]u8 = undefined; var line: [std.Io.Dir.max_path_bytes + 32]u8 = undefined; const dir = std.mem.span(@as([*:0]u8, @ptrCast(std.c.getcwd(&cwd, cwd.len) orelse return error.NoCwd))); _ = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/build.zig.zon", .{dir}) }); // Joined while it is open: in the session's Recent, in no replica's. const r = try joinedNow(a, 1, 0); defer r.deinit(); const msg = try gpa.dupe(u8, try r.input(.{ .command = "Del" })); defer gpa.free(msg); r.confirm(try a.take(msg)); r.settle(); try std.testing.expectEqual(@as(usize, 1), a.core.store.closed.items.len); try agrees(a, r); } test "a client leaves, and one joins: what the leave queued (a terminal's resize) is done in its unit, on every side, before the join's dump" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, PtyHost.host()); defer a.deinit(); const first = try gpa.dupe(u8, try a.unit(0, 0)); defer gpa.free(first); const old = try Replica.init(gpa, 1, first); defer old.deinit(); // A second client, bigger, types into the terminal: it sizes it. const opened = try a.openView(2); old.confirm(opened.unit); var buf: [256]u8 = undefined; old.confirm(try a.take(try inputOf(&buf, 2, 1, .{ .resize = .{ .cols = 120, .rows = 40 } }))); old.confirm(try a.take(try inputOf(&buf, 2, 2, .{ .key = .{ .cp = 'x', .text = "x" } }))); // It leaves: the terminal is the first view's size again, its pty's // resize queued for the next pump; and a client joins at that boundary. var was = Stepping.begin(&a.t, null); a.core.closeView(.at(opened.view)); was.end(); old.confirm(try a.unit(0, 100)); // The client left idle takes its copy ahead (Replica.ready): of a core // with nothing queued. old.ready(); was = Stepping.begin(&a.t, null); const k = a.core.openView() orelse return error.NoView; was.end(); old.confirm(try a.unit(0, 101)); const joiner = try joinedNow(a, 3, k.index()); defer joiner.deinit(); try std.testing.expectEqual(digestOf(a), joiner.digest()); // The next pump's unit, every client's. const u = try gpa.dupe(u8, try a.local(.tick)); defer gpa.free(u); old.confirm(u); joiner.confirm(u); try agrees(a, old); try agrees(a, joiner); } test "a client that diverged joins again for its view: kept for it meanwhile, its pane in it again; the other client agrees" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const first = try gpa.dupe(u8, try a.unit(0, 0)); defer gpa.free(first); const old = try Replica.init(gpa, 1, first); defer old.deinit(); const opened = try a.openView(2); old.confirm(opened.unit); var buf: [256]u8 = undefined; old.confirm(try a.take(try inputOf(&buf, 2, 1, .{ .command = "New" }))); const made = a.core.view().active; // Its bye says it joins again: its view is kept, as every replica keeps it. var was = Stepping.begin(&a.t, null); a.core.awayView(.at(opened.view)); was.end(); old.confirm(try a.unit(0, 100)); try agrees(a, old); // Back for it: its own, its pane in it, in the dump it loads. was = Stepping.begin(&a.t, null); try std.testing.expect(a.core.rejoinView(.at(opened.view))); was.end(); old.confirm(try a.unit(0, 101)); const back = try joinedNow(a, 3, opened.view); defer back.deinit(); try std.testing.expectEqual(digestOf(a), back.digest()); a.view_of[3] = .at(opened.view); const u = try gpa.dupe(u8, try a.take(try back.input(.{ .key = .{ .cp = 'l', .text = "l" } }))); defer gpa.free(u); old.confirm(u); back.confirm(u); try std.testing.expectEqual(made, a.core.view().active); try std.testing.expect(pardes.layout.findPane(a.core, made) != null); try agrees(a, old); try agrees(a, back); } /// A session's side of its clients' links in memory (`Peers.threads` /// false, the soak's): a connection handed to it and joined at its next /// boundary, the replica loaded from what its writer would write (the /// welcome, the dump with its blobs in place); what a client wrote, taken /// by its peer's reader; and what the session queued for one, down its /// link in order. const MemoryLinks = struct { /// `old`: the link it had, whose end the session hears after this /// join came: held until then. fn join(ps: *Peers, core: *Pardes, view: ?u8, fd: *c_int, old: ?*Peer) !struct { r: *Replica, peer: *Peer } { var fds: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; fd.* = fds[1]; ps.handed(fds[0], view); ps.boundary(core); if (old) |o| { for (ps.list) |slot| if (slot) |p| if (p.fd == fds[0]) return error.NotHeld; ps.post(.{ .gone = o }); ps.boundary(core); ps.boundary(core); } const peer = for (ps.list) |slot| { if (slot) |p| if (p.fd == fds[0]) break p; } else return error.Refused; var word: [16]u8 = undefined; const far = try wire.encodeClient(&word, .{ .far = false }); _ = peer.take(far[0], far[wire.header_len..]); return .{ .r = try load(ps, peer), .peer = peer }; } /// `peer`'s join as its writer writes it, loaded: written whole, its /// pins let go at the next boundary. fn load(ps: *Peers, peer: *Peer) !*Replica { const gpa = std.testing.allocator; const f = (try wire.framed(peer.welcome[0..peer.welcome_len])) orelse return error.BadWelcome; const w = (try wire.decodeServer(f.tag, f.payload)).welcome; var whole: std.ArrayListUnmanaged(u8) = .empty; defer whole.deinit(gpa); var pos: usize = 0; for (peer.blobs.items) |b| { try whole.appendSlice(gpa, peer.dump[pos..b.at]); try whole.appendSlice(gpa, b.bytes); pos = b.at; } try whole.appendSlice(gpa, peer.dump[pos..]); peer.written = peer.gen; ps.post(.{ .joined = .{ .peer = peer, .gen = peer.gen } }); const r = try Replica.initDump(gpa, w.client, w.view.index(), whole.items, .{ .cols = 80, .rows = 24 }); if (!r.loaded(w.digest)) { r.deinit(); return error.LoadedAnother; } return r; } /// What its client wrote on its link, taken by its reader. fn up(peer: *Peer) !void { var buf: [4096]u8 = undefined; const n = libc.read(peer.fd, &buf, buf.len); if (n <= 0) return error.NothingWritten; var at: usize = 0; while (try wire.framed(buf[at..@intCast(n)])) |f| : (at += f.total) if (!peer.take(f.tag, f.payload)) return error.LinkEnded; } fn down(peer: *Peer, link: *Link) !void { var at: usize = 0; while (try wire.framed(peer.out.items[at..])) |f| : (at += f.total) { link.take(switch (std.enums.fromInt(wire.ServerTag, f.tag) orelse return error.BadFrame) { .unit => .{ .unit = try std.heap.c_allocator.dupe(u8, f.payload) }, .refused => .{ .refused = try std.heap.c_allocator.dupe(u8, (try wire.decodeServer(f.tag, f.payload)).refused) }, else => return error.UnexpectedFrame, }); } peer.out.clearRetainingCapacity(); } }; /// A session whose client is cut off: queued past its bound with its link /// stalled, told why, nothing more sent it. fn cutOff(core: *Pardes, ps: *Peers, peer: *Peer, link: *Link) !void { core.update(.{ .key = .{ .cp = 'i', .text = "i" } }); try core.pump(core.host); ps.boundary(core); try MemoryLinks.down(peer, link); try std.testing.expect(!link.quit and link.r.diverged == null); peer.limit = 16 << 10; const text: [6000]u8 = @splat('t'); for (0..3) |_| { core.update(.{ .paste = &text }); try core.pump(core.host); ps.boundary(core); } try std.testing.expect(peer.cut); try MemoryLinks.down(peer, link); try std.testing.expect(link.quit and !link.gone); } test "a client's end and its writer's note after it, taken in one batch, let the client go once: nothing reads it freed" { const gpa = std.testing.allocator; const core = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer core.deinit(); core.host = TestHost.host(); try core.pump(core.host); // The session's own allocations a page each: a client let go is // unmapped, and a read of it after faults where it reads. var ps: Peers = .{ .gpa = std.heap.page_allocator, .io = std.testing.io, .threads = false }; defer ps.deinit(); defer ps.dropAll(core); var fd: c_int = -1; const first = try MemoryLinks.join(&ps, core, null, &fd, null); defer _ = libc.close(fd); first.r.deinit(); ps.boundary(core); // Its reader's end, then its writer's note that its join is written // whole (the writer descheduled between its last write and its post): // one boundary's batch. ps.post(.{ .gone = first.peer }); ps.post(.{ .joined = .{ .peer = first.peer, .gen = first.peer.gen } }); ps.boundary(core); try std.testing.expectEqual(@as(usize, 0), ps.count()); } test "a client cut off for what it left unread is told why and comes back over its own link: its goodbye and its hello there, the session's dump there in the view it has, no other connection; it loads it and agrees" { const gpa = std.testing.allocator; const core = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer core.deinit(); core.host = TestHost.host(); try core.pump(core.host); var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .threads = false }; defer ps.deinit(); defer ps.dropAll(core); var fd: c_int = -1; const first = try MemoryLinks.join(&ps, core, null, &fd, null); defer _ = libc.close(fd); var link: Link = .{ .r = first.r, .fd = fd }; defer link.deinit(gpa); const view = first.peer.view; const conn = first.peer.fd; try cutOff(core, &ps, first.peer, &link); // Its link is up: it comes back over it (runtime/client.zig `run`). try std.testing.expect(link.backHere()); try std.testing.expect(comeBack(fd, "t", view.index())); try MemoryLinks.up(first.peer); try std.testing.expect(link.rejoins()); try std.testing.expect(std.mem.indexOf(u8, link.notice(), "behind") != null); ps.boundary(core); // Dumped there: the same peer on the same connection, its view as it // was, the cut over, the daemon not asked (nothing handed). try std.testing.expectEqual(@as(usize, 1), ps.count()); try std.testing.expect(ps.list[0] == first.peer and first.peer.fd == conn and !first.peer.cut); try std.testing.expectEqual(view, first.peer.view); try std.testing.expectEqual(@as(u32, 1), ps.again_here); const back = try MemoryLinks.load(&ps, first.peer); defer back.deinit(); first.r.deinit(); try std.testing.expectEqual(view.index(), back.view); link.reset(back, &.{ .fd = fd, .pid = 0, .client = back.id, .view = view.index(), .gmtoff = 0, .dump = &.{} }); core.update(.{ .paste = "back" }); try core.pump(core.host); ps.boundary(core); try MemoryLinks.down(first.peer, &link); try std.testing.expect(!link.quit and back.diverged == null and back.quiet()); try std.testing.expectEqual(tape.digestOf(core), back.digest()); } test "a client that says it joins again and shuts its link (one of another build, gone to exec this one: sameBuild), dialled again before the session heard that link's end: its join waits for it, its view kept for it meanwhile" { const gpa = std.testing.allocator; const core = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer core.deinit(); core.host = TestHost.host(); try core.pump(core.host); var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .threads = false }; defer ps.deinit(); defer ps.dropAll(core); var fd: c_int = -1; const first = try MemoryLinks.join(&ps, core, null, &fd, null); defer _ = libc.close(fd); const view = first.peer.view; // Its goodbye, then its link shut at once, before the session's reader // has heard the end; the join comes on another connection. var out: [16]u8 = undefined; const said_bye = try wire.encodeClient(&out, .{ .bye = .{ .again = true } }); try std.testing.expect(first.peer.take(said_bye[0], said_bye[wire.header_len..])); first.r.deinit(); _ = libc.close(fd); const back = try MemoryLinks.join(&ps, core, view.index(), &fd, first.peer); defer back.r.deinit(); try std.testing.expectEqual(view, back.peer.view); var link: Link = .{ .r = back.r, .fd = fd }; defer link.deinit(gpa); core.update(.{ .paste = "back" }); try core.pump(core.host); ps.boundary(core); try MemoryLinks.down(back.peer, &link); try std.testing.expect(!link.quit and back.r.diverged == null and back.r.quiet()); try std.testing.expectEqual(tape.digestOf(core), back.r.digest()); } /// A session's links with their threads (the runtime's), its steps a thread /// of their own (`Peers.boundary`, the session's loop), until `stop`. const LiveLinks = struct { core: *Pardes, ps: Peers, stop: std.atomic.Value(bool) = .init(false), thread: ?std.Thread = null, fn init(l: *LiveLinks, name: []const u8) !void { const gpa = std.testing.allocator; l.* = .{ .core = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }), .ps = .{ .gpa = gpa, .io = std.testing.io, .name = name } }; l.core.host = TestHost.host(); try l.core.pump(l.core.host); } fn start(l: *LiveLinks) !void { l.thread = try std.Thread.spawn(.{}, run, .{l}); } fn run(l: *LiveLinks) void { while (!l.stop.load(.acquire)) { l.ps.boundary(l.core); const ts: libc.timespec = .{ .sec = 0, .nsec = std.time.ns_per_ms }; _ = libc.nanosleep(&ts, null); } } fn halt(l: *LiveLinks) void { l.stop.store(true, .release); if (l.thread) |t| t.join(); l.thread = null; } fn deinit(l: *LiveLinks) void { l.halt(); l.ps.dropAll(l.core); l.ps.deinit(); live_peers = null; l.core.deinit(); } }; /// A far client's blobs on disk, the test's own. const TestHave = struct { tmp: std.testing.TmpDir, buf: [4200]u8 = undefined, have: Have, fn init(h: *TestHave, far: bool) !?*Have { h.tmp = std.testing.tmpDir(.{}); h.have = .{ .io = std.testing.io }; if (!far) return null; h.have.cache = try testCache(&h.tmp, &h.buf, 64 << 20); return &h.have; } fn deinit(h: *TestHave) void { h.have.deinit(); h.tmp.cleanup(); } }; /// A join's dump let go as `replica.join` lets it go. fn dumpDone(j: *Joined, have: ?*Have) void { if (have) |h| { h.store(std.testing.allocator, j); h.wait(); } else std.testing.allocator.free(j.dump); j.dump = &.{}; } fn backOverLink(far: bool) !void { const gpa = std.testing.allocator; var live: LiveLinks = undefined; try live.init("back"); defer live.deinit(); var fds: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; defer _ = libc.close(fds[1]); live.ps.handed(fds[0], null); try live.start(); var th: TestHave = undefined; const have = try th.init(far); defer th.deinit(); var why: [600]u8 = @splat(0); const o: pardes.Options = .{ .cols = 80, .rows = 24 }; var j = joinOn(gpa, fds[1], null, &why, have, null, null, .{}) orelse return error.JoinFailed; defer j.rest.deinit(gpa); const r = fromDump(gpa, &j, o, have, &why, 0, "back") orelse return error.LoadFailed; dumpDone(&j, have); var link: Link = .{ .r = r, .fd = fds[1] }; defer link.deinit(gpa); link.reset(r, &j); const view = r.view; // Its stream on a reader thread, as its loop has it (client.zig `read`). const Sink = struct { units: std.atomic.Value(u32) = .init(0), fn post(x: *@This(), msg: Said) bool { if (msg == .unit) _ = x.units.fetchAdd(1, .monotonic); switch (msg) { .unit, .refused, .blob => |b| std.heap.c_allocator.free(b), .checked, .ended, .left => {}, } return true; } fn read(fd: c_int, rest: *Framer, l: *Link, x: *@This()) void { readLink(std.testing.allocator, fd, rest, l, x, post); } }; var sink: Sink = .{}; const reader = try std.Thread.spawn(.{}, Sink.read, .{ fds[1], &j.rest, &link, &sink }); // Keys go in, and their units come back (raw: a replica stepping beside // the session's thread would share the process's tape globals). for ("abc") |cp| { var out: [64]u8 = undefined; try std.testing.expect(writeAll(fds[1], try wire.encodeClient(&out, .{ .event = .{ .key = .{ .cp = cp, .text = &[1]u8{cp} } } }))); } var waited: u32 = 0; while (sink.units.load(.monotonic) < 3) : (waited += 1) { if (waited > 10_000) return error.NoUnits; const ts: libc.timespec = .{ .sec = 0, .nsec = std.time.ns_per_ms }; _ = libc.nanosleep(&ts, null); } // Put off the session's state: its link up, it comes back over it. r.fail("put off by the test"); link.quit = true; try std.testing.expect(link.backHere()); link.back.store(true, .release); try std.testing.expect(comeBack(fds[1], "back", view)); reader.join(); try std.testing.expect(link.rejoins()); // Its dump made (the session's step), loaded here after it. const peer = live.ps.list[0] orelse return error.Gone; waited = 0; while (true) : (waited += 1) { peer.lock.lockUncancelable(std.testing.io); const dumped_ = peer.gen == 2; peer.lock.unlock(std.testing.io); if (dumped_) break; if (waited > 10_000) return error.NoDump; const ts: libc.timespec = .{ .sec = 0, .nsec = std.time.ns_per_ms }; _ = libc.nanosleep(&ts, null); } const back = join(gpa, &j, "/nowhere/no.sock", "back", o, have, &why, r, true) orelse { std.debug.print("joined again: {s}\n", .{std.mem.sliceTo(&why, 0)}); return error.JoinFailed; }; defer back.deinit(); if (have) |h| h.wait(); live.halt(); // The same connection, the view it had, a dump there; the daemon (no // socket at that path) never asked. try std.testing.expectEqual(fds[1], j.fd); try std.testing.expectEqual(view, back.view); try std.testing.expectEqual(@as(u32, 1), live.ps.again_here); try std.testing.expectEqual(@as(usize, 1), live.ps.count()); // Far: what it held came from the core it left, not over the link. if (far) try std.testing.expect(j.from_memory + 1 >= j.blobs); } test "a client that diverged comes back over its own link, with the session's threads: its goodbye and hello there, the stream it leaves let go up to the session's welcome, the dump there for the view it had; the same connection, nothing dialled" { try backOverLink(false); } test "a far client that diverged comes back over its own link: the stream's frame it leaves ended, the join's a frame of its own, its blobs from the core it leaves" { try backOverLink(true); } /// A first join whose welcome's digest is not the session's at the dump /// (as a dump that does not carry what the digest covers: the upgrade /// round's fault D): its load is refused, and it asks once more over its /// link, which the session answers with a right one. fn askedOnceMore(far: bool) !void { const gpa = std.testing.allocator; var live: LiveLinks = undefined; try live.init("once"); defer live.deinit(); var fds: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; defer _ = libc.close(fds[1]); live.ps.threads = false; live.ps.join(live.core, .{ .fd = fds[0] }); live.ps.threads = true; const peer = live.ps.list[0] orelse return error.Refused; const f = (try wire.framed(peer.welcome[0..peer.welcome_len])) orelse return error.BadWelcome; var w = (try wire.decodeServer(f.tag, f.payload)).welcome; w.digest +%= 1; var copy: [wire.hello_max + 64]u8 = undefined; const said_ = try wire.encodeServer(©, .{ .welcome = w }); @memcpy(peer.welcome[0..said_.len], said_); peer.writer = try std.Thread.spawn(.{}, Peer.writeLoop, .{peer}); peer.reader = try std.Thread.spawn(.{}, Peer.readLoop, .{peer}); try live.start(); var th: TestHave = undefined; const have = try th.init(far); defer th.deinit(); var why: [600]u8 = @splat(0); var j = joinOn(gpa, fds[1], null, &why, have, null, null, .{}) orelse return error.JoinFailed; defer j.rest.deinit(gpa); const r = fromDump(gpa, &j, .{ .cols = 80, .rows = 24 }, have, &why, 0, "once") orelse { std.debug.print("asked once more: {s}\n", .{std.mem.sliceTo(&why, 0)}); return error.LoadFailed; }; defer r.deinit(); dumpDone(&j, have); live.halt(); try std.testing.expectEqual(fds[1], j.fd); try std.testing.expectEqual(@as(u32, 1), live.ps.again_here); } test "a client whose load of the session's dump is refused asks once more over its link, the session's digest a word a field after the second dump, and goes on with the second" { try askedOnceMore(false); } test "a far client whose load is refused asks once more over its link: the stream's frame ended before the second join's" { try askedOnceMore(true); } test "a client whose load is refused twice gives up, naming the fields that differ by the digest a field at a time its dump ends with" { const gpa = std.testing.allocator; const core = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer core.deinit(); core.host = TestHost.host(); try core.pump(core.host); var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; defer blobs.deinit(core.gpa); const state = (try pardes.dump.dumpJoin(core, &blobs)).bytes; defer core.gpa.free(state); var whole: std.ArrayListUnmanaged(u8) = .empty; defer whole.deinit(gpa); var pos: usize = 0; for (blobs.items) |b| { try whole.appendSlice(gpa, state[pos..b.at]); try whole.appendSlice(gpa, b.bytes); pos = b.at; } try whole.appendSlice(gpa, state[pos..]); // The session's digest a field at a time the dump ends with // (dump.joinParts), its first field's word not what the dump loads. const theirs = pardes.dump.joinParts(gpa, whole.items) orelse return error.NoParts; defer gpa.free(theirs); whole.items[whole.items.len - 16 - theirs.len * 8] +%= 1; var fds: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; defer _ = libc.close(fds[0]); // A session played by hand: a welcome whose digest is not its dump's, // twice. const Play = struct { fn run(fd: c_int, dump: []const u8) void { var welcome: [wire.hello_max + 64]u8 = undefined; const w = wire.encodeServer(&welcome, .{ .welcome = .{ .pid = 1, .session = "named", .client = 1, .dump_len = dump.len, .digest = 1 } }) catch return; var heard: [256]u8 = undefined; for (0..2) |_| { // Its far word (both times), then its goodbye and hello. if (libc.read(fd, &heard, heard.len) <= 0) return; if (!writeAll(fd, w) or !writePieces(fd, dump)) return; } _ = libc.read(fd, &heard, heard.len); } }; const player = try std.Thread.spawn(.{}, Play.run, .{ fds[0], whole.items }); defer player.join(); var why: [600]u8 = @splat(0); var j = joinOn(gpa, fds[1], null, &why, null, null, null, .{}) orelse return error.JoinFailed; defer j.rest.deinit(gpa); defer gpa.free(j.dump); try std.testing.expect(fromDump(gpa, &j, .{ .cols = 80, .rows = 24 }, null, &why, 0, "named") == null); _ = libc.close(j.fd); const words = std.mem.sliceTo(&why, 0); try std.testing.expect(std.mem.startsWith(u8, words, "the session's dump loaded as another session twice")); const first = comptime walk.fieldNames(Pardes)[0]; try std.testing.expect(std.mem.indexOf(u8, words, first) != null); } test "a client whose session's units come more than two seconds later than its quickest lets its link go, says so once, and joins again; its first unit after a join learns the clocks again" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const r = try Replica.init(gpa, 1, try a.unit(0, 0)); var fds: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; defer for (fds) |fd| { _ = libc.close(fd); }; var link: Link = .{ .r = r, .fd = fds[1] }; defer link.deinit(gpa); const Late = struct { // A unit the session made at `made` ms on its clock, taken at `at` // ms on the client's. fn take(l: *Link, from: *Authority, made: i64, at: u64) !void { const u = try std.heap.c_allocator.dupe(u8, try from.local(.tick)); std.mem.writeInt(i64, u[14..22], made * std.time.ns_per_ms, .little); l.now = at * std.time.ns_per_ms; l.take(.{ .unit = u }); } }; // The client's clock 5 s on from the session's, the link 100 ms: the // second unit 1.9 s later than the first, the third 2.1 s. try Late.take(&link, a, 0, 5_100); try Late.take(&link, a, 1_000, 8_000); try std.testing.expect(!link.quit); try Late.take(&link, a, 1_100, 8_300); try std.testing.expect(link.quit); // A check answered after it let go, behind the unit it let go of: its // core is behind on purpose, no divergence. link.take(.{ .checked = digestOf(a) +% 1 }); try std.testing.expect(r.diverged == null); // It comes back over its link; far, it dials again (`backHere`). try std.testing.expect(link.backHere()); link.far = true; try std.testing.expect(!link.backHere()); link.far = false; try std.testing.expect(link.rejoins()); try std.testing.expectEqualStrings("joined again: 2.1 s behind", link.notice()); try std.testing.expect(!link.rejoins()); r.deinit(); // Joined again, its first unit 3 s later than any before (the session's // clock stood still, its machine asleep; or the dump took that long): // taken as the link now, not let go of again. const back = try joinedNow(a, 1, 0); defer back.deinit(); link.reset(back, &.{ .fd = fds[1], .pid = 0, .client = 1, .view = 0, .gmtoff = 0, .dump = &.{} }); try Late.take(&link, a, 2_000, 10_100); try Late.take(&link, a, 2_100, 10_250); try std.testing.expect(!link.quit and back.diverged == null); } test "a client's writer, the client cut off while it waits on the socket, writes what it has in hand, then the words why, and nothing after them: its link stays up for its client's goodbye and hello again there" { const gpa = std.testing.allocator; var ps: Peers = .{ .gpa = gpa, .io = std.testing.io }; defer ps.deinit(); var fds: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; defer _ = libc.close(fds[1]); const peer = try gpa.create(Peer); peer.* = .{ .peers = &ps, .fd = fds[0], .id = 1, .view = .at(0), .dump_gpa = gpa, .far = false, .limit = 256 << 10 }; peer.welcome_len = (try wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = 1, .session = "t" } })).len; peer.writer = try std.Thread.spawn(.{}, Peer.writeLoop, .{peer}); defer ps.letGo(peer); // Units its client does not read: the socket fills, the writer waits // on it with a batch in hand, and the rest queues up to the bound. const unit: [16 << 10]u8 = @splat('u'); const head = wire.header(@backingInt(wire.ServerTag.unit), unit.len); // The first taken in hand. peer.send(&.{ &head, &unit }); while (true) { peer.lock.lockUncancelable(std.testing.io); const taken = peer.out.items.len == 0; peer.lock.unlock(std.testing.io); if (taken) break; std.Thread.yield() catch {}; } var sent: u32 = 1; while (!peer.cut) : (sent += 1) peer.send(&.{ &head, &unit }); const Heard = struct { units: u32 = 0, last: ?[]u8 = null, fn post(h: *@This(), msg: Said) bool { switch (msg) { .unit => |b| { std.heap.c_allocator.free(b); h.units += 1; }, .refused => |words| h.last = words, else => return false, } return true; } }; var heard: Heard = .{}; var rest: Framer = .{}; defer rest.deinit(gpa); var no_link: Link = .{ .r = undefined, .fd = fds[1] }; readLink(gpa, fds[1], &rest, &no_link, &heard, Heard.post); const words = heard.last orelse return error.NotTold; defer std.heap.c_allocator.free(words); try std.testing.expectEqualStrings("0 MB behind the session", words); try std.testing.expect(heard.units > 0 and heard.units < sent); // Its link not shut after them, as it was when a cut ended it. const wait: libc.timespec = .{ .sec = 0, .nsec = 100 * std.time.ns_per_ms }; _ = libc.nanosleep(&wait, null); try std.testing.expect(!hungUp(fds[1])); } test "a client joined from a dump moves through another view's pane as the session does, its lines not wrapped" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host()); defer a.deinit(); // The first client's Wrap off (SPC t w), and its cursor down into the // file's long lines, near the bottom of its view. var buf: [256]u8 = undefined; var seq: u32 = 1; const before = [_]pardes.Event{.{ .command = "Wrap" }} ++ @as([10]pardes.Event, @splat(.{ .key = .{ .cp = 'd', .ctrl = true } })) ++ @as([15]pardes.Event, @splat(.{ .key = .{ .cp = 'j', .text = "j" } })); for (before) |ev| { _ = try a.take(try inputOf(&buf, 1, seq, ev)); seq += 1; } // Another client joins, its view not live; the first's keys go on. _ = try a.openView(2); const joiner = try joinedNow(a, 3, 1); defer joiner.deinit(); try std.testing.expectEqual(digestOf(a), joiner.digest()); for (0..3) |_| { const u = try gpa.dupe(u8, try a.take(try inputOf(&buf, 1, seq, .{ .key = .{ .cp = 'd', .ctrl = true } }))); defer gpa.free(u); seq += 1; joiner.confirm(u); try agrees(a, joiner); } } test "a client joined from a dump makes a `/` query's rows as the session does, though only the session has drawn its owner" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host()); defer a.deinit(); // The session draws: its owner's colours painted for the view (File.refreshHighlights). { 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()); } _ = try a.openView(2); const joiner = try joinedNow(a, 3, 1); defer joiner.deinit(); try std.testing.expectEqual(digestOf(a), joiner.digest()); var buf: [256]u8 = undefined; for ("/co", 1..) |c, seq| { const u = try gpa.dupe(u8, try a.take(try inputOf(&buf, 1, @intCast(seq), .{ .key = .{ .cp = c, .text = &.{c} } }))); defer gpa.free(u); joiner.confirm(u); try agrees(a, joiner); } } // A query row's colours come from what this process has (its frames' // paint of the owner, File.highlights; a worker's paint kept in the // locations cache): out of the rows' digest. Whether a step asks a // worker to paint the rows' file (Stream.paintRows, an effect on the // tape) must not come from them: a session whose host paints on workers // (search), that has drawn its owner, and a client that has not. test "a client joined from a dump asks a worker for a `/` query's colours as the session does, though only the session has drawn its owner" { const Paints = struct { fn search(_: ?*anyopaque, _: u32) void {} const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .search = search }; }; const gpa = std.testing.allocator; // A view as tall as the text: the frame paints every line of it. const a = try Authority.init(gpa, .{ .cols = 80, .rows = 500, .file = "build.zig" }, .{ .vtable = &Paints.vtable }); defer a.deinit(); { 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()); } _ = try a.openView(2); const joiner = try joinedNow(a, 3, 1); defer joiner.deinit(); var buf: [256]u8 = undefined; for ("/co", 1..) |c, seq| { const u = try gpa.dupe(u8, try a.take(try inputOf(&buf, 1, @intCast(seq), .{ .key = .{ .cp = c, .text = &.{c} } }))); defer gpa.free(u); joiner.confirm(u); try agrees(a, joiner); } } // The same for the colours a worker painted earlier, kept in the session's // locations cache (a Grep since has asked again of every file): a dump // carries no cache, so a client joined since has none. test "a client joined from a dump asks a worker for a `/` query's colours as the session does, though only the session has them from an earlier paint" { const Paints = struct { fn search(_: ?*anyopaque, _: u32) void {} const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .search = search }; }; const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, .{ .vtable = &Paints.vtable }); defer a.deinit(); { const p = a.core; const f = &p.panes[0].?.file.?; const colors = try pardes.syntax.highlightFileRange(gpa, f.path, f.content, 0, f.content.len); defer gpa.free(colors); try p.locations_cache.put(p.tree_sitter_gpa, f.path, f.content, colors); } _ = try a.openView(2); const joiner = try joinedNow(a, 3, 1); defer joiner.deinit(); var buf: [256]u8 = undefined; for ("/co", 1..) |c, seq| { const u = try gpa.dupe(u8, try a.take(try inputOf(&buf, 1, @intCast(seq), .{ .key = .{ .cp = c, .text = &.{c} } }))); defer gpa.free(u); joiner.confirm(u); try agrees(a, joiner); } } test "a replica with no code for a kind whose state is not plain shows its pane as a line saying so, and its keys go to the authority" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); // What the host read off the library, as the `addon` event: the // replica's core takes the kind's words, never its code. var words: [64]pardes.Kind.LoadedWord = undefined; const counter = pardes.Kind.loadedOf(&Counter.ops, "/x/counter.so", @splat(7), &words); r.confirm(try a.local(.{ .addon = .{ .op = .load, .pane = .at(0), .kind = &counter } })); r.confirm(try a.local(.{ .command = "Counter" })); try std.testing.expect(r.core().kinds.ops[r.core().kinds.n - 1] == null); try std.testing.expect(try shows(r.core(), "addon counter 1 does not run in this client")); // A key into it, typed at the replica: the authority's kind takes it. var sent: std.ArrayListUnmanaged([]u8) = .empty; defer { for (sent.items) |m| gpa.free(m); sent.deinit(gpa); } try key(r, 'x', &sent); for (sent.items) |m| { r.confirm(try a.take(m)); r.settle(); } try std.testing.expect(try shows(a.core, "count 1")); try std.testing.expect(!try shows(r.core(), "count 1")); if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); try std.testing.expect(r.diverged == null); try std.testing.expectEqual(digestOf(a), r.digest()); } /// A kind whose place (`where`) is the rows its last view was told: a /// session's step that tells it moves its place, never a key's. const Placed = struct { const pa = pardes.Kind.c; 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(_: ?*anyopaque, _: [*c]const pa.pa_window, _: [*c]pa.pa_paint) callconv(.c) void {} fn view(st: ?*anyopaque, v: [*c]const pa.pa_view) callconv(.c) void { const n: *u32 = @ptrCast(@alignCast(st.?)); n.* = v.*.rows; } fn where(st: ?*anyopaque, buf: [*c]u8, len: u32) callconv(.c) u32 { const n: *u32 = @ptrCast(@alignCast(st.?)); return @intCast((std.fmt.bufPrint(buf[0..len], "1:0 {d}", .{n.*}) catch return 0).len); } const words = [_]pa.pa_word{std.mem.zeroInit(pa.pa_word, .{ .name = "Placed", .opens = 1, .doc = "a place" })}; 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 = "placed".* ++ @as([10]u8, @splat(0)), .version = 1, .exts = "", .words = &words, .nwords = 1 }), .open = open, .paint = paint, .view = view, .where = where, }); }; test "a kind's place moved in a step of another view's: a replica's key that reads it guesses the authority's" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); var words: [64]pardes.Kind.LoadedWord = undefined; const placed = pardes.Kind.loadedOf(&Placed.ops, "/x/placed.so", @splat(7), &words); r.confirm(try a.local(.{ .addon = .{ .op = .load, .pane = .at(0), .kind = &placed } })); // The replica's view opens the kind's pane, and an Esc goes back to // the file (Last): view 0 has the file. const own = try a.openView(1); r.view = own.view; r.confirm(own.unit); for ([_]pardes.Event{ .{ .command = "Placed" }, .{ .key = .{ .cp = pardes.Key.escape } } }) |ev| { r.confirm(try a.take(try r.input(ev))); r.settle(); } // View 0 resized, and a step of the session's own tells the kind: its // place moves in a step whose view has the file, which reads it not. var buf: [256]u8 = undefined; r.confirm(try a.take(try inputOf(&buf, 2, 1, .{ .resize = .{ .cols = 80, .rows = 20 } }))); r.confirm(try a.local(.tick)); // The replica's Esc back to the kind's pane: its jump reads the place. const fast = r.stats.fast; const missed = r.stats.mispredicted; const msg = try gpa.dupe(u8, try r.input(.{ .key = .{ .cp = pardes.Key.escape } })); defer gpa.free(msg); try std.testing.expectEqual(@as(usize, 1), r.applied); r.confirm(try a.take(msg)); r.settle(); try std.testing.expectEqual(missed, r.stats.mispredicted); try std.testing.expectEqual(fast + 1, r.stats.fast); try agrees(a, r); } /// Placed, plain (PA_PLAIN): a client runs it, and its state is the rows /// its last view was told. const Viewed = struct { const pa = pardes.Kind.c; const words = [_]pa.pa_word{std.mem.zeroInit(pa.pa_word, .{ .name = "Viewed", .opens = 1, .doc = "the rows its view was told" })}; 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 = "viewed".* ++ @as([10]u8, @splat(0)), .version = 1, .exts = "", .flags = pa.PA_PLAIN, .words = &words, .nwords = 1 }), .open = Placed.open, .paint = Placed.paint, .view = Placed.view, }); }; test "a client joins with its session's geometry as the session holds it: the view opened for it, not laid out yet, is not laid out in the client either, and a plain kind is told the same views on both" { // The soak's (test/replicas.zig): a client parted at its first unit // after its join, `addon pdf: its state after view is not the // session's`: it had laid every view out at its load, its own new one // too, which the session lays out at that view's first input. const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); var words: [64]pardes.Kind.LoadedWord = undefined; const viewed = pardes.Kind.loadedOf(&Viewed.ops, "/x/viewed.so", @splat(7), &words); _ = try a.local(.{ .addon = .{ .op = .load, .pane = .at(0), .kind = &viewed } }); _ = try a.local(.{ .command = "Viewed" }); const kid = a.core.view().active; const joined = (try a.join(1, null)).?; defer gpa.free(joined.dump); const r = try Replica.initDump(gpa, 1, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); defer r.deinit(); try std.testing.expect(r.loaded(joined.digest)); try runsHere(r, kid, &Viewed.ops); try std.testing.expectEqual(a.core.views[joined.view].?.rects[kid], r.core().views[joined.view].?.rects[kid]); // The session's own step tells the kind each view whose facts changed. r.confirm(try a.local(.tick)); r.settle(); try agrees(a, r); } /// A kind whose every key asks a job, for the job tokens' test. const Jobber = struct { const pa = pardes.Kind.c; fn open(_: [*c]const u8, _: [*c]const u8, _: u64) callconv(.c) ?*anyopaque { return pardes.Kind.api.alloc.?(4); } fn paint(_: ?*anyopaque, _: [*c]const pa.pa_window, _: [*c]pa.pa_paint) callconv(.c) void {} fn press(_: ?*anyopaque, _: [*c]const pa.pa_key) callconv(.c) c_int { _ = pardes.Kind.api.job.?(null, 0); return 1; } const words = [_]pa.pa_word{std.mem.zeroInit(pa.pa_word, .{ .name = "Jobber", .opens = 1, .doc = "a key a job" })}; 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 = "jobber".* ++ @as([10]u8, @splat(0)), .version = 1, .exts = "", .words = &words, .nwords = 1 }), .open = open, .paint = paint, .key = press, }); }; test "a client joined from a dump numbers a kind's next job as the session does" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); var words: [64]pardes.Kind.LoadedWord = undefined; const jobber = pardes.Kind.loadedOf(&Jobber.ops, "/x/jobber.so", @splat(7), &words); _ = try a.local(.{ .addon = .{ .op = .load, .pane = .at(0), .kind = &jobber } }); _ = try a.local(.{ .command = "Jobber" }); for (0..3) |_| _ = try a.local(.{ .key = .{ .cp = 'x', .text = "x" } }); const id = a.core.view().active; try std.testing.expectEqual(@as(u32, 3), a.core.panes[id].?.addon.?.tokens); const joiner = try joinedNow(a, 2, 1); defer joiner.deinit(); try std.testing.expectEqual(@as(u32, 3), joiner.core().panes[id].?.addon.?.tokens); try std.testing.expectEqual(digestOf(a), joiner.digest()); } test "a replica's word that opens a kind's pane with no file waits for the authority's open: never mispredicted" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); var words: [64]pardes.Kind.LoadedWord = undefined; const placed = pardes.Kind.loadedOf(&Placed.ops, "/x/placed.so", @splat(7), &words); r.confirm(try a.local(.{ .addon = .{ .op = .load, .pane = .at(0), .kind = &placed } })); // Its replica has no code for the kind: the open's outcome (its place, // `1:0 0`) is the authority's to say. const msg = try gpa.dupe(u8, try r.input(.{ .command = "Placed" })); defer gpa.free(msg); try std.testing.expectEqual(@as(usize, 0), r.applied); r.confirm(try a.take(msg)); r.settle(); try std.testing.expectEqual(@as(u32, 0), r.stats.mispredicted); try agrees(a, r); try std.testing.expect(r.core().panes[r.core().view().active].?.addon != null); } test "a client joined from a dump tells a kind each view's facts as the session does, the live one's and another's" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); var words: [64]pardes.Kind.LoadedWord = undefined; const placed = pardes.Kind.loadedOf(&Placed.ops, "/x/placed.so", @splat(7), &words); _ = try a.local(.{ .addon = .{ .op = .load, .pane = .at(0), .kind = &placed } }); _ = try a.local(.{ .command = "Placed" }); // A message in its pane: a band over its body, in each view. _ = try a.local(.{ .command = "Placed x" }); // The second client's view laid out by an input of its own, then the // first's resized: its kind told at the session's next step of its own. _ = try a.openView(2); var buf: [256]u8 = undefined; _ = try a.take(try inputOf(&buf, 2, 1, .{ .resize = .{ .cols = 80, .rows = 24 } })); _ = try a.take(try inputOf(&buf, 1, 1, .{ .resize = .{ .cols = 80, .rows = 20 } })); const joiner = try joinedNow(a, 3, 1); defer joiner.deinit(); try std.testing.expectEqual(digestOf(a), joiner.digest()); joiner.confirm(try a.local(.tick)); try agrees(a, joiner); } /// A plain kind whose key asks a job and whose job's answer moves its /// block: run by a client as by its session. const Asker = struct { const pa = pardes.Kind.c; fn open(_: [*c]const u8, _: [*c]const u8, _: u64) callconv(.c) ?*anyopaque { return pardes.Kind.api.alloc.?(4); } fn paint(_: ?*anyopaque, _: [*c]const pa.pa_window, _: [*c]pa.pa_paint) callconv(.c) void {} fn press(_: ?*anyopaque, _: [*c]const pa.pa_key) callconv(.c) c_int { _ = pardes.Kind.api.job.?(null, 0); return 1; } fn run(_: [*c]const u8, _: u32, out: [*c]pa.pa_out) callconv(.c) u32 { const b: [*]u8 = @ptrCast(out.*.alloc.?(out, 1) orelse return 0); b[0] = 1; return 1; } fn done(st: ?*anyopaque, _: u32, _: [*c]const u8, _: u32) callconv(.c) void { const n: *u32 = @ptrCast(@alignCast(st.?)); n.* += 1; } const words = [_]pa.pa_word{std.mem.zeroInit(pa.pa_word, .{ .name = "Asker", .opens = 1, .doc = "a key a job" })}; 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 = "asker".* ++ @as([11]u8, @splat(0)), .version = 1, .exts = "", .flags = pa.PA_PLAIN, .words = &words, .nwords = 1 }), .open = open, .paint = paint, .key = press, .job_run = run, .job_done = done, }); }; /// A host whose workers are all busy (tui.zig's `job` with its 16 tasks /// out): a kind's job runs at once, inside the host's call. const BusyHost = struct { var core: ?*Pardes = null; var tasks: @import("selection_pipe.zig").Tasks = .{ .len = @import("selection_pipe.zig").Tasks.capacity }; fn job(_: ?*anyopaque, id: pardes.Pane.Id, serial: u32, token: u32) void { const pane = id.index(); pardes.host_io.KindJob.start(std.testing.io, core.?, &tasks, pane, serial, token, null, never); } fn never(_: ?*anyopaque, j: *pardes.host_io.KindJob) void { j.drop(); } const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .job = job }; }; test "a kind's job answered at once inside its host's call (no worker free) is taken by a client as the session took it" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &BusyHost.vtable }); defer a.deinit(); BusyHost.core = a.core; const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); var words: [64]pardes.Kind.LoadedWord = undefined; const asker = pardes.Kind.loadedOf(&Asker.ops, "/x/asker.so", @splat(7), &words); r.confirm(try a.local(.{ .addon = .{ .op = .load, .pane = .at(0), .kind = &asker } })); // The client has its code (as a library of its own found by its scan). r.core().kinds.ops[r.core().kinds.byName("asker").?] = &Asker.ops; r.confirm(try a.local(.{ .command = "Asker" })); const id = a.core.view().active; // Its key asks a job, answered inside the key's unit: an input the // host made inside its call, on the tape (Effect.perform with no host // `job` lands it on the core's side, on no tape: a host must have one). r.confirm(try a.local(.{ .key = .{ .cp = 'x', .text = "x" } })); try agrees(a, r); try std.testing.expectEqual(@as(u32, 1), std.mem.bytesToValue(u32, a.core.panes[id].?.addon.?.plain.?[0..4])); try std.testing.expectEqualSlices(u8, a.core.panes[id].?.addon.?.plain.?, r.core().panes[id].?.addon.?.plain.?); } test "a closed terminal with a kitty image brought back on a client: its image drawn under a speculation, rolled back by another's unit, is drawn again from what the emulator holds" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host()); defer a.deinit(); const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.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 2x2 picture in RGB (f=24): drawn, the emulator keeps it as RGBA // of its own (TerminalImages.converted). a.output(.{ .output = .{ .pane = .at(shell), .bytes = "\x1b_Ga=T,i=7,f=24,s=2,v=2;ESIzESIzESIzESIz\x1b\\" } }); r.confirm((try a.pending()).?); // Closed and brought back: the client loads the session's dump of it, // its image with it. a.core.view().active = shell; r.confirm(try a.local(.{ .command = "Del" })); var line: [32]u8 = undefined; r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look @p{d}", .{a.core.store.closed.items[0].serial}) })); const back = for (r.core().panes) |slot| { if (slot) |pane| if (pane.terminal) |state| break state; } else return error.NotBack; try std.testing.expect(pardes.Term.hasImages(back)); // Typing goes to the text pane (the host's write of `active`, taped). a.core.view().active = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.file != null) break id; } else return error.NoTextPane; r.confirm(try a.local(.{ .focus = true })); const Seen = struct { px: ?[4]u8 = null, fn take(ctx: ?*anyopaque, s: *const pardes.Surface) bool { const seen: *@This() = @ptrCast(@alignCast(ctx.?)); for (s.placements.items) |pl| seen.px = pl.raster.bytes()[0..4].*; return true; } }; var sent: std.ArrayListUnmanaged([]u8) = .empty; defer { for (sent.items) |m| gpa.free(m); sent.deinit(gpa); } // Its own key, at once, a copy held; a frame drawn over it. try key(r, 'o', &sent); try std.testing.expect(r.copy.held); var seen: Seen = .{}; _ = r.draw(.{ .ctx = &seen, .f = Seen.take }); try std.testing.expectEqual([4]u8{ 0x11, 0x22, 0x33, 0xff }, seen.px.?); // The session's own key first: back to the copy, the key applied again. r.confirm(try a.local(.{ .key = .{ .cp = 'l', .text = "l" } })); r.settle(); seen = .{}; _ = r.draw(.{ .ctx = &seen, .f = Seen.take }); try std.testing.expectEqual([4]u8{ 0x11, 0x22, 0x33, 0xff }, seen.px.?); r.confirm(try a.take(sent.items[0])); r.settle(); try agrees(a, r); } /// The core's fields whose digests differ between the session and a /// client, named (tape.partsDiffer); empty when they agree. fn partsApart(a: *Authority, r: *Replica, arena: std.mem.Allocator) ![]const u8 { const want = try arena.create(tape.Parts); const got = try arena.create(tape.Parts); const w = digested: { const was = Stepping.begin(&a.t, null); defer was.end(); break :digested tape.digestParts(a.core, want); }; const g = digested: { const was = Stepping.begin(&r.t, &r.epoch); defer was.end(); break :digested tape.digestParts(r.core(), got); }; return if (std.mem.eql(u64, w, g)) "" else tape.partsDiffer(g, w, arena); } test "a terminal's program shows a kitty image: the client's emulator has it as the session's does, and its tag says what the session's does" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host()); defer a.deinit(); const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); const shell: u8 = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break @intCast(id); } else return error.NoShell; try std.testing.expectEqualStrings("", try partsApart(a, r, arena.allocator())); // In the session's order: the pump's unit, its bytes fed on every side; // then a step after it. a.output(.{ .output = .{ .pane = .at(shell), .bytes = "\x1b_Ga=T,i=7,f=24,s=2,v=2;ESIzESIzESIzESIz\x1b\\" } }); r.confirm((try a.pending()).?); r.settle(); r.confirm(try a.local(.{ .focus = true })); r.settle(); try std.testing.expect(pardes.Term.hasImages(a.core.panes[shell].?.terminal)); try std.testing.expect(pardes.Term.hasImages(r.core().panes[shell].?.terminal)); try std.testing.expectEqualStrings("", try partsApart(a, r, arena.allocator())); try agrees(a, r); const prefix = try pardes.tagline.prefixIn(r.core(), arena.allocator(), r.core().panes[shell].?); try std.testing.expect(std.mem.indexOf(u8, prefix, " petscii:") != null); } test "a command typed into a shell with prompt marks: every side notes it as its own emulator, fed the same bytes, numbers it, and Kill finds it" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const ShellHost = struct { fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool { return false; } fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {} const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write }; }; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &ShellHost.vtable }); defer a.deinit(); const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); const shell: u8 = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break @intCast(id); } else return error.NoShell; // pardes's own bash marks (host_io.zig): one command run, a prompt. const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; a.output(.{ .output = .{ .pane = .at(shell), .bytes = prompt ++ "ls\r\n\x1b]133;C;aid=pardes\x07a b\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt } }); r.confirm((try a.pending()).?); r.settle(); a.core.view().active = shell; r.confirm(try a.local(.{ .focus = true })); r.settle(); try std.testing.expectEqualStrings("", try partsApart(a, r, arena.allocator())); // Exec'd in the shell: typed at its prompt, the command noted. r.confirm(try a.local(.{ .command = "Exec sleep 9" })); r.settle(); // Its marks are its bytes' on every side: numbered alike. try std.testing.expectEqual(@as(u32, 2), a.core.panes[shell].?.sent_command.?.seq); try std.testing.expectEqual(@as(u32, 2), r.core().panes[shell].?.sent_command.?.seq); try std.testing.expectEqualStrings("", try partsApart(a, r, arena.allocator())); // Its echo and its C mark: running. Kill is asked for it. a.output(.{ .output = .{ .pane = .at(shell), .bytes = "sleep 9\r\n\x1b]133;C;aid=pardes\x07" } }); r.confirm((try a.pending()).?); r.settle(); r.confirm(try a.local(.{ .command = "Kill" })); r.settle(); try std.testing.expectEqualStrings("", try partsApart(a, r, arena.allocator())); try agrees(a, r); } test "a step of the session's own that reads a terminal right after its output, in one pump: its client replays it over the terminal as that output left it (the pty's bytes in the unit, fed in the tape's order)" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const ShellHost = struct { fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool { return false; } fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {} const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write }; }; const core = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }); defer core.deinit(); core.host = .{ .vtable = &ShellHost.vtable }; try core.pump(core.host); const shell: u8 = for (core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break @intCast(id); } else return error.NoShell; core.view().active = shell; // The session as runtime/session.zig runs it; the client's link in // memory. var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .threads = false }; defer ps.deinit(); defer ps.dropAll(core); var fds: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; defer _ = libc.close(fds[1]); ps.handed(fds[0], null); ps.boundary(core); const peer = for (ps.list) |slot| { if (slot) |x| if (x.fd == fds[0]) break x; } else return error.Refused; const f = (try wire.framed(peer.welcome[0..peer.welcome_len])).?; const w = (try wire.decodeServer(f.tag, f.payload)).welcome; var word: [16]u8 = undefined; const far = try wire.encodeClient(&word, .{ .far = false }); _ = peer.take(far[0], far[wire.header_len..]); ps.post(.{ .joined = .{ .peer = peer, .gen = peer.gen } }); var whole: std.ArrayListUnmanaged(u8) = .empty; defer whole.deinit(gpa); var pos: usize = 0; for (peer.blobs.items) |b| { try whole.appendSlice(gpa, peer.dump[pos..b.at]); try whole.appendSlice(gpa, b.bytes); pos = b.at; } try whole.appendSlice(gpa, peer.dump[pos..]); const r = try Replica.initDump(gpa, w.client, w.view.index(), whole.items, .{ .cols = 80, .rows = 24, .boot = .tty }); defer r.deinit(); try std.testing.expect(r.loaded(w.digest)); var link: Link = .{ .r = r, .fd = fds[1] }; defer link.deinit(gpa); const Down = struct { // What the session queued for its client, taken in order. fn all(from: *Peer, l: *Link) !void { var at: usize = 0; while (try wire.framed(from.out.items[at..])) |m| : (at += m.total) l.take(switch (std.enums.fromInt(wire.ServerTag, m.tag).?) { .unit => .{ .unit = try std.heap.c_allocator.dupe(u8, m.payload) }, else => return error.UnexpectedFrame, }); from.out.clearRetainingCapacity(); } }; const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; core.update(.{ .output = .{ .pane = .at(shell), .bytes = prompt } }); try core.pump(core.host); ps.boundary(core); try Down.all(peer, &link); try std.testing.expect(r.diverged == null); try std.testing.expectEqual(tape.digestOf(core), r.digest()); // One pump: its shell echoes a line typed at the prompt, then an Exec of // the session's own (a 9P ctl write, a timer's) asks whether the prompt // is empty to type at. The session reads "no" and opens a command pane; // the client must read the same. core.update(.{ .output = .{ .pane = .at(shell), .bytes = "typed" } }); core.update(.{ .command = "Exec true" }); try core.pump(core.host); ps.boundary(core); try Down.all(peer, &link); if (r.diverged) |why| { std.debug.print("the client: {s}\n", .{why}); return error.Diverged; } try std.testing.expectEqual(tape.digestOf(core), r.digest()); } test "a far client's own Del of a pane whose kind's state is not plain, rolled back by another's unit: the pane comes back whole, and is closed again with the session's order" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); var words: [64]pardes.Kind.LoadedWord = undefined; const counter = pardes.Kind.loadedOf(&Counter.ops, "/x/counter.so", @splat(7), &words); _ = try a.local(.{ .addon = .{ .op = .load, .pane = .at(0), .kind = &counter } }); _ = try a.local(.{ .command = "Counter" }); // Joined from the dump: the kind's pane is a line here (no code), its // slot the dump's. const r = try joinedNow(a, 1, 0); defer r.deinit(); const id = r.core().view().active; try std.testing.expect(r.core().panes[id].?.addon != null); var sent: std.ArrayListUnmanaged([]u8) = .empty; defer { for (sent.items) |m| gpa.free(m); sent.deinit(gpa); } // Its own Del at once, and a key after it: the pane's teardown (its // slot freed) is that key's step's (`reapPanes`). try sent.append(gpa, try gpa.dupe(u8, try r.input(.{ .command = "Del" }))); try key(r, 'j', &sent); try std.testing.expectEqual(@as(usize, 2), r.applied); try std.testing.expect(r.core().panes[id] == null); // The session's own key first: back to the copy, the pane with it. r.confirm(try a.local(.{ .key = .{ .cp = 'l', .text = "l" } })); r.settle(); for (sent.items) |m| { r.confirm(try a.take(m)); r.settle(); } try agrees(a, r); try std.testing.expect(r.core().panes[id] == null); } /// A session's host whose fire-and-forget entries a test counts: a /// clipboard set, a paste asked, a link opened; with `tell`, a clipboard /// set says so into the core during the call, as a host's `saved` does. /// A client joined from the session's dump in its view, the unit after the /// join taken (the session's host said to it, as at any join's first), at /// the start of a second (`freshSecond`). fn joinedFresh(a: *Authority) !*Replica { _ = try a.unit(0, 0); const r = try joinedNow(a, 1, 0); errdefer r.deinit(); r.confirm(try a.local(.tick)); r.settle(); freshSecond(); return r; } const SeenHost = struct { core: ?*Pardes = null, yanked: u32 = 0, asked: u32 = 0, linked: u32 = 0, tell: bool = false, fn of(ctx: ?*anyopaque) *SeenHost { return @ptrCast(@alignCast(ctx.?)); } fn setClipboard(ctx: ?*anyopaque, _: []const u8) void { const h = of(ctx); h.yanked += 1; if (h.tell) h.core.?.setMessage(.at(h.core.?.view().active), "yanked"); } fn readClipboard(ctx: ?*anyopaque) void { of(ctx).asked += 1; } fn openLink(ctx: ?*anyopaque, _: []const u8) void { of(ctx).linked += 1; } fn watchTheme(_: ?*anyopaque, _: u32, _: bool) void {} fn watchFile(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8, _: bool, _: pardes.WatchMode) void {} const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .set_clipboard = setClipboard, .read_clipboard = readClipboard, .open_link = openLink, .watch_theme = watchTheme, .watch_file = watchFile }; fn host(h: *SeenHost) pardes.Host { return .{ .ctx = h, .vtable = &vtable }; } }; test "a client's step that asks the session's host for something that returns nothing goes on at once, and the session's unit confirms it: nothing rolled back" { const gpa = std.testing.allocator; var h: SeenHost = .{}; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host()); defer a.deinit(); h.core = a.core; const r = try joinedFresh(a); defer r.deinit(); const msg = try gpa.dupe(u8, try r.input(.{ .command = "ClipYank" })); defer gpa.free(msg); try std.testing.expectEqual(@as(usize, 1), r.applied); try std.testing.expectEqual(@as(u32, 0), r.stats.stopped); r.confirm(try a.take(msg)); r.settle(); try std.testing.expectEqual(@as(u32, 1), h.yanked); try std.testing.expectEqual(@as(u32, 1), r.stats.fast); try std.testing.expectEqual(@as(u32, 0), r.stats.mispredicted); try agrees(a, r); } test "a client's step whose session's host says something into the core during the call it made: its speculation rolled back, then the session's state" { const gpa = std.testing.allocator; var h: SeenHost = .{ .tell = true }; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host()); defer a.deinit(); h.core = a.core; const r = try joinedFresh(a); defer r.deinit(); const msg = try gpa.dupe(u8, try r.input(.{ .command = "ClipYank" })); defer gpa.free(msg); try std.testing.expectEqual(@as(u32, 0), r.stats.stopped); r.confirm(try a.take(msg)); r.settle(); try std.testing.expectEqual(@as(u32, 1), r.stats.mispredicted); try agrees(a, r); } test "a client's ThemeFile waits for the session, whose host loads the file into the core; a Theme after it lets the file go at once" { const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "t.zon", .data = ".{ .name = \"seen\" }\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 line: [std.Io.Dir.max_path_bytes + 16]u8 = undefined; var h: SeenHost = .{}; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host()); defer a.deinit(); h.core = a.core; const r = try joinedFresh(a); defer r.deinit(); for ([_][]const u8{ try std.fmt.bufPrint(&line, "ThemeFile {s}/t.zon", .{dir}), "Theme acme" }, [_]u32{ 1, 0 }) |cmd, stops| { const before = r.stats.stopped; const msg = try gpa.dupe(u8, try r.input(.{ .command = cmd })); defer gpa.free(msg); try std.testing.expectEqual(stops, r.stats.stopped - before); r.confirm(try a.take(msg)); r.settle(); try agrees(a, r); } try std.testing.expectEqual(@as(u32, 0), r.stats.mispredicted); } test "a client's yank and paste of the system clipboard are its own frontend's: its view counts them, at once and as the session does, and the session's host is asked neither" { const gpa = std.testing.allocator; var h: SeenHost = .{}; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host()); defer a.deinit(); h.core = a.core; _ = try a.unit(0, 0); const j = (try a.join(1, null)) orelse return error.NoView; defer gpa.free(j.dump); const r = try Replica.initDump(gpa, 1, j.view, j.dump, .{ .cols = 80, .rows = 24 }); defer r.deinit(); r.confirm(try a.local(.tick)); r.settle(); freshSecond(); for ([_][]const u8{ "ClipYank", "ClipPaste" }) |cmd| { const msg = try gpa.dupe(u8, try r.input(.{ .command = cmd })); defer gpa.free(msg); r.confirm(try a.take(msg)); r.settle(); } try std.testing.expectEqual(@as(u32, 0), r.stats.stopped); try std.testing.expectEqual(@as(u32, 0), r.stats.mispredicted); try std.testing.expectEqual(@as(u32, 0), h.yanked + h.asked); for ([_]*Pardes{ a.core, r.core() }) |c| { try std.testing.expectEqual(@as(u32, 1), c.views[j.view].?.yanks); try std.testing.expectEqual(@as(u32, 1), c.views[j.view].?.pastes); } try agrees(a, r); // The session's own view's yank is its host's, as before. _ = try a.own(.{ .command = "ClipYank" }); try std.testing.expectEqual(@as(u32, 1), h.yanked); } test "a client's own Zerox and Del of a file pane are instant: what Recent keeps of the file is what its open learned, not a question to the disk; Recent has its place as the session's always did" { const gpa = std.testing.allocator; var h: SeenHost = .{}; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, h.host()); defer a.deinit(); h.core = a.core; var cwd: [std.Io.Dir.max_path_bytes]u8 = undefined; var line: [std.Io.Dir.max_path_bytes + 32]u8 = undefined; var path_buf: [std.Io.Dir.max_path_bytes + 32]u8 = undefined; const dir = std.mem.span(@as([*:0]u8, @ptrCast(std.c.getcwd(&cwd, cwd.len) orelse return error.NoCwd))); const path = try std.fmt.bufPrint(&path_buf, "{s}/build.zig.zon", .{dir}); _ = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{path}) }); const r = try joinedFresh(a); defer r.deinit(); // The twin, then each closed: the twin, the file. for ([_][]const u8{ "Zerox", "Del", "Del" }) |cmd| { const msg = try gpa.dupe(u8, try r.input(.{ .command = cmd })); 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, 0), r.stats.mispredicted); try std.testing.expect(a.core.recent.get(path) != null); } /// A kind whose state is plain and that takes no keys: normal mode has /// them in its pane. const Still = struct { const pa = pardes.Kind.c; fn open(_: [*c]const u8, _: [*c]const u8, _: u64) callconv(.c) ?*anyopaque { return pardes.Kind.api.alloc.?(4); } fn paint(_: ?*anyopaque, _: [*c]const pa.pa_window, _: [*c]pa.pa_paint) callconv(.c) void {} const words = [_]pa.pa_word{std.mem.zeroInit(pa.pa_word, .{ .name = "Still", .opens = 1, .doc = "a pane that takes no keys" })}; 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 = "still".* ++ @as([11]u8, @splat(0)), .version = 1, .exts = "", .flags = pa.PA_PLAIN, .words = &words, .nwords = 1 }), .open = open, .paint = paint, }); }; test "a client's n in a kind's pane is a motion: it steps to the next place a result row holds at once, asking the disk nothing of words that might name files" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); var cwd: [std.Io.Dir.max_path_bytes]u8 = undefined; const dir = std.mem.span(@as([*:0]u8, @ptrCast(std.c.getcwd(&cwd, cwd.len) orelse return error.NoCwd))); var words: [64]pardes.Kind.LoadedWord = undefined; const still = pardes.Kind.loadedOf(&Still.ops, "/x/still.so", @splat(7), &words); _ = try a.local(.{ .addon = .{ .op = .load, .pane = .at(0), .kind = &still } }); // The kind's pane, its +Search (a place a row, as a kind's `/` leaves // it), and a scratch whose words name files in the session's directory // (as a command's output would). _ = try a.local(.{ .command = "Still" }); const kid = a.core.view().active; try pardes.panes.Output.fillResults(a.core, kid, dir, .search, "first", try a.core.gpa.dupe(u8, "build.zig:1:1 first\n"), null); const rid = a.core.panes[kid].?.search_pane.?; _ = try a.local(.{ .command = "New" }); for ("ibuild.zig mise.toml") |ch| _ = try a.local(.{ .key = .{ .cp = ch, .text = &[1]u8{ch} } }); _ = try a.local(.{ .key = .{ .cp = pardes.Key.escape } }); // The walk last stood in the scratch, at its start: its words first. const scratch = a.core.panes[a.core.view().active].?; scratch.body.cur_row = 0; scratch.body.cur_col = 0; a.core.look_walk_owner = scratch.serial; a.core.view().active = kid; const r = try joinedFresh(a); defer r.deinit(); r.core().kinds.ops[r.core().kinds.byName("still").?] = &Still.ops; const msg = try gpa.dupe(u8, try r.input(.{ .key = .{ .cp = 'n', .text = "n" } })); defer gpa.free(msg); try std.testing.expectEqual(@as(u32, 0), r.stats.stopped); try std.testing.expectEqual(rid, r.core().view().active); r.confirm(try a.take(msg)); r.settle(); try std.testing.expectEqual(@as(u32, 1), r.stats.fast); try agrees(a, r); } // ---- the line a far client draws: what may wait, and nothing else ---- /// The kinds of pane the walk below stands in: a file's, a plain kind's, /// a shell's raw (its program has the keys) and a shell's in normal mode /// (pardes's own keys over its history). `any` is a row's for all four. /// `addon`: a kind whose state is its own on the session (a PDF's), which /// the walk does not stand in (its Still has no search, place or word): /// the soak's (test/replicas.zig) PDF and pictures are, judged by name. /// `command`: a pane in a directory with a finished command pane, which a /// line run there runs in again (exec.runCommand); the walk stands in none: /// the soak's are, judged by name, and the test after the walk. const On = enum { any, file, kind, shell, shell_normal, addon, dir, command }; /// What a far client may wait a round trip for (the user's line, P14: a /// side effect on the system may be slow; motions, edits and layout are /// instant): a word (`Look`), a key (`C-x`, `A-x`, `g x`: after a prefix), /// or a gesture (`click shell`), on a kind of pane, the stop's name /// (`Tape.poisoned_by`), and why. A `*` in a row takes any text there. /// The test below walks every word of the registry, every key and the /// gestures between panes against it: what stops and is not here fails /// it, and a row nothing stopped at says it is stale. const Wait = struct { what: []const u8, on: On, stop: []const u8, why: []const u8 }; const may_wait = [_]Wait{ // A shell's program has the keys: what reaches it is its input (a far // shell may feel like ssh). .{ .what = "*", .on = .shell, .stop = "pty_write", .why = "a key into a shell's program" }, // A file from the session's disk (P14). .{ .what = "Look *", .on = .any, .stop = "resolve", .why = "a name looked for on the session's disk" }, .{ .what = "Look *", .on = .any, .stop = "read_file", .why = "a jump from a held pane (a kind's, a listing's) opens its reader on the file, read from the session's disk: a reading pane showing it is not focused (pick-ui SPEC §6.1)" }, .{ .what = "LookNext", .on = .any, .stop = "resolve", .why = "a Look's walk: each word asked of the disk" }, .{ .what = "LookPrev", .on = .any, .stop = "resolve", .why = "a Look's walk: each word asked of the disk" }, .{ .what = "Mini *", .on = .any, .stop = "resolve", .why = "a file opened by name, from the session's disk" }, .{ .what = "Get", .on = .any, .stop = "read_file", .why = "the file read again from the session's disk" }, .{ .what = "Get", .on = .dir, .stop = "dir_listing", .why = "a directory listed again from the session's disk" }, // A directory's pane (Dir.zig): its entries are names on the session's disk. .{ .what = "Enter", .on = .dir, .stop = "resolve", .why = "the entry under the cursor opened, from the session's disk" }, .{ .what = "* Enter", .on = .dir, .stop = "resolve", .why = "the entry opened (Enter after a prefix still opens it)" }, .{ .what = "Tab", .on = .dir, .stop = "kind", .why = "what the entry under the cursor is, asked of the session's disk" }, .{ .what = "* Tab", .on = .dir, .stop = "kind", .why = "what the entry is (Tab after a prefix still asks)" }, .{ .what = "Save", .on = .any, .stop = "write_file", .why = "a save" }, // A program run, a shell opened or closed: the session's processes. .{ .what = "Exec *", .on = .any, .stop = "kind", .why = "a program run: its name asked of the disk first" }, .{ .what = "Root *", .on = .any, .stop = "kind", .why = "the project's root, a `.jj` or `.git` at or above the pane's directory asked of the session's disk (Pick.workTree), as Find's listing and a program run are the session's (SPC f F, SPC f G, SPC :'s line)" }, .{ .what = "Exec *", .on = .any, .stop = "tty_taken", .why = "a program run in a shell: whether one has it, the session's" }, .{ .what = "Exec *", .on = .command, .stop = "run a command", .why = "a line run again in its directory's finished command pane: its process and its emulator are the session's" }, .{ .what = "Term", .on = .any, .stop = "kind", .why = "a shell opened: its name asked of the disk first" }, .{ .what = "A-n", .on = .any, .stop = "open a terminal", .why = "a shell opened" }, .{ .what = "* A-n", .on = .any, .stop = "open a terminal", .why = "a shell opened (Alt-n after a prefix is still the global key)" }, .{ .what = "Del", .on = .any, .stop = "close a terminal", .why = "a shell closed: its pty and emulator are the session's" }, .{ .what = "DelAbove", .on = .any, .stop = "close a terminal", .why = "a shell closed" }, .{ .what = "DelBelow", .on = .any, .stop = "close a terminal", .why = "a shell closed" }, .{ .what = "Delcol", .on = .any, .stop = "close a terminal", .why = "a shell closed with its column" }, .{ .what = "SPC d", .on = .any, .stop = "close a terminal", .why = "Del, a shell closed" }, .{ .what = "C-w d", .on = .any, .stop = "close a terminal", .why = "Del, a shell closed" }, // The session's own: it dumps, quits, execs itself, lets its frontend go. .{ .what = "Exit", .on = .any, .stop = "write_dump", .why = "the session's: it dumps and quits" }, .{ .what = "SPC q", .on = .any, .stop = "write_dump", .why = "Exit" }, .{ .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 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" }, .{ .what = "Panes", .on = .any, .stop = "the authority's own state", .why = "the session's closed panes" }, .{ .what = "Recent", .on = .any, .stop = "the authority's own state", .why = "Recent, the user's" }, .{ .what = "History", .on = .any, .stop = "the authority's own state", .why = "History, the user's" }, .{ .what = "Plumb", .on = .any, .stop = "the authority's own state", .why = "the plumbing rules, the session's file" }, .{ .what = "Config", .on = .any, .stop = "the authority's own state", .why = "the config file, the session's" }, .{ .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 +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" }, // jj run in the session's tree (jj.zig `show`, `diffChange`, // `diffPair`): what its repository holds, the session's disk. .{ .what = "At *", .on = .any, .stop = "jj", .why = "a file at a revision, asked of the session's repository" }, // 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" }, .{ .what = "*", .on = .addon, .stop = "a kind's address", .why = "a place in a kind's pane (`Look doc.pdf:3`): its own state" }, .{ .what = "*", .on = .addon, .stop = "a kind's close", .why = "a kind's pane closed: its state let go on the session" }, .{ .what = "*", .on = .addon, .stop = "a kind's word", .why = "a word to a kind (a key it takes as one): its own state" }, .{ .what = "*", .on = .addon, .stop = "a kind's open", .why = "a kind's pane opened (`Life`): its state made on the session" }, .{ .what = "*", .on = .addon, .stop = "a key into a kind's pane", .why = "a key to a kind this client does not run (no library for it here, or not PA_PLAIN): its state the session's" }, } ++ (if (pardes.builtins.capabilities.font_picker) [_]Wait{ // A window's view's words, which a terminal's build has too: a window // client of its session runs them. .{ .what = "Font *", .on = .any, .stop = "fonts", .why = "the session's machine's fonts, its disk" }, .{ .what = "Fonts", .on = .any, .stop = "fonts", .why = "the session's machine's fonts, its disk" }, } else [_]Wait{}); /// Whether a stop of that name (`Tape.poisoned_by`) is one `may_wait` /// lists for something: the soak's (test/replicas.zig) judge of its /// clients' inputs, which it cannot name as the walk does. pub fn mayWait(stop: []const u8) bool { for (may_wait) |row| if (std.mem.eql(u8, row.stop, stop)) return true; return false; } /// The keys the walk types: every printable one, and the specials a /// frontend reads; each plain, with Ctrl and with Alt. const walk_keys = keys: { @setEvalBranchQuota(20000); var ks: []const pardes.Key = &.{}; for (0x20..0x7f) |c| ks = ks ++ .{pardes.Key{ .cp = c, .text = &[1]u8{c} }}; const K = pardes.Key; for ([_]u21{ K.enter, K.escape, K.tab, K.backspace, K.up, K.down, K.left, K.right, K.home, K.end, K.page_up, K.page_down, K.delete, K.insert }) |cp| ks = ks ++ .{pardes.Key{ .cp = cp }}; for (0..12) |n| ks = ks ++ .{pardes.Key{ .cp = K.f1 + n }}; var all: []const pardes.Key = ks; for (ks) |k| all = all ++ .{pardes.Key{ .cp = k.cp, .ctrl = true }}; for (ks) |k| all = all ++ .{pardes.Key{ .cp = k.cp, .alt = true }}; break :keys all; }; /// Every prefix key the normal mode has (config's `*_prefix`), the leader /// and Ctrl-w: each is typed before every key of `walk_keys`. const walk_prefixes = prefixes: { @setEvalBranchQuota(200000); const config = pardes.config; var ks: []const pardes.Key = &.{}; for (@typeInfo(config).@"struct".decl_names) |d| { if (std.mem.indexOf(u8, d, "_prefix") == null and !std.mem.eql(u8, d, "leader")) continue; const v = @field(config, d); if (@TypeOf(v) == comptime_int) { ks = ks ++ .{pardes.Key{ .cp = v, .text = &[1]u8{v} }}; } else if (@TypeOf(v) == []const config.Chord) { const c = v[0]; ks = ks ++ .{pardes.Key{ .cp = c.cp, .ctrl = c.ctrl, .alt = c.alt, .text = if (c.ctrl or c.alt) "" else &[1]u8{c.cp} }}; } } break :prefixes ks; }; /// The argument a word that means nothing without one is walked with, and /// Root's, whose bare `:` line asks the disk nothing. const walk_samples = [_]struct { []const u8, []const u8 }{ .{ "Look", "mise.toml" }, .{ "Exec", "echo" }, .{ "Mount", "x" }, .{ "Unmount", "x" }, .{ "Msg", "hi" }, .{ "ThemeFile", "t.zon" }, .{ "Edit", "s/a/b/" }, .{ "Mini", "x" }, .{ "Find", "x" }, .{ "Grep", "x" }, .{ "Rename", "x" }, .{ "WsSymbols", "x" }, .{ "Theme", "acme" }, .{ "Font", "Mono 12" }, .{ "TaglineSize", "100" }, .{ "WindowOpacity", "100" }, .{ "MessageLinger", "1000" }, .{ "InactiveDim", "0" }, .{ "GripWidth", "100" }, .{ "At", "@-" }, .{ "Root", "Find" }, }; fn keyName(buf: []u8, k: pardes.Key) []const u8 { const K = pardes.Key; const mod: []const u8 = if (k.ctrl) "C-" else if (k.alt) "A-" else ""; const special: ?[]const u8 = switch (k.cp) { ' ' => "SPC", K.enter => "Enter", K.escape => "Esc", K.tab => "Tab", K.backspace => "BS", K.up => "Up", K.down => "Down", K.left => "Left", K.right => "Right", K.home => "Home", K.end => "End", K.page_up => "PgUp", K.page_down => "PgDn", K.delete => "Del", K.insert => "Ins", else => null, }; if (special) |s| return std.fmt.bufPrint(buf, "{s}{s}", .{ mod, s }) catch unreachable; if (k.cp >= K.f1 and k.cp < K.f1 + 25) return std.fmt.bufPrint(buf, "{s}F{d}", .{ mod, k.cp - K.f1 + 1 }) catch unreachable; return std.fmt.bufPrint(buf, "{s}{u}", .{ mod, k.cp }) catch unreachable; } /// `v` with every entry a step may ask that it leaves out doing nothing /// (answering zero): a client's step stops, or goes on, as against a real /// session's (a client's tape offers only the entries its session's host /// has). The loop's own (`now`, `wait_input`, the frame's) no step asks. pub fn everyEntry(comptime v: pardes.Host.VTable) pardes.Host.VTable { const Noop = struct { fn Of(comptime F: type) type { const info = @typeInfo(@typeInfo(@typeInfo(F).optional.child).pointer.child).@"fn"; const R = info.return_type.?; const P = info.param_types; return switch (P.len) { 1 => struct { fn f(_: ?*anyopaque) R { return std.mem.zeroes(R); } }, 2 => struct { fn f(_: ?*anyopaque, _: P[1].?) R { return std.mem.zeroes(R); } }, 3 => struct { fn f(_: ?*anyopaque, _: P[1].?, _: P[2].?) R { return std.mem.zeroes(R); } }, 4 => struct { fn f(_: ?*anyopaque, _: P[1].?, _: P[2].?, _: P[3].?) R { return std.mem.zeroes(R); } }, 5 => struct { fn f(_: ?*anyopaque, _: P[1].?, _: P[2].?, _: P[3].?, _: P[4].?) R { return std.mem.zeroes(R); } }, else => @compileError("a host entry of more arguments"), }; } }; var all = v; for (@typeInfo(pardes.Host.VTable).@"struct".field_names) |name| { if (std.mem.eql(u8, name, "now") or std.mem.eql(u8, name, "wait_input") or std.mem.eql(u8, name, "present") or std.mem.eql(u8, name, "post_present") or std.mem.eql(u8, name, "poll_frame")) continue; if (@field(all, name) == null) @field(all, name) = &Noop.Of(@FieldType(pardes.Host.VTable, name)).f; } return all; } /// A session's host with every entry a step may ask, each doing nothing. const FullHost = struct { const vtable = everyEntry(.{}); fn host() pardes.Host { return .{ .vtable = &vtable }; } }; /// One pane's walk: each input (or few) applied by the client at once, or /// stopped, then taken back, so the next starts where it did. const Walk = struct { r: *Replica, on: On, seen: *[may_wait.len]bool, hit: *[may_wait.len]bool, unlisted: u32 = 0, tried: u32 = 0, /// `pattern` with at most one `*`, which takes any text. fn matches(pattern: []const u8, what: []const u8) bool { const star = std.mem.indexOfScalar(u8, pattern, '*') orelse return std.mem.eql(u8, pattern, what); return what.len >= pattern.len - 1 and std.mem.startsWith(u8, what, pattern[0..star]) and std.mem.endsWith(u8, what, pattern[star + 1 ..]); } /// Every word, with a sample argument where one is required. fn words(w: *Walk) !void { var line: [128]u8 = undefined; for (std.enums.values(pardes.builtins.registry.Builtin())) |b| { const name = @tagName(b); const arg: ?[]const u8 = for (walk_samples) |s| { if (std.mem.eql(u8, s[0], name)) break s[1]; } else null; if (pardes.builtins.registry.requiresArg(b) and arg == null) { std.debug.print("may_wait: `{s}` requires an argument: give it one in walk_samples\n", .{name}); return error.NoSample; } const cmd = if (arg) |x| try std.fmt.bufPrint(&line, "{s} {s}", .{ name, x }) else name; try w.try_(cmd, &.{.{ .command = cmd }}); } } /// The name of what stopped the inputs, "" when none did. fn try_(w: *Walk, what: []const u8, evs: []const pardes.Event) !void { const r = w.r; w.tried += 1; r.stats.stops = @splat(.{}); const before = r.stats.stopped; for (evs) |ev| _ = try r.input(ev); const stopped = r.stats.stopped != before; // Taken back: the copy put back, nothing pending. r.toConfirmed(); for (r.pending.items) |p| r.freePending(p); r.pending.clearRetainingCapacity(); r.blocked = null; r.dirty = false; if (r.diverged) |why| { std.debug.print("may_wait: `{s}` on {t}: the client failed: {s}\n", .{ what, w.on, why }); return error.Diverged; } for (may_wait, 0..) |row, i| if ((row.on == .any or row.on == w.on) and matches(row.what, what)) { w.seen[i] = true; }; if (!stopped) return; for (r.stats.stops) |st| if (st.n > 0) { const listed = for (may_wait, 0..) |row, i| { if ((row.on == .any or row.on == w.on) and matches(row.what, what) and std.mem.eql(u8, row.stop, st.name)) { w.hit[i] = true; break true; } } else false; if (!listed) { w.unlisted += 1; std.debug.print("may_wait: `{s}` on {t} stopped at `{s}`: far away it waits a round trip; keep its step off the device, or list it in may_wait with why\n", .{ what, w.on, st.name }); } }; } }; test "a far client's every word and key, on a file's pane, a kind's and a shell's, and the gestures between them beside a shell that asked for focus events: what waits is in may_wait, with why, and nothing else waits" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 120, .rows = 40, .boot = .tty }, FullHost.host()); defer a.deinit(); var cwd: [std.Io.Dir.max_path_bytes]u8 = undefined; var line: [std.Io.Dir.max_path_bytes + 32]u8 = undefined; const dir = std.mem.span(@as([*:0]u8, @ptrCast(std.c.getcwd(&cwd, cwd.len) orelse return error.NoCwd))); // The shell the session booted (none without a terminal), its program // asking for focus events; a file; a plain kind's pane. const shell: ?usize = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break id; } else null; if (shell) |id| { a.output(.{ .output = .{ .pane = .at(id), .bytes = "\x1b[?1004h$ " } }); _ = (try a.pending()).?; } _ = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/mise.toml", .{dir}) }); const file = a.core.view().active; var words: [64]pardes.Kind.LoadedWord = undefined; const still = pardes.Kind.loadedOf(&Still.ops, "/x/still.so", @splat(7), &words); _ = try a.local(.{ .addon = .{ .op = .load, .pane = .at(0), .kind = &still } }); _ = try a.local(.{ .command = "Still" }); const kind = a.core.view().active; try std.testing.expect(file != kind and a.core.panes[file].?.file != null and a.core.panes[kind].?.addon != null); // A directory's pane (Dir.zig), listed from the disk. _ = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/", .{dir}) }); const listing = a.core.view().active; try std.testing.expect(a.core.panes[listing].?.file.?.listing != null); var seen: [may_wait.len]bool = @splat(false); var hit: [may_wait.len]bool = @splat(false); var unlisted: u32 = 0; var tried: u32 = 0; const stands = [_]struct { On, ?usize }{ .{ .file, file }, .{ .kind, kind }, .{ .shell, shell }, .{ .shell_normal, shell }, .{ .dir, listing } }; for (stands) |stand| { const on, const at = stand; const id = at orelse continue; a.core.view().active = id; if (on == .shell_normal) _ = try a.local(.{ .key = .{ .cp = a.core.opts.tty_toggle, .ctrl = true } }); defer if (on == .shell_normal) { a.core.view().active = id; _ = a.local(.{ .key = .{ .cp = a.core.opts.tty_toggle, .ctrl = true } }) catch {}; }; const r = try joinedFresh(a); defer r.deinit(); r.core().kinds.ops[r.core().kinds.byName("still").?] = &Still.ops; r.settle(); try std.testing.expectEqual(id, r.core().view().active); if (on == .shell) try std.testing.expect(pardes.Term.modes(r.core().panes[id].?.terminal).focus); var w: Walk = .{ .r = r, .on = on, .seen = &seen, .hit = &hit }; try w.words(); // Every key, plain, with Ctrl and with Alt, and after each prefix. var name_buf: [64]u8 = undefined; for (walk_keys) |k| try w.try_(keyName(&name_buf, k), &.{.{ .key = k }}); for (walk_prefixes) |pk| { var pre_buf: [16]u8 = undefined; const pre = keyName(&pre_buf, pk); for (walk_keys) |k| { var both: [96]u8 = undefined; try w.try_(try std.fmt.bufPrint(&both, "{s} {s}", .{ pre, keyName(&name_buf, k) }), &.{ .{ .key = pk }, .{ .key = k } }); } } // The gestures between panes: a click on each pane's body, each // pane's grip dragged up two rows, the window's keyboard lost and // lost and found again. const v = r.core().view(); for ([_]struct { []const u8, ?usize }{ .{ "file", file }, .{ "kind", kind }, .{ "shell", shell } }) |target| { const tname, const tid = target; const t = tid orelse continue; const rect = v.rects[t]; const body_row = rect.y + r.core().panes[t].?.tag_rows + 1; const click = [_]pardes.Event{ .{ .mouse = .{ .button = .left, .kind = .press, .col = rect.x + 2, .row = body_row } }, .{ .mouse = .{ .button = .left, .kind = .release, .col = rect.x + 2, .row = body_row } }, }; try w.try_(try std.fmt.bufPrint(&line, "click {s}", .{tname}), &click); const up = rect.y -| 2; const grip = [_]pardes.Event{ .{ .mouse = .{ .button = .left, .kind = .press, .col = rect.x, .row = rect.y } }, .{ .mouse = .{ .button = .left, .kind = .drag, .col = rect.x, .row = up } }, .{ .mouse = .{ .button = .left, .kind = .release, .col = rect.x, .row = up } }, }; try w.try_(try std.fmt.bufPrint(&line, "grip {s}", .{tname}), &grip); } try w.try_("focus lost", &.{.{ .focus = false }}); try w.try_("focus lost and found", &.{ .{ .focus = false }, .{ .focus = true } }); unlisted += w.unlisted; tried += w.tried; } // A terminal's build has the window's words too, which a window's view // runs (a window client of its session; builtins.capabilities): its // words walked again in one. if (comptime pardes.builtins.desktop and pardes.platform != .gui) { a.core.view().active = file; _ = try a.local(.{ .frontend = .{ .windowed = true } }); const r = try joinedFresh(a); defer r.deinit(); var w: Walk = .{ .r = r, .on = .file, .seen = &seen, .hit = &hit }; try w.words(); unlisted += w.unlisted; tried += w.tried; } // A row is stale where every kind of pane was walked: with no terminal // compiled in (core-test), a shell's rows stop nothing. var stale: u32 = 0; if (shell != null) for (may_wait, seen, hit) |row, s, h| if (s and !h) { stale += 1; std.debug.print("may_wait: the row `{s}` on {t} at `{s}` is stale: nothing walked stopped there (delete it)\n", .{ row.what, row.on, row.stop }); }; if (unlisted + stale > 0) std.debug.print("may_wait: {d} inputs walked, {d} stopped unlisted, {d} rows stale\n", .{ tried, unlisted, stale }); try std.testing.expectEqual(@as(u32, 0), unlisted); try std.testing.expectEqual(@as(u32, 0), stale); } test "a far client's line run again in its directory's finished command pane waits for the session's order, at a stop may_wait lists: its process and its emulator are the session's" { // The soak's (test/replicas.zig, seed 3 rtt 80): a client's key stopped // at `spawn`, which may_wait does not list. Its speculation ran the // reused pane's whole run (exec.runCommand): the emulator's writes // refused (`a terminal's output`), then the spawn effect (a host entry // that keeps stopping), the last one naming the stop. if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane's terminal const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const file = a.core.view().active; _ = try a.local(.{ .command = "Exec true" }); const cmd = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.command != null) break id; } else return error.NoCommandPane; _ = try a.local(.{ .exited = .{ .pane = .at(cmd), .status = 0 } }); _ = try a.local(.{ .eof = .{ .pane = .at(cmd) } }); try std.testing.expect(a.core.panes[cmd].?.command_done); a.core.view().active = file; const r = try joinedFresh(a); defer r.deinit(); // The same line from the file's pane: its directory's finished pane runs it. const stopped = r.stats.stopped; const msg = try gpa.dupe(u8, try r.input(.{ .command = "Exec true" })); defer gpa.free(msg); try std.testing.expectEqual(stopped + 1, r.stats.stopped); if (!mayWait(r.t.poisoned_by)) std.debug.print("stopped at `{s}`\n", .{r.t.poisoned_by}); try std.testing.expect(mayWait(r.t.poisoned_by)); r.confirm(try a.take(msg)); r.settle(); try agrees(a, r); try std.testing.expect(!a.core.panes[cmd].?.command_done); } test "a far client's click into a shell whose program asked for focus events is instant: the session's step tells the program, a round trip later, and the client's guess is confirmed" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const Told = struct { var bytes: [64]u8 = undefined; var len: usize = 0; fn write(_: ?*anyopaque, _: pardes.Pane.Id, b: []const u8) void { @memcpy(bytes[len..][0..b.len], b); len += b.len; } const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .pty_write = write }; }; Told.len = 0; const a = try Authority.init(gpa, .{ .cols = 120, .rows = 40, .boot = .tty }, .{ .vtable = &Told.vtable }); 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" }); const r = try joinedFresh(a); defer r.deinit(); r.settle(); Told.len = 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); } 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 } }))); try std.testing.expectEqual(@as(u32, 0), r.stats.stopped); try std.testing.expectEqual(@as(usize, shell), r.core().view().active); for (sent.items) |m| { const u = try gpa.dupe(u8, try a.take(m)); defer gpa.free(u); r.confirm(u); r.settle(); } try std.testing.expectEqualStrings("\x1b[I", Told.bytes[0..Told.len]); try std.testing.expectEqual(@as(u32, 0), r.stats.mispredicted); try std.testing.expectEqual(@as(u32, 2), r.stats.fast); try agrees(a, r); } test "a far client's own Look of ~/x, bare Shell and a word that runs in the session's directory read the session's facts: its speculation asks its own machine's environment nothing" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const r = try joinedFresh(a); defer r.deinit(); try std.testing.expectEqualStrings(a.core.sessionShell(), r.core().sessionShell()); try std.testing.expectEqualStrings(a.core.sessionDir(), r.core().sessionDir()); for ([_][]const u8{ "Look ~/x", "Shell", "Tutor" }) |cmd| { _ = try r.input(.{ .command = cmd }); // What it recorded: applied, its speculation's; stopped, the tape's // last (a speculation runs to its end, stopped or not). const records = if (r.applied > 0) r.pending.items[0].spec.? else r.t.buf.items; var records_text: std.Io.Writer.Allocating = .init(gpa); defer records_text.deinit(); tape.describe(records, &records_text.writer); if (std.mem.indexOf(u8, records_text.written(), "host env\n") != null) { std.debug.print("{s} read the environment:\n{s}", .{ cmd, records_text.written() }); return error.ReadTheEnvironment; } r.toConfirmed(); for (r.pending.items) |p| r.freePending(p); r.pending.clearRetainingCapacity(); r.blocked = null; r.dirty = false; } } test "a far client's replay of the session's DumpDir takes the session's answer to whether the directory may be written, not its own disk's" { if (std.c.getuid() == 0) return error.SkipZigTest; // root writes anywhere const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); 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 ro_buf: [std.Io.Dir.max_path_bytes + 8:0]u8 = undefined; const ro = try std.fmt.bufPrintSentinel(&ro_buf, "{s}/ro", .{dir}, 0); // The session's machine: a directory it may not write in. if (std.c.mkdir(ro, 0o500) != 0) return error.NoDir; defer _ = std.c.chmod(ro, 0o700); const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); const r = try joinedFresh(a); defer r.deinit(); var line: [std.Io.Dir.max_path_bytes + 32]u8 = undefined; const u = try gpa.dupe(u8, try a.local(.{ .command = try std.fmt.bufPrint(&line, "DumpDir {s}/dumps", .{ro}) })); defer gpa.free(u); try std.testing.expectEqualStrings("", a.core.settings.dump_dir.get()); // The client's machine: the same path, and it may. if (std.c.chmod(ro, 0o700) != 0) return error.NoChmod; r.confirm(u); r.settle(); try agrees(a, r); try std.testing.expectEqualStrings("", r.core().settings.dump_dir.get()); } test "a far client's replay of the session's Fonts and Font takes the session's machine's fonts, not its own" { if (comptime !pardes.builtins.capabilities.font_picker) return error.SkipZigTest; const gpa = std.testing.allocator; const fonts = @import("dev").fonts; const Shell = @import("dev").host_io.Shell; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.createDirPath(std.testing.io, "session/.local/share/fonts"); try tmp.dir.createDirPath(std.testing.io, "client"); const face = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, "assets/MapleMono-NF-Regular.ttf", gpa, .limited(64 << 20)); defer gpa.free(face); // Its family renamed, so that no face of this machine's shares its name. for ([_][]const u8{ "Maple", "\x00M\x00a\x00p\x00l\x00e" }, [_][]const u8{ "Qzxjv", "\x00Q\x00z\x00x\x00j\x00v" }) |from, to| { var at: usize = 0; while (std.mem.indexOfPos(u8, face, at, from)) |i| : (at = i + to.len) @memcpy(face[i..][0..to.len], to); } try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "session/.local/share/fonts/seen.ttf", .data = face }); 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 homes: [2][std.Io.Dir.max_path_bytes + 16:0]u8 = undefined; const session_home = try std.fmt.bufPrintSentinel(&homes[0], "{s}/session", .{dir}, 0); const client_home = try std.fmt.bufPrintSentinel(&homes[1], "{s}/client", .{dir}, 0); // HOME as it was, after (a test's: runtime never sets the environment). const was = if (std.c.getenv("HOME")) |h| try gpa.dupeSentinel(u8, std.mem.span(h), 0) else null; defer if (was) |h| gpa.free(h); _ = Shell.setenv("PARDES_TEST_ENVIRON_COPIED", "1", 1); defer _ = if (was) |h| Shell.setenv("HOME", h, 1) else @import("dev").host_io.testUnsetenv("HOME"); // The face the session's machine has and the client's lacks: its name. var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); _ = Shell.setenv("HOME", session_home, 1); const name = for (fonts.list(arena.allocator(), null)) |f| { if (std.mem.startsWith(u8, f.path, session_home)) break f.name; } else return error.SkipZigTest; // not a face the scan takes // The two machines answer differently, or this one cannot stand for two. const session_first = fonts.list(arena.allocator(), name)[0].path; const session_faces = fonts.list(arena.allocator(), null).len; _ = Shell.setenv("HOME", client_home, 1); const client_named = fonts.list(arena.allocator(), name); if (fonts.list(arena.allocator(), null).len == session_faces and client_named.len > 0 and std.mem.eql(u8, client_named[0].path, session_first)) return error.SkipZigTest; _ = Shell.setenv("HOME", session_home, 1); // A window's view: the font words are a window's. const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .windowed = true }, TestHost.host()); defer a.deinit(); const r = try joinedFresh(a); defer r.deinit(); var line: [256]u8 = undefined; const units = [_][]u8{ try gpa.dupe(u8, try a.local(.{ .command = "Fonts" })), try gpa.dupe(u8, try a.local(.{ .command = try std.fmt.bufPrint(&line, "Font {s} 13", .{name}) })), }; defer for (units) |u| gpa.free(u); _ = Shell.setenv("HOME", client_home, 1); for (units) |u| r.confirm(u); r.settle(); try agrees(a, r); } // An idle client asked the session's digest once quiet after a change; the // session's pump that answers it sends a unit before the answer (its clock // read), which must not count as a change, or an idle pair asks, wakes and // answers every 300 ms for ever. A unit while asked is the answer's to // cover; an answer let go (not quiet then) covers nothing. test "an idle client's check answered covers the units that came while it was asked: it asks no other until something changes" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host()); defer a.deinit(); const r = try joinedNow(a, 1, 0); defer r.deinit(); var fds: [2]c_int = undefined; try std.testing.expectEqual(@as(c_int, 0), libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds)); defer for (fds) |fd| { _ = libc.close(fd); }; var c: Link = .{ .r = r, .fd = fds[0], .now = std.time.ns_per_s }; // Each unit made as the client takes it, on its clock (Link.behind). const unit = struct { fn of(au: *Authority, l: *const Link) !Said { const u = try std.heap.c_allocator.dupe(u8, try au.local(.tick)); std.mem.writeInt(i64, u[14..22], @intCast(l.now.?), .little); return .{ .unit = u }; } }.of; // Something changed, 300 ms quiet since its last input: asked. c.take(try unit(a, &c)); try std.testing.expectEqual(@as(?u32, null), c.quietCheck()); try std.testing.expect(c.asked); // The session's pump for it (a unit), then the answer: agreed, and // nothing to ask after it however long it stays quiet. c.take(try unit(a, &c)); c.take(.{ .checked = digestOf(a) }); try std.testing.expect(!c.asked and c.r.diverged == null); c.now.? += 10 * std.time.ns_per_s; try std.testing.expectEqual(@as(?u32, null), c.quietCheck()); try std.testing.expect(!c.asked); // A unit after it is a change again. c.take(try unit(a, &c)); c.now.? += std.time.ns_per_s; _ = c.quietCheck(); try std.testing.expect(c.asked); // An answer let go (an input of its own pending then) covers nothing: // asked again once quiet. _ = try r.pend(.{ .key = .{ .cp = 'j' } }); 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()); 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()); 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 } }, // Two rows for the two panes under the window row (a lone column has // no column row, UX K'2): one each. .{ .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()); 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 }); 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" }); const r = try joinedFresh(a); defer r.deinit(); 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| { const u = try gpa.dupe(u8, try a.take(m)); defer gpa.free(u); 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); } } } }; const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, .{ .vtable = &WorkerSearch.vtable }); 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()); 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(); } 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 }); 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 }); 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.expectEqualStrings("--:--:-- yanked x", r.core().messages.headline().?.text.slice()); } // A script's `pty/run` in a shell (ninep/pty.zig): the open, the line, the // marks that end it, its answer read and the open released, each a step of // the session's, with a client that joined from a dump taking every unit. test "a client joined from a dump takes a 9P pty/run in a shell as the session does: the line sent at the prompt, its end answered" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; const RunHost = struct { fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool { return false; } fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {} const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write }; }; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &RunHost.vtable }); defer a.deinit(); const r = try Replica.init(gpa, 1, try a.unit(0, 0)); defer r.deinit(); const shell: u8 = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break @intCast(id); } else return error.NoShell; const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; a.output(.{ .output = .{ .pane = .at(shell), .bytes = prompt ++ "ls\r\n\x1b]133;C;aid=pardes\x07a b\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt } }); r.confirm((try a.pending()).?); r.settle(); // A script's listing open, held across the join (a reader of /index). { const was = Stepping.begin(&a.t, null); _ = a.core.serveFs(.{ .tag = 9, .op = .open, .node = @backingInt(pardes.ctlfs.TopFile.index) }); was.end(); a.seq += 1; r.confirm(try a.unit(0, a.seq)); r.settle(); } const joined = (try a.join(2, null)).?; defer gpa.free(joined.dump); r.confirm(joined.unit); const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); defer late.deinit(); late.core().echo = null; try std.testing.expectEqual(joined.digest, late.digest()); const node = pardes.ctlfs.Node.of(a.core.panes[shell].?.serial, .pty_run); const Serve = struct { fn serve(s: *Authority, rs: []const *Replica, req: pardes.ctlfs.Req) !pardes.ctlfs.Reply { const was = Stepping.begin(&s.t, null); const reply = s.core.serveFs(req); s.core.pump(s.host) catch {}; was.end(); s.seq += 1; const u = try s.unit(0, s.seq); for (rs) |x| { x.confirm(u); x.settle(); } return reply; } fn output(s: *Authority, rs: []const *Replica, pane: u8, bytes: []const u8) !void { s.output(.{ .output = .{ .pane = .at(pane), .bytes = bytes } }); const u = (try s.pending()).?; for (rs) |x| { x.confirm(u); x.settle(); } } }; const both = [_]*Replica{ r, late }; const h = (try Serve.serve(a, &both, .{ .tag = 1, .op = .open, .node = node, .omode = 2 })).handle; _ = try Serve.serve(a, &both, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "true\n" }); try Serve.output(a, &both, shell, "true\r\n\x1b]133;C;aid=pardes\x07\x1b]133;D;0;aid=pardes\x07" ++ prompt); const answer = try Serve.serve(a, &both, .{ .tag = 3, .op = .read, .node = node, .handle = h, .size = 64 }); try std.testing.expectEqualStrings("exit 0\n", a.core.fsPayload(answer)); _ = try Serve.serve(a, &both, .{ .tag = 4, .op = .release, .node = node, .handle = h, .opened = true }); try Serve.output(a, &both, shell, "\x1b]133;A;cl=line;aid=pardes\x07"); try agrees(a, r); try agrees(a, late); } test "a script's half line held over a copy taken ahead, its next write run and its rest moved to the front in place, put back by a rollback: the line replayed is the session's" { var n = try NinepJoin.init("one\n", TestHost.host()); defer n.deinit(); try n.join(); const r = n.late.?; const exec = n.node(.exec); const h = (try n.serve(.{ .tag = 1, .op = .open, .node = exec, .omode = 1 }, true)).handle; _ = try n.serve(.{ .tag = 2, .op = .write, .node = exec, .handle = h, .data = "Ta" }, true); r.ready(); // Replayed over the copy and kept: `Tab 8` runs, `Un` is held where // `Ta` was, in the buffer the copy holds. _ = try n.serve(.{ .tag = 3, .op = .write, .node = exec, .handle = h, .data = "b 8\nUn" }, true); try std.testing.expect(r.copy.held and r.since.items.len > 0); var sent: std.ArrayListUnmanaged([]u8) = .empty; defer { for (sent.items) |m| std.testing.allocator.free(m); sent.deinit(std.testing.allocator); } try key(r, 'l', &sent); try std.testing.expectEqual(@as(usize, 1), r.applied); // The session's key first: a rollback, the write replayed again. try n.send(try n.a.local(.{ .key = .{ .cp = 'j', .text = "j" } })); try std.testing.expect(r.stats.foreign > 0); try n.send(try n.a.take(sent.items[0])); _ = try n.serve(.{ .tag = 4, .op = .write, .node = exec, .handle = h, .data = "do\n" }, true); _ = try n.serve(.{ .tag = 5, .op = .release, .node = exec, .handle = h, .opened = true }, true); if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); try std.testing.expect(r.diverged == null and r.quiet()); try n.agree(); } // Del with a pane above and below asks which way the space goes, its // question shown once a delay is up (builtins.zig): its time was the // host's clock read in the step, an answering entry a speculation stops at. test "a far client's Del with panes above and below is applied at once, and its question's time is the session's" { const gpa = std.testing.allocator; const Clocked = struct { var now_ns: u64 = 7 * std.time.ns_per_s; fn now(_: ?*anyopaque) u64 { return now_ns; } const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .now = now }; }; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 30, .file = "mise.toml" }, .{ .vtable = &Clocked.vtable }); defer a.deinit(); _ = try a.local(.{ .command = "New" }); const mid = a.core.view().active; _ = try a.local(.{ .command = "New" }); { const was = Stepping.begin(&a.t, null); defer was.end(); a.core.view().active = mid; } const r = try joinedFresh(a); defer r.deinit(); var sent: std.ArrayListUnmanaged([]u8) = .empty; defer { for (sent.items) |m| gpa.free(m); sent.deinit(gpa); } Clocked.now_ns += std.time.ns_per_s; try key(r, ' ', &sent); try key(r, 'd', &sent); try std.testing.expectEqual(@as(usize, 2), r.applied); try std.testing.expect(r.core().panes[mid].?.prompt == .del_side); 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); // The question shows a delay after it was asked, on the session's clock. a.pump(); r.confirm((try a.pending()).?); r.settle(); try agrees(a, r); try std.testing.expectEqual(Clocked.now_ns + pardes.config.del_question_delay_ns, r.core().panes[mid].?.question_due_ns); } // ---- a client that joins a session with 9P work under way ---- // // A 9P request is an input every replica replays, so the state the 9P // tree builds from the requests (the open records, each pane's `fs`) is // a client's for everything after its join: what was made before it // comes in the join's dump, or the client steps the next request // otherwise than its session. /// A session with a file pane and its 9P server, and a client joined /// from its dump (`join`) that takes every unit after. const NinepJoin = struct { a: *Authority, late: ?*Replica = null, serial: u32, fn init(text: []const u8, host: pardes.Host) !NinepJoin { const a = try Authority.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, host); errdefer a.deinit(); const was = Stepping.begin(&a.t, null); const pane = try a.core.setTestFile(text); was.end(); _ = try a.unit(0, 0); return .{ .a = a, .serial = pane.serial }; } fn deinit(n: *NinepJoin) void { if (n.late) |r| r.deinit(); n.a.deinit(); } fn node(n: *const NinepJoin, file: pardes.ctlfs.PaneFile) u64 { return pardes.ctlfs.Node.of(n.serial, file); } /// One request as the session's 9P server serves it, a step of its /// own, then (`pumped`) its loop's pass: a join can come between the /// two, the session's loop being elsewhere. Its unit to the client. fn serve(n: *NinepJoin, req: pardes.ctlfs.Req, pumped: bool) !pardes.ctlfs.Reply { const a = n.a; const was = Stepping.begin(&a.t, null); const reply = a.core.serveFs(req); if (pumped) a.core.pump(a.host) catch {}; was.end(); a.seq += 1; try n.send(try a.unit(0, a.seq)); return reply; } /// A pass of the session's loop with no request: its unit. fn pump(n: *NinepJoin) !void { n.a.pump(); try n.send((try n.a.pending()).?); } fn send(n: *NinepJoin, u: []const u8) !void { const r = n.late orelse return; const kept = try std.testing.allocator.dupe(u8, u); defer std.testing.allocator.free(kept); r.confirm(kept); r.settle(); } /// A client joins now, from the session's dump, at the digest the /// session had. fn join(n: *NinepJoin) !void { const joined = (try n.a.join(1, null)).?; defer std.testing.allocator.free(joined.dump); const r = try Replica.initDump(std.testing.allocator, 1, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); r.core().echo = null; n.late = r; try std.testing.expectEqual(joined.digest, r.digest()); } fn agree(n: *NinepJoin) !void { try agrees(n.a, n.late.?); } fn opened(n: *NinepJoin, at: u64, mode: u8) !u32 { const h = (try n.serve(.{ .tag = 1, .op = .open, .node = at, .omode = mode }, true)).handle; if (h == 0) return error.NoRecord; return h; } fn wrote(n: *NinepJoin, at: u64, h: u32, data: []const u8) !void { _ = try n.serve(.{ .tag = 2, .op = .write, .node = at, .handle = h, .data = data }, true); } fn loadsSame(n: *NinepJoin) !void { try loadsAsSession(n.a, 1); } }; /// A client `client` of the session `a` joined now, as `Peers.join` joins /// one, and let go: its load is the session as dumped, at the welcome's /// digest; the fields that differ named (`loadDiffers`) when it is not. /// A test's session ends with it to say its state crosses a join whole. pub fn loadsAsSession(a: *Authority, client: u16) !void { const gpa = std.testing.allocator; const joined = (try a.join(client, null)) orelse return error.NoView; defer gpa.free(joined.dump); const r = try Replica.initDump(gpa, client, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); defer r.deinit(); if (!r.loaded(joined.digest)) { var named: [400]u8 = undefined; std.debug.print("the client's load is not the session: {s}\n", .{loadDiffers(r, joined.dump, &named)}); return error.LoadedAnother; } _ = try a.leave(client, false); } /// Every type the core's walk reaches that walks itself by hand /// (walk.handWalked: a `digest` or a dump of its own, which can take what /// the other does not), and the test that joins a client from a dump of a /// session holding it and checks the load by the welcome's digest. The one /// walk holds every other field: its digest, its dump and its rollback copy /// are the same fields by one declaration (walk.zig `replica`). const hand_walked = .{ .{ pardes.filesystem.Namespace, "a client joined while 9P requests hold each kind of state the core keeps for them" }, .{ pardes.ctlfs.Open.What, "a client joined while 9P requests hold each kind of state the core keeps for them" }, .{ pardes.ctlfs.pane.State, "a client joined after a script set a pane's addr, its limit, or truncated its dot" }, .{ Term.State, "bytes: a client joins from a dump with its terminals whole" }, .{ pardes.Kind.Slot, "a client joined from a dump numbers a kind's next job as the session does" }, .{ @import("locations.zig").Row, "a client joined from a dump makes a `/` query's rows as the session does" }, .{ @import("jj.zig").Session, "a client replays Changes from what the session's jj answered and ends equal" }, .{ pardes.panes.File.Layers, "a client replays Changes from what the session's jj answered and ends equal" }, .{ pardes.panes.File.Layer, "a client replays the layer's lines and an edit refused among them, and ends equal; a client joined over a pane showing the layer loads its lines" }, }; test "every type the core's walk reaches that hashes or dumps itself by hand has a test joining a client over it (hand_walked)" { inline for (comptime walk.handWalked(&.{Pardes})) |T| { const listed = comptime for (hand_walked) |entry| { if (entry[0] == T) break true; } else false; if (!listed) { std.debug.print("{s} walks itself by hand and no test joins a client over it: one, and its line in hand_walked\n", .{@typeName(T)}); return error.NotListed; } } // ...and every line is a type that does: one that walks itself by the // one walk again leaves no line behind. inline for (hand_walked) |entry| { const reached = comptime for (walk.handWalked(&.{Pardes})) |T| { if (entry[0] == T) break true; } else false; if (!reached) { std.debug.print("{s} no longer walks itself by hand: its line in hand_walked goes\n", .{@typeName(entry[0])}); return error.Stale; } } } test "a client whose load is not the session says which field, in its words and its log" { const gpa = std.testing.allocator; var n = try NinepJoin.init("one\n", TestHost.host()); defer n.deinit(); const before = (try n.a.join(1, null)).?; defer gpa.free(before.dump); _ = try n.a.leave(1, false); _ = try n.serve(.{ .tag = 1, .op = .open, .node = @backingInt(pardes.ctlfs.TopFile.screen) }, true); const after = (try n.a.join(1, null)).?; defer gpa.free(after.dump); // The dump before the open, checked by the digest after it and named // by its fields: what a dump made at one moment and a digest taken at // another said. const Tail = struct { fn at(dump: []const u8) usize { const parts = pardes.dump.joinParts(std.testing.allocator, dump).?; defer std.testing.allocator.free(parts); return dump.len - parts.len * 8 - 16; } }; var spliced: std.ArrayListUnmanaged(u8) = .empty; defer spliced.deinit(gpa); try spliced.appendSlice(gpa, before.dump[0..Tail.at(before.dump)]); try spliced.appendSlice(gpa, after.dump[Tail.at(after.dump)..]); var j: Joined = .{ .fd = -1, .pid = 0, .client = 1, .view = before.view, .gmtoff = 0, .dump = spliced.items, .digest = after.digest, .semantics = wire.semantics }; var why: [600]u8 = @splat(0); try std.testing.expect(fromDump(gpa, &j, .{ .cols = 80, .rows = 24 }, null, &why, nowNs(), "") == null); try std.testing.expectEqualStrings("the session's dump loaded as another session: fs differs", std.mem.sliceTo(&why, 0)); } /// Each kind of state 9P requests leave in the core between two requests /// of a script's (fs.Namespace and the `tree.Open` records it holds: what /// each `What` holds, a half line, a line being discarded, a name taken, a /// look's results, writes held as one edit, a header's truncation), made by /// the requests a script makes. const NinepKinds = struct { const top = pardes.ctlfs.TopFile; fn screen(n: *NinepJoin) !void { _ = try n.opened(@backingInt(top.screen), 0); } fn logReader(n: *NinepJoin) !void { _ = try n.opened(@backingInt(top.log), 0); } fn listing(n: *NinepJoin) !void { _ = try n.opened(@backingInt(top.index), 0); } fn event(n: *NinepJoin) !void { _ = try n.opened(n.node(.event), 2); } fn lock(n: *NinepJoin) !void { try n.wrote(n.node(.ctl), try n.opened(n.node(.ctl), 1), "lock\n"); } fn halfLine(n: *NinepJoin) !void { try n.wrote(n.node(.exec), try n.opened(n.node(.exec), 1), "Ne"); } fn discarding(n: *NinepJoin) !void { try n.wrote(n.node(.exec), try n.opened(n.node(.exec), 1), "a\x01b"); } fn named(n: *NinepJoin) !void { try n.wrote(n.node(.name), try n.opened(n.node(.name), 1), "/tmp/named.txt\n"); } fn results(n: *NinepJoin) !void { try n.wrote(n.node(.exec), try n.opened(n.node(.exec), 2), "Zerox\n"); } fn heldWrites(n: *NinepJoin) !void { try n.wrote(n.node(.body), try n.opened(n.node(.body), 1), "two\n"); } fn sel(n: *NinepJoin) !void { try n.wrote(n.node(.sel), try n.opened(n.node(.sel), 1), "a"); } fn pager(n: *NinepJoin) !void { try n.wrote(@backingInt(top.pager), try n.opened(@backingInt(top.pager), 1), "/\nheld text"); } fn plumb(n: *NinepJoin) !void { try n.wrote(@backingInt(top.send), try n.opened(@backingInt(top.send), 1), "src\n"); } fn port(n: *NinepJoin) !void { _ = try n.opened(pardes.ctlfs.Node.ofPort(pardes.Plumb.portIndex(n.a.core, "edit") orelse return error.NoPort), 0); } fn headerCut(n: *NinepJoin) !void { // Its open holds no record: the truncation is the session's. const h = (try n.serve(.{ .tag = 1, .op = .open, .node = @backingInt(top.tag), .omode = 1 }, true)).handle; _ = try n.serve(.{ .tag = 3, .op = .setattr, .node = @backingInt(top.tag), .handle = h, .truncate = true }, true); } const all = .{ .{ "an open of /screen (What.snapshot)", screen }, .{ "a reader of /log (What.log)", logReader }, .{ "a listing frozen at its open (What.frozen)", listing }, .{ "a pane's event reader (What.event)", event }, .{ "a ctl open holding a pane's lock (What.ctl)", lock }, .{ "half a line held on exec (What.lines, Open.pending)", halfLine }, .{ "a refused line's tail being discarded (Open.discarding)", discarding }, .{ "a name taken by an open (Open.named)", named }, .{ "a look's results on its open and the session's (Open.results, Namespace.results)", results }, .{ "writes to a body held as one edit (What.writes, Namespace.batch)", heldWrites }, .{ "an open of sel writing on from its last (What.writes)", sel }, .{ "a /pager open holding its text (What.pager)", pager }, .{ "a plumb message short of its data (What.plumb)", plumb }, .{ "a reader of a plumb port (What.port)", port }, .{ "the workspace's tag truncated (Namespace.header_*)", headerCut }, }; }; test "a client joined while 9P requests hold each kind of state the core keeps for them loads the session: digest(load(dump)) is the session's, kind by kind" { inline for (NinepKinds.all) |case| { var n = try NinepJoin.init("one\n", TestHost.host()); defer n.deinit(); const empty = walk.digest(pardes.filesystem.Namespace, &n.a.core.fs); try case[1](&n); // The kind is there: the core's 9P state holds something. try std.testing.expect(walk.digest(pardes.filesystem.Namespace, &n.a.core.fs) != empty); n.loadsSame() catch |err| { std.debug.print("the kind: {s}\n", .{case[0]}); return err; }; } } test "a client joined at any point of a script's random 9P requests (opens of every kind, writes, reads, releases, truncations) loads the session: a seeded few hundred joins" { var prng = std.Random.DefaultPrng.init(0x5eed_d16e); const rand = prng.random(); var n = try NinepJoin.init("one two\nthree\n", TestHost.host()); defer n.deinit(); const top = pardes.ctlfs.TopFile; const nodes = [_]u64{ @backingInt(top.screen), @backingInt(top.log), @backingInt(top.index), @backingInt(top.tag), @backingInt(top.pager), @backingInt(top.send), pardes.ctlfs.Node.ofPort(pardes.Plumb.portIndex(n.a.core, "edit").?), @backingInt(top.exec), n.node(.exec), n.node(.body), n.node(.ctl), n.node(.event), n.node(.sel), n.node(.look), n.node(.data), n.node(.addr), }; const words = [_][]const u8{ "Ne", "w\n", "a\x01", "b\n", "lock\n", "unlock\n", "one", "\n", "src\n", "#0,#3", "x" }; var held: [24]struct { node: u64, h: u32 } = undefined; var nheld: usize = 0; var joins: usize = 0; var tag: u64 = 10; while (joins < 300) { tag += 1; const pick = rand.uintLessThan(u8, 10); if (pick >= 8) { try n.loadsSame(); joins += 1; continue; } if (pick < 3 or nheld == 0) { if (nheld == held.len) continue; const node = nodes[rand.uintLessThan(usize, nodes.len)]; const h = (try n.serve(.{ .tag = tag, .op = .open, .node = node, .omode = rand.uintLessThan(u8, 3) }, true)).handle; if (h != 0) { held[nheld] = .{ .node = node, .h = h }; nheld += 1; } continue; } const at = rand.uintLessThan(usize, nheld); const o = held[at]; switch (pick) { 3, 4 => _ = try n.serve(.{ .tag = tag, .op = .write, .node = o.node, .handle = o.h, .data = words[rand.uintLessThan(usize, words.len)] }, true), 5 => _ = try n.serve(.{ .tag = tag, .op = .read, .node = o.node, .handle = o.h, .size = 64 }, true), 6 => _ = try n.serve(.{ .tag = tag, .op = .setattr, .node = o.node, .handle = o.h, .truncate = true }, true), else => { _ = try n.serve(.{ .tag = tag, .op = .release, .node = o.node, .handle = o.h, .opened = true }, true); held[at] = held[nheld - 1]; nheld -= 1; }, } } } test "a 9P request answered while a join's dump is out in the host is the client's next unit's, not its load's: a join asks the host nothing, and the client loads the session at the welcome's digest" { var n = try NinepJoin.init("one\n", TestHost.host()); defer n.deinit(); // The session's io, whose stat lets a connection task in first, as the // turn's yield around a host call does (tape.out): a script's open of // /screen, a request that waits for no quiet (ninep/tree.zig needsQuiet). const Gap = struct { var on: *NinepJoin = undefined; var base: std.Io = undefined; var vtable: std.Io.VTable = undefined; var served: u32 = 0; fn stat(ud: ?*anyopaque, dir: std.Io.Dir, path: []const u8, o: std.Io.Dir.StatFileOptions) std.Io.Dir.StatFileError!std.Io.File.Stat { served += 1; _ = on.a.core.serveFs(.{ .tag = 9, .op = .open, .node = @backingInt(pardes.ctlfs.TopFile.screen) }); return base.vtable.dirStatFile(ud, dir, path, o); } }; Gap.on = &n; Gap.base = n.a.t.io; Gap.vtable = n.a.t.io.vtable.*; Gap.vtable.dirStatFile = Gap.stat; n.a.t.io = .{ .userdata = Gap.base.userdata, .vtable = &Gap.vtable }; const yields = pardes.turn.yields; n.loadsSame() catch |err| { std.debug.print("the join's dump asked the host {d} times, gave up the turn {d} times\n", .{ Gap.served, pardes.turn.yields - yields }); return err; }; try std.testing.expectEqual(yields, pardes.turn.yields); try std.testing.expectEqual(0, Gap.served); } test "a client joined while a script's open of a pane's exec holds half a line runs the line its session runs" { var n = try NinepJoin.init("one\n", TestHost.host()); defer n.deinit(); const exec = n.node(.exec); const h = (try n.serve(.{ .tag = 1, .op = .open, .node = exec, .omode = 1 }, true)).handle; _ = try n.serve(.{ .tag = 2, .op = .write, .node = exec, .handle = h, .data = "Ne" }, true); try n.join(); _ = try n.serve(.{ .tag = 3, .op = .write, .node = exec, .handle = h, .data = "w\n" }, true); _ = try n.serve(.{ .tag = 4, .op = .release, .node = exec, .handle = h, .opened = true }, true); try n.agree(); } test "a client joined between two writes of one open to a body makes them one undo step, as its session does" { var n = try NinepJoin.init("one\n", TestHost.host()); defer n.deinit(); const body = n.node(.body); const h = (try n.serve(.{ .tag = 1, .op = .open, .node = body, .omode = 1 }, true)).handle; _ = try n.serve(.{ .tag = 2, .op = .write, .node = body, .handle = h, .data = "a\n" }, true); try n.join(); _ = try n.serve(.{ .tag = 3, .op = .write, .node = body, .handle = h, .data = "b\n" }, true); _ = try n.serve(.{ .tag = 4, .op = .release, .node = body, .handle = h, .opened = true }, true); _ = try n.serve(.{ .tag = 5, .op = .write, .node = n.node(.ctl), .data = "Undo" }, true); try n.agree(); } test "a client joined while a script's ctl open holds a pane's lock refuses another open's lock, as its session does" { var n = try NinepJoin.init("one\n", TestHost.host()); defer n.deinit(); const ctl = n.node(.ctl); const h = (try n.serve(.{ .tag = 1, .op = .open, .node = ctl, .omode = 1 }, true)).handle; _ = try n.serve(.{ .tag = 2, .op = .write, .node = ctl, .handle = h, .data = "lock\n" }, true); try n.join(); const g = (try n.serve(.{ .tag = 3, .op = .open, .node = ctl, .omode = 1 }, true)).handle; try std.testing.expectEqual(pardes.ctlfs.Status.err, (try n.serve(.{ .tag = 4, .op = .write, .node = ctl, .handle = g, .data = "lock\n" }, true)).status); // Who holds it, by name: on the base no digest covered it. const id = n.a.core.paneBySerial(n.serial).?; try std.testing.expectEqual(n.a.core.panes[id].?.fs.lock, n.late.?.core().panes[id].?.fs.lock); try n.agree(); _ = try n.serve(.{ .tag = 5, .op = .release, .node = ctl, .handle = g, .opened = true }, true); _ = try n.serve(.{ .tag = 6, .op = .release, .node = ctl, .handle = h, .opened = true }, true); try n.agree(); } test "a client joined after a script set a pane's addr, its limit, or truncated its dot writes where its session writes" { // addr: the next data write replaces what it says. { var n = try NinepJoin.init("one two\nthree\n", TestHost.host()); defer n.deinit(); _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.addr), .data = "/two/" }, true); try n.join(); _ = try n.serve(.{ .tag = 2, .op = .write, .node = n.node(.data), .data = "2" }, true); try n.agree(); } // limit: an address is looked for inside it. { var n = try NinepJoin.init("one two\nthree\n", TestHost.host()); defer n.deinit(); _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.limit), .data = "#0,#3" }, true); try n.join(); _ = try n.serve(.{ .tag = 2, .op = .write, .node = n.node(.addr), .data = "/two/" }, true); _ = try n.serve(.{ .tag = 3, .op = .write, .node = n.node(.data), .data = "2" }, true); try n.agree(); } // dot truncated: its open's release with no write empties it. { var n = try NinepJoin.init("one two\nthree\n", TestHost.host()); defer n.deinit(); const dot = n.node(.dot); _ = try n.serve(.{ .tag = 1, .op = .write, .node = dot, .data = "#0,#3" }, true); const h = (try n.serve(.{ .tag = 2, .op = .open, .node = dot, .omode = 1 }, true)).handle; _ = try n.serve(.{ .tag = 3, .op = .setattr, .node = dot, .handle = h, .truncate = true }, true); try n.join(); _ = try n.serve(.{ .tag = 4, .op = .release, .node = dot, .handle = h, .opened = true }, true); try n.agree(); } } test "a client joined between two writes of one open to a pane's sel runs the second on from the first, as its session does" { var n = try NinepJoin.init("one two\n", TestHost.host()); defer n.deinit(); const sel = n.node(.sel); const h = (try n.serve(.{ .tag = 1, .op = .open, .node = sel, .omode = 1 }, true)).handle; _ = try n.serve(.{ .tag = 2, .op = .write, .node = sel, .handle = h, .data = "a" }, true); try n.join(); _ = try n.serve(.{ .tag = 3, .op = .write, .node = sel, .handle = h, .data = "b" }, true); _ = try n.serve(.{ .tag = 4, .op = .release, .node = sel, .handle = h, .opened = true }, true); try n.agree(); } test "a client joined after a script's nomark or noscroll writes as its session does" { // nomark: writes under it are one undo step. { var n = try NinepJoin.init("one\n", TestHost.host()); defer n.deinit(); _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.ctl), .data = "nomark" }, true); try n.join(); // Two opens' writes, each its own undo step but for nomark. const body = n.node(.body); for ([_][]const u8{ "two\n", "three\n" }) |text| { const h = (try n.serve(.{ .tag = 2, .op = .open, .node = body, .omode = 1 }, true)).handle; _ = try n.serve(.{ .tag = 3, .op = .write, .node = body, .handle = h, .data = text }, true); _ = try n.serve(.{ .tag = 4, .op = .release, .node = body, .handle = h, .opened = true }, true); } _ = try n.serve(.{ .tag = 5, .op = .write, .node = n.node(.ctl), .data = "mark" }, true); _ = try n.serve(.{ .tag = 6, .op = .write, .node = n.node(.ctl), .data = "Undo" }, true); try n.agree(); } // noscroll: a write past the screen leaves the view where it was. { var n = try NinepJoin.init("one\n", TestHost.host()); defer n.deinit(); _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.scroll), .data = "0" }, true); try n.join(); _ = try n.serve(.{ .tag = 2, .op = .write, .node = n.node(.body), .data = &@as([100]u8, @splat('\n')) }, true); try n.agree(); } } test "a client joined after a script truncated a pane's tag writes the tag its session writes" { var n = try NinepJoin.init("one\n", TestHost.host()); defer n.deinit(); const tag = n.node(.tag); const h = (try n.serve(.{ .tag = 1, .op = .open, .node = tag, .omode = 1 }, true)).handle; _ = try n.serve(.{ .tag = 2, .op = .setattr, .node = tag, .handle = h, .truncate = true }, true); try n.join(); _ = try n.serve(.{ .tag = 3, .op = .write, .node = tag, .handle = h, .data = "Get Put\n" }, true); _ = try n.serve(.{ .tag = 4, .op = .release, .node = tag, .handle = h, .opened = true }, true); try n.agree(); } test "a client joined after a script truncated the workspace's tag writes the tag its session writes" { var n = try NinepJoin.init("one\n", TestHost.host()); defer n.deinit(); const tag: u64 = @backingInt(pardes.ctlfs.TopFile.tag); const h = (try n.serve(.{ .tag = 1, .op = .open, .node = tag, .omode = 1 }, true)).handle; _ = try n.serve(.{ .tag = 2, .op = .setattr, .node = tag, .handle = h, .truncate = true }, true); try n.join(); _ = try n.serve(.{ .tag = 3, .op = .write, .node = tag, .handle = h, .data = "Exit\n" }, true); _ = try n.serve(.{ .tag = 4, .op = .release, .node = tag, .handle = h, .opened = true }, true); try n.agree(); } test "a client joined while a chorded exec waits for its event reader's write-back runs it with its argument, as its session does" { var n = try NinepJoin.init("Msg said\narg-text\n", TestHost.host()); defer n.deinit(); const event = n.node(.event); const h = (try n.serve(.{ .tag = 1, .op = .open, .node = event, .omode = 2 }, true)).handle; // The session's chorded click, told to the reader, its argument kept. { const was = Stepping.begin(&n.a.t, null); const id = n.a.core.paneBySerial(n.serial).?; try std.testing.expect(pardes.mouse.reportRange(n.a.core, id, pardes.config.exec_cmd, "Msg", false, .{ .q0 = 0, .q1 = 3 }, "arg-text")); was.end(); n.a.seq += 1; _ = try n.a.unit(0, n.a.seq); } try n.join(); // The command's record written back alone: its argument is the one kept. _ = try n.serve(.{ .tag = 2, .op = .write, .node = event, .handle = h, .data = "MX0 3 9 3 Msg\n" }, true); _ = try n.serve(.{ .tag = 3, .op = .release, .node = event, .handle = h, .opened = true }, true); try n.agree(); } test "a client joined while a script's writes to a body are held to go in as one edit puts them in as its session does" { // A host with a clock: held writes go in once they have paused // (pane.batch_pause_ns), and the join came before that. const Clock = struct { var now_ns: u64 = 5 * std.time.ns_per_s; fn now(_: ?*anyopaque) u64 { return now_ns; } const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .now = now }; }; var n = try NinepJoin.init("one\n", .{ .vtable = &Clock.vtable }); defer n.deinit(); const body = n.node(.body); const h = (try n.serve(.{ .tag = 1, .op = .open, .node = body, .omode = 1 }, true)).handle; _ = try n.serve(.{ .tag = 2, .op = .write, .node = body, .handle = h, .data = "two\n" }, true); try std.testing.expect(n.a.core.fs.batch.bytes.items.len > 0); try n.join(); Clock.now_ns += std.time.ns_per_s; try n.pump(); try n.agree(); _ = try n.serve(.{ .tag = 3, .op = .release, .node = body, .handle = h, .opened = true }, true); try n.agree(); } test "a client runs an Edit a script's write started once, as its session does, when the held write is asked again" { var n = try NinepJoin.init("b\na\n", TestHost.host()); defer n.deinit(); try n.join(); const ctl = n.node(.ctl); const req: pardes.ctlfs.Req = .{ .tag = 7, .op = .write, .node = ctl, .data = "Edit , | sort\n" }; // The step alone: its loop's pass would run the command (here, with no // host to run it, fail it). const first = try n.serve(req, false); try std.testing.expectEqual(pardes.ctlfs.Status.ok, first.status); // The write held as the session's listener holds it (runtime/9p_io.zig). n.a.core.fs.edit_hold = .{ .asker = @ptrCast(n.a.core), .slot = 0, .seq = 1, .tag = req.tag, .node = ctl, .handle = 0, .written = first.written }; // Its command answers: the Edit is done. n.a.apply(.{ .pipe_resp = .{ .id = n.a.core.pipe.edit_run.?.id, .success = true, .outputs = &.{"a\nb\n"} } }); n.a.seq += 1; try n.send(try n.a.unit(0, n.a.seq)); try n.agree(); // A retry of the held write's park, as the listener serves it: its // answer from the hold, no step, the Edit not run again by anyone. const again = pardes.filesystem.EditHold.retried(&n.a.core.fs, req) orelse try n.serve(req, true); try std.testing.expectEqual(pardes.ctlfs.Status.ok, again.status); try std.testing.expect(n.a.core.pipe.edit_run == null); try n.agree(); } test "an Edit's stop token is each process's own (selection_pipe.next_token): a client's differs from its session's, and they agree" { var n = try NinepJoin.init("b\na\n", TestHost.host()); defer n.deinit(); try n.join(); _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.ctl), .data = "Edit , | sort\n" }, false); const session = n.a.core.pipe.edit_run.?.request.token; const client = n.late.?.core().pipe.edit_run.?.request.token; try std.testing.expect(session != client); try n.agree(); } /// A session with a shell, for a run's 9P state across a join: a host /// whose pty takes the line and whose tty nobody else holds. const RunJoin = struct { fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool { return false; } fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {} const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write }; const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; /// The session at its shell's first prompt, and the shell's slot. fn init(n: *NinepJoin) !u8 { const a = try Authority.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &vtable }); n.* = .{ .a = a, .serial = 0 }; _ = try a.unit(0, 0); const shell: u8 = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.isTerminal()) break @intCast(id); } else return error.NoShell; n.serial = a.core.panes[shell].?.serial; return shell; } fn output(n: *NinepJoin, shell: u8, bytes: []const u8) !void { n.a.output(.{ .output = .{ .pane = .at(shell), .bytes = bytes } }); try n.send((try n.a.pending()).?); } }; test "a client joined while a script's pty/run waits on the command it sent ends the run as its session does" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell var n: NinepJoin = undefined; const shell = try RunJoin.init(&n); defer n.deinit(); // The shell's greeting (`ls`) run at its first prompt, done. try RunJoin.output(&n, shell, RunJoin.prompt ++ "ls\r\n\x1b]133;C;aid=pardes\x07a b\r\n\x1b]133;D;0;aid=pardes\x07" ++ RunJoin.prompt); const run = n.node(.pty_run); const h = (try n.serve(.{ .tag = 1, .op = .open, .node = run, .omode = 2 }, true)).handle; _ = try n.serve(.{ .tag = 2, .op = .write, .node = run, .handle = h, .data = "true\n" }, true); try n.join(); try RunJoin.output(&n, shell, "true\r\n\x1b]133;C;aid=pardes\x07\x1b]133;D;0;aid=pardes\x07" ++ RunJoin.prompt); const answer = try n.serve(.{ .tag = 3, .op = .read, .node = run, .handle = h, .size = 64 }, true); try std.testing.expectEqualStrings("exit 0\n", n.a.core.fsPayload(answer)); // The open's next line, sent at the prompt the first left. _ = try n.serve(.{ .tag = 4, .op = .write, .node = run, .handle = h, .data = "false\n" }, true); try RunJoin.output(&n, shell, "false\r\n\x1b]133;C;aid=pardes\x07\x1b]133;D;1;aid=pardes\x07" ++ RunJoin.prompt); _ = try n.serve(.{ .tag = 5, .op = .release, .node = run, .handle = h, .opened = true }, true); try n.agree(); } test "a client joined after its session's shell was found to have no prompt marks answers a pty/run as its session does" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell var n: NinepJoin = undefined; const shell = try RunJoin.init(&n); defer n.deinit(); { const was = Stepping.begin(&n.a.t, null); n.a.core.acknowledgeShell(.at(shell), "/bin/sh", false); was.end(); n.a.seq += 1; _ = try n.a.unit(0, n.a.seq); } try n.join(); const run = n.node(.pty_run); const h = (try n.serve(.{ .tag = 1, .op = .open, .node = run, .omode = 2 }, true)).handle; _ = try n.serve(.{ .tag = 2, .op = .write, .node = run, .handle = h, .data = "true\n" }, true); const answer = try n.serve(.{ .tag = 3, .op = .read, .node = run, .handle = h, .size = 64 }, true); try std.testing.expectEqualStrings("error no prompt marks\n", n.a.core.fsPayload(answer)); _ = try n.serve(.{ .tag = 4, .op = .release, .node = run, .handle = h, .opened = true }, true); try n.agree(); } test "a picker's preview opens and closes a plain kind's state in the pane it lands in, no pane opened or closed: a client with a copy ahead never replays it over the copy, and every state the kind opens is closed once" { // The soak's (test/replicas.zig with the pdf addon): `allocator leaks // detected` at seed 0 rtt 80, the documents of PDFs a picker previewed // (Pick.showKind) on a client, opened by a unit it kept to replay over // its copy and opened again by the replay, the first never closed. // A plain kind that holds something of its own outside its block for // each state it opens, as the pdf addon holds a document (its `Own`): // each open notes its block, each close lets it go, so a state opened // and never closed stays noted. Its files are `.own`. const Owned = struct { const pa = pardes.Kind.c; var noted: [8]?*anyopaque = @splat(null); fn open(_: [*c]const u8, _: [*c]const u8, _: u64) callconv(.c) ?*anyopaque { const st = pardes.Kind.api.alloc.?(4); for (¬ed) |*n| if (n.* == null) { n.* = st; break; }; return st; } fn close(st: ?*anyopaque) callconv(.c) void { for (¬ed) |*n| if (n.* == st) { n.* = null; return; }; } fn paint(_: ?*anyopaque, _: [*c]const pa.pa_window, _: [*c]pa.pa_paint) callconv(.c) void {} fn held() usize { var n: usize = 0; for (noted) |st| n += @intFromBool(st != null); return n; } 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 = "owned".* ++ @as([11]u8, @splat(0)), .version = 1, .exts = ".own", .flags = pa.PA_PLAIN }), .open = open, .close = close, .paint = paint, }); }; const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "notes.txt", .data = "the notes\n" }); try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "paper.own", .data = "own" }); 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 line: [std.Io.Dir.max_path_bytes + 32]u8 = undefined; { const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); defer a.deinit(); var words: [64]pardes.Kind.LoadedWord = undefined; const owned = pardes.Kind.loadedOf(&Owned.ops, "/x/owned.so", @splat(7), &words); _ = try a.local(.{ .addon = .{ .op = .load, .pane = .at(0), .kind = &owned } }); _ = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/notes.txt", .{dir}) }); // A client in a view of its own, running the kind's code. const joined = (try a.join(1, null)).?; defer gpa.free(joined.dump); const r = try Replica.initDump(gpa, 1, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); defer r.deinit(); r.core().kinds.ops[r.core().kinds.byName("owned").?] = &Owned.ops; // SPC f f p at the session, in its view: its picker lists the tree, // and paper.own, the one row, shows through the kind in the pane it // lands in. The client idle meanwhile: its copy taken ahead, each // unit replayed on top of it. const At = struct { fn sessionView(au: *Authority) void { const was = Stepping.begin(&au.t, null); au.core.toView(.at(0)); was.end(); } }; At.sessionView(a); for (" ffp") |c| { r.ready(); r.confirm(try a.local(.{ .key = .{ .cp = c, .text = &.{c} } })); r.ready(); r.confirm(try a.local(.tick)); } const landing = for (a.core.panes, 0..) |slot, id| { if (slot) |pane| if (pane.addon != null) break id; } else return error.NoPreview; try std.testing.expect(r.core().panes[landing].?.addon != null); // A key of the client's own on top, and the session's own key // first: the client back to its copy, the units since replayed. var sent: std.ArrayListUnmanaged([]u8) = .empty; defer { for (sent.items) |m| gpa.free(m); sent.deinit(gpa); } try key(r, 'j', &sent); try std.testing.expectEqual(@as(usize, 1), r.applied); const foreign = r.stats.foreign; r.confirm(try a.local(.{ .key = .{ .cp = 'q', .text = "q" } })); r.settle(); try std.testing.expectEqual(foreign + 1, r.stats.foreign); for (sent.items) |m| { r.confirm(try a.take(m)); r.settle(); } try agrees(a, r); // Esc in the picker's view: the preview's state closed, the pane's // own text back. At.sessionView(a); r.confirm(try a.local(.{ .key = .{ .cp = pardes.Key.escape } })); r.settle(); try agrees(a, r); try std.testing.expect(r.core().panes[landing].?.addon == null); } try std.testing.expectEqual(@as(usize, 0), Owned.held()); }