summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--abi/wire.zig20
-rw-r--r--core/Core.zig19
-rw-r--r--core/Names.zig20
-rw-r--r--core/Places.zig21
-rw-r--r--core/Turn.zig10
-rw-r--r--core/dump.zig7
-rw-r--r--core/replica.zig44
-rw-r--r--core/tape.zig128
-rw-r--r--dev/gui/gui.zig21
-rw-r--r--dev/tui/tui.zig10
-rw-r--r--docs/next-daemon.md7
-rw-r--r--runtime/client.zig54
-rw-r--r--runtime/macos.zig1
-rw-r--r--runtime/main.zig99
-rw-r--r--runtime/session.zig7
-rw-r--r--runtime/upgrade.zig12
-rw-r--r--test/daemon.py368
-rw-r--r--test/panes.zig4
-rw-r--r--test/perf.zig138
-rw-r--r--test/replicas.zig2
-rw-r--r--test/session.zig15
21 files changed, 840 insertions, 167 deletions
diff --git a/abi/wire.zig b/abi/wire.zig
index 8713ba98..6c86685d 100644
--- a/abi/wire.zig
+++ b/abi/wire.zig
@@ -10,6 +10,8 @@ const pardes = @import("core");
const config = @import("pardes_options");
const build_info = @import("build_info");
+/// 24: a bye's byte says the client's window was closed (2), which ends a
+/// pair's session at its last client;
/// 23: a pane of a kind's frame names its rasters by key, their pixels
/// crossing before it as strips of 4 MiB at most over the rows it shows
/// (screen kind 5), and a replica lacking one asks for its pane again
@@ -36,7 +38,7 @@ const build_info = @import("build_info");
/// part B); 14: the hello names a session and
/// carries the semantics hash, and a ping is answered (phase 5's
/// groundwork); 13: the frames went (phase 3).
-pub const version: u16 = 23;
+pub const version: u16 = 24;
/// The terminal's build and the window's step alike (`semantics`).
const family = switch (config.platform) {
@@ -296,8 +298,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.
- bye: struct { again: bool = false },
+ /// 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).
+ bye: struct { again: bool = false, close: bool = false },
/// A round trip's probe, answered `pong` with the same value.
ping: u64,
screen_ack: []const u8,
@@ -514,7 +517,8 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 {
try putSlice16(&w, h.session);
try w.writeByte(h.view orelse 0xff);
},
- .bye => |b| try w.writeByte(@intFromBool(b.again)),
+ // 0 it leaves, 1 it joins again, 2 its window was closed.
+ .bye => |b| try w.writeByte(if (b.close) 2 else @intFromBool(b.again)),
.ping => |v| try w.writeInt(u64, v, .little),
.screen_ack, .want => |bytes| try w.writeAll(bytes),
.check => {},
@@ -584,7 +588,12 @@ pub fn decodeClient(tag: u8, payload: []const u8) Error!ClientMsg {
else => |k| k,
},
} },
- .bye => .{ .bye = .{ .again = try getBool(&r) } },
+ .bye => .{ .bye = switch (try r.takeByte()) {
+ 0 => .{},
+ 1 => .{ .again = true },
+ 2 => .{ .close = true },
+ else => return error.BadValue,
+ } },
.ping => .{ .ping = try r.takeInt(u64, .little) },
.screen_ack => return .{ .screen_ack = payload },
.check => .check,
@@ -699,6 +708,7 @@ test "detached wire: every Event variant round-trips" {
try testing.expectEqualStrings("work", got.hello.session);
}
try testing.expect((try roundClient(&buf, .{ .bye = .{ .again = true } })).bye.again);
+ try testing.expect((try roundClient(&buf, .{ .bye = .{ .close = true } })).bye.close);
try testing.expectEqual(@as(?u8, 2), (try roundClient(&buf, .{ .hello = .{ .session = "work", .view = 2 } })).hello.view);
try testing.expectEqual(@as(u64, 0xfeed_beef_0000_0001), (try roundClient(&buf, .{ .ping = 0xfeed_beef_0000_0001 })).ping);
{
diff --git a/core/Core.zig b/core/Core.zig
index 7ebcc020..e736d43b 100644
--- a/core/Core.zig
+++ b/core/Core.zig
@@ -528,9 +528,9 @@ pub const perform = @import("Effect.zig").perform;
/// second copy of this drifted once, leaving restored tags without an
/// allocator and every 9P mtime 0.
pub fn create(gpa: std.mem.Allocator, opts: Options) !*Pardes {
- // The global still set beside the field (P20): a core made while
- // a tape records (PARDES_RECORD, a replica's step) is its.
- const tape = opts.tape orelse pardes.tape.on orelse &pardes.tape.none;
+ // Its options' (a recording session's, an authority's, a replay's), or
+ // the one nobody records.
+ const tape = opts.tape orelse &pardes.tape.none;
const p = try gpa.create(Pardes);
p.* = .{
.gpa = gpa,
@@ -561,10 +561,9 @@ pub fn create(gpa: std.mem.Allocator, opts: Options) !*Pardes {
return p;
}
-/// A new session, its tape written from here when PARDES_RECORD asks.
+/// A new session, recorded from here on its options' tape.
pub fn init(gpa: std.mem.Allocator, opts: Options) !*Pardes {
// By hand, not `taped`: no core yet to enter on; the tape adopts the one made.
- pardes.tape.startFromEnv();
const taped = pardes.tape.enter(null, .{ .init = opts });
// The tape adopts the core made, none on a failure.
var made: ?*Pardes = null;
@@ -821,8 +820,8 @@ fn recentFound(p: *Pardes, hash: u64) ?recent_files.Entry {
pub fn deinit(p: *Pardes) void {
// By hand, not `taped`: what it records is no argument (`current`), and it leaves on no core.
- const taped = pardes.tape.enter(p, .{ .deinit = pardes.tape.current(p) });
- pardes.tape.forget(p);
+ const taped = pardes.tape.enter(p, .{ .deinit = p.tape.current(p) });
+ p.tape.forget(p);
defer pardes.tape.leave(null, taped);
if (std.c.getenv("PARDES_FRAMES")) |path| p.frames.dump(std.mem.span(path));
// Every file open now is closed with its dot, and the list kept.
@@ -2284,6 +2283,10 @@ pub const Options = struct {
/// first effects (runtime/session.zig); a client's session is on it,
/// its first join made there with no hello (replica.join).
pair: ?c_int = null,
+ /// A client exec'd at an Upgrade (runtime/client.zig `execAgain`,
+ /// PARDES_JOIN_VIEW): the view it had, which the session kept for it
+ /// (views.away), joined again for as a rejoin dials (replica.join).
+ join_view: ?u8 = null,
mounts: []const filesystem.Mount = &.{},
config_dir: ?[]const u8 = null,
/// Where what outlives the session is kept (Db.zig): the user's state
@@ -2299,7 +2302,7 @@ pub const Options = struct {
/// A client's: the kinds it caught breaking PA_PLAIN, its frontend's
/// list, which outlives each core it joins with. In no tape and no dump.
distrusted: ?*pardes.Addon.Distrusted = null,
- /// The core's tape (`Pardes.tape`); null: `tape.on`'s, or `tape.none`.
+ /// The core's tape (`Pardes.tape`); null: `tape.none`.
tape: ?*pardes.tape.Tape = null,
/// What the host's scan of the addon directories found (Addon.scan).
addons: []const pardes.Kind.Loaded = &.{},
diff --git a/core/Names.zig b/core/Names.zig
index fff2c84f..2fbbec37 100644
--- a/core/Names.zig
+++ b/core/Names.zig
@@ -2,7 +2,7 @@
//! directory (listed by the disk engine, Stream.zig), the recent files, the open panes,
//! a file's declarations. Each keystroke scores them again with a small
//! fzf-style scorer (subsequence, Smith-Waterman with affine gaps, bonuses
-//! at the starts of words and path segments), a frame's budget at a time,
+//! at the starts of words and path segments), a frame's count at a time,
//! the best kept first. Lifted from the pick prototype (Pick.zig), whose
//! scorer took ~1 ms for 20k paths in a release build. Embedded in a
//! Query; the rows it shows are the Query's to make.
@@ -56,8 +56,12 @@ pub const max_query = 64;
/// A candidate is scored over its first this many bytes.
const max_text = 512;
const max_cands = 200_000;
-/// A keystroke's scoring, and a frame's: what is left waits a frame.
-const score_budget_ns = 4 * std.time.ns_per_ms;
+/// A keystroke's scoring, and a frame's: at most this many of the
+/// scorer's cells (a key's bytes times the query's and one: what `match`
+/// can visit of a candidate); what is left waits a frame. A count, not the
+/// clock: a client's guess of a key scores as far as the session's step
+/// (P27, P30). About 4 ms in a release build (`pardes-perf --search`).
+const score_cells = 3_000_000;
pub fn deinit(n: *Names, gpa: std.mem.Allocator) void {
n.bytes.deinit(gpa);
@@ -136,12 +140,12 @@ pub fn typed(n: *Names, gpa: std.mem.Allocator, text: []const u8) void {
}
/// Scores the pending candidates, then `cands[scored..]`, into `hits`, and
-/// sorts them: at most `score_budget_ns` of it a call, the rest on the
-/// next frames while the best so far is shown.
+/// sorts them: at most `score_cells` of it a call, the rest on the next
+/// frames while the best so far is shown.
pub fn rescore(n: *Names, gpa: std.mem.Allocator) void {
const q = n.queryText();
const empty = std.mem.trim(u8, q, " ").len == 0;
- const started = pardes.FrameStats.nowNs();
+ var left: usize = score_cells;
const had = n.hits.items.len;
const was_scored = n.scored;
var count: usize = 0;
@@ -157,8 +161,8 @@ pub fn rescore(n: *Names, gpa: std.mem.Allocator) void {
const key = n.bytes.items[c.start + c.key ..][0..c.key_len];
const s = if (empty) 0 else match(q, key, n.lower.items[c.start + c.key ..][0..c.key_len], c.base, null, null);
if (s) |score| n.hits.append(gpa, .{ .cand = i, .score = score }) catch break;
- // The clock every 256 candidates: reading it is not free either.
- if (!empty and count % 256 == 255 and pardes.tape.over(started, score_budget_ns)) break;
+ left -|= @as(usize, @min(c.key_len, max_text)) * (q.len + 1);
+ if (!empty and left == 0) break;
}
// An empty query keeps the source's order (the walk's, recency): no
// row moves as the walk goes on, it only grows at the foot.
diff --git a/core/Places.zig b/core/Places.zig
index 9ffbff88..35b79805 100644
--- a/core/Places.zig
+++ b/core/Places.zig
@@ -46,13 +46,14 @@ pub const Provenance = enum { typed, search, list };
/// Places past this many are not kept. ponytail: 16 bytes a place, 16 MB
/// at the cap; a sparse count past it if a million is ever too few.
pub const max_hits = 1 << 20;
-/// What one frame spends finding places: about 4 ms on the clock, checked
-/// between pieces of the text; mvzr's steps (Regex.budget is about 300 ms
-/// of them, so this is about 5 ms), which bound one slow piece; and bytes
-/// read, the bound where there is no clock.
-pub const frame_ns: u64 = 4 * std.time.ns_per_ms;
+/// What one frame spends finding places: bytes of the text read (and the
+/// places an insert above the view moves, as many bytes), about 4 ms in a
+/// release build (`pardes-perf --search`); and mvzr's steps (Regex.budget
+/// is about 300 ms of them, so this is about 5 ms), which bound one slow
+/// piece. Counts, not the clock: a replica finds as many places a frame as
+/// its session (P27, P30).
pub const frame_steps: u64 = regexp.Regex.budget / 64;
-pub const frame_bytes: usize = 8 << 20;
+pub const frame_bytes: usize = 512 << 10;
/// The text is searched in pieces of about this much, each ending at a
/// line's end, so that a budget runs out between pieces, not inside one.
/// A folding set lowers its copy of the text a piece at a time too.
@@ -405,7 +406,6 @@ fn restart(set: *Places, p: *Pardes, f: *File.State) void {
/// been searched, make it current. Run after every step (with no budget:
/// the view only) and every tick (a frame's).
pub fn fill(set: *Places, p: *Pardes, pane: *Pane, bytes: usize, steps: u64) void {
- const started_ns = pardes.FrameStats.nowNs();
if (!set.started) return;
set.derive(p.gpa);
const f = if (pane.file) |*file| file else return set.clear(p.gpa);
@@ -490,17 +490,14 @@ pub fn fill(set: *Places, p: *Pardes, pane: *Pane, bytes: usize, steps: u64) voi
}
if (forward) set.hi = at else {
set.hits.insertSlice(gpa, set.nhead, head.items) catch return;
+ // With many places below, moving them is most of the work.
+ left -|= (set.hits.items.len - set.nhead - head.items.len) * @sizeOf(Hit);
if (set.current) |*c| c.* += head.items.len;
set.nhead += head.items.len;
set.head_to = at;
}
left -|= at - from;
if (short) break;
- // A frame's time spent (a whole search's for n and N, whose steps
- // are mvzr's whole budget).
- // The clock's verdict is the session's (core/tape.zig): a replica
- // finds as many places a frame as this did.
- if (started_ns != 0 and bytes != std.math.maxInt(usize) and pardes.tape.over(started_ns, frame_ns)) break;
}
if (set.hits.items.len != found_before) {
set.gen +%= 1;
diff --git a/core/Turn.zig b/core/Turn.zig
index 687e287f..249c6795 100644
--- a/core/Turn.zig
+++ b/core/Turn.zig
@@ -17,7 +17,6 @@
//! come from a shell performing a save between steps -- so a parked request
//! is never the syscall's own.
const std = @import("std");
-const tape = @import("tape.zig");
const Turn = @This();
@@ -46,6 +45,10 @@ restores: u64 = 0,
lsp_answers: u64 = 0,
/// All of the above, and `out` reaching zero.
settled: std.Io.Condition = .init,
+/// Every `yield`, ever: a replica's step makes none (each syscall of its
+/// core is a tape site), which its tape checks by this count across a
+/// speculation and a replayed input (core/tape.zig `stray`).
+yields: u64 = 0,
/// The editor's thread takes the turn for good; it has it until `stop`.
pub fn start(t: *Turn, io: std.Io) void {
@@ -79,10 +82,7 @@ pub fn wake(t: *Turn) void {
/// a step. Nests: a directory listing that resolves each entry yields
/// inside a yield, and only the outermost one lets go.
pub fn yield(t: *Turn) void {
- // A replica makes no syscall: each is a site of the tape's. One that
- // is none stops a speculation and diverges a replay (it joins
- // again), never the process (a window client's `Term fish`, H17).
- if (tape.replaying()) tape.stray();
+ t.yields +%= 1;
const io = t.io orelse return;
yield_depth += 1;
if (yield_depth != 1) return;
diff --git a/core/dump.zig b/core/dump.zig
index c348dec2..7ce54bce 100644
--- a/core/dump.zig
+++ b/core/dump.zig
@@ -531,17 +531,20 @@ fn restoreInner(p: *Pardes, bytes: []const u8, from: []const u8) !*Pardes {
var opts = p.opts;
opts.cols = p.view().screen_w;
opts.rows = p.view().screen_h;
+ // Loaded on the session's tape (one with clients has it from no
+ // options), which the replacement's options do not keep.
+ opts.tape = p.tape;
const replacement = try loadAndRevive(p.gpa, opts, bytes, p, null);
+ replacement.opts.tape = p.opts.tape;
replacement.pointRestoreAt(from);
// The tape follows the replacement from here (it is the session).
- pardes.tape.adopt(replacement);
+ p.tape.adopt(replacement);
pardes.ctlfs.events.notePath(replacement, "restore", from);
return replacement;
}
pub fn initFromDump(gpa: std.mem.Allocator, opts: Options, bytes: []const u8) !*Pardes {
// By hand, not `taped`: no core yet to enter on, as `Pardes.init`.
- pardes.tape.startFromEnv();
const taped = pardes.tape.enter(null, .{ .init_from_dump = .{ .opts = opts, .bytes = bytes } });
// The tape adopts the core made, none on a failure.
var made: ?*Pardes = null;
diff --git a/core/replica.zig b/core/replica.zig
index 781bd211..49787c76 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -182,6 +182,7 @@ pub const Authority = struct {
a.t.whole_digest = screens and std.c.getenv("PARDES_REPLICA_TRACE") == null;
// A digest at a unit's end, as the session's (Peers.unit).
a.t.no_digest = true;
+ opts.tape = &a.t;
const was = Stepping.begin(&a.t, null);
defer was.end();
a.core = try Pardes.init(gpa, opts);
@@ -1672,6 +1673,8 @@ pub const Peer = struct {
/// 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.
again: bool = false,
+ /// ...or that its window was closed (Peers.closed).
+ close: bool = false,
/// Its number in the session's `Screens`.
sid: u16 = 0,
/// Inputs read (each one's seq, as the client numbered them).
@@ -1931,7 +1934,9 @@ pub const Peer = struct {
switch (t) {
.hello => return false,
.bye => {
- peer.again = (wire.decodeClient(tag, payload) catch return false).bye.again;
+ const b = (wire.decodeClient(tag, payload) catch return false).bye;
+ peer.again = b.again;
+ peer.close = b.close;
return false;
},
.ping => {
@@ -2054,6 +2059,10 @@ pub const Peers = struct {
/// No frontend of its own (the host says): with no client either, the
/// session is unattended.
detached: bool = false,
+ /// Its last client left by closing its window, and no Detach was typed
+ /// in any (`kept`): a pair's session ends there (runtime/session.zig).
+ closed: bool = false,
+ kept: bool = false,
/// The worst a join cost the session's step, and the last one's dump.
join_ns: u64 = 0,
each_join: std.ArrayListUnmanaged(u64) = .empty,
@@ -2353,6 +2362,7 @@ pub const Peers = struct {
core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view));
ps.closeViewOf(core, peer, peer.again);
if (ps.count() == 0) core.unattended = ps.detached;
+ if (ps.count() == 0 and peer.close and !ps.kept) ps.closed = true;
ps.seq += 1;
ps.unit(0, ps.seq);
ps.letGo(peer);
@@ -2457,6 +2467,7 @@ pub const Peers = struct {
/// (`left`), its last word; the client goes, and its reader says so.
pub fn detach(ps: *Peers, k: u8) bool {
for (ps.list) |slot| if (slot) |peer| if (peer.view == k) {
+ ps.kept = true;
var out: [wire.max_name + 8]u8 = undefined;
peer.last(wire.encodeServer(&out, .{ .left = ps.name[0..@min(ps.name.len, wire.max_name)] }) catch unreachable);
return true;
@@ -2927,10 +2938,11 @@ pub fn askCheck(fd: c_int) bool {
return writeAll(fd, wire.encodeClient(&out, .check) catch unreachable);
}
-/// The client's last word: `again`, it joins again for its view at once.
-pub fn bye(fd: c_int, again: bool) void {
+/// The client's last word: `again`, it joins again for its view at once;
+/// `close`, its window was closed.
+pub fn bye(fd: c_int, how: @FieldType(wire.ClientMsg, "bye")) void {
var out: [16]u8 = undefined;
- if (wire.encodeClient(&out, .{ .bye = .{ .again = again } })) |b| _ = writeAll(fd, b) else |_| {}
+ if (wire.encodeClient(&out, .{ .bye = how })) |b| _ = writeAll(fd, b) else |_| {}
}
/// What the session streams a client after its dump, as its frontend's loop
@@ -2984,6 +2996,13 @@ pub fn ended(why: []const u8) bool {
/// The words a client goes with when its session runs another build now.
const upgrade_words = "session upgraded to a newer pardes: upgrade this client too";
+/// A join's failure that is its session's running another build now: a
+/// client whose own start path holds a newer one execs that instead
+/// (runtime/client.zig).
+pub fn otherBuild(why: []const u8) bool {
+ return std.mem.endsWith(u8, std.mem.sliceTo(why, 0), upgrade_words);
+}
+
/// A replica client's join, the terminal's and the window's alike (their
/// `runClient`): the session at `path` dialled (or, first, the one on its
/// pair, `o.pair`), its build checked to be this
@@ -3008,7 +3027,10 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
};
if (have) |h| h.left();
prev.deinit();
- } else j.* = sameBuild(gpa, (if (o.pair) |fd| joinOn(gpa, fd, null, why, have, null) else dial(gpa, path, session, why, have, null)) orelse return null, why) orelse return null;
+ } else j.* = (if (o.join_view) |v|
+ redial(gpa, path, session, why, have, true, v)
+ else
+ sameBuild(gpa, (if (o.pair) |fd| joinOn(gpa, fd, null, why, have, null) else dial(gpa, path, session, why, have, null)) orelse return null, why)) orelse return null;
defer {
if (have) |h| h.store(gpa, j) else gpa.free(j.dump);
j.dump = &.{};
@@ -3043,7 +3065,7 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
/// an upgrade under way may not have said yet.
fn sameBuild(gpa: Allocator, j: Joined, why: []u8) ?Joined {
if (j.semantics == wire.semantics) return j;
- bye(j.fd, false);
+ bye(j.fd, .{});
_ = libc.close(j.fd);
var jj = j;
jj.rest.deinit(gpa);
@@ -3064,7 +3086,10 @@ fn redial(gpa: Allocator, path: []const u8, session: []const u8, why: *[600]u8,
while (true) : (tries += 1) {
why.* = @splat(0);
if (dial(gpa, path, session, why, have, view)) |j| return sameBuild(gpa, j, why);
- if (std.mem.indexOf(u8, std.mem.sliceTo(why, 0), "runs another build") != null) {
+ // Another build, or another protocol (the daemon moved with its
+ // session): no dial again will do.
+ const words = std.mem.sliceTo(why, 0);
+ if (std.mem.indexOf(u8, words, "runs another build") != null or std.mem.indexOf(u8, words, "run the same pardes at both ends") != null) {
_ = std.fmt.bufPrint(why, "{s}\x00", .{upgrade_words}) catch {};
return null;
}
@@ -3081,6 +3106,8 @@ pub const Link = struct {
r: *Replica,
fd: c_int,
quit: bool = false,
+ /// ...because its window was closed: said in its bye.
+ close: bool = false,
/// The session hung up.
gone: bool = false,
/// Something to draw: an input applied, a unit taken.
@@ -6772,9 +6799,6 @@ test "a client joined from a dump lands a click on a rail's tick as the session
r.confirm(try a.take(m));
r.settle();
}
- // (The key may be mispredicted: a step's places are a frame's time's
- // worth, `tape.over`, the session's verdict, and its drawn caches let
- // it find more in that time than the client's speculation did.)
try agrees(a, r);
try std.testing.expectEqual(a.core.panes[owner].?.places.current, r.core().panes[owner].?.places.current);
}
diff --git a/core/tape.zig b/core/tape.zig
index 7f28621e..09985d15 100644
--- a/core/tape.zig
+++ b/core/tape.zig
@@ -114,7 +114,6 @@ pub const Site = enum(u16) {
fonts,
// Read in place (`value`).
clock,
- budget,
wake,
env,
interpreter,
@@ -281,6 +280,8 @@ pub const Tape = struct {
/// checks.
speculating: bool = false,
poisoned: bool = false,
+ /// The turn's yields when the speculation began (`stray`).
+ yields: u64 = 0,
/// What stopped it: a host function's or a site's name, or a poison's
/// reason (PARDES_REPLICA_STATS counts them).
poisoned_by: []const u8 = "",
@@ -410,7 +411,7 @@ pub const Tape = struct {
if (!t.host_side) return .{};
t.host_side = false;
t.depth += 1;
- if (t.replay) return .{ .outer = true };
+ if (t.replay) return .{ .tape = t };
if (p) |core| {
if (t.core == null) t.core = core;
t.noteWrites();
@@ -422,7 +423,7 @@ pub const Tape = struct {
bare.update.args[0].output.bytes = &.{};
t.record(.input, Input, &bare);
} else t.record(.input, Input, input);
- return .{ .outer = true };
+ return .{ .tape = t };
}
fn leaveInput(t: *Tape, p: ?*Pardes) void {
@@ -665,6 +666,9 @@ pub const Tape = struct {
defer t.applying = outer;
t.host_side = true;
defer t.host_side = true;
+ // Not at the end: the dump checked there reads through no tape.
+ const yields = pardes.turn.yields;
+ defer if (input != .deinit) t.stray(yields);
switch (input) {
.init, .init_from_dump => {
var opts = switch (input) {
@@ -768,12 +772,6 @@ pub const Tape = struct {
return t.value(.authority, f, args);
}
- /// A budget of `budget_ns` from `since_ns` on the monotonic clock is spent:
- /// what the clock said is taped, so a replica stops its work where this did.
- pub fn over(t: *Tape, since_ns: u64, budget_ns: u64) bool {
- return t.value(.budget, overNow, .{ since_ns, budget_ns });
- }
-
/// A body whose first parameter is an `std.Io` its caller does not pass
/// is handed the tape's (`args` are the rest): the only way core/ comes
/// to hold one.
@@ -865,11 +863,13 @@ pub const Tape = struct {
return t.replay or t.speculating;
}
- /// A syscall of the core's that is no site, made by a replica: what it
- /// returns is the authority's to say. A speculation waits for it, and a
- /// replay has diverged.
- pub fn stray(t: *Tape) void {
- if (t.through) return;
+ /// A syscall of the core's that is no site, made by a replica since the
+ /// turn's count of yields was `since`: what it returned is the
+ /// authority's to say. A speculation waits for it, and a replay has
+ /// diverged (it joins again), never the process (a window client's
+ /// `Term fish`, H17).
+ fn stray(t: *Tape, since: u64) void {
+ if (pardes.turn.yields == since) return;
if (t.speculating) t.poisoned = true else t.diverge("a syscall that is no tape site, made replaying", .{});
}
@@ -1023,44 +1023,45 @@ fn partsDiffer(got: []const u64, want: []const u64, a: std.mem.Allocator) []cons
return said.items;
}
-/// A call into the core: the host's, and recorded, or the core's own.
-pub const Entered = struct { outer: bool = false };
+/// A call into the core: the host's, and recorded, or the core's own. The
+/// tape it entered (null: the core's own, or nobody records), so `leave`
+/// needs neither the global nor a core `init` did not make or `deinit` freed.
+pub const Entered = struct { tape: ?*Tape = null };
pub inline fn enter(p: ?*Pardes, input: Input) Entered {
- // A core's tape is the one `on` says while both are (P20: the global
- // goes at the last step): every entry a safe build makes checks it.
- // With none on, a client's core is entered between its steps (its own
- // frame drawn, Replica.draw), its tape idle.
- //
- // The idle tape, the rule for the step that has this read the field
- // (P20's last): a client's tape between its steps is neither replaying
- // nor speculating, and its core is entered all the same (its frame);
- // `enter` must not record into an idle replica's tape. Only a tape
- // stepping its core records. The test "a client's frame drawn between
- // its steps records nothing into its idle tape" (this file's end)
- // fails when it does.
- if (std.debug.runtime_safety) if (p) |core| if (if (on) |t| core.tape != t else core.tape.stepping())
+ // While the global is (P20: the terminal's questions read it), a core
+ // stepped is the one it says: every entry a safe build makes checks it.
+ if (std.debug.runtime_safety) if (p) |core| if (on) |was| if (core.tape != was)
@panic("tape: a core's field is not the tape being stepped (tape.on)");
- const t = on orelse return .{};
+ const t = tapeOf(p, &input);
+ // A client's tape between its steps records nothing (its frame drawn,
+ // its core freed: the test "a client's frame drawn between its steps
+ // records nothing into its idle tape"); an authority's records every
+ // entry, in a Stepping scope or not, as a real session's.
+ if (!records(t)) return .{};
return t.enterInput(p, &input);
}
-pub inline fn leave(p: ?*Pardes, e: Entered) void {
- if (e.outer) on.?.leaveInput(p);
-}
-
-// The entry points on `on`, the methods' (`Tape.site` and the rest).
-
-pub fn adopt(p: *Pardes) void {
- (on orelse &none).adopt(p);
+/// The tape an entry steps: its core's; for a session not made yet, the one
+/// its options name (`Pardes.create`'s).
+fn tapeOf(p: ?*Pardes, input: *const Input) *Tape {
+ if (p) |core| return core.tape;
+ const opts = switch (input.*) {
+ .init => |o| o,
+ .init_from_dump => |d| d.opts,
+ else => return &none,
+ };
+ return opts.tape orelse &none;
}
-pub fn current(p: *const Pardes) bool {
- return (on orelse &none).current(p);
+/// Whether an entry on `t` is recorded: not on the tape nobody records, nor
+/// on a replica's between its steps (a client's frame drawn, its core freed).
+fn records(t: *const Tape) bool {
+ return !(t.through or (t.replica and !t.replaying()));
}
-pub fn forget(p: *Pardes) void {
- (on orelse &none).forget(p);
+pub inline fn leave(p: ?*Pardes, e: Entered) void {
+ if (e.tape) |t| t.leaveInput(p);
}
/// An entry written once (P22): its public name made from the private
@@ -1324,14 +1325,6 @@ pub fn resync(t: *Tape) void {
t.real = .{};
}
-pub fn over(since_ns: u64, budget_ns: u64) bool {
- return (on orelse &none).over(since_ns, budget_ns);
-}
-
-fn overNow(since_ns: u64, budget_ns: u64) bool {
- return pardes.FrameStats.nowNs() -| since_ns > budget_ns;
-}
-
/// One host call, `f(args)`, made out of the turn (pardes.turn).
pub fn out(comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? {
pardes.turn.yield();
@@ -1343,10 +1336,6 @@ pub fn replaying() bool {
return (on orelse &none).replaying();
}
-pub fn stray() void {
- (on orelse &none).stray();
-}
-
/// A replica speculating (core/replica.zig): state only the authority
/// changes (a terminal's emulator) is left alone, and the input waits.
pub fn speculating() bool {
@@ -1477,12 +1466,14 @@ pub fn beginSpeculation(t: *Tape) void {
t.poisoned_by = "";
t.touched = false;
t.no_digest = true;
+ t.yields = pardes.turn.yields;
t.buf.clearRetainingCapacity();
t.seeFields();
}
/// Whether it stayed clean (no host call, no syscall, no authority state).
pub fn endSpeculation(t: *Tape) bool {
+ t.stray(t.yields);
t.speculating = false;
t.no_digest = false;
return !t.poisoned;
@@ -1588,19 +1579,21 @@ pub fn digestOf(p: *const Pardes) u64 {
return walk.digest(Pardes, p);
}
-/// PARDES_RECORD set: the tape is written from the session's first call.
-pub fn startFromEnv() void {
- if (on != null) return;
- const prefix = std.mem.span(libc.getenv("PARDES_RECORD") orelse return);
- if (prefix.len == 0) return;
+/// PARDES_RECORD set: the tape a session is written to from its first
+/// call, which whoever starts it hands in `Options.tape` (runtime/session.zig,
+/// the Mac's start). `on` too, while the terminal's questions read it (P20).
+pub fn fromEnv() ?*Tape {
+ const prefix = std.mem.span(libc.getenv("PARDES_RECORD") orelse return null);
+ if (prefix.len == 0) return null;
const gpa = std.heap.c_allocator;
var path_buf: [4096]u8 = undefined;
- const path = std.fmt.bufPrintSentinel(&path_buf, "{s}{d}.tape", .{ prefix, libc.getpid() }, 0) catch return;
+ const path = std.fmt.bufPrintSentinel(&path_buf, "{s}{d}.tape", .{ prefix, libc.getpid() }, 0) catch return null;
const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644));
- if (fd < 0) return;
- const t = gpa.create(Tape) catch return;
+ if (fd < 0) return null;
+ const t = gpa.create(Tape) catch return null;
t.* = .{ .gpa = gpa, .replay = false, .fd = fd, .scratch = .init(gpa), .arena = .init(gpa), .every = libc.getenv("PARDES_RECORD_EVERY") != null };
on = t;
+ return t;
}
/// `PARDES_REPLAY=<tape>`: the tape replayed into three replicas, each
@@ -1657,16 +1650,19 @@ test "a syscall that is no site, made replaying, diverges the replay and poisons
defer t.scratch.deinit();
defer t.arena.deinit();
defer if (t.diverged) |why| gpa.free(why);
- on = &t;
- defer on = null;
+ const since = pardes.turn.yields;
+ t.stray(since);
+ try std.testing.expect(t.diverged == null);
pardes.turn.yield();
pardes.turn.back();
+ t.stray(since);
try std.testing.expect(t.diverged != null);
t.replay = false;
t.speculating = true;
+ t.yields = pardes.turn.yields;
pardes.turn.yield();
pardes.turn.back();
- try std.testing.expect(t.poisoned);
+ try std.testing.expect(!endSpeculation(&t));
}
test "a replay that finds no answer where its core reads one diverges, and the read goes on harmless" {
@@ -1696,7 +1692,7 @@ test "a replay that finds no answer where its core reads one diverges, and the r
/// The functions of core/ that set `on` and leave a core's field be, each
/// with why the field is that tape already.
const sets_on_alone = [_]struct { []const u8, []const u8, []const u8 }{
- .{ "tape.zig", "startFromEnv", "no core yet: the one made next takes `on` (Pardes.create)" },
+ .{ "tape.zig", "fromEnv", "no core yet: its starter hands the tape in Options.tape" },
.{ "tape.zig", "replayBytes", "its replay's core is made with this tape in its options (apply)" },
.{ "replica.zig", "begin", "Stepping: the core stepped holds this tape already (adoptCore), which `enter` checks in a safe build" },
.{ "replica.zig", "end", "Stepping: `on` put back as `begin` found it" },
diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig
index 201c23df..521f685f 100644
--- a/dev/gui/gui.zig
+++ b/dev/gui/gui.zig
@@ -1428,12 +1428,22 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
.done => {},
.gone => Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{to.session}),
.failed => Said.no(io, "{s}", .{start.said()}),
+ // A new process's window: the build at its start path, exec'd.
+ .upgrade => |view| Said.no(io, "{s}", .{client_loop.execAgain(&start, view)}),
.left => {
var said: [600]u8 = undefined;
std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes-gui: detached from '{s}', which is still running; come back with `pardes-gui attach {s}`\n", .{ to.session, to.session }) catch "pardes-gui: detached\n") catch {};
std.process.exit(0);
},
- .ended => |code| std.process.exit(code),
+ .ended => |code| {
+ // A pair's window is its session's parent: its status once it
+ // is gone, as the terminal's (tui.zig `runClient`).
+ if (opts_in.pair != null) {
+ var status: c_int = 0;
+ while (libc.waitpid(@intCast(start.joined.pid), &status, 0) < 0 and libc.errno(-1) == .INTR) {}
+ }
+ std.process.exit(code);
+ },
}
}
@@ -1485,6 +1495,7 @@ const StdinFeed = struct {
// so a driver exercises the real pointer path (pixel to cell,
// tag and body hits). SGR mouse carries only cells.
// finger;<kind>;<id>;<x>;<y>;<pressure>
+ // close: the window's close button
// One the read cut short, or what may yet begin one, waits for
// the next read.
const rest = f.buf[seq_start..len];
@@ -1548,6 +1559,12 @@ const StdinFeed = struct {
dispatch(gp, in, &sev);
c.SDL_SetModState(before);
}
+ } else if (std.mem.eql(u8, event[0..semi], "close")) {
+ if (g) |gp| {
+ var sev = std.mem.zeroes(c.SDL_Event);
+ sev.type = c.SDL_EVENT_WINDOW_CLOSE_REQUESTED;
+ dispatch(gp, in, &sev);
+ }
} else if (std.mem.eql(u8, event[0..semi], "finger")) {
if (parseFinger(fields)) |finger| if (g) |gp| {
var wpw: c_int = 0;
@@ -1728,6 +1745,8 @@ const Input = struct {
fn close(in: *Input) void {
if (in.client) |r| {
+ // Its bye says so: a pair's session ends at its last client's.
+ r.loop.link.close = true;
r.loop.link.quit = true;
in.quit = true;
return;
diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig
index e5e28f6e..72028b04 100644
--- a/dev/tui/tui.zig
+++ b/dev/tui/tui.zig
@@ -809,6 +809,12 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8,
screen.leave();
Said.no(io, "{s}", .{start.said()});
},
+ .upgrade => |view| {
+ // The blink: its screen left, the build at its start path
+ // exec'd, which enters it again.
+ screen.leave();
+ Said.no(io, "{s}", .{client_loop.execAgain(&start, view)});
+ },
}
}
@@ -1271,6 +1277,10 @@ const Shell = struct {
const core = s.core;
var why: [800]u8 = undefined;
const path = upgrade.exe() orelse return core.reportFailure(pane, "Upgrade: this process does not know the path it was started from");
+ // A client of a session no daemon keeps is a pair's first (no other
+ // can attach): let go, it has no socket to find the session again
+ // by, and the session would end with its last link.
+ if (s.peers.count() > 0 and daemon.link < 0) return core.reportFailure(pane, "Upgrade: no daemon keeps this session, so its client could not join it again; this session stays as it is");
// 9P is served while the new binary is asked (its clients' clunks
// and reads after the word are answered), and not after.
pardes.turn.rest();
diff --git a/docs/next-daemon.md b/docs/next-daemon.md
index 37ba0241..538729e6 100644
--- a/docs/next-daemon.md
+++ b/docs/next-daemon.md
@@ -710,9 +710,10 @@ Decisions taken at the forks, with the ponytail lens:
- **Clock.** `advance`'s wakes are the recording session's
(`tape.value(.wake, nextWake)`): a picture decoding or a fade asks a
frame, and a replica that draws none must still take the session's
- ticks. The budgets of Places, Names and Tables are taped verdicts
- (`tape.over`), as are a message's time of day (TZ included), File.mtime
- and the pump's clock read (made whether or not it waits). A message's
+ ticks. The budgets of Places and Names are counts (bytes read, the
+ scorer's cells), the same on every side, never the clock's verdict
+ (P27, P30). A message's time of day (TZ included), File.mtime
+ and the pump's clock read (made whether or not it waits) are taped. A message's
stamp and an unattended session's expiry of it read the clock through
the tape too, not the session clock: that is the last pump's, and
stamped by it a message written over 9P after an idle spell was as old
diff --git a/runtime/client.zig b/runtime/client.zig
index 1314d3fb..329bdab3 100644
--- a/runtime/client.zig
+++ b/runtime/client.zig
@@ -37,6 +37,7 @@ const std = @import("std");
const libc = std.c;
const pardes = @import("core");
const replica = pardes.replica;
+const upgrade = @import("upgrade.zig");
/// A wait with no wake of its own: until an input or a message.
pub const forever: u32 = std.math.maxInt(u32);
@@ -92,6 +93,8 @@ pub const Start = struct {
s.o.distrusted = &s.distrusted;
// Its frame timings, this process's (Pardes.frames).
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;
return true;
}
@@ -111,8 +114,44 @@ pub const Start = struct {
/// How a client's joins ended: it quit, the session let it go, it could
/// not join again (`Start.said`), it left the session running (a Detach in
-/// it), or the session ended, with its code.
-pub const Ended = union(enum) { done, gone, failed, left, ended: u8 };
+/// it), the session ended, with its code, or it runs another build now and
+/// one is installed at this client's start path since it started: the
+/// frontend lets its screen go and execs that, for this view (`execAgain`).
+pub const Ended = union(enum) { done, gone, failed, left, ended: u8, upgrade: u8 };
+
+/// An Upgrade's client again (`Ended.upgrade`), its frontend's screen let
+/// go: this process exec'd as the file at its start path, an attach of the
+/// same session through the same socket (a far one's forward, its ssh this
+/// process's child still), joining for `view` (PARDES_JOIN_VIEW; far,
+/// PARDES_REPLICA_FAR). The terminal's blink: no record crosses the exec.
+/// Returns only when the exec failed: why.
+pub fn execAgain(s: *Start, view: u8) []const u8 {
+ const path = upgrade.exe() orelse return "Upgrade: this client does not know the path it was started from";
+ var at_buf: [4200]u8 = undefined;
+ const at = std.fmt.bufPrintSentinel(&at_buf, "--attach={s}:{s}", .{ s.dial.path, s.dial.session }, 0) catch return "Upgrade: the session's socket's path is too long to attach again by";
+ const argv = [_:null]?[*:0]const u8{ path, at };
+ var view_buf: [32]u8 = undefined;
+ const joining = std.fmt.bufPrintSentinel(&view_buf, "PARDES_JOIN_VIEW={d}", .{view}, 0) catch unreachable; // a u8 fits 32
+ var n: usize = 0;
+ while (libc.environ[n] != null) n += 1;
+ const envp = s.gpa.allocSentinel(?[*:0]const u8, n + 2, null) catch return "Upgrade: no memory for this client's environment";
+ var k: usize = 0;
+ for (libc.environ[0..n]) |e| {
+ const entry = std.mem.span(e.?);
+ if (std.mem.startsWith(u8, entry, "PARDES_JOIN_VIEW=") or std.mem.startsWith(u8, entry, "PARDES_REPLICA_FAR=")) continue;
+ envp[k] = e;
+ k += 1;
+ }
+ envp[k] = joining.ptr;
+ k += 1;
+ if (s.have != null) {
+ envp[k] = "PARDES_REPLICA_FAR=1";
+ k += 1;
+ }
+ envp[k] = null;
+ _ = libc.execve(path, &argv, envp.ptr);
+ return "Upgrade: the build at this client's start path would not start";
+}
pub fn Loop(comptime Frontend: type) type {
return struct {
@@ -142,6 +181,8 @@ pub fn Loop(comptime Frontend: type) type {
/// the session let it go to upgrade; the frontend stays as it is.
pub fn run(l: *L, s: *Start) !Ended {
const link = &l.link;
+ // Its start path's file, for an Upgrade's question (`upgrade`).
+ upgrade.locate();
while (true) {
link.reset(s.r, &s.joined);
l.fe.start(l);
@@ -152,7 +193,7 @@ 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, s.r.diverged != null);
+ if (!link.gone) replica.bye(s.joined.fd, .{ .again = s.r.diverged != null, .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).
@@ -177,8 +218,11 @@ 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
- return if (replica.ended(&s.why)) .gone else .failed;
+ s.r = replica.join(s.gpa, &s.joined, s.dial.path, s.dial.session, s.o, s.have, &s.why, s.r) orelse {
+ if (replica.ended(&s.why)) return .gone;
+ if (replica.otherBuild(&s.why) and upgrade.replaced()) return .{ .upgrade = s.joined.view };
+ return .failed;
+ };
}
}
diff --git a/runtime/macos.zig b/runtime/macos.zig
index cfe93b13..4f9a9c33 100644
--- a/runtime/macos.zig
+++ b/runtime/macos.zig
@@ -348,6 +348,7 @@ fn initCore(runtime: ?*const Callbacks, cols_arg: u16, rows_arg: u16) !void {
pardes.syntax.start(allocs.tree_sitter);
errdefer pardes.syntax.stop();
+ opts.tape = pardes.tape.fromEnv();
const core = try pardes.Pardes.init(allocs.pardes, opts);
errdefer core.deinit();
// The workspace tag row is the macOS menu bar's business here (see
diff --git a/runtime/main.zig b/runtime/main.zig
index be2aa54b..a21eb83f 100644
--- a/runtime/main.zig
+++ b/runtime/main.zig
@@ -1157,6 +1157,13 @@ fn nativeMain(std_init: std.process.Init) !void {
upgrade.resumed = upgrade.Record.decode(args[1][upgrade.flag.len..]) catch badArgs(init.io, "--upgraded: a record this build cannot read", .{});
};
const resuming = upgrade.resumed != null;
+ // A window's pair's session (`pair`): the pardes beside a pardes-gui,
+ // exec'd in its child, its first client on the fd named, the window's
+ // arguments after it.
+ const paired: ?c_int = if (!resuming and args.len > 1 and std.mem.startsWith(u8, args[1], upgrade.paired_flag))
+ std.fmt.parseInt(c_int, args[1][upgrade.paired_flag.len..], 10) catch badArgs(init.io, "{s}: not a descriptor", .{args[1]})
+ else
+ null;
var session_only = true;
var new_session = false;
// `pardes new`: with --detach it returns once the session runs.
@@ -1166,21 +1173,21 @@ fn nativeMain(std_init: std.process.Init) !void {
var attach: ?[]const u8 = null;
var positional: ?[:0]const u8 = null;
var wait = false;
- var i: usize = if (resuming) 2 else 1;
+ var i: usize = if (resuming or paired != null) 2 else 1;
// A command's name first: new and attach go on to start or join a
// session, with the flags after them; the rest are done in `command`.
- if (!resuming and args.len > 1) if (std.meta.stringToEnum(Cmd, args[1])) |cmd| switch (cmd) {
+ if (!resuming and args.len > i) if (std.meta.stringToEnum(Cmd, args[i])) |cmd| switch (cmd) {
.new => {
new_session = true;
new_verb = true;
- i = 2;
+ i += 1;
},
.attach => {
- const named = args.len > 2 and args[2].len > 0 and args[2][0] != '-';
- attach = if (named) args[2] else "";
- i = if (named) 3 else 2;
+ const named = args.len > i + 1 and args[i + 1].len > 0 and args[i + 1][0] != '-';
+ attach = if (named) args[i + 1] else "";
+ i += if (named) 2 else 1;
},
- else => runCommand(init, cmd, args[2..]),
+ else => runCommand(init, cmd, args[i + 1 ..]),
};
while (i < args.len) : (i += 1) {
const a = args[i];
@@ -1521,11 +1528,8 @@ fn nativeMain(std_init: std.process.Init) !void {
// detached session, as `pardes --detach` (`ps` says tty), its
// windows clients. Without one there, it carries on as a window's.
if (comptime pardes.platform == .gui) if (!resuming) {
- var exe: [4096]u8 = undefined;
- const n = std.c.readlink("/proc/self/exe", &exe, exe.len);
- if (n > 0) if (std.Io.Dir.path.dirname(exe[0..@intCast(n)])) |bin| if (args.len < 64) {
- var path_buf: [4104]u8 = undefined;
- const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/pardes", .{bin}, 0) catch unreachable; // 4096 + 8 fits
+ var path_buf: [4104]u8 = undefined;
+ if (pardesBeside(&path_buf)) |path| if (args.len < 64) {
var argv: [64:null]?[*:0]const u8 = @splat(null);
argv[0] = path.ptr;
for (args[1..], 1..) |a, k| argv[k] = a.ptr;
@@ -1567,10 +1571,18 @@ fn nativeMain(std_init: std.process.Init) !void {
};
detached = if (pardes.platform == .gui) !rec.window else rec.nttys == 0;
daemon.resumeLink(rec.link, rec.stub, kind, opts.ninep_name, detached);
- } else if (pardes.platform == .tui and detach == null and std.c.getenv("PARDES_PAIR") != null) {
+ } else if (paired) |fd| {
+ // A window's pair's session: its first client on `fd`, the daemon
+ // its own to dial (and to start, when none runs).
+ opts.pair = fd;
+ term = .detached;
+ detached = true;
+ if (daemon.wanted()) _ = daemon.register(null, kind, opts.ninep_name, true);
+ } else if (detach == null and std.c.getenv("PARDES_PAIR") != null) {
// The last step's way, behind its variable until it is the default:
- // this terminal a client of a session forked off for it (`pair`).
- pair(init, &opts);
+ // this terminal or window a client of a session forked off for it
+ // (`pair`).
+ pair(init, &opts, args);
term = .detached;
} else if (daemon.wanted()) {
if (detach != null or pardes.platform == .gui) {
@@ -1708,23 +1720,48 @@ fn commOf(io: std.Io, pid: []const u8, buf: *[64]u8) []const u8 {
return std.mem.trimEnd(u8, std.Io.Dir.cwd().readFile(io, path, buf) catch return "", "\n");
}
-/// PARDES_PAIR: `pardes` in a terminal as a session and its first client
-/// over a socket pair (docs/next-run.md; the last step's design, 1.1). The
-/// daemon dialled first, as for a stub; then a fork: the parent the CLIENT
-/// (the shell's job, the terminal its own; signals reach what draws), its
-/// first join on its end of the pair; the child the SESSION (setsid, 0, 1
-/// and 2 on /dev/null, detached), its end of the pair its first client,
-/// taken before its first effects (runtime/session.zig). Returns in the
-/// session; the client exits. No fork to be had: returns, and this process
-/// is the session, with no terminal: said by the caller's run.
-fn pair(init: std.process.Init, opts: *pardes.Options) void {
- const conn: ?c_int = if (daemon.wanted()) daemon.connect(true) else null;
+/// The terminal's binary beside this one, as /proc names this one (Linux),
+/// in `buf`.
+fn pardesBeside(buf: *[4104]u8) ?[:0]const u8 {
+ var exe: [4096]u8 = undefined;
+ const n = std.c.readlink("/proc/self/exe", &exe, exe.len);
+ if (n <= 0) return null;
+ const bin = std.Io.Dir.path.dirname(exe[0..@intCast(n)]) orelse return null;
+ return std.fmt.bufPrintSentinel(buf, "{s}/pardes", .{bin}, 0) catch unreachable; // 4096 + 8 fits
+}
+
+/// PARDES_PAIR: `pardes` in a terminal, or `pardes-gui`, as a session and
+/// its first client over a socket pair (docs/next-run.md; the last step's
+/// design, 1.1 and 1.2). The daemon dialled first, as for a stub; then a
+/// fork: the parent the CLIENT (the shell's job, the terminal its own,
+/// signals reach what draws; or the window), its first join on its end of
+/// the pair; the child the SESSION (setsid, 0, 1 and 2 on /dev/null,
+/// detached), its end of the pair its first client, taken before its first
+/// effects (runtime/session.zig). A window's child execs the `pardes`
+/// beside it (`--paired=FD` first, its arguments after), which dials the
+/// daemon itself: a window's session loop is woken through SDL (gui.zig
+/// `sdlWake`), a terminal's needs none. Returns in a terminal's session;
+/// the client exits. No fork to be had: returns, and this process is the
+/// session, with no terminal: said by the caller's run. A window with no
+/// `pardes` beside it returns at once, its own session as before.
+fn pair(init: std.process.Init, opts: *pardes.Options, args: []const [:0]const u8) void {
+ var path_buf: [4104]u8 = undefined;
+ var fd_buf: [32]u8 = undefined;
+ var argv: [64:null]?[*:0]const u8 = @splat(null);
+ if (pardes.platform == .gui) {
+ const path = pardesBeside(&path_buf) orelse return;
+ if (args.len >= argv.len - 1 or std.c.access(path, std.c.X_OK) != 0) return;
+ argv[0] = path.ptr;
+ for (args[1..], 2..) |a, k| argv[k] = a.ptr;
+ }
+ const conn: ?c_int = if (pardes.platform == .tui and daemon.wanted()) daemon.connect(true) else null;
var fds: [2]c_int = undefined;
if (std.c.socketpair(std.c.AF.UNIX, std.c.SOCK.STREAM | std.c.SOCK.CLOEXEC, 0, &fds) != 0)
die(init.io, "no socket pair for a session and its terminal", .{});
+ if (pardes.platform == .gui) argv[1] = (std.fmt.bufPrintSentinel(&fd_buf, upgrade.paired_flag ++ "{d}", .{fds[0]}, 0) catch unreachable).ptr; // an fd fits 32
// The session laid out at the terminal's size: no reflow at the join.
var ws: std.posix.winsize = undefined;
- if (std.c.ioctl(0, std.posix.T.IOCGWINSZ, &ws) == 0 and ws.col > 0 and ws.row > 0) {
+ if (pardes.platform == .tui and std.c.ioctl(0, std.posix.T.IOCGWINSZ, &ws) == 0 and ws.col > 0 and ws.row > 0) {
opts.cols = ws.col;
opts.rows = ws.row;
}
@@ -1738,6 +1775,12 @@ fn pair(init: std.process.Init, opts: *pardes.Options) void {
_ = std.c.dup2(null_fd, @intCast(i));
};
if (null_fd > 2) _ = std.c.close(null_fd);
+ if (pardes.platform == .gui) {
+ // Its end of the pair across the exec.
+ _ = std.c.fcntl(fds[0], std.c.F.SETFD, @as(c_int, 0));
+ _ = execvp(argv[0].?, &argv);
+ std.c._exit(127);
+ }
opts.pair = fds[0];
// The daemon is the client's to start; the hello is this one's.
daemon.startPending(false);
@@ -1752,7 +1795,7 @@ fn pair(init: std.process.Init, opts: *pardes.Options) void {
var sock_buf: [ninep_io.sun_path_len:0]u8 = undefined;
var o = opts.*;
o.pair = fds[1];
- @import("dev").tui.runClient(init, o, daemon.replicaSocket(&sock_buf) orelse "", name, false) catch |err| die(init.io, "{t}", .{err});
+ clientOf(init, o, daemon.replicaSocket(&sock_buf) orelse "", name, false) catch |err| die(init.io, "{t}", .{err});
std.process.exit(0);
}
diff --git a/runtime/session.zig b/runtime/session.zig
index e4eb0300..9c8446e3 100644
--- a/runtime/session.zig
+++ b/runtime/session.zig
@@ -73,6 +73,7 @@ pub fn Loop(comptime Frontend: type) type {
o.tree_sitter_allocator = l.allocs.tree_sitter;
o.frame_allocator = l.allocs.frame;
fe.options(&o);
+ o.tape = pardes.tape.fromEnv();
l.core = if (upgrade.resumed) |*rec|
try upgrade.load(l.gpa, l.allocs.pardes, o, rec)
else if (o.load_path) |lp| blk: {
@@ -127,8 +128,10 @@ pub fn Loop(comptime Frontend: type) type {
// Its unit to each replica client, and theirs taken in.
l.peers.boundary(l.core);
// A pair's session with no daemon ends with its last link:
- // nothing could attach to it again.
- if (o.pair != null and daemon.link < 0 and l.peers.count() == 0) break;
+ // nothing could attach to it again; with one, when its last
+ // client closed its window (a close, not a loss), no Detach
+ // typed in any.
+ if (o.pair != null and l.peers.count() == 0 and (daemon.link < 0 or l.peers.closed)) break;
fe.sent();
upgrade.locate();
// Asked in the step (the word), done between steps: the
diff --git a/runtime/upgrade.zig b/runtime/upgrade.zig
index 2a8d6edf..37d4890b 100644
--- a/runtime/upgrade.zig
+++ b/runtime/upgrade.zig
@@ -22,6 +22,9 @@ const pardes = @import("core");
pub const supported = builtin.os.tag == .linux or builtin.os.tag == .freebsd;
pub const flag = "--upgraded=";
+/// A window's pair's session's first word (main.zig `pair`): its first
+/// client's fd, which an Upgrade does not name again (that client joined).
+pub const paired_flag = "--paired=";
/// What this build says it is (`pardes --version`'s first line).
pub const version_line = if (pardes.commit) |c| "pardes " ++ pardes.version ++ " (" ++ c ++ ")" else "pardes " ++ pardes.version;
@@ -46,6 +49,7 @@ var located = false;
/// deleted).
pub fn remember(args: []const [:0]const u8) void {
given = if (args.len > 1 and std.mem.startsWith(u8, args[1], flag)) args[2..] else if (args.len > 0) args[1..] else &.{};
+ if (given.len > 0 and std.mem.startsWith(u8, given[0], paired_flag)) given = given[1..];
if (resumed) |*rec| if (rec.exe.len > 0 and rec.exe.len < exe_buf.len) {
@memcpy(exe_buf[0..rec.exe.len], rec.exe);
exe_buf[rec.exe.len] = 0;
@@ -91,6 +95,14 @@ pub fn newer() bool {
return true;
}
+/// Another file at its start path than the one it started from: a build
+/// installed there since (`locate` first). A client's question at an
+/// Upgrade (client.zig).
+pub fn replaced() bool {
+ const was = started_inode orelse return false;
+ return (inodeOf(exe() orelse return false) orelse return false) != was;
+}
+
pub fn exe() ?[:0]const u8 {
return if (exe_len == 0) null else exe_buf[0..exe_len :0];
}
diff --git a/test/daemon.py b/test/daemon.py
index f8402af2..b28d16ea 100644
--- a/test/daemon.py
+++ b/test/daemon.py
@@ -241,7 +241,7 @@ class Replica:
"""A replica's connection (abi/wire.zig): length-prefixed
messages, a tag byte and a little-endian u32 length. It is a near
client: its first word after the hello says so."""
- WIRE = 23
+ WIRE = 24
def __init__(self, path, timeout=10):
self.path, self.timeout = path, timeout
@@ -653,12 +653,16 @@ def pair(binary):
c2 = lone.spawn([binary, '--9p=lone', str(notes)], dict(env, PARDES_DAEMON='off'))
nine2, session2 = session_of('lone')
wait_for('the lone pair drawn', lambda: b'line 3 of the notes' in lone.text(), timeout=30)
+ # An Upgrade refused, with why: its client could not find it again.
+ nine2.write('/ctl', b'Upgrade\n')
+ wait_for('the Upgrade refused', lambda: 'its client could not join it again' in screen_text(nine2), timeout=20)
+ assert alive(session2) and c2.poll() is None
nine2.socket.close()
os.kill(c2.pid, signal.SIGKILL)
c2.wait(timeout=10)
wait_for('the lone session ended with its last link', lambda: not alive(session2), timeout=20)
wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
- print(f'pair: with no daemon, client {c2.pid} killed outright, its session {session2} ended; nothing left behind')
+ print(f'pair: with no daemon, an Upgrade refused in words; client {c2.pid} killed outright, its session {session2} ended; nothing left behind')
finally:
for p in processes(root):
try:
@@ -1737,6 +1741,138 @@ def games(binary, libs, secs=10):
shutil.rmtree(root, ignore_errors=True)
+def far_find(binary):
+ """A far client types a query into a Find over 40,000 names: each key
+ scores the names again a slice at a time (core/Names.zig `rescore`),
+ the client's guess of the key first. The slice is a count, the same on
+ both sides, so no guess is wrong (a slice the clock ended was the
+ client's clock's verdict, which the session's own contradicted)."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rq-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_REPLICA_FAR='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ tree = root / 'tree'
+ for d in range(200):
+ (tree / f'module_{d}').mkdir(parents=True)
+ for f in range(200):
+ (tree / f'module_{d}' / f'replica_{f}.zig').touch()
+ notes = tree / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
+ started, terms = [], []
+ try:
+ sess = subprocess.Popen([binary, '--detach=find', 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-find.sock').exists)
+ nine = Client(root / 'pardes-9p-find.sock')
+ text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ t = Term(30, 100)
+ terms.append(t)
+ c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:find'],
+ dict(env, PARDES_REPLICA_CHECK=str(root / 'q.check'), PARDES_REPLICA_STATS=str(root / 'q.stats')))
+ started.append(c.pid)
+ wait_for('the client\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=30)
+ time.sleep(.3)
+ # SPC f f: the Find, typed into, its names walked on the session's worker.
+ os.write(t.master, b' ff')
+ time.sleep(3)
+ wait_for('the client agrees once the walk is done', lambda: agreed(root / 'q.check', 0), timeout=60)
+ query = b'module_19/replica_3'
+ for ch in query:
+ os.write(t.master, bytes([ch]))
+ time.sleep(.15)
+ seen = len(checks(root / 'q.check'))
+ wait_for('the client agrees once quiet', lambda: agreed(root / 'q.check', seen), timeout=60)
+ c.send_signal(signal.SIGHUP)
+ c.wait(timeout=20)
+ line = (root / 'q.stats').read_text().split()
+ got = {line[i]: line[i + 1] for i in range(0, len(line) - 1, 2)}
+ print(f'daemon: a far client typed {len(query)} keys into a Find over 40,000 names: of its {got["inputs"]} inputs '
+ f'{got["mispredicted"]} mispredicted, {got["stopped"]} stopped, {got["fast"]} applied at once')
+ assert got['mispredicted'] == '0', got
+ exit_session(nine, text)
+ sess.wait(timeout=60)
+ nine.socket.close()
+ finally:
+ for term in terms:
+ term.close()
+ for pid in started + processes(root):
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
+def restore_client(binary):
+ """A Restore while a client is attached: the client is let go (its link
+ ends), the replacement core is the session's (its tape adopts it, its
+ options keep none), and a client attached after agrees with it, its
+ keys reaching it."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rr-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
+ started, terms = [], []
+ try:
+ sess = subprocess.Popen([binary, '--detach=back', 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-back.sock').exists)
+ nine = Client(root / 'pardes-9p-back.sock')
+ text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ def client(name):
+ t = Term(30, 100)
+ terms.append(t)
+ c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:back'],
+ dict(env, PARDES_REPLICA_CHECK=str(root / f'{name}.check')))
+ 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
+ t, c = client('a')
+ nine.write(f'/pane/{text}/exec', b'Dump\n')
+ nine.write(f'/pane/{text}/exec', b'Restore\n')
+ wait_for('client a let go at the Restore', lambda: c.poll() is not None, timeout=30)
+ # The 9P link was the old core's.
+ nine.socket.close()
+ nine = reconnect(root / 'pardes-9p-back.sock')
+ text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ t, c = client('r')
+ os.write(t.master, b'Oafter the restore\x1b')
+ texts = lambda: b''.join(nine.read(f'/pane/{row.split()[0].decode()}/body') for row in nine.read('/index').splitlines()
+ if row.split()[1] == b'text')
+ wait_for('the client\'s keys in the restored session', lambda: b'after the restore' in texts(), timeout=30)
+ seen = len(checks(root / 'r.check'))
+ wait_for('the client agrees once quiet', lambda: agreed(root / 'r.check', seen), timeout=60)
+ assert c.poll() is None, 'the client ended'
+ print(f'daemon: a Restore with a client attached: it was let go, and one attached after agreed ({len(checks(root / "r.check"))} checks), its keys in the restored session')
+ exit_session(nine, text)
+ sess.wait(timeout=60)
+ nine.socket.close()
+ finally:
+ for term in terms:
+ term.close()
+ for pid in started + processes(root):
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
def 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
@@ -2120,6 +2256,90 @@ def gui(binary, cycles):
shutil.rmtree(root, ignore_errors=True)
+def gui_pair(gui_binary):
+ """PARDES_PAIR in a window (the last step's design, 1.2): `pardes-gui
+ FILE` is a window client and a session with no SDL, the `pardes` beside
+ it exec'd in a child (a window's session needs SDL for its wake, a
+ terminal's binary none): the session the window's child, in a session
+ of its own, listed detached with the window its client; the file in
+ the window's first frame, keys in. The window's close ends the session,
+ its last client (a CLOSE); the window killed leaves it running (a LOSS),
+ and with no daemon the session ends with its last link. Test mode:
+ hidden windows, offscreen."""
+ binary = gui_binary.replace('pardes-gui', 'pardes')
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rgp-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_DAEMON='on', TERM='xterm-256color', PARDES_PAIR='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(30)))
+ windows = []
+
+ def listed():
+ return subprocess.run([binary, 'ps'], env=env, capture_output=True, timeout=30).stdout.decode()
+
+ def started(name, e):
+ w = Window(root, name, [gui_binary, f'--9p={name}', str(notes)], e)
+ windows.append(w)
+ sock = root / f'pardes-9p-{name}.sock'
+ wait_for(f'session {name}\'s 9P socket', sock.exists, timeout=30)
+ nine = Client(sock)
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ assert session != w.pid and ppid(session) == w.pid and os.getsid(session) == session, (session, w.pid)
+ assert Path(cmdline(session)[0].decode()).name == 'pardes', ('the session is the pardes beside it', cmdline(session))
+ wait_for('the window\'s first frame', lambda: (root / name / 'latest.ppm').exists(), timeout=30)
+ pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ assert nine.read(f'/pane/{pane}/body').startswith(b'line 0 of the notes'), 'the file is the session\'s'
+ return w, nine, session, pane
+
+ try:
+ w, nine, session, pane = started('gp', env)
+ wait_for('the window listed its client', lambda: f'session gp {session} (tty, detached)' in listed()
+ and f'client {w.pid} ' in listed())
+ w.keys(b'Ofrom-the-window\x1b')
+ wait_for('its keys in the session\'s text', lambda: b'from-the-window' in nine.read(f'/pane/{pane}/body'))
+ # The close button (the test feed's word for it): its last client
+ # closed, the session ends.
+ w.p.stdin.write(b'\x1b]777;close\x07')
+ w.p.stdin.flush()
+ assert w.p.wait(timeout=30) == 0, (w.p.returncode, w.said()[-400:])
+ wait_for('the session ended with its window', lambda: not alive(session), timeout=20)
+ nine.socket.close()
+ print(f'pair window: client {w.pid} (the window) and session {session} (the pardes beside it, exec\'d in its child, '
+ 'setsid, listed detached with the window); drawn, typed; the window closed ended both')
+ w, nine, session, pane = started('gl', env)
+ wait_for('the client listed', lambda: f'client {w.pid} ' in listed())
+ os.kill(w.pid, signal.SIGKILL)
+ w.p.wait(timeout=10)
+ wait_for('the client unlisted', lambda: f'client {w.pid} ' not in listed())
+ assert alive(session) and f'session gl {session} (tty, detached)' in listed(), listed()
+ nine.socket.close()
+ assert subprocess.run([binary, 'kill', 'gl'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('the session ended', lambda: not alive(session), timeout=30)
+ print('pair window: the window killed: the session runs on, listed (a loss); killed by name')
+ w, nine, session, pane = started('gn', dict(env, PARDES_DAEMON='off'))
+ nine.socket.close()
+ os.kill(w.pid, signal.SIGKILL)
+ w.p.wait(timeout=10)
+ wait_for('the lone session ended with its last link', lambda: not alive(session), timeout=20)
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
+ print('pair window: with no daemon, the window killed, its session ended; nothing left behind')
+ finally:
+ for w in windows:
+ if w.p.poll() is None:
+ w.p.kill()
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
def screen_text(client):
shown = client.screen()
cells = ''.join(cell[0] for cell in shown['cells'])
@@ -2300,7 +2520,9 @@ def upgrades(old, new):
# its terminal and its stub's pipe let go once its stub is told
# (two fewer).
def level():
- gone = 2 if b'detached from' in term2.text() else 1
+ # (A client of a build that execs at an Upgrade comes back: its
+ # connection is the session's again.)
+ gone = 2 if b'detached from' in term2.text() else 0 if knows_exec(old) and stub2.poll() is None else 1
return fds_before[0] - 2 - gone + min(state_fds(session), 1) - state_before, fds_before[1]
try:
wait_for('the fds level', lambda: (fds(session), fds(daemon)) == level(), timeout=5)
@@ -2320,7 +2542,9 @@ def upgrades(old, new):
# build's own, let go (a session shows one frontend of its own now),
# its stub told.
wait_for('the second terminal redrawn or let go', lambda: b'\x1b[?1049h' in term2.text()[before[1]:] or
- (stub2.poll() is not None and (b'detached from' in term2.text() or b'upgrade this client too' in term2.text())))
+ (stub2.poll() is not None and (b'detached from' in term2.text() or b'upgrade this client too' in term2.text()
+ or b'run the same pardes at both ends' in term2.text())),
+ timeout=30)
wait_for('the word said', lambda: 'Upgrade: now pardes' in screen_text(client))
# The daemon lists the session under its new build.
said = Replica(root / 'pardes-replica.sock').hello('work', new_build)
@@ -2409,7 +2633,10 @@ def upgrades(old, new):
install(new, binary)
os.kill(session, signal.SIGKILL)
stub.wait(timeout=10)
- stub2.wait(timeout=10)
+ try:
+ stub2.wait(timeout=30)
+ except subprocess.TimeoutExpired:
+ raise AssertionError(('the second terminal\'s client on', cmdline(stub2.pid), term2.text()[-1200:]))
client.socket.close()
term.close()
term2.close()
@@ -2454,6 +2681,124 @@ def upgrades(old, new):
shutil.rmtree(root, ignore_errors=True)
+def knows_exec(binary):
+ """Whether a build's client execs the build at its start path at an
+ Upgrade, for the view it is handed (PARDES_JOIN_VIEW)."""
+ return b'PARDES_JOIN_VIEW' in Path(binary).read_bytes()
+
+
+def upgrade_clients(old, new):
+ """Upgrade with near clients (the last step's design, 1.4): a session
+ (`new --detach`) with a terminal client and a window client attached,
+ each in its own view with a pane of its own there, onto another build installed at the path all three were
+ started from. A client of a build that execs (its start path holding
+ another file than the one it runs, the session another build than its
+ own) comes back on the build at its start path, the same process, for
+ its view: the terminal's leaves its screen and enters it again (the
+ blink), the window is a new one; in ITS view when that build joins for
+ a view it is handed (PARDES_JOIN_VIEW), else in a view of its own. One
+ of a build before it is let go and told to upgrade too. The session's
+ shell alive throughout; nothing left behind."""
+ old_gui, new_gui = old.with_name('pardes-gui'), new.with_name('pardes-gui')
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='ruc-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ 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')
+ (root / 'bin').mkdir()
+ binary, gui_binary = root / 'bin' / 'pardes', root / 'bin' / 'pardes-gui'
+ install(old, binary)
+ install(old_gui, gui_binary)
+ terms = []
+ procs = []
+
+ def still(check, key):
+ """Its view the live one (made_live's, for either client)."""
+ seen = len(checks(check))
+ key(b'gg')
+ wait_for('the client\'s key stepped', lambda: agreed(check, seen + 1), timeout=30)
+
+ try:
+ out = subprocess.run([str(binary), 'new', '--detach=up'], env=env, cwd=root, capture_output=True, timeout=30)
+ assert out.returncode == 0, out
+ sock = root / 'pardes-9p-up.sock'
+ nine = Client(sock)
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ shell = terminals(nine)[0]
+ shell_pid = int(run(nine, shell, b'echo $$\n').split(b'\n')[1])
+ t = Term(30, 100)
+ terms.append(t)
+ tc = t.spawn([str(binary), 'attach', 'up'], dict(env, PARDES_REPLICA_CHECK=str(root / 't.check')))
+ procs.append(tc)
+ wait_for('the terminal client drawn', lambda: b'\x1b[?1049h' in t.text(), timeout=30)
+ w = Window(root, 'w', [str(gui_binary), 'attach', 'up'], dict(env, PARDES_REPLICA_CHECK=str(root / 'w.check')))
+ procs.append(w.p)
+ wait_for('the window client drawn', lambda: (root / 'w' / 'latest.ppm').exists(), timeout=30)
+ tkey = lambda b: os.write(t.master, b) # noqa: E731
+ # Each client's view live in turn, a pane of its own made there (New).
+ owners = ((w.keys, root / 'w.check'), (tkey, root / 't.check'))
+ mine = []
+ for key, check in owners:
+ still(check, key)
+ shown = view_panes(nine)
+ nine.write('/exec', b'New\n')
+ mine.append(wait_for('a pane in the client\'s view', lambda: view_panes(nine) - shown).pop())
+ for (key, check), pane, theirs in zip(owners, mine, reversed(mine)):
+ still(check, key)
+ assert pane in view_panes(nine) and theirs not in view_panes(nine), ('each its own view', pane, theirs, nine.read('/layout'))
+ install(new, binary)
+ install(new_gui, gui_binary)
+ mark = len(t.text())
+ nine.write('/ctl', b'Upgrade\n')
+ nine.socket.close()
+ wait_for('the session on the new build', lambda: exe_of(session) == (str(binary), True), timeout=30)
+ nine = reconnect(sock)
+ if not knows_exec(old):
+ # A build before the exec: let go, dialled again for 20 s, told.
+ assert tc.wait(timeout=60) == 1 and w.p.wait(timeout=60) == 1, (tc.returncode, w.p.returncode)
+ said = t.text()[mark:] + w.said().encode()
+ assert b'upgrade this client too' in said or b'run the same pardes at both ends' in said, said[-600:]
+ print('upgrade with clients: the clients of a build before it were let go, dialled again, and told to upgrade too')
+ else:
+ wait_for('the terminal client on the new build', lambda: exe_of(tc.pid) == (str(binary), True), timeout=30)
+ wait_for('the window client on the new build', lambda: exe_of(w.pid) == (str(gui_binary), True), timeout=30)
+ # The blink: its screen left, and entered again.
+ wait_for('the terminal entered again', lambda: t.text().rfind(b'\x1b[?1049h') > t.text().rfind(b'\x1b[?1049l') > mark, timeout=30)
+ assert tc.poll() is None and w.p.poll() is None
+ for (key, check), pane, theirs in zip(owners, mine, reversed(mine)):
+ still(check, key)
+ if knows_exec(new):
+ shown = view_panes(nine)
+ assert pane in shown and theirs not in shown, ('its own view again', pane, theirs, nine.read('/layout'))
+ print('upgrade with clients: a terminal client and a window client exec\'d the build at their start path, the same processes, '
+ + ('each back in its own view, its own pane in it' if knows_exec(new) else 'each in a view of its own (that build joins for no view it is handed)'))
+ assert alive(shell_pid) and ppid(shell_pid) == session
+ for p in procs:
+ if p.poll() is None:
+ p.terminate()
+ p.wait(timeout=20)
+ nine.socket.close()
+ assert subprocess.run([str(binary), 'kill', 'up'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('the session ended', lambda: not alive(session), timeout=30)
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
+ print('upgrade with clients: the shell ran on throughout; nothing left behind')
+ finally:
+ for p in procs:
+ if p.poll() is None:
+ p.kill()
+ 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 gui_upgrades(old, new):
"""Upgrade in a window session (test mode: hidden windows, captured):
its window, a client window, an unsaved edit and a shell's job, onto
@@ -2548,6 +2893,11 @@ if __name__ == '__main__':
gui_upgrades(Path(sys.argv[3]).resolve(), Path(sys.argv[4]).resolve())
elif sys.argv[1:2] == ['--upgrade']:
upgrades(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
+ # With a pardes-gui beside each: the clients carried too.
+ if all(Path(a).resolve().with_name('pardes-gui').exists() for a in sys.argv[2:4]):
+ upgrade_clients(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
+ elif sys.argv[1:2] == ['--upgrade-clients']:
+ upgrade_clients(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
elif sys.argv[1:2] == ['--clients']:
clients(sys.argv[2])
elif sys.argv[1:2] == ['--manage']:
@@ -2565,13 +2915,21 @@ if __name__ == '__main__':
elif sys.argv[1:2] == ['--far']:
far(sys.argv[2])
by_hash(sys.argv[2])
+ far_find(sys.argv[2])
+ elif sys.argv[1:2] == ['--far-find']:
+ far_find(sys.argv[2])
+ elif sys.argv[1:2] == ['--restore']:
+ restore_client(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])
elif sys.argv[1:2] == ['--ping']:
ping(sys.argv[2], sys.argv[3], sys.argv[4], int(sys.argv[5]) if len(sys.argv) > 5 else 50)
+ elif sys.argv[1:2] == ['--pair-gui']:
+ gui_pair(sys.argv[2])
elif '--gui' in sys.argv:
args = [a for a in sys.argv[1:] if a != '--gui']
gui(args[0], int(args[1]) if len(args) > 1 else 50)
+ gui_pair(args[0])
else:
main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 50)
diff --git a/test/panes.zig b/test/panes.zig
index 6bda3519..38eb0a71 100644
--- a/test/panes.zig
+++ b/test/panes.zig
@@ -3949,6 +3949,10 @@ const PdfAddon = struct {
}
};
const id = try opened(a, Land{ .a = a, .r = r });
+ // The effects `jobs` took last are the session's steps: a unit of
+ // its own before the client's input.
+ a.seq += 1;
+ r.confirm(try a.unit(0, a.seq));
const guessed = r.stats.mispredicted;
const stopped = r.stats.stopped;
const told = a.core.panes[id].?.addon.?.views;
diff --git a/test/perf.zig b/test/perf.zig
index 7920dedf..8c88ef01 100644
--- a/test/perf.zig
+++ b/test/perf.zig
@@ -391,6 +391,8 @@ const Options = struct {
creation: bool = false,
startup: bool = false,
mini: bool = false,
+ /// The scans a frame's slice bounds, a call at a time (`measureSearch`).
+ search: bool = false,
terminal_mib: ?usize = null,
/// The real binary's keystroke-to-present, `yes` stream and big open
/// (a tty pardes), or its keystrokes alone (a pardes-gui).
@@ -407,13 +409,14 @@ const Options = struct {
while (i < args.len) : (i += 1) {
const arg = args[i];
if (!std.mem.startsWith(u8, arg, "--")) return error.UnknownOption;
- const option = std.meta.stringToEnum(enum { json, creation, startup, mini, @"terminal-mib", @"self-test", reps, cols, rows, base, only, op, @"max-ratio", live, @"live-gui" }, arg[2..]) orelse
+ const option = std.meta.stringToEnum(enum { json, creation, startup, mini, search, @"terminal-mib", @"self-test", reps, cols, rows, base, only, op, @"max-ratio", live, @"live-gui" }, arg[2..]) orelse
return error.UnknownOption;
switch (option) {
.json => opts.json = true,
.creation => opts.creation = true,
.startup => opts.startup = true,
.mini => opts.mini = true,
+ .search => opts.search = true,
.@"self-test" => opts.self_test = true,
else => {
i += 1;
@@ -475,6 +478,7 @@ pub fn main(init: std.process.Init) !void {
if (opts.creation) return measureCreation(init.io, reps, opts.json);
if (opts.terminal_mib) |mib| return measureTerminalSession(init.io, mib, reps, opts.json);
if (opts.mini) return measureMini(init.io, init.gpa, reps, opts.json);
+ if (opts.search) return measureSearch(init.io);
if (opts.live) |exe| return measureLive(init.io, exe, false, reps, opts.json);
if (opts.live_gui) |exe| return measureLive(init.io, exe, true, reps, opts.json);
// The image-frame cells load the image addon by the path the build baked
@@ -1742,6 +1746,138 @@ fn measureMini(io: std.Io, fallback: std.mem.Allocator, reps: usize, json: bool)
}
}
+/// `--search`: the two scans a frame's slice bounds, each call timed and
+/// its instructions counted (user space, this thread): a find's names
+/// scored again as a query is typed into it over 200,000 paths
+/// (core/Names.zig `rescore`, Names' cap), and a search's places found a
+/// tick at a time over the large fixture, the view in its middle
+/// (core/Places.zig `settle` on a tick). The longest call of each is the
+/// slice a key or a frame can take.
+fn measureSearch(io: std.Io) !void {
+ var random: [12]u8 = undefined;
+ io.random(&random);
+ const dir = try std.fmt.allocPrint(gpa, "/tmp/pardes-perf-{x}", .{random});
+ defer gpa.free(dir);
+ try std.Io.Dir.createDirAbsolute(io, dir, .default_dir);
+ defer std.Io.Dir.cwd().deleteTree(io, dir) catch {};
+ var counter: Instructions = try .open();
+ defer counter.close();
+
+ const Names = @FieldType(pardes.panes.Query, "names");
+ var names: Names = .{};
+ defer names.deinit(gpa);
+ const dirs = [_][]const u8{ "core", "dev/gui", "dev/tui", "runtime", "test/behaviour", "addons/pdf", "zig-pkg/ghostty/src/terminal" };
+ const words = [_][]const u8{ "layout", "places", "names", "query", "stream", "surface", "replica", "tape", "kitty", "render" };
+ var row: [160]u8 = undefined;
+ for (0..200_000) |i| {
+ const path = try std.fmt.bufPrint(&row, "{s}/module_{d}/{s}_{d}.zig", .{ dirs[i % dirs.len], i / 64 % 997, words[i * 7 % words.len], i });
+ try names.add(gpa, path, 0, path.len, Names.baseOf(path), 0);
+ }
+ // Typed a key at a time, as into a find: each key's call, then the
+ // calls of the frames after it while it is busy.
+ for ([_][]const u8{ "m", "tape", "places zig", "core/module_9/replica_1", "zig-pkg/ghostty/src/terminal/module_99/kitty" }) |query| {
+ var slow: Slowest = .{};
+ names.typed(gpa, "");
+ for (1..query.len + 1) |n| {
+ var calls: usize = 0;
+ while (true) : (calls += 1) {
+ const was = counter.read();
+ const t0 = nowNs();
+ if (calls == 0) names.typed(gpa, query[0..n]) else names.rescore(gpa);
+ slow.add(nowNs() -| t0, counter.read() -| was, names.hits.items.len);
+ if (!names.busy()) break;
+ }
+ }
+ slow.report("rescore", query, names.hits.items.len);
+ }
+
+ const fx = fixtures[2];
+ const path = try std.fmt.allocPrint(gpa, "{s}/{s}.zig", .{ dir, fx.name });
+ defer gpa.free(path);
+ const text = try generate(fx);
+ try writeFile(path, text);
+ gpa.free(text);
+ for ([_][]const u8{ "e", "lorem.*amet", "helper_[0-9]+", "qqq" }) |pattern| {
+ const core = try boot();
+ defer core.deinit();
+ pardes.look.lookAt(core, 0, path);
+ pump(core);
+ const id = filePane(core) orelse return error.OpenDidNotOpenFile;
+ const pane = core.panes[id].?;
+ seek(pane, fx, 0);
+ pane.file.?.scroll = fx.lines / 2;
+ pane.body.cur_row = @intCast(fx.lines / 2);
+ _ = try frame(core);
+ const set = &pane.places;
+ set.search(core, pane, .typed, pane.serial, pattern, false, null, false);
+ var slow: Slowest = .{};
+ while (set.busy(pane) and slow.calls < 100_000) {
+ const was = counter.read();
+ const t0 = nowNs();
+ set.settle(core, pane, true);
+ slow.add(nowNs() -| t0, counter.read() -| was, 0);
+ }
+ slow.report("fill", pattern, set.hits.items.len);
+ }
+}
+
+/// The longest of a scan's calls.
+const Slowest = struct {
+ calls: usize = 0,
+ total_ns: u64 = 0,
+ ns: u64 = 0,
+ /// The instructions of the longest call (by time), and the most of any.
+ ins: u64 = 0,
+ most_ins: u64 = 0,
+ /// The same of the calls that left under 1,000 hits to sort: the scan
+ /// alone, nearly (`Names.rescore` sorts every hit at each call).
+ few_ns: u64 = 0,
+ few_ins: u64 = 0,
+
+ fn add(s: *Slowest, ns: u64, ins: u64, hits: usize) void {
+ s.calls += 1;
+ if (hits < 1000 and ns > s.few_ns) {
+ s.few_ns = ns;
+ s.few_ins = ins;
+ }
+ s.total_ns += ns;
+ if (ns > s.ns) {
+ s.ns = ns;
+ s.ins = ins;
+ }
+ s.most_ins = @max(s.most_ins, ins);
+ }
+
+ fn report(s: *const Slowest, what: []const u8, of: []const u8, hits: usize) void {
+ std.debug.print("{s} \"{s}\": {d} calls, {d} hits, {d:.2} ms in all; longest {d} us ({d} instructions); most instructions {d}; longest with under 1,000 hits {d} us ({d} instructions)\n", .{
+ what, of, s.calls, hits, @as(f64, @floatFromInt(s.total_ns)) / 1e6, s.ns / 1000, s.ins, s.most_ins, s.few_ns / 1000, s.few_ins,
+ });
+ }
+};
+
+/// This thread's instructions in user space (perf_event_open).
+const Instructions = struct {
+ fd: std.posix.fd_t,
+
+ fn open() !Instructions {
+ const linux = std.os.linux;
+ var attr: linux.perf_event_attr = .{ .type = .HARDWARE, .config = @intFromEnum(linux.PERF.COUNT.HW.INSTRUCTIONS), .flags = .{ .exclude_kernel = true, .exclude_hv = true } };
+ const rc = linux.perf_event_open(&attr, 0, -1, -1, 0);
+ if (linux.errno(rc) != .SUCCESS) return error.NoInstructionCounter;
+ return .{ .fd = @intCast(rc) };
+ }
+
+ fn read(c: Instructions) u64 {
+ var n: u64 = 0;
+ _ = std.os.linux.read(c.fd, std.mem.asBytes(&n), 8);
+ return n;
+ }
+
+ fn close(c: Instructions) void {
+ _ = std.os.linux.close(c.fd);
+ }
+};
+
fn seek(pane: *pardes.Pane, fx: Fixture, n: usize) void {
const f = &pane.file.?;
const span = @max(1, fx.lines * 8 / 10);
diff --git a/test/replicas.zig b/test/replicas.zig
index 7610ad8c..6a6d43b4 100644
--- a/test/replicas.zig
+++ b/test/replicas.zig
@@ -699,7 +699,7 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run,
const r = cl.r.?;
const link = &cl.loop.link;
// Its link ended by the session (a Detach), it says nothing more.
- if (!link.gone) replica.bye(link.fd, r.diverged != null);
+ if (!link.gone) replica.bye(link.fd, .{ .again = r.diverged != null });
try drain(cl, c, net, now);
cl.live = 0;
if (r.diverged) |why| {
diff --git a/test/session.zig b/test/session.zig
index 1cbee9df..d437ecf2 100644
--- a/test/session.zig
+++ b/test/session.zig
@@ -53,7 +53,7 @@ pub const Session = struct {
/// A session showing one file pane holding `text`, keeping what outlives
/// it in a database in memory (core/Db.zig).
pub fn initFile(gpa: std.mem.Allocator, text: []const u8) !Session {
- const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory });
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory, .tape = recording });
errdefer p.deinit();
_ = try p.setTestFile(text);
var s: Session = .{ .core = p, .arena = .init(gpa) };
@@ -75,7 +75,7 @@ pub const Session = struct {
/// A session showing one file pane, its startup file `init` (as
/// `~/.config/pardes/init` is read) applied first.
pub fn initStartup(gpa: std.mem.Allocator, init: []const u8) !Session {
- const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory, .startup_config = init });
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory, .startup_config = init, .tape = recording });
errdefer p.deinit();
_ = try p.setTestFile("x\n");
var s: Session = .{ .core = p, .arena = .init(gpa) };
@@ -85,7 +85,7 @@ pub const Session = struct {
/// A session showing its terminal pane, as `pardes` starts.
pub fn initTerm(gpa: std.mem.Allocator) !Session {
- const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory });
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory, .tape = recording });
var s: Session = .{ .core = p, .arena = .init(gpa) };
s.drain();
return s;
@@ -99,7 +99,7 @@ pub const Session = struct {
var arena: std.heap.ArenaAllocator = .init(gpa);
errdefer arena.deinit();
const config = try std.fmt.allocPrint(arena.allocator(), "DumpDir {s}\n", .{dir});
- const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .disk, .startup_config = config });
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .disk, .startup_config = config, .tape = recording });
var s: Session = .{ .core = p, .arena = arena };
s.drain();
return s;
@@ -206,12 +206,16 @@ pub const Session = struct {
s.drain();
}
+ /// The tape `recordTape` started: every session made after it records on it.
+ var recording: ?*pardes.tape.Tape = null;
+
/// Every session started from here on records what it consumes as a
/// tape in memory, as PARDES_RECORD has a real one record it
/// (core/tape.zig); `replayTape` replays it once the session is gone.
pub fn recordTape(gpa: std.mem.Allocator) !void {
const t = try gpa.create(pardes.tape.Tape);
t.* = pardes.tape.memory(gpa);
+ recording = t;
pardes.tape.on = t;
}
@@ -221,7 +225,8 @@ pub const Session = struct {
/// its end loaded to its digest and dumped to its bytes again. False
/// when a replica diverged (said on stderr). After `deinit`.
pub fn replayTape(gpa: std.mem.Allocator) bool {
- const t = pardes.tape.on orelse return true;
+ const t = recording orelse return true;
+ recording = null;
pardes.tape.on = null;
defer {
pardes.tape.release(t);