diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-23 09:02:14 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-23 09:02:14 -0300 |
| commit | 62479337e68da42e013e449ef680826a323354f1 (patch) | |
| tree | 78240b991aa9bf211e2e7bd4ebc32aad25c680ff | |
| parent | 5a864360e6b0e72fc9734ab76c085a38fe1e60ba (diff) | |
| parent | 100fe567edc8be7bea9b36ae7fbf20cc66d55164 (diff) | |
| download | pardes-62479337e68da42e013e449ef680826a323354f1.tar.gz pardes-62479337e68da42e013e449ef680826a323354f1.zip | |
merge: the link's rejoin over the same connection (pardes-rejoin, `rnllpvzw`) under the pair's round 13 (pardes-pair-13: `xmrlkxtn` on `prnotlyq` on `nrollumu`)
Co-Authored-By: Claude Opus <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
| -rw-r--r-- | abi/wire.zig | 12 | ||||
| -rw-r--r-- | core/replica.zig | 1053 | ||||
| -rw-r--r-- | core/root.zig | 2 | ||||
| -rw-r--r-- | runtime/client.zig | 47 | ||||
| -rw-r--r-- | test/daemon.py | 142 | ||||
| -rw-r--r-- | test/replicas.zig | 122 |
6 files changed, 1095 insertions, 283 deletions
diff --git a/abi/wire.zig b/abi/wire.zig index 8949edff..7b6a22f1 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -12,9 +12,12 @@ const build_info = @import("build_info"); /// 31: where a view stands in a terminal's history is the view's: a pane's /// `scrolled_to` (and its share's in each view) in the dump and the digest, -/// the emulator's own view out of both (its `Parts.view` gone); and the +/// the emulator's own view out of both (its `Parts.view` gone); the /// core's count of its emulators' writes (`outside`) in both, which the -/// replica engine's one question of a unit reads; +/// replica engine's one question of a unit reads; and a client whose link +/// is up joins again over it (its bye's `again`, then its hello there: +/// core/replica.zig `Peers.joinAgain`), as one whose load was refused asks +/// once more; /// 30: the terminals' one road: the screen-state messages are retired (a /// replica's `screen_ack`, 0x04, and the session's `screen`, 0x06: gaps), /// a welcome says no road (its `bytes` byte gone), and a pane's @@ -324,8 +327,9 @@ pub fn helloVersion(payload: []const u8) Error!u16 { /// one call and no longer. pub const ClientMsg = union(enum) { hello: Hello, - /// The client's end: `again`, it joins again for its view at once; - /// `close`, its window was closed (a pair's session ends at its last). + /// The client's end: `again`, it joins again for its view at once (its + /// hello next, on this link while it is up); `close`, its window was + /// closed (a pair's session ends at its last). bye: struct { again: bool = false, close: bool = false }, /// A round trip's probe, answered `pong` with the same value. ping: u64, diff --git a/core/replica.zig b/core/replica.zig index 214cc34e..6c4f0b2c 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -1295,6 +1295,20 @@ pub const Framer = struct { } } + /// 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 { @@ -1340,8 +1354,10 @@ pub const Peer = struct { 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 (a divergence's rejoin): - /// kept for it (views.away), not closed. Its reader's, read after its end. + /// 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, @@ -1366,9 +1382,15 @@ pub const Peer = struct { /// 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 are the last it is sent, and its - /// view is kept for it (views.away), as for a bye's `again`. + /// 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, @@ -1399,22 +1421,36 @@ pub const Peer = struct { 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) return peer.farJoin(); - // Its client made this core itself (a pair's): nothing to send. - if (boot == peer.digest) return true; - 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 (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 writePieces(peer.fd, peer.dump[pos..]); + return true; } /// A far client's join, in one zstd frame: the list of the dump's blobs @@ -1455,6 +1491,11 @@ pub const Peer = struct { 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); @@ -1520,8 +1561,9 @@ pub const Peer = struct { /// `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, after which its writer ends its link - /// (`writeLoop`); it joins again from a dump, for its view (`leave`). + /// 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); @@ -1596,45 +1638,90 @@ pub const Peer = struct { 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); - if (!peer.writeJoin()) { - _ = libc.shutdown(peer.fd, 2); - return; - } - // Its pins let go at the next boundary. - peer.peers.post(.{ .joined = peer }); while (true) { peer.lock.lockUncancelable(io); - while (peer.out.items.len == 0 and !peer.closing and !peer.cut) peer.cond.waitUncancelable(io, &peer.lock); - if (peer.out.items.len == 0) { + 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; } - std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &peer.sending); - // Cut off: the words why came last, and its link ends after them. - const cut_off = peer.cut; + if (!joining) std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &peer.sending); peer.lock.unlock(io); - const ok = if (peer.z != null) peer.zWrite(peer.sending.items, .flush) else writeAll(peer.fd, peer.sending.items); - peer.sending.clearRetainingCapacity(); - if (!ok or cut_off) { + 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) { - .hello => return false, + // 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 false; + return b.again; }, .ping => { var out: [16]u8 = undefined; @@ -1746,7 +1833,10 @@ pub const Peers = struct { 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 @@ -1792,6 +1882,8 @@ pub const Peers = struct { 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 @@ -1799,7 +1891,9 @@ pub const Peers = struct { /// (`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: *Peer }; + 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 }; @@ -1821,6 +1915,8 @@ pub const Peers = struct { 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; @@ -1874,14 +1970,17 @@ pub const Peers = struct { std.mem.swap(std.ArrayListUnmanaged(Note), &ps.inbox, &ps.taken); ps.mail.store(false, .release); ps.lock.unlock(ps.io); - for (ps.taken.items) |note| switch (note) { + 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), - .joined => |peer| released(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}); @@ -1969,14 +2068,8 @@ pub const Peers = struct { 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); }; - ps.seq += 1; - ps.unit(0, ps.seq); - // The session's mutable state, dumped now; 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. var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; - const dumped = pardes.dump.dumpJoin(core, &blobs) catch |err| { - blobs.deinit(core.gpa); + const got = ps.dumped(core, &blobs) catch |err| { core.undrawn &= ~(@as(u8, 1) << @intCast(k)); core.closeView(.at(k)); ps.unit(0, ps.seq); @@ -1984,31 +2077,17 @@ pub const Peers = struct { var why: [96]u8 = undefined; return daemon.refuseReplica(fd, std.fmt.bufPrint(&why, "that session could not be dumped: {t}", .{err}) catch "that session could not be dumped"); }; - const bytes = dumped.bytes; - var whole = bytes.len; - for (blobs.items) |b| { - pardes.memory.pin(b.bytes); - whole += b.bytes.len; - } - ps.dump_bytes = whole; - ps.state_bytes = bytes.len; - // 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. - tape.resync(&ps.t); + 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 = bytes, .blobs = blobs, .dump_gpa = core.gpa, .pair = joining.own }; + 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; - // The session's digest as dumped, for the joiner to check its load by - // (a pair's client, its own boot: `writeJoin`). - const digest = dumped.digest; - peer.digest = digest; - peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = @intCast(libc.getpid()), .session = ps.name[0..@min(ps.name.len, wire.max_name)], .client = peer.id, .view = peer.view, .dump_len = whole, .gmtoff = gmtoff(), .digest = digest, .semantics = wire.semantics, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len; + 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)) { @@ -2021,10 +2100,90 @@ pub const Peers = struct { 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, whole >> 10, bytes.len >> 10, (nowNs() - t0) / 1000 }); + 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 @@ -2108,28 +2267,35 @@ pub const Peers = struct { if (peer.want) |b| ps.gpa.free(b); if (peer.z) |z| _ = zstd.ZSTD_freeCCtx(z); peer.zout.deinit(ps.gpa); - // What its reader posted after it was let go (its end) is nobody's. + // 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); - var i: usize = 0; - while (i < ps.inbox.items.len) { - const mine = switch (ps.inbox.items[i]) { + 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, .joined => |p| p == peer, + .gone, .check, .again => |p| p == peer, + .joined => |w| w.peer == peer, .join => false, }; if (!mine) { i += 1; continue; } - switch (ps.inbox.items[i]) { - .input => |in| ps.gpa.free(in.msg), - else => {}, - } - _ = ps.inbox.orderedRemove(i); + if (list.items[i] == .input) ps.gpa.free(list.items[i].input.msg); + _ = list.orderedRemove(i); } - ps.lock.unlock(io); - if (peer.rejoin) |j| ps.post(.{ .join = j }); - ps.gpa.destroy(peer); } /// Every client told the session is upgrading and let go, its view with @@ -2271,7 +2437,7 @@ pub const Peers = struct { for (ps.inbox.items) |note| switch (note) { .join => |j| _ = libc.close(j.fd), .input => |in| ps.gpa.free(in.msg), - .gone, .check, .joined => {}, + .gone, .check, .joined, .again => {}, }; ps.inbox.clearRetainingCapacity(); ps.lock.unlock(ps.io); @@ -2289,10 +2455,11 @@ pub const Peers = struct { 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}\n", .{ + 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; @@ -2361,15 +2528,17 @@ pub fn dial(gpa: Allocator, path: []const u8, session: []const u8, why: []u8, ha _ = libc.close(fd); return said(why, "nothing answers at {s}", .{path}); } - return joinOn(gpa, fd, session, why, have, view, null); + return joinOn(gpa, fd, session, why, have, view, null, .{}); } -/// `dial`'s, on a connection made: the hello, then the join. The -/// connection is closed if the join fails. No session named: no hello, a -/// pair's (Options.pair), whose session took it as its first client. `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) ?Joined { +/// `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); @@ -2377,7 +2546,7 @@ fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Ha } 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 = &.{} }; + var j: Joined = .{ .fd = fd, .pid = 0, .client = 0, .view = 0, .gmtoff = 0, .dump = &.{}, .rest = rest }; const Read = struct { j: *Joined, gpa: Allocator, @@ -2462,6 +2631,9 @@ fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Ha 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"), } } @@ -2515,6 +2687,7 @@ fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Ha 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", .{}); } @@ -2698,6 +2871,17 @@ pub fn bye(fd: c_int, how: @FieldType(wire.ClientMsg, "bye")) void { 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. @@ -2705,21 +2889,46 @@ pub const Said = union(enum) { unit: []u8, checked: u64, refused: []u8, blob: [] /// 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). -pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime post: fn (@TypeOf(ctx), Said) bool) void { - const Take = struct { - fn take(x: @TypeOf(ctx), tag: u8, payload: []const u8) bool { +/// 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 => .{ .unit = std.heap.c_allocator.dupe(u8, payload) catch return false }, - .blob => .{ .blob = std.heap.c_allocator.dupe(u8, payload) catch return false }, - .check => .{ .checked = (wire.decodeServer(tag, payload) catch return false).check }, + .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, }; - if (!post(x, msg)) switch (msg) { + 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 => {}, }; @@ -2727,11 +2936,16 @@ pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime return msg == .unit or msg == .checked or msg == .blob; } }; - rest.run(gpa, fd, ctx, Take.take); + 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; - if (!post(ctx, .{ .refused = words })) std.heap.c_allocator.free(words); + _ = x.said(.{ .refused = words }); } /// A join's failure that is its session's end, whenever it came (the @@ -2786,18 +3000,28 @@ pub fn otherBuild(why: []const u8) bool { /// `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 once old's link has -/// ended, for old's view (`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) ?*Replica { +/// 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| { - j.* = redial(gpa, path, session, why, have, prev.diverged == null, j.view) orelse { + 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); @@ -2818,27 +3042,48 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o if (have) |h| h.store(gpa, j) else gpa.free(j.dump); j.dump = &.{}; } - return fromDump(gpa, j, o, have, why, t0); + 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`; null, and -/// why in `why`, when it does not load as the session. -fn fromDump(gpa: Allocator, j: *Joined, o: pardes.Options, have: ?*Have, why: []u8, t0: u64) ?*Replica { - const r = Replica.initDump(gpa, j.client, j.view, j.dump, o) catch |err| { - _ = std.fmt.bufPrint(why, "the session's dump would not load: {t}\x00", .{err}) catch {}; - return null; - }; - if (!r.loaded(j.digest)) { +/// 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) { + const r = Replica.initDump(gpa, j.client, j.view, j.dump, o) catch |err| { + _ = std.fmt.bufPrint(why, "the session's dump would not load: {t}\x00", .{err}) 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}", .{ j.client, fields }); - _ = std.fmt.bufPrint(why, "the session's dump loaded as another session: {s}differs\x00", .{fields}) catch {}; - return null; + 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; } - takeJoined(r, j, have, t0); - return r; +} + +/// 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 @@ -2909,7 +3154,7 @@ fn ownBoot(gpa: Allocator, j: *Joined, fd: c_int, o: pardes.Options, why: *[600] 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; + 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; @@ -2919,7 +3164,7 @@ pub fn confirmBoot(gpa: Allocator, j: *Joined, r: *Replica, o: pardes.Options, w gpa.free(j.dump); j.dump = &.{}; } - const loaded = fromDump(gpa, j, o, null, why, t0) orelse return null; + const loaded = fromDump(gpa, j, o, null, why, t0, "") orelse return null; r.deinit(); return loaded; } @@ -3057,9 +3302,16 @@ pub const Link = struct { 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(); @@ -3093,6 +3345,7 @@ pub const Link = struct { 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; @@ -3281,6 +3534,23 @@ pub const Link = struct { 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). @@ -3423,7 +3693,7 @@ fn farJoinOnce(ps: *Peers, core: *Pardes, have: ?*Have) !Joined { 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 { + 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; }; @@ -3541,7 +3811,7 @@ test "a client joining again after a divergence is told at once that its session 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(joinOn(std.testing.allocator, fds[0], "gone", &why, null, 1, null, .{}) == null); try std.testing.expect(ended(&why)); } @@ -4421,7 +4691,7 @@ test "a Restore tells its clients so before it lets them go (each joins again, s 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; + 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. @@ -4439,7 +4709,9 @@ test "a Restore tells its clients so before it lets them go (each joins again, s } }; var last: Last = .{}; - readLink(gpa, fds[1], &j.rest, &last, Last.post); + // 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); @@ -4505,7 +4777,7 @@ fn ownBootAgainst(edited: bool) !void { o.pair = fds[1]; var j: Joined = undefined; var why: [600]u8 = @splat(0); - const booted = join(gpa, &j, "", "", o, null, &why, null) orelse return error.JoinFailed; + 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; @@ -4558,9 +4830,9 @@ fn firstOnPair(by_dump: bool) !void { 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; + 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 { + 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; }; @@ -4569,7 +4841,7 @@ fn firstOnPair(by_dump: bool) !void { 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) orelse { + 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; }; @@ -5322,66 +5594,129 @@ test "a client that diverged joins again for its view: kept for it meanwhile, it try agrees(a, back); } -test "a client cut off for what it left unread is told why and joins again for its view, kept for it meanwhile: it loads the session's dump and agrees" { - // 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); and what it queued for one, - // down its link in order, the link's end after it if it was cut off. - 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 } { - 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; - fd.* = fds[1]; - ps.handed(fds[0], view); +/// 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); - 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; - 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..]); - 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 }); - const r = try Replica.initDump(gpa, w.client, w.view.index(), whole.items, .{ .cols = 80, .rows = 24 }); - if (!r.loaded(w.digest)) return error.LoadedAnother; - return .{ .r = r, .peer = peer }; } + 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 }; + } - 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(); - if (!peer.cut) return; - link.quit = true; - link.gone = true; + /// `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(); @@ -5396,37 +5731,59 @@ test "a client cut off for what it left unread is told why and joins again for i var link: Link = .{ .r = first.r, .fd = fd }; defer link.deinit(gpa); const view = first.peer.view; - // The session's own input, taken by the client. - core.update(.{ .key = .{ .cp = 'i', .text = "i" } }); + 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 first.r.diverged == null); - // Its link stalls; the session goes on, and what waits for it passes - // the bound: it is cut off. - first.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(first.peer.cut); - try std.testing.expectEqual(@as(u32, 1), ps.cut); - try MemoryLinks.down(first.peer, &link); - try std.testing.expect(link.quit); - // It was told why, and joins again (as a divergence's client does)... - try std.testing.expect(link.rejoins()); - try std.testing.expect(std.mem.indexOf(u8, link.notice(), "behind") != null); - // ...its old link shut, at once (runtime/client.zig `run`): a join that - // comes before that link's end is heard, on another connection, waits - // for it, its view kept for it meanwhile. + 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); - link.reset(back.r, &.{ .fd = fd, .pid = 0, .client = back.r.id, .view = view.index(), .gmtoff = 0, .dump = &.{} }); + var link: Link = .{ .r = back.r, .fd = fd }; + defer link.deinit(gpa); core.update(.{ .paste = "back" }); try core.pump(core.host); ps.boundary(core); @@ -5435,6 +5792,280 @@ test "a client cut off for what it left unread is told why and joins again for i 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()); @@ -5468,6 +6099,11 @@ test "a client whose session's units come more than two seconds later than its q // 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()); @@ -5483,7 +6119,7 @@ test "a client whose session's units come more than two seconds later than its q 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 ends the link" { +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(); @@ -5528,11 +6164,16 @@ test "a client's writer, the client cut off while it waits on the socket, writes var heard: Heard = .{}; var rest: Framer = .{}; defer rest.deinit(gpa); - readLink(gpa, fds[1], &rest, &heard, Heard.post); + 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" { @@ -6086,7 +6727,7 @@ test "a step of the session's own that reads a terminal right after its output, 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 }); + ps.post(.{ .joined = .{ .peer = peer, .gen = peer.gen } }); var whole: std.ArrayListUnmanaged(u8) = .empty; defer whole.deinit(gpa); var pos: usize = 0; @@ -7808,7 +8449,7 @@ test "a client whose load is not the session says which field, in its words and 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.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)); } diff --git a/core/root.zig b/core/root.zig index a476f90f..2f3e4494 100644 --- a/core/root.zig +++ b/core/root.zig @@ -637,7 +637,7 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{ .{ "jj.zig", 11, "jj run under tape.site(.jj) on an io of its own (the tape's spawns nothing) with this process's environment, the signal mask cleared as Stream's children's: the session's, a replica replays its answer; or on a worker for `Changes`, its answer an input, with the wall clock it was made at (tape.value(.clock) on the loop) for its descriptions' ages; a test's shell inbox (dev)" }, .{ "look.zig", 6, "openLink's fork (the host's: a view's frontend opens a link) and a remote's error name" }, .{ "memory.zig", 7, "the memory regions themselves (mmap, madvise, their locks)" }, - .{ "replica.zig", 76, "the client and session engines: sockets, threads, clocks, the blob cache, traces" }, + .{ "replica.zig", 89, "the client and session engines: sockets, threads, clocks, the blob cache, traces" }, .{ "rollback.zig", 1, "a test helper's directory" }, .{ "root.zig", 4, "dev's modules re-exported (host_io, file_watch, glide, fonts)" }, .{ "selection_pipe.zig", 14, "a pipe's child processes and their files: the host's `pipe` entry" }, diff --git a/runtime/client.zig b/runtime/client.zig index 43fdf98d..1d348aea 100644 --- a/runtime/client.zig +++ b/runtime/client.zig @@ -95,7 +95,7 @@ pub const Start = struct { s.o.frames = &s.frames; // Exec'd at an Upgrade (`execAgain`): for the view it had. if (init.environ_map.get("PARDES_JOIN_VIEW")) |v| s.o.join_view = std.fmt.parseInt(u8, v, 10) catch null; - s.r = replica.join(s.gpa, &s.joined, dial.path, dial.session, s.o, s.have, &s.why, null) orelse return false; + s.r = replica.join(s.gpa, &s.joined, dial.path, dial.session, s.o, s.have, &s.why, null, false) orelse return false; return true; } @@ -175,7 +175,7 @@ pub fn Loop(comptime Frontend: type) type { frames: *pardes.FrameStats, pub fn init(fe: *Frontend, s: *Start) !L { - var l: L = .{ .link = .{ .r = s.r, .fd = s.joined.fd }, .fe = fe, .frames = &s.frames }; + var l: L = .{ .link = .{ .r = s.r, .fd = s.joined.fd, .far = s.have != null }, .fe = fe, .frames = &s.frames }; try l.link.fromEnv(s.gpa, s.env); return l; } @@ -209,11 +209,23 @@ pub fn Loop(comptime Frontend: type) type { l.after(); } if (s.env.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file); - if (!link.gone) replica.bye(s.joined.fd, .{ .again = s.r.diverged != null or link.lagged != 0, .close = link.close }); - // The link's reader ends with the link, posting as it goes: - // what it posted is let go until it has (a terminal's queue - // is bounded: a reader blocked on it would never end). - _ = libc.shutdown(s.joined.fd, 2); + // Its link up and the session's state to take again: its + // goodbye and its hello said on it, the session's dump comes + // there (`replica.comeBack`); its reader reads on to the welcome, + // letting the stream it leaves go. Only a link that is gone + // is dialled again. + const here = link.backHere() and s.joined.rest.overlong() == null and back: { + link.back.store(true, .release); + break :back replica.comeBack(s.joined.fd, s.dial.session, s.r.view); + }; + if (!here) { + if (!link.gone) replica.bye(s.joined.fd, .{ .again = s.r.diverged != null or link.lagged != 0, .close = link.close }); + _ = libc.shutdown(s.joined.fd, 2); + } + // The link's reader ends with the link (or at the welcome), + // posting as it goes: what it posted is let go until it has + // (a terminal's queue is bounded: a reader blocked on it + // would never end). while (true) { const ended = done.load(.acquire); l.fe.drop(); @@ -221,14 +233,23 @@ pub fn Loop(comptime Frontend: type) type { std.Thread.yield() catch {}; } reader.join(); - _ = libc.close(s.joined.fd); - s.joined.rest.deinit(s.gpa); + if (!here) { + _ = libc.close(s.joined.fd); + s.joined.rest.deinit(s.gpa); + } // Its link cut with no word by a session that is there still // (an Upgrade's exec): joined again, as when told so. if (link.gone and link.refused == null and link.ended == null and !link.left and replica.cutListed("the session hung up", s.dial.session, s.have != null)) link.refused = std.heap.c_allocator.dupe(u8, replica.upgrading) catch null; - // Why it joins again is in its notice until a key. - if (!link.rejoins()) { + // A last word goes first, one read after it said it comes + // back too (a Detach in it, the session's end). Why it joins + // again is in its notice until a key. + const goes = link.ended != null or link.left; + if (here and goes) { + _ = libc.close(s.joined.fd); + s.joined.rest.deinit(s.gpa); + } + if (goes or !link.rejoins()) { // What it made since it joined, kept for its next start. if (s.have) |h| h.keep(s.r.core()); s.r.deinit(); @@ -238,7 +259,7 @@ pub fn Loop(comptime Frontend: type) type { } // The session again, the core it leaves held meanwhile: its // blobs are not sent again. - s.r = replica.join(s.gpa, &s.joined, s.dial.path, s.dial.session, s.o, s.have, &s.why, s.r) orelse { + s.r = replica.join(s.gpa, &s.joined, s.dial.path, s.dial.session, s.o, s.have, &s.why, s.r, here) orelse { if (replica.ended(&s.why)) return .gone; if (replica.otherBuild(&s.why) and upgrade.replaced()) return .{ .upgrade = s.joined.view }; return .failed; @@ -272,7 +293,7 @@ pub fn Loop(comptime Frontend: type) type { /// and its end. fn read(l: *L, s: *Start, done: *std.atomic.Value(bool)) void { defer done.store(true, .release); - replica.readLink(s.gpa, s.joined.fd, &s.joined.rest, l.fe, Frontend.said); + replica.readLink(s.gpa, s.joined.fd, &s.joined.rest, &l.link, l.fe, Frontend.said); l.fe.ended(); } diff --git a/test/daemon.py b/test/daemon.py index 4114fac1..7f1adfdb 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -286,6 +286,31 @@ def links(pid): return out +def sockets(pid): + """The sockets process `pid` holds (`socket:[inode]`): a client's link + among them, the same one while it joins again over it.""" + out = set() + for fd in os.listdir(f'/proc/{pid}/fd'): + try: + link = os.readlink(f'/proc/{pid}/fd/{fd}') + except OSError: + continue + if link.startswith('socket:'): + out.add(link) + return out + + +def session_stats(path): + """A session's PARDES_REPLICA_STATS line, its words a dict, and its joins' + count (`joins_us`'s).""" + text = path.read_text() if path.exists() else '' + line = next((l for l in text.splitlines() if l.startswith('session inputs')), '') + w = line.split() + d = {w[i]: w[i + 1] for i in range(1, len(w) - 1, 2)} + joins = next((len(l.split()) - 2 for l in text.splitlines() if l.startswith('session joins_us')), 0) + return d, joins + + def state_fds(pid): """Its fds on the state file, which a session keeps open (Db.zig).""" return sum(1 for path in links(pid) if path.endswith('/pardes.xitdb')) @@ -489,8 +514,10 @@ def clients(binary): started = [] terms = [] try: - sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + # Its joins counted at its end (PARDES_REPLICA_STATS): those over a + # client's own link (`again`) and all of them (`joins_us`). + sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=dict(env, PARDES_REPLICA_STATS=str(root / 'session.stats')), + cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) started.append(sess.pid) sock = root / 'pardes-replica.sock' wait_for('the replica socket', sock.exists) @@ -536,6 +563,7 @@ def clients(binary): started.append(d.pid) wait_for('client D\'s first frame', lambda: b'line 3 of the notes' in td.text(), timeout=20) made_live(td, root / 'd.check') + d_links = sockets(d.pid) shown = view_panes(nine) nine.write('/exec', b'New\n') mine = wait_for('a pane in client D\'s view', lambda: view_panes(nine) - shown).pop() @@ -546,6 +574,9 @@ def clients(binary): os.write(ta.master, b'jk') time.sleep(.2) assert d.poll() is None + # Over its own link: the same connection, no hand-over (counted at + # the session's end). + assert sockets(d.pid) == d_links, ('client D joined again over its own link', d_links, sockets(d.pid)) made_live(td, root / 'd.check') assert mine in view_panes(nine), ('client D in its own view again', mine, nine.read('/layout')) seen = len(checks(root / 'd.check')) @@ -598,8 +629,12 @@ def clients(binary): exit_session(nine, pane) sess.wait(timeout=60) nine.socket.close() + said, joins = session_stats(root / 'session.stats') + here = int(said.get('again', '-1')) + assert here >= 1, ('the session joined client D again over its link', said) wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10) - print('daemon: replica clients\' session ended, nothing left behind') + print(f'daemon: replica clients\' session ended, nothing left behind; its joins: {joins}, of them over a ' + f'client\'s own link {here}, handed by the daemon {joins - here}') finally: for t in terms: t.close() @@ -948,6 +983,86 @@ def pair_rows(binary): shutil.rmtree(root, ignore_errors=True) +def pair_back(binary): + """A pair with no daemon (PARDES_DAEMON=off, the pair's default-to-be + with none reachable): its client put off the session's state + (PARDES_TEST_DIVERGE), and apart from that stopped 3 s while the + session's file is edited over 9P (SIGSTOP: past replica.behind_max_ms): + each time it joins again over its own link ("joined again" on its + screen, its socket the same), the session lives on with the text typed + in it, unsaved, and the client agrees; its terminal closed, the session + ends with its last link. Before pardes-link-1 its rejoin dialled the + daemon's socket, nothing took it, and the whole session went (the + client exit 1: reports/pardes-pair-12.md, 2b).""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rb-', dir=scratch)) + env = base_env() + env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', + SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1', PARDES_DAEMON='off') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + notes = root / 'notes.txt' + notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30))) + terms = [] + try: + for how in ('diverged', 'behind'): + t = Term(30, 100) + terms.append(t) + check = root / f'{how}.check' + e = dict(env, PARDES_REPLICA_CHECK=str(check), **({'PARDES_TEST_DIVERGE': '3'} if how == 'diverged' else {})) + c = t.spawn([binary, f'--9p={how}', str(notes)], e) + wait_for('the socket', (root / f'pardes-9p-{how}.sock').exists) + nine = Client(root / f'pardes-9p-{how}.sock') + session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) + pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') + wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30) + links = sockets(c.pid) + mark = len(t.text()) + words = f'unsaved-{how}'.encode() + os.write(t.master, b'O' + words + b'\x1b') + wait_for('its keys in the session\'s text', lambda: words in nine.read(f'/pane/{pane}/body')) + if how == 'behind': + os.kill(c.pid, signal.SIGSTOP) + for k in range(30): + nine.write(f'/pane/{pane}/exec', f'Edit 3a/ edit {k} /\n'.encode()) + time.sleep(.1) + os.kill(c.pid, signal.SIGCONT) + deadline = time.monotonic() + 30 + while b'joined again' not in t.text()[mark:]: + went = [w for w, gone in (('the client', c.poll() is not None), ('the session', not alive(session))) if gone] + assert not went, (f'{how}: {" and ".join(went)} went (client exit {c.poll()}); ' + f'its terminal\'s last bytes: {t.text()[-600:]!r}') + assert time.monotonic() < deadline, f'{how}: the client joined again' + os.write(t.master, b'jk') + time.sleep(.2) + said = b'this client diverged' if how == 'diverged' else b' s behind' + wait_for(f'{how}: its notice says why', lambda: said in t.text()[mark:], timeout=10) + assert c.poll() is None and alive(session), (how, c.poll()) + assert sockets(c.pid) == links, (f'{how}: joined again over its own link', links, sockets(c.pid)) + assert words in nine.read(f'/pane/{pane}/body'), how + seen = len(checks(check)) + os.write(t.master, b'jj') + wait_for(f'{how}: the client agrees after it', lambda: agreed(check, seen), timeout=30) + nine.socket.close() + t.close() + terms.remove(t) + c.wait(timeout=20) + wait_for(f'{how}: the session ended with its last link', lambda: not alive(session), timeout=20) + print(f'pair back: no daemon, its client {how}: joined again over its own link, the session alive, ' + f'its unsaved text there, agreed; its terminal closed, the session ended') + wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20) + finally: + for p in processes(root): + try: + os.kill(p, signal.SIGKILL) + except OSError: + pass + for t in terms: + t.close() + shutil.rmtree(root, ignore_errors=True) + + def attach_upgrading(binary, rounds=6, dump=True): """`pardes attach` as its session upgrades: started at once after the Upgrade's word, it is handed to the session before the exec; told the @@ -2251,8 +2366,8 @@ def far_flood(binary): started = [] terms = [] try: - sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=dict(env, PARDES_REPLICA_STATS=str(root / 'session.stats')), + cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) started.append(sess.pid) sock = root / 'pardes-replica.sock' wait_for('the replica socket', sock.exists) @@ -2276,13 +2391,24 @@ def far_flood(binary): dict(env, PARDES_REPLICA_FAR='1', PARDES_REPLICA_CHECK=str(check), PARDES_REPLICA_STATS=str(stats))) started.append(c.pid) wait_for('the far client\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=60) + links = sockets(c.pid) nine.write(f'/pane/{shell}/pty/data', b'timeout 20 yes; echo yes-done\r') wait_for('yes ended', lambda: b'yes-done' in nine.read(f'/pane/{shell}/body').replace(b'\r', b''), timeout=60) + ended_at = time.monotonic() seen = len(checks(check)) wait_for('the far client agrees once yes ended', lambda: agreed(check, seen), timeout=120) # Queued behind the flood, let go for its lag, joined again from a # dump: a link of its ended (its stats line), and its notice says why. assert joins(stats), ('no link of the far client ended under the flood', checks(stats)) + # Fallen behind, a far client dials again (core/replica.zig + # `Link.backHere`: the second road until bounded flight): a new + # connection, not what the old one holds for it read through; each + # join's time and the KB it was sent; the flood's end to its agreement. + same = sockets(c.pid) == links + print(f'far flood: the far client\'s link {"the same" if same else "another"} after {len(joins(stats))} joins again ' + f'(join ms {[j.get("join_ms") for j in joins(stats)]}, sent KB {[j.get("sent_kb") for j in joins(stats)]}); ' + f'agreed {time.monotonic() - ended_at:.1f} s after yes ended') + assert not same, ('the far client behind dialled again: another connection', links, sockets(c.pid)) wait_for('the far client\'s notice of its join again', lambda: b'joined again: ' in t.text() and b' s behind' in t.text(), timeout=30) os.write(t.master, b'echo from-far\r') wait_for('the far client\'s keys in the shell', lambda: b'from-far' in nine.read(f'/pane/{shell}/body'), timeout=30) @@ -2843,6 +2969,7 @@ def main(binary, cycles): launch(binary) pair(binary) pair_rows(binary) + pair_back(binary) attach_upgrading(binary) kept_views(binary) pair_upgrade_views(binary) @@ -3967,8 +4094,11 @@ if __name__ == '__main__': elif sys.argv[1:2] == ['--pair']: pair(sys.argv[2]) pair_rows(sys.argv[2]) + pair_back(sys.argv[2]) attach_upgrading(sys.argv[2], dump=False) pair_upgrade_views(sys.argv[2]) + elif sys.argv[1:2] == ['--pair-back']: + pair_back(sys.argv[2]) elif sys.argv[1:2] == ['--attach-upgrading']: attach_upgrading(sys.argv[2]) elif sys.argv[1:2] == ['--relink']: @@ -3981,6 +4111,8 @@ if __name__ == '__main__': far_flood(sys.argv[2]) by_hash(sys.argv[2]) far_find(sys.argv[2]) + elif sys.argv[1:2] == ['--far-flood']: + far_flood(sys.argv[2]) elif sys.argv[1:2] == ['--far-find']: far_find(sys.argv[2]) elif sys.argv[1:2] == ['--kitty-image']: diff --git a/test/replicas.zig b/test/replicas.zig index 8f3e5ca5..3aa9263e 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -251,6 +251,8 @@ const Totals = struct { /// Joins from a dump, refused, again after a divergence put on it /// (PARDES_TEST_DIVERGE's), and clients that left; quiet checks. joins: u64 = 0, + /// ...of them again over the client's own link (no dial). + here: u64 = 0, refused: u64 = 0, /// A pair's client's own boot the session's core at its join (`--pair`), /// or not (its dump loaded instead, the fields that differ said). @@ -527,11 +529,10 @@ const Client = struct { stops: @FieldType(replica.Stats, "stops") = @splat(.{}), /// Its Peer's writer's (`Soak.write`): the batch swapped out of the /// session's queue for it (the Peers' allocator's), how much of it went - /// down the link, whether a cut's words end it, a wake asked for room; - /// how much of the queue carries the soak's clock (`Soak.stamp`). + /// down the link, a wake asked for room; how much of the queue carries + /// the soak's clock (`Soak.stamp`). sending: std.ArrayListUnmanaged(u8) = .empty, at: usize = 0, - last: bool = false, draining: bool = false, marked: usize = 0, /// The session's unit its last join's dump came after. @@ -752,14 +753,17 @@ fn describe(buf: []u8, ev: pardes.Event) []const u8 { } catch "?"; } -/// Its link ended (it diverged, or it quits): its bye, and its join again -/// for its view after a divergence (`Link.rejoins`), the core it leaves -/// held until the dump comes, as `replica.join` holds it. +/// Its link ended (it diverged, fell behind, was cut off, or it quits): +/// its join again for its view (`Link.rejoins`), over its link while that +/// is up (its goodbye and hello said there: runtime/client.zig `run`), the +/// core it leaves held until the dump comes, as `replica.join` holds it; +/// else its bye. fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run, typing: *usize) !void { const r = cl.r.?; const link = &cl.loop.link; + const here = link.backHere() and replica.comeBack(link.fd, "soak", r.view); // Its link ended by the session (a Detach), it says nothing more. - if (!link.gone) replica.bye(link.fd, .{ .again = r.diverged != null or link.lagged != 0 }); + if (!here and !link.gone) replica.bye(link.fd, .{ .again = r.diverged != null or link.lagged != 0 }); try drain(cl, c, net, now); cl.live = 0; if (link.lagged != 0) { @@ -775,6 +779,10 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run, if (link.rejoins()) { cl.back = r.view; cl.dialling = true; + if (here) { + totals.here += 1; + return; + } return net.send(.{ .at = net.cross(&net.up[c], c, now, &.{}, 3), .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); } try totals.add(&r.stats); @@ -1435,10 +1443,8 @@ const Soak = struct { if (!there) cl.peer = null; }; // A join taken (its Peer holds the dup handed) or refused (its dup - // closed, daemon.refuseReplica): its writer's join first (the - // welcome, then the dump with the session's blobs put back where - // they go: Peer.writeJoin), its far word read (`far` false: on - // this machine), and its pins let go at the next boundary. + // closed, daemon.refuseReplica): its writer's join first (`joinDown`), + // its far word read (`far` false: on this machine). for (s.clients, 0..) |*cl, c| if (cl.handed >= 0) { defer cl.handed = -1; const peer = for (ps.list) |slot| { @@ -1448,44 +1454,17 @@ const Soak = struct { try net.toClient(c, now, .refused, cl.gen, &.{}); continue; }; - const f = (try pardes.wire.framed(peer.welcome[0..peer.welcome_len])) orelse return error.BadWelcome; - const welcome = (try pardes.wire.decodeServer(f.tag, f.payload)).welcome; - var whole: std.ArrayListUnmanaged(u8) = .empty; - errdefer 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..]); var word: [16]u8 = undefined; const far = try pardes.wire.encodeClient(&word, .{ .far = false }); _ = peer.take(far[0], far[pardes.wire.header_len..]); - ps.post(.{ .joined = peer }); - cl.peer = peer; - cl.shut = false; - cl.read_done = false; - cl.join_seq = ps.seq; - cl.sending.clearRetainingCapacity(); - cl.at = 0; - cl.last = false; - cl.marked = 0; - // What the join cost the session's step (Peers.join's measure). - s.join_worst = @max(s.join_worst, ps.join_ns); - try s.totals.join_session_ns.append(gpa, ps.join_ns); - ps.join_ns = 0; - cl.gen += 1; - cl.id = welcome.client; - cl.view = welcome.view.index(); - cl.digest = welcome.digest; - s.totals.joins += 1; - Witness.joined(c, cl, try gpa.dupe(u8, whole.items), cl.join_seq); - try net.toClient(c, now, .dump, cl.gen, try whole.toOwnedSlice(gpa)); + try s.joinDown(cl, c, peer); }; - // A Detach typed in a client's view, or one cut off for its lag: its - // link shut, it hears its end and nothing after; its reader's end - // said (the next boundary lets it go). + // A join again over a client's own link (Peers.joinAgain): its writer's + // next, the stream it leaves let go. + for (s.clients, 0..) |*cl, c| if (cl.peer) |peer| if (peer.written != peer.gen) try s.joinDown(cl, c, peer); + // A Detach typed in a client's view: its link shut, it hears its end + // and nothing after; its reader's end said (the next boundary lets + // it go). if (s.detach_view) |k| for (s.clients) |*cl| if (cl.peer) |p| if (p.view.index() == k and !cl.shut) { cl.shut = true; }; @@ -1513,6 +1492,44 @@ const Soak = struct { s.echo.clearRetainingCapacity(); } + /// Client `c`'s Peer's writer's join (Peer.writeJoin): the welcome, then + /// the dump with the session's blobs put back where they go, down its + /// link, what was queued before it let go; its pins let go at the next + /// boundary. + fn joinDown(s: *Soak, cl: *Client, c: usize, peer: *replica.Peer) !void { + const ps = &s.l.peers; + const f = (try pardes.wire.framed(peer.welcome[0..peer.welcome_len])) orelse return error.BadWelcome; + const welcome = (try pardes.wire.decodeServer(f.tag, f.payload)).welcome; + var whole: std.ArrayListUnmanaged(u8) = .empty; + errdefer 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 } }); + cl.peer = peer; + cl.shut = false; + cl.read_done = false; + cl.join_seq = ps.seq; + cl.sending.clearRetainingCapacity(); + cl.at = 0; + cl.marked = 0; + // What the join cost the session's step (Peers.join's measure). + s.join_worst = @max(s.join_worst, ps.join_ns); + try s.totals.join_session_ns.append(gpa, ps.join_ns); + ps.join_ns = 0; + cl.gen += 1; + cl.id = welcome.client; + cl.view = welcome.view.index(); + cl.digest = welcome.digest; + s.totals.joins += 1; + Witness.joined(c, cl, try gpa.dupe(u8, whole.items), cl.join_seq); + try s.net.toClient(c, s.now, .dump, cl.gen, try whole.toOwnedSlice(gpa)); + } /// The units the session queued for client `cl` since, their heads /// carrying the soak's clock, the session's here (its host's `now`): /// what the client's lag is measured by. Its replica guesses no clock @@ -1534,7 +1551,7 @@ const Soak = struct { /// frame a message. The far link takes no more than `throttle_window` /// ahead of what has crossed: the rest waits in the queue, as it does /// for a writer blocked on its socket, until room comes (`.drain`). A - /// cut's words end a batch, and its link after them. + /// cut's words are its last until its client's hello again there. fn write(s: *Soak, cl: *Client, c: usize) !void { const peer = cl.peer orelse return; const net = s.net; @@ -1543,11 +1560,9 @@ const Soak = struct { if (cl.at == cl.sending.items.len) { cl.sending.clearRetainingCapacity(); cl.at = 0; - if (cl.last) return s.shut(cl, c); const io = s.l.peers.io; peer.lock.lockUncancelable(io); std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &cl.sending); - cl.last = peer.cut; peer.lock.unlock(io); cl.marked = 0; if (cl.sending.items.len == 0) return; @@ -1590,11 +1605,10 @@ const Soak = struct { } /// Client `c`'s link ended at the session's side (a Detach typed in its - /// view, or the words of a cut sent): it hears its end and nothing after, - /// and its reader's end is said (the next boundary lets it go). + /// view): it hears its end and nothing after, and its reader's end is + /// said (the next boundary lets it go). fn shut(s: *Soak, cl: *Client, c: usize) !void { cl.shut = true; - cl.last = false; if (cl.read_done) return; cl.read_done = true; s.l.peers.post(.{ .gone = cl.peer.? }); @@ -3400,7 +3414,7 @@ pub fn main(init: std.process.Init) !void { try stop_lines.print(gpa, "{d:>4} {d:>8} {d:>6} {d:>6} {d:>3}/{d}/{d} ", .{ rtt, t.unlisted, t.wakes, t.draws, t.asked[0], t.asked[1], t.asked[2] }); for (t.stops) |st| if (st.n > 0) try stop_lines.print(gpa, "{s}:{d} ", .{ st.name, st.n }); try stop_lines.append(gpa, '\n'); - try join_lines.print(gpa, "{d:>4} {d:>5} {d:>7} {d:>8} {d:>8} {d:>6} {d:>5}/{d:<5} {d:>5}/{d:<6} {d:>7} {d:>5}/{d}/{d}\n", .{ rtt, t.joins, t.refused, t.rejoined, t.detached, t.detach_words, t.agree, t.differ, t.checks, t.units, t.resizes, t.kind_panes[0], t.kind_panes[1], t.kind_panes[2] }); + try join_lines.print(gpa, "{d:>4} {d:>5} {d:>4} {d:>7} {d:>8} {d:>8} {d:>6} {d:>5}/{d:<5} {d:>5}/{d:<6} {d:>7} {d:>5}/{d}/{d}\n", .{ rtt, t.joins, t.here, t.refused, t.rejoined, t.detached, t.detach_words, t.agree, t.differ, t.checks, t.units, t.resizes, t.kind_panes[0], t.kind_panes[1], t.kind_panes[2] }); try far_lines.print(gpa, "{d:>4} {d:>5} {d:>4} {d:>6.1}/{d:<6.1} {d:>6.1}/{d:<6.1} {d:>8} {d:>3} {d:>6.1}/{d:<6.1} {d:>6.1}/{d:<6.1} ({d}) {d:>6.0}/{d:<6.0} {d}\n", .{ rtt, t.far_joins, t.far_lags, secs(pct(t.far_gaps.items, 50)), secs(pct(t.far_gaps.items, 100)), @@ -3419,8 +3433,8 @@ pub fn main(init: std.process.Init) !void { } std.debug.print("terminals: a peer's unit bytes a second under the flood (the pty's bytes ride in them); KB of units sent to the peers in all\n", .{}); std.debug.print(" rtt unit B/s units KB\n{s}", .{term_lines.items}); - std.debug.print("clients: joins from a dump, refused (every view taken), joined again after a divergence put on them, left (of them by a Detach); quiet checks of the session's digest agreed/differed; the digests the clients compared (units and quiet), of the units they took; resizes the windows posted; the kinds' panes the session opened (image/life/pdf)\n", .{}); - std.debug.print(" rtt joins refused rejoined detached detach agree/differ checks/units resizes kinds\n{s}", .{join_lines.items}); + std.debug.print("clients: joins from a dump (here: of them again over the client's own link, no dial), refused (every view taken), joined again after a divergence put on them, left (of them by a Detach); quiet checks of the session's digest agreed/differed; the digests the clients compared (units and quiet), of the units they took; resizes the windows posted; the kinds' panes the session opened (image/life/pdf)\n", .{}); + std.debug.print(" rtt joins here refused rejoined detached detach agree/differ checks/units resizes kinds\n{s}", .{join_lines.items}); std.debug.print("stops: the wakes the clients' loops asked, the frames they drew, the yanks, pastes and links their frontends did (y/p/l), and what stopped their inputs (a stop counted again as its input is applied again), by name; those at a name replica.may_wait does not list fail the run\n", .{}); std.debug.print(" rtt unlisted wakes draws y/p/l stops\n{s}", .{stop_lines.items}); std.debug.print("far: the third client's link 1 Mbit/s and 200 ms each way (zstd's bytes): its joins from a dump, of them for its lag (Link.behind past replica.behind_max_ms), s between two from the flood's start (p50/max), s from the flood's end to its final screen (p50/max: a run that never shows it fails), the session's queue for it at most, clients cut off; a join's cost to the replicas there before it, ms on this process's clock (p50/max): the session's step (reloads and dump), a client's unit (reloads), how many; ms behind the session at most (Link.behind), the far client and the others, and the others' joins for it (0, or the run fails)\n", .{}); |
