diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-17 23:28:13 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-17 23:42:48 -0300 |
| commit | 9b20d00ca5ffbab640b87249d65e4165414d22c1 (patch) | |
| tree | e62644195d40b5a41ed92a5e19548fa84cff4821 | |
| parent | 6c61169832d6f396ee7a6e9e0b09d9c055d08f8d (diff) | |
| download | pardes-9b20d00ca5ffbab640b87249d65e4165414d22c1.tar.gz pardes-9b20d00ca5ffbab640b87249d65e4165414d22c1.zip | |
replica: a record of a MiB or more crosses to a client by its hash, beside its unit (tape.zig by_hash_min, Big; wire blob): a file over the wire's 16 MiB bound opened while a client was attached was one unit, past the bound, so a Debug session panicked and a release one dropped it, its client diverging at the next unit and joining again to be sent the whole file in the dump; now the read's answer is recorded as the file's BLAKE3, a client on the session's machine reads the path itself and checks it, a far one is sent it in 1 MiB pieces before the unit and keeps it in its cache.xitdb (XDG_CACHE_HOME/pardes), so a far client that joins after is sent none of it; any other record that long (a reload's text, a paste) goes to every client so; test/daemon.py by_hash: a 17 MiB file under a near and a far client, both agree, neither joins again, the near one reads it itself, the far one is sent 8848 KB of zstd and a far client after it none of its 2 blobs; the slot's own BLAKE3 the brief asked for was built and taken out (a hash a kind's open, 7 instructions a byte on the perf build's CPU, for no reader until a client renders kinds); perf --only medium --reps 10 instructions:u 2,459.25M -> 2,459.36M, --terminal-mib 8 3,928.50M -> 3,928.51M; tui core-test 811/950 (139 skipped), shell-test passes, replicas pass (diverged 0, checked/wrong 0), behaviour-test 269/273 (the four addon ABI tests the base fails), --replay 20 seeds 0 failures, process-test 2 of 144 failed (lspcomplete and lspcompletemoved, the base's; headersweep and headersweep-restored failed once at load 14 and pass alone), test/daemon.py passes
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
| -rw-r--r-- | src/fs.zig | 4 | ||||
| -rw-r--r-- | src/gui/gui.zig | 2 | ||||
| -rw-r--r-- | src/replica.zig | 86 | ||||
| -rw-r--r-- | src/tape.zig | 120 | ||||
| -rw-r--r-- | src/tui/tui.zig | 4 | ||||
| -rw-r--r-- | src/wire.zig | 8 | ||||
| -rw-r--r-- | test/daemon.py | 84 |
7 files changed, 291 insertions, 17 deletions
@@ -726,7 +726,9 @@ fn readFileLimit(gpa: std.mem.Allocator, path: []const u8, limit: usize) ![]u8 { return pardes.tape.site(.read_file, gpa, readHost, .{ gpa, path_z, limit }); } -fn readHost(gpa: std.mem.Allocator, path_z: [:0]const u8, limit: usize) ![]u8 { +/// The disk's file at `path_z`, whole: the session's read, and a replica +/// client's of a read it was sent by hash (tape.zig `byHash`). +pub fn readHost(gpa: std.mem.Allocator, path_z: [:0]const u8, limit: usize) ![]u8 { const fd = libc.open(path_z, .{ .ACCMODE = .RDONLY, .NONBLOCK = true }); if (fd < 0) return switch (libc.errno(fd)) { .ACCES, .PERM => error.PermissionDenied, diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 9bd6f5b9..92117c19 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1483,7 +1483,7 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ reader.join(); client.lock.lockUncancelable(io); for (client.inbox.items) |msg| switch (msg) { - .unit, .screen, .refused => |b| std.heap.c_allocator.free(b), + .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b), .checked => {}, }; client.inbox.clearRetainingCapacity(); diff --git a/src/replica.zig b/src/replica.zig index 09746377..fa888021 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -689,6 +689,14 @@ pub const Replica = struct { screen_out: std.ArrayListUnmanaged(u8) = .empty, /// Its Shadows' rasters, from the session's strips (17.3). blobs: pardes.Kind.Blobs = .{}, + /// A record's bytes by hash coming in pieces (`blobPiece`), and how + /// many of them came. + incoming: ?tape.Big = null, + incoming_got: usize = 0, + /// A far client's blobs on disk (its Have's), where a file it is sent + /// goes for its next join. + cache: ?Cache = null, + io: std.Io = undefined, /// Its predicted echo (src/term/echo.zig), drawn over its core's terminals: /// fed by its keys, its units and its deltas here, and by `echoFrame`. echo: Echo = .{}, @@ -777,6 +785,7 @@ pub const Replica = struct { was.end(); } r.blobs.deinit(r.gpa); + if (r.incoming) |b| r.gpa.free(b.bytes); r.copy.deinit(); for (r.pending.items) |p| r.freePending(p); r.pending.deinit(r.gpa); @@ -1261,6 +1270,33 @@ pub const Replica = struct { return r.screen_out.items; } + /// A piece of a record's bytes by hash (Peer.blob): whole and checked + /// against its hash, kept for the unit that names it (tape.keepFile), + /// and a file's, a far client's, on disk (`cache`) for its next join. + pub fn blobPiece(r: *Replica, msg: []const u8) void { + if (msg.len < 49) return r.fail("a short piece of a record by hash"); + const total = std.math.cast(usize, std.mem.readInt(u64, msg[32..40], .little)) orelse return r.fail("a record by hash too long"); + const at = std.mem.readInt(u64, msg[40..48], .little); + if (at == 0) { + if (r.incoming) |b| r.gpa.free(b.bytes); + r.incoming = .{ .hash = msg[0..32].*, .bytes = r.gpa.alloc(u8, total) catch return r.fail("out of memory for a record by hash"), .path = msg[48] != 0 }; + r.incoming_got = 0; + } + const b = r.incoming orelse return r.fail("a piece of a record by hash out of order"); + const piece = msg[49..]; + if (at != r.incoming_got or b.bytes.len != total or piece.len > total - at) return r.fail("a piece of a record by hash out of order"); + @memcpy(b.bytes[at..][0..piece.len], piece); + r.incoming_got += piece.len; + if (r.incoming_got < total) return; + r.incoming = null; + if ((b.path and b.bytes.len < 9) or !std.mem.eql(u8, &tape.Big.hashOf(b.bytes, b.path), &b.hash)) { + r.gpa.free(b.bytes); + return r.fail("a record by hash came other than its hash"); + } + if (b.path) if (r.cache) |c| if (b.bytes.len - 9 <= c.cap) c.put(r.io, &.{.{ .hash = b.hash, .bytes = b.bytes[9..] }}, &.{}); + tape.keepFile(&r.t, b); + } + pub fn digest(r: *Replica) u64 { const was = Stepping.begin(&r.t, &r.epoch); defer was.end(); @@ -1697,6 +1733,33 @@ pub const Peer = struct { peer.cond.signal(io); } + /// A record's bytes by hash (tape.Big) queued for it in pieces, before + /// the unit that names them: for a far client, and for one on this + /// machine unless they are a file it reads itself (tape.zig `byHash`). + /// Never cut off for them: a big file is no lag. + fn blob(peer: *Peer, b: tape.Big) void { + const io = peer.peers.io; + peer.lock.lockUncancelable(io); + defer peer.lock.unlock(io); + if (peer.cut or peer.closing or (b.path and peer.far == false)) return; + var at: usize = 0; + while (at < b.bytes.len) : (at += dump_piece) { + const piece = b.bytes[at..@min(b.bytes.len, at + dump_piece)]; + var meta: [49]u8 = undefined; + meta[0..32].* = b.hash; + std.mem.writeInt(u64, meta[32..40], b.bytes.len, .little); + std.mem.writeInt(u64, meta[40..48], at, .little); + meta[48] = @intFromBool(b.path); + const head = wire.header(@backingInt(wire.ServerTag.blob), meta.len + piece.len); + for ([_][]const u8{ &head, &meta, piece }) |part| peer.out.appendSlice(peer.peers.gpa, part) catch { + peer.cut = true; + _ = libc.shutdown(peer.fd, 2); + return; + }; + } + peer.cond.signal(io); + } + fn writeLoop(peer: *Peer) void { const io = peer.peers.io; defer peer.done.store(true, .release); @@ -1912,6 +1975,13 @@ pub const Peers = struct { const bytes = ps.t.buf.items; unitHeader(&ps.head, origin, seq); trace(ps.gpa, "session: unit {d}/{d}, {d} bytes, to {d} clients:\n", .{ origin, seq, bytes.len, ps.count() }, &.{bytes}); + // Its records by hash first (tape.by_hash_min: a file read), each + // whole before the unit that names it. + for (ps.t.big.items) |b| { + for (ps.list) |slot| if (slot) |peer| peer.blob(b); + ps.gpa.free(b.bytes); + } + ps.t.big.clearRetainingCapacity(); const head = wire.header(@backingInt(wire.ServerTag.unit), unit_head + bytes.len); for (ps.list) |slot| if (slot) |peer| peer.send(&.{ &head, &ps.head, bytes }); ps.t.buf.clearRetainingCapacity(); @@ -2692,7 +2762,7 @@ pub fn bye(fd: c_int, again: bool) void { /// What the session streams a client after its dump, as its frontend's loop /// takes it: a unit's and a terminal message's bytes and a refusal's words /// on the C heap, the loop's to free. -pub const Said = union(enum) { unit: []u8, screen: []u8, checked: u64, refused: []u8 }; +pub const Said = union(enum) { unit: []u8, screen: []u8, checked: u64, refused: []u8, blob: []u8 }; /// 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 @@ -2704,12 +2774,13 @@ pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime const msg: Said = switch (t) { .unit => .{ .unit = std.heap.c_allocator.dupe(u8, payload) catch return false }, .screen => .{ .screen = 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 }, .refused => .{ .refused = std.heap.c_allocator.dupe(u8, (wire.decodeServer(tag, payload) catch return false).refused) catch return false }, .pong, .welcome, .dump, .blobs, .zstd => return true, }; if (!post(x, msg)) switch (msg) { - .unit, .screen, .refused => |b| std.heap.c_allocator.free(b), + .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b), .checked => {}, }; return msg != .refused; @@ -2766,6 +2837,13 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o return null; } r.gmtoff = j.gmtoff; + // On the session's machine: a file read sent by hash is read here; + // far, it goes to the disk for the next join. + r.t.local_files = have == null; + if (have) |h| { + r.cache = h.cache; + r.io = h.io; + } j.ms = (nowNs() - t0) / std.time.ns_per_ms; return r; } @@ -2923,6 +3001,10 @@ pub const Link = struct { if (c.r.screen(bytes)) |reply| if (!sendScreen(c.fd, reply)) c.cut(); c.dirty = true; }, + .blob => |bytes| { + defer std.heap.c_allocator.free(bytes); + c.r.blobPiece(bytes); + }, .checked => |d| c.checked(d), .refused => |words| { if (c.refused) |old| std.heap.c_allocator.free(old); diff --git a/src/tape.zig b/src/tape.zig index eaae601e..9dca5ee8 100644 --- a/src/tape.zig +++ b/src/tape.zig @@ -183,7 +183,27 @@ fn Watched(comptime name: []const u8) type { return if (@hasField(Pardes.View, name)) @FieldType(Pardes.View, name) else @FieldType(Pardes, name); } -const Kind = enum(u8) { input, done, host, ret, set, digest }; +/// `blob`: a record of `by_hash_min` bytes or more, in the replica stream, +/// as its kind and its bytes' BLAKE3 (`Big`): its bytes go beside the unit. +const Kind = enum(u8) { input, done, host, ret, set, digest, blob }; +/// A record at least this long crosses to a replica by hash: a unit stays +/// under the wire's bound (16 MiB) whatever a file read holds. +pub const by_hash_min = 1 << 20; +/// A record's bytes by hash: the session's (`Tape.big`), to send; a +/// replica's (`Tape.files`), to replay. `path`: a file read's answer, which +/// a replica on the session's machine reads itself, its hash the file's +/// own bytes' (after the answer's 9: yes, a length), as a dump's text is. +pub const Big = struct { + hash: [32]u8, + bytes: []u8, + path: bool = false, + + pub fn hashOf(bytes: []const u8, path: bool) [32]u8 { + var h: [32]u8 = undefined; + std.crypto.hash.Blake3.hash(if (path) bytes[9..] else bytes, &h, .{}); + return h; + } +}; /// A digest record's kind byte (replica.zig reads a unit's last). pub const digest_kind: u8 = @backingInt(Kind.digest); pub const set_kind: u8 = @backingInt(Kind.set); @@ -275,13 +295,36 @@ pub const Tape = struct { /// time, so the guess a speculation recorded is what the authority /// records (a message's millisecond, an edit's second never miss). stamp: ?Guess = null, + /// The replica stream's records by hash (`unit_digests`), until the + /// unit is sent (src/replica.zig `Peers.unit`). + big: std.ArrayListUnmanaged(Big) = .empty, + /// A replica's: the last few records by hash it was sent or read. + files: std.ArrayListUnmanaged(Big) = .empty, + /// A replica on the session's machine: a file read by hash is read + /// here, by its path, and checked. + local_files: bool = false, + /// The path a `read_file` site reads, while it is recorded or replayed. + reading: ?[:0]const u8 = null, fn record(t: *Tape, kind: Kind, comptime T: type, v: *const T) void { t.scratch.clearRetainingCapacity(); walk.encode(T, v, &t.scratch.writer) catch @panic("tape: out of memory"); - const payload = t.scratch.written(); + var payload = t.scratch.written(); + var kind_ = kind; + var by_hash: [34]u8 = undefined; + if (t.unit_digests and payload.len >= by_hash_min) { + // A file read's yes, by the file's bytes' hash. + const path = t.reading != null and kind == .ret and payload[0] == 1; + by_hash[0] = @backingInt(kind); + by_hash[1..33].* = Big.hashOf(payload, path); + by_hash[33] = @intFromBool(path); + const bytes = t.gpa.dupe(u8, payload) catch @panic("tape: out of memory"); + t.big.append(t.gpa, .{ .hash = by_hash[1..33].*, .bytes = bytes, .path = path }) catch @panic("tape: out of memory"); + payload = &by_hash; + kind_ = .blob; + } const len: u32 = @intCast(payload.len); - t.buf.append(t.gpa, @backingInt(kind)) catch @panic("tape: out of memory"); + t.buf.append(t.gpa, @backingInt(kind_)) catch @panic("tape: out of memory"); t.buf.appendSlice(t.gpa, std.mem.asBytes(&len)) catch @panic("tape: out of memory"); t.buf.appendSlice(t.gpa, payload) catch @panic("tape: out of memory"); if (t.buf.items.len > 1 << 20) t.flush(); @@ -386,12 +429,45 @@ pub const Tape = struct { const head = t.in.take(5) catch return null; const len = std.mem.bytesToValue(u32, head[1..5]); const payload = t.in.take(len) catch return null; - return .{ .kind = @fromBackingInt(@intCast(head[0])), .payload = .{ .bytes = payload } }; + const kind: Kind = @fromBackingInt(@intCast(head[0])); + if (kind != .blob) return .{ .kind = kind, .payload = .{ .bytes = payload } }; + if (payload.len != 34) { + t.diverge("a record by hash is short", .{}); + return null; + } + const bytes = t.byHash(payload[1..33], payload[33] != 0) orelse { + t.diverge("a record by hash {x} is not here", .{payload[1..9]}); + return null; + }; + return .{ .kind = @fromBackingInt(@intCast(payload[0])), .payload = .{ .bytes = bytes } }; } fn peek(t: *const Tape) ?Kind { if (t.in.bytes.len - t.in.at < 5) return null; - return @fromBackingInt(@intCast(t.in.bytes[t.in.at])); + const kind: Kind = @fromBackingInt(@intCast(t.in.bytes[t.in.at])); + if (kind == .blob and t.in.bytes.len - t.in.at > 5) return @fromBackingInt(@intCast(t.in.bytes[t.in.at + 5])); + return kind; + } + + /// The bytes of a record by hash: sent, or read here (a file read's + /// answer, on the session's machine), each checked against its hash. + fn byHash(t: *Tape, hash: *const [32]u8, is_path: bool) ?[]const u8 { + for (t.files.items) |f| if (std.mem.eql(u8, &f.hash, hash)) return f.bytes; + const path = t.reading orelse return null; + if (!t.local_files or !is_path) return null; + const file = pardes.filesystem.readHost(t.gpa, path, pardes.memory.limits.max_file_bytes) catch return null; + defer t.gpa.free(file); + // The answer as `record` wrote it: an error union's yes, a length, the bytes. + const bytes = t.gpa.alloc(u8, 9 + file.len) catch return null; + bytes[0] = 1; + std.mem.writeInt(u64, bytes[1..9], file.len, .little); + @memcpy(bytes[9..], file); + if (!std.mem.eql(u8, &Big.hashOf(bytes, true), hash)) { + t.gpa.free(bytes); + return null; + } + keepFile(t, .{ .hash = hash.*, .bytes = bytes, .path = true }); + return bytes; } fn diverge(t: *Tape, comptime why: []const u8, args: anytype) void { @@ -412,7 +488,7 @@ pub const Tape = struct { .set => t.applySet(&rec.payload), .host => t.skipHost(), .digest => t.check(rec.payload.bytes), - .done => return t.diverge("a host call's records are out of order", .{}), + .done, .blob => return t.diverge("a host call's records are out of order", .{}), } } } @@ -444,7 +520,7 @@ pub const Tape = struct { .host => if (t.skips_render) t.skipHost() else return t.diverge("the core did not make the host call {d} the tape has", .{std.mem.bytesToValue(u16, rec.payload.bytes[0..2])}), .input => t.apply(&rec.payload), .digest => t.check(rec.payload.bytes), - .ret => return t.diverge("the core's input ended before the recorded one", .{}), + .ret, .blob => return t.diverge("the core's input ended before the recorded one", .{}), } } } @@ -465,7 +541,7 @@ pub const Tape = struct { .input => t.apply(&rec.payload), .set => t.applySet(&rec.payload), .digest => t.check(rec.payload.bytes), - .host, .done => { + .host, .done, .blob => { t.diverge("a host call's records are out of order", .{}); return false; }, @@ -917,6 +993,10 @@ fn call(comptime s: Site, a: ?std.mem.Allocator, comptime f: anytype, args: anyt // No tape where there is no host to record or replay one. const t = on orelse return if (yields) out(f, args) else @call(.auto, f, args); const id: u16 = @as(u16, host_fns.len) + @backingInt(s); + if (comptime s == .read_file) t.reading = args[1]; + defer if (comptime s == .read_file) { + t.reading = null; + }; if (t.replay) { // Diverged (said in `diverged`): what a speculation gets, harmless, // for the rest of the input. A replica joins again; a replay says so. @@ -955,6 +1035,13 @@ fn call(comptime s: Site, a: ?std.mem.Allocator, comptime f: anytype, args: anyt pub const Guess = struct { real_ns: i64, mono_ns: i64, gmtoff: i32 }; +/// A record's bytes by hash kept for a replica's replays (`files`, the +/// tape's allocator's): the last eight, a rollback's units' and the next's. +pub fn keepFile(t: *Tape, b: Big) void { + if (t.files.items.len == 8) t.gpa.free(t.files.orderedRemove(0).bytes); + t.files.append(t.gpa, b) catch t.gpa.free(b.bytes); +} + /// A clock read of the session's, as a replica client guesses it: a file's /// mtime (realtime seconds), a message's clock (monotonic ms), a message's /// time of day (in the session's zone). @@ -1129,6 +1216,10 @@ pub fn memory(gpa: std.mem.Allocator) Tape { /// What a tape in memory holds, given back (its core is gone already). pub fn release(t: *Tape) void { + for (t.big.items) |b| t.gpa.free(b.bytes); + t.big.deinit(t.gpa); + for (t.files.items) |b| t.gpa.free(b.bytes); + t.files.deinit(t.gpa); t.answers.deinit(t.gpa); t.buf.deinit(t.gpa); t.scratch.deinit(); @@ -1154,7 +1245,7 @@ pub fn replayUnit(t: *Tape, bytes: []const u8) ?[]const u8 { }, .set => t.applySet(&rec.payload), .digest => t.check(rec.payload.bytes), - .host, .ret, .done => t.diverge("a {t} record at the top", .{kind}), + .host, .ret, .done, .blob => t.diverge("a {t} record at the top", .{kind}), } } return t.diverged; @@ -1210,7 +1301,16 @@ pub fn describe(bytes: []const u8, w: *std.Io.Writer) void { while (true) { const head = r.take(5) catch return; const payload = r.take(std.mem.bytesToValue(u32, head[1..5])) catch return; - const kind: Kind = @fromBackingInt(@intCast(head[0])); + const raw: Kind = @fromBackingInt(@intCast(head[0])); + // A record by hash, as the kind it stands for (its bytes are not here). + const kind: Kind = if (raw == .blob and payload.len > 0) @fromBackingInt(@intCast(payload[0])) else raw; + if (raw == .blob) { + w.splatByteAll(' ', depth * 2) catch {}; + w.print("{t} by hash\n", .{kind}) catch {}; + if (kind == .done or kind == .ret) depth -|= 1; + if (kind == .input or kind == .host) depth += 1; + continue; + } if (kind == .done or kind == .ret) depth -|= 1; w.splatByteAll(' ', depth * 2) catch {}; switch (kind) { diff --git a/src/tui/tui.zig b/src/tui/tui.zig index 349ced56..919eeded 100644 --- a/src/tui/tui.zig +++ b/src/tui/tui.zig @@ -805,7 +805,7 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, const ended = reader_done.load(.acquire); while (loop.tryEvent() catch null) |ev| switch (ev) { .said => |said| switch (said) { - .unit, .screen, .refused => |b| std.heap.c_allocator.free(b), + .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b), .checked => {}, }, .paste => |b| gpa.free(@constCast(b)), @@ -1732,7 +1732,7 @@ const Shell = struct { c.link.take(said); if (said == .refused) return true; } else switch (said) { - .unit, .screen, .refused => |b| std.heap.c_allocator.free(b), + .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b), .checked => {}, }, .link_gone => if (s.client) |c| { diff --git a/src/wire.zig b/src/wire.zig index 9773d222..864c2fd8 100644 --- a/src/wire.zig +++ b/src/wire.zig @@ -183,6 +183,10 @@ pub const ServerTag = enum(u8) { /// A piece of a far client's stream from here on, zstd-compressed: the /// messages in it are framed as these are. Opaque here. zstd = 0x09, + /// A piece of a record's bytes by hash (tape.zig `Big`), before the + /// unit naming it: the hash, the whole's length and this piece's place + /// (u64le each), then at most 1 MiB of it (src/replica.zig). + blob = 0x0a, }; pub const ServerMsg = union(ServerTag) { @@ -199,6 +203,7 @@ pub const ServerMsg = union(ServerTag) { check: u64, blobs: []const u8, zstd: []const u8, + blob: []const u8, }; /// A message's header, for a payload sent on its own (a unit, a dump's @@ -233,6 +238,7 @@ pub fn decodeServer(tag: u8, payload: []const u8) Error!ServerMsg { .check => .{ .check = try r.takeInt(u64, .little) }, .blobs => return .{ .blobs = payload }, .zstd => return .{ .zstd = payload }, + .blob => return .{ .blob = payload }, }; try end(&r); return msg; @@ -255,7 +261,7 @@ pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { }, .refused => |words| try putSlice16(&w, words), .pong => |v| try w.writeInt(u64, v, .little), - .dump, .unit, .screen, .blobs, .zstd => |bytes| try w.writeAll(bytes), + .dump, .unit, .screen, .blobs, .zstd, .blob => |bytes| try w.writeAll(bytes), .check => |v| try w.writeInt(u64, v, .little), } try finishMessage(&w, at); diff --git a/test/daemon.py b/test/daemon.py index 5c620ba4..c497bb19 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -1096,6 +1096,88 @@ def far(binary): shutil.rmtree(root, ignore_errors=True) +def by_hash(binary): + """A file over the wire's 16 MiB bound opened while clients are + attached (its read was one unit, dropped: the client joined again, a + Debug session panicked): it goes by its hash, a client on this machine + reading it itself and a far one sent it once, kept on disk; a far client + that joins after is sent nothing of it.""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rh-', dir=scratch)) + cache = root / 'cache' + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} + env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), + XDG_CACHE_HOME=str(cache), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + notes = root / 'notes.txt' + notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300))) + big = root / 'big.txt' + with open(big, 'wb') as f: + for i in range(17 << 14): + f.write(b'%08d %s\n' % (i, os.urandom(27).hex().encode()[:54])) + started, terms = [], [] + + def client(name, far): + t = Term(24, 90) + terms.append(t) + c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:files'], + dict(env, PARDES_REPLICA_CHECK=str(root / f'{name}.check'), PARDES_REPLICA_STATS=str(root / f'{name}.stats'), + **({'PARDES_REPLICA_FAR': '1'} if far else {}))) + started.append(c.pid) + wait_for(f'client {name}\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=30) + time.sleep(.3) + return t, c + + def read(pid): + return next(int(line.split()[1]) for line in open(f'/proc/{pid}/io') if line.startswith('rchar')) + try: + sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + started.append(sess.pid) + wait_for('the replica socket', (root / 'pardes-replica.sock').exists) + wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists) + nine = Client(root / 'pardes-9p-files.sock') + pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') + (ta, a), (tf, f) = client('a', False), client('f', True) + seen = {n: len(checks(root / f'{n}.check')) for n in 'af'} + was = {c.pid: read(c.pid) for c in (a, f)} + nine.write(f'/pane/{pane}/exec', f'Look {big}\n'.encode()) + for n in 'af': + wait_for(f'client {n} agrees with the big file open', lambda: agreed(root / f'{n}.check', seen[n] + 1), timeout=60) + assert sess.poll() is None and a.poll() is None and f.poll() is None + assert not any(b'joined again' in t.text() for t in (ta, tf)) + size = big.stat().st_size + # This machine's read it from disk; the far one was sent it, zstd. + got = {c.pid: read(c.pid) - was[c.pid] for c in (a, f)} + assert size <= got[a.pid] < size + (512 << 10), (size, got) + assert got[f.pid] < size, (size, got) + tg, g = client('g', True) + os.write(tg.master, b' sD') + wait_for('client G let go', lambda: g.poll() is not None, timeout=20) + g_join = joins(root / 'g.stats')[0] + assert g_join['from_disk'] == g_join['blobs'] and g_join['sent_kb'] == 0, g_join + print(f'daemon: a {size >> 20} MiB file opened under two clients went by its hash: the one on this machine read ' + f'it itself, the far one was sent {got[f.pid] >> 10} KB and kept it; a far client that joined after was ' + f'sent none of its {g_join["blobs"]} blobs') + for t, c in ((ta, a), (tf, f)): + os.write(t.master, b' sD') + wait_for('a client let go', lambda: c.poll() is not None, timeout=20) + exit_session(nine, pane) + sess.wait(timeout=10) + nine.socket.close() + finally: + for t in terms: + t.close() + for pid in started + processes(root): + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + shutil.rmtree(root, ignore_errors=True) + + def far_joins(sock, session, binary, n): """`n` far joins of one session in a row, each read whole (its blobs asked for by none, its zstd frames unpacked) and answering a ping, then @@ -1191,6 +1273,7 @@ def main(binary, cycles): replicas(root, binary, session, daemon) clients(binary) far(binary) + by_hash(binary) manage(binary) shell = terminals(client)[0] shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1]) @@ -1863,6 +1946,7 @@ if __name__ == '__main__': manage(sys.argv[2]) elif sys.argv[1:2] == ['--far']: far(sys.argv[2]) + by_hash(sys.argv[2]) elif sys.argv[1:2] == ['--window-clients']: window_clients(sys.argv[2], sys.argv[3]) pdf_window(sys.argv[2], sys.argv[3]) |
