summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--build/patches.zig5
-rw-r--r--core/Core.zig15
-rw-r--r--core/File.zig14
-rw-r--r--core/Names.zig20
-rw-r--r--core/Places.zig21
-rw-r--r--core/Turn.zig10
-rw-r--r--core/body_layer.zig5
-rw-r--r--core/dump.zig7
-rw-r--r--core/replica.zig4
-rw-r--r--core/tape.zig128
-rw-r--r--dev/Inbox.zig75
-rw-r--r--dev/Ptys.zig34
-rw-r--r--dev/gui/gui.zig79
-rw-r--r--dev/host_io.zig55
-rw-r--r--dev/tui/tui.zig161
-rw-r--r--docs/next-daemon.md7
-rw-r--r--runtime/9p_io.zig6
-rw-r--r--runtime/daemon.zig48
-rw-r--r--runtime/macos.zig1
-rw-r--r--runtime/main.zig8
-rw-r--r--runtime/session.zig37
-rw-r--r--test/daemon.py246
-rw-r--r--test/delay_relay.py10
-rw-r--r--test/e2e_harness.zig18
-rw-r--r--test/panes.zig4
-rw-r--r--test/perf.zig138
-rw-r--r--test/process/terminals.zig9
-rw-r--r--test/process/tty_terminals.zig4
-rw-r--r--test/replicas.zig1
-rw-r--r--test/session.zig15
30 files changed, 822 insertions, 363 deletions
diff --git a/build/patches.zig b/build/patches.zig
index 7c7b2d60..7d87b9f1 100644
--- a/build/patches.zig
+++ b/build/patches.zig
@@ -34,7 +34,8 @@ fn apply(b: *std.Build, patch: *std.Build.Step.Compile, dep: *std.Build.Dependen
/// startup width queries' `CSI 1;1R` arrived as two F3s, which a shell
/// pane took for text (build/patches/vaxis_parser.zig).
/// - ESC before a CSI or SS3 key (rxvt's Alt+arrow) is Alt on that key,
-/// not Alt+Escape followed by `[A` as text.
+/// not Alt+Escape followed by `[A` as text; before anything else (a
+/// mouse report: Alt is in its button) it is the Escape key.
/// - An X10 mouse report and a kitty graphics reply cut short by a read
/// wait for their rest: the first became three bytes of text, the
/// second sliced past its input.
@@ -56,7 +57,7 @@ const vaxis_parser = [_]Edit{
\\ if (inner.n == 0) return inner;
\\ if (inner.event) |*event| switch (event.*) {
\\ .key_press, .key_release => |*key| key.mods.alt = true,
- \\ else => {},
+ \\ else => return .{ .event = .{ .key_press = .{ .codepoint = Key.escape } }, .n = 1 },
\\ };
\\ inner.n += 1;
\\ return inner;
diff --git a/core/Core.zig b/core/Core.zig
index c08eb883..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.
@@ -2303,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/File.zig b/core/File.zig
index 51773c89..ceb6d03b 100644
--- a/core/File.zig
+++ b/core/File.zig
@@ -2356,6 +2356,20 @@ test "a caret deep in a long line scrolls the view sideways to it, measured from
try std.testing.expectEqual(@as(i32, 0), pane.hscroll);
}
+test "a caret left of a view scrolled sideways is not drawn in the gutter" {
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
+ defer p.deinit();
+ p.settings.wrap = false;
+ const pane = try p.setTestFile("short1 END_A_MARKER_WAY_OUT_RIGHT_padpadpadpadpadpadpadpadpadpadpad_TAIL\n");
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ try std.testing.expect((try p.render(arena.allocator())).cursor != null);
+ // One wheel notch (4 columns) of the 7 the gutter is: the caret, at
+ // column 0, was drawn 3 columns into the gutter.
+ pane.hscroll = 4;
+ try std.testing.expect((try p.render(arena.allocator())).cursor == null);
+}
+
test "undo and redo walk back and forth through every step of random edits, joined entries and all" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
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/body_layer.zig b/core/body_layer.zig
index 7dc097ad..1582136c 100644
--- a/core/body_layer.zig
+++ b/core/body_layer.zig
@@ -512,7 +512,10 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane
)
else
ccol;
- if (prow >= pane.tag_rows and cx >= 0 and prow < body_bottom and cx < tw)
+ // Left of a view scrolled sideways it is off the view, not
+ // in the gutter.
+ const left: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0;
+ if (prow >= pane.tag_rows and cx >= left and prow < body_bottom and cx < tw)
s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = body_y + @as(u16, @intCast(prow - pane.tag_rows)), .bar = pane.body.mode == .insert };
}
} else if (pane.terminal != null) visible: {
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 9edc96d2..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);
@@ -6798,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/Inbox.zig b/dev/Inbox.zig
index aac1f7a1..d733b971 100644
--- a/dev/Inbox.zig
+++ b/dev/Inbox.zig
@@ -47,8 +47,12 @@ pub const Msg = union(enum) {
}
};
-pub const capacity = 512;
-pub const output_capacity = capacity - pardes.MAX_PANES;
+/// The ring's room: output up to `output_capacity` (a reader waits for
+/// more), an Adopt's shells beyond it (one note's: never lost to a flood),
+/// and each pane's end of file beyond those (lost to neither).
+pub const output_capacity = 512 - pardes.MAX_PANES;
+const adopt_capacity = output_capacity + pardes.MAX_PANES + 1;
+pub const capacity = adopt_capacity + pardes.MAX_PANES;
pub const Batch = struct {
items: [capacity + 2 * selection_pipe.Tasks.capacity + 2]Msg = undefined,
@@ -63,6 +67,11 @@ gpa: std.mem.Allocator,
lsp_allocator: std.mem.Allocator,
/// The query in flight; the UI thread's alone (spawnLsp, teardown).
lsp_task: ?Lsp.Task = null,
+/// The `|` pipes' and the addons' jobs' and draws' workers in flight, each
+/// posting its answer here (`pushPipe`, `pushJob`); the loop's thread's
+/// alone: joined as their answers land (`land`), canceled at the end.
+pipe_tasks: selection_pipe.Tasks = .{},
+job_tasks: selection_pipe.Tasks = .{},
/// Wakes the host's loop after a push from another thread: an SDL
/// event, a macOS runtime callback. Null: nobody to wake (tests).
wake_fn: ?*const fn (?*anyopaque) void = null,
@@ -77,6 +86,11 @@ len: usize = 0,
closed: bool = false,
files_changed: bool = false,
readers: [pardes.MAX_PANES]?u32 = @splat(null),
+/// Each pane's reads read out of its pty and not yet applied (`applied`):
+/// a command's exit is told only once none is (Ptys.unapplied), since
+/// the poll that asks whether its output is in (CommandWatch.due) cannot
+/// see a read the reader holds or the queue does.
+unapplied: [pardes.MAX_PANES]std.atomic.Value(u32) = @splat(.init(0)),
waiting: usize = 0,
lsp_id: ?u32 = null,
completions: [2 * selection_pipe.Tasks.capacity + 1]Msg = undefined,
@@ -101,6 +115,12 @@ pub fn acceptReader(q: *Inbox, pane: pardes.Pane.Id, gen: u32) void {
q.readers[pane.index()] = gen;
}
+/// One of `pane`'s reads applied, or dropped unapplied.
+pub fn applied(q: *Inbox, pane: pardes.Pane.Id) void {
+ const n = &q.unapplied[pane.index()];
+ if (n.load(.acquire) > 0) _ = n.fetchSub(1, .acq_rel);
+}
+
pub fn cancelReader(q: *Inbox, pane: pardes.Pane.Id, gen: u32) void {
q.lock();
defer q.unlock();
@@ -114,7 +134,10 @@ pub fn cancelReader(q: *Inbox, pane: pardes.Pane.Id, gen: u32) void {
.eof => |e| e.pane == pane and e.gen == gen,
else => false,
};
- if (matches) q.removeAt(i).deinit(q.gpa, q.lsp_allocator) else i += 1;
+ if (matches) {
+ if (msg == .output) q.applied(pane);
+ q.removeAt(i).deinit(q.gpa, q.lsp_allocator);
+ } else i += 1;
}
q.space.broadcast(q.io);
}
@@ -189,7 +212,7 @@ pub fn push(q: *Inbox, m: Msg) void {
return;
}
std.debug.assert(q.len < q.items.len);
- } else if (q.len >= output_capacity) {
+ } else if (q.len >= @as(usize, if (m == .adopted) adopt_capacity else output_capacity)) {
q.unlock();
m.deinit(q.gpa, q.lsp_allocator);
return;
@@ -262,9 +285,11 @@ pub fn close(q: *Inbox) void {
}
pub fn deinit(q: *Inbox) void {
- // The query in flight ends first: what it still delivers is dropped.
+ // The workers in flight end first: what they still deliver is dropped.
if (q.lsp_task) |*t| t.future.cancel(q.io);
q.lsp_task = null;
+ q.pipe_tasks.cancelAll(q.io);
+ q.job_tasks.cancelAll(q.io);
q.close();
std.debug.assert(q.waiting == 0);
}
@@ -291,11 +316,14 @@ fn readPty(q: *Inbox, pty: std.Io.File, pane: pardes.Pane.Id, gen: u32) void {
},
};
if (n == 0) continue;
+ // Counted at once: out of the pty, the poll no longer sees it.
+ _ = q.unapplied[pane.index()].fetchAdd(1, .acq_rel);
const bytes = q.gpa.dupe(u8, buf[0..n]) catch |err| {
+ q.applied(pane);
failure = err;
break;
};
- if (!q.pushOutput(pane, gen, bytes)) return;
+ if (!q.pushOutput(pane, gen, bytes)) return q.applied(pane);
}
q.push(.{ .eof = .{ .pane = pane, .gen = gen, .failure = failure } });
}
@@ -311,9 +339,10 @@ pub fn startLsp(q: *Inbox, core: *pardes.Pardes, e: Lsp.Request) void {
Lsp.start(q.io, q.lsp_allocator, core, &q.lsp_task, e, q, pushLspRows);
}
-/// A language server's answer or status line taken off the queue, to the
-/// core (whichever frontend took it).
-pub fn landLsp(q: *Inbox, core: *pardes.Pardes, m: Msg) void {
+/// A worker's answer taken off the queue, to the core (whichever frontend
+/// took it), its worker joined: a language server's answer or status line,
+/// a pipe's, a search's rows, an addon's job or draw, a handover's end.
+pub fn land(q: *Inbox, core: *pardes.Pardes, m: Msg) void {
switch (m) {
.lsp => |l| {
core.update(.{ .lsp_resp = .{ .id = l.id, .rows = l.rows } });
@@ -324,7 +353,30 @@ pub fn landLsp(q: *Inbox, core: *pardes.Pardes, m: Msg) void {
core.setStatus(.at(core.view().active), pardes.Messages.Message.stamp(&mbuf, "lsp", text));
q.lsp_allocator.free(text);
},
- else => unreachable,
+ .pipe => |response_value| {
+ var response = response_value;
+ core.update(.{ .pipe_resp = .{
+ .id = response.id,
+ .success = response.success,
+ .outputs = response.outputs,
+ .failure = response.failure,
+ } });
+ response.deinit(q.gpa);
+ q.pipe_tasks.finish(q.io, response_value.id);
+ },
+ .search => |b| {
+ core.update(.{ .search = b });
+ b.deinit(q.gpa);
+ },
+ .kind_job => |j| {
+ q.job_tasks.finish(q.io, j.id);
+ j.land(core);
+ },
+ .handed => |h| {
+ core.update(.{ .handed = .{ .seq = h.seq, .to = if (h.ok) h.words else "", .failure = if (h.ok) null else h.words } });
+ q.gpa.free(h.words);
+ },
+ .output, .eof, .files_changed, .fs_ready, .adopted => unreachable,
}
}
@@ -340,12 +392,13 @@ pub fn lspStatus(ctx: ?*anyopaque, text: []const u8) void {
q.push(.{ .lsp_status = copy });
}
-/// A `|` job's answer (selection_pipe.start's sink).
+/// An addon's job or draw done (KindJob.go's sink).
pub fn pushJob(ctx: ?*anyopaque, j: *KindJob) void {
const q: *Inbox = @ptrCast(@alignCast(ctx.?));
q.push(.{ .kind_job = j });
}
+/// A `|` pipe's answer (selection_pipe.start's sink).
pub fn pushPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void {
const q: *Inbox = @ptrCast(@alignCast(ctx.?));
q.push(.{ .pipe = response });
diff --git a/dev/Ptys.zig b/dev/Ptys.zig
index 16a31939..583e3c38 100644
--- a/dev/Ptys.zig
+++ b/dev/Ptys.zig
@@ -180,6 +180,7 @@ pub fn close(p: *Ptys, id: pardes.Pane.Id) void {
/// A reader's read, off the queue (freed here).
pub fn output(p: *Ptys, core: *pardes.Pardes, o: @FieldType(Inbox.Msg, "output")) void {
defer p.queue.gpa.free(o.bytes);
+ defer p.queue.applied(o.pane);
if (p.gens[o.pane.index()] == o.gen) core.update(.{ .output = .{ .pane = o.pane, .bytes = o.bytes } });
}
@@ -213,6 +214,11 @@ pub fn takeExits(p: *Ptys, core: *pardes.Pardes) void {
host_io.takeExits(core, &p.slots, p, closeWatched);
}
+/// Whether pane `id` has reads not yet applied (host_io.takeExits).
+pub fn unapplied(p: *const Ptys, id: usize) bool {
+ return p.queue.unapplied[id].load(.acquire) > 0;
+}
+
fn closeWatched(p: *Ptys, id: usize) void {
p.close(.at(id));
}
@@ -401,3 +407,31 @@ test "a post of an older generation is passed over" {
try std.testing.expect(std.mem.indexOf(u8, text, "old session") == null);
try std.testing.expect(std.mem.indexOf(u8, text, "current session") != null);
}
+
+test "a command's exit is told after its output a reader read, however long that waits in the queue" {
+ const gpa = std.testing.allocator;
+ const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
+ defer core.deinit();
+ var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa };
+ defer queue.deinit();
+ var p = testing(&queue);
+ defer p.deinit();
+ // A command done (reaped), its pty held open by what it left running
+ // (the pipe's write end): no end of file, and no output in the kernel
+ // once the reader has read it.
+ var fds: [2]c_int = undefined;
+ if (libc.pipe(&fds) != 0) return error.PipeFailed;
+ defer _ = libc.close(fds[1]);
+ p.slots[0] = .{ .fd = fds[0], .pid = 0, .cmd = .{ .watched = true, .fd = fds[0], .exited = true, .status = 0 } };
+ p.slots[0].?.reader = try queue.startReader(.{ .handle = fds[0], .flags = .{ .nonblocking = false } }, .at(0), p.gens[0]);
+ try std.testing.expect(host_io.writeFd(fds[1], "LAST"));
+ const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000;
+ while (queue.len == 0 and std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) try std.testing.io.sleep(.fromMilliseconds(1), .awake);
+ try std.testing.expectEqual(@as(usize, 1), queue.len);
+ p.takeExits(core);
+ try std.testing.expect(!p.slots[0].?.cmd.told);
+ var batch = queue.take();
+ for (batch.slice()) |msg| p.output(core, msg.output);
+ p.takeExits(core);
+ try std.testing.expect(p.slots[0].?.cmd.told);
+}
diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig
index 60176642..521f685f 100644
--- a/dev/gui/gui.zig
+++ b/dev/gui/gui.zig
@@ -379,7 +379,6 @@ fn sdlWake(_: ?*anyopaque) void {
sev.type = c.SDL_EVENT_USER;
_ = c.SDL_PushEvent(&sev);
}
-const PipeTasks = selection_pipe.Tasks;
const output_capacity = Queue.output_capacity;
const Gui = struct {
@@ -991,7 +990,6 @@ const Own = struct {
g: *Gui,
test_mode: bool,
detached: bool,
- pipe_tasks: PipeTasks = .{},
shell: Shell = undefined,
const Session = session_loop.Loop(Own);
@@ -1024,7 +1022,6 @@ const Own = struct {
.lsp_allocator = l.allocs.lsp,
.ptys = &l.ptys,
.queue = &l.inbox,
- .pipe_tasks = &o.pipe_tasks,
.watches = &l.watches,
.fs = l.fs,
.test_mode = o.test_mode,
@@ -1044,15 +1041,10 @@ const Own = struct {
return host;
}
- pub fn close(o: *Own, l: *Session) void {
- const io = l.io;
+ pub fn close(o: *Own, _: *Session) void {
o.shell.fs = null;
host_io.setExitWake(null, null);
pardes.Kind.drawer = null;
- o.shell.job_tasks.cancelAll(io);
- o.pipe_tasks.cancelAll(io);
- // Its worker may be waiting on the queue for room.
- l.core.stream.cancelTask();
o.g.hit_core = null;
}
@@ -1079,12 +1071,7 @@ const Own = struct {
if (o.shell.upgrade_asked) |pane| o.shell.upgradeNow(pane);
}
- pub fn note(o: *Own, n: daemon.Note) void {
- deliverNote(&o.shell, n);
- }
-
pub fn restoring(o: *Own, nc: *pardes.Pardes) void {
- o.pipe_tasks.cancelAll(o.shell.io);
// One view, the window's (host_io.restoreCore).
o.shell.gview = 0;
o.g.cells.clearImages();
@@ -1415,7 +1402,6 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = start.allocs.lsp, .wake_fn = sdlWake };
defer queue.deinit();
var ptys: host_io.Ptys = .{ .queue = &queue, .prompt_rcs = undefined };
- var pipe_tasks: PipeTasks = .{};
var no_watches: file_watch.Watches = .{ .io = io, .gpa = gpa, .queue = &queue };
var no_peers: replica.Peers = .{};
var shell: Shell = .{
@@ -1426,7 +1412,6 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
.lsp_allocator = start.allocs.lsp,
.ptys = &ptys,
.queue = &queue,
- .pipe_tasks = &pipe_tasks,
.watches = &no_watches,
.test_mode = test_mode,
.client = &window,
@@ -1435,7 +1420,6 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
window.shell = &shell;
pardes.Kind.drawer = .{ .ctx = &shell, .go = kindDraw };
defer pardes.Kind.drawer = null;
- defer shell.job_tasks.cancelAll(io);
g.no_blink = test_mode;
defer g.hit_core = null;
_ = c.SDL_StartTextInput(g.window);
@@ -2376,8 +2360,6 @@ const Shell = struct {
queue: *Queue,
/// What drainQueue takes each wakeup, kept rather than rebuilt.
batch: Queue.Batch = .{},
- pipe_tasks: *PipeTasks,
- job_tasks: PipeTasks = .{},
/// The session's file watches (runtime/session.zig's); a client's,
/// none.
watches: *file_watch.Watches,
@@ -2586,10 +2568,7 @@ const Shell = struct {
fn takeDraws(s: *Shell) bool {
s.queue.takeInto(&s.batch);
for (s.batch.slice()) |m| switch (m) {
- .kind_job => |j| {
- s.job_tasks.finish(s.io, j.id);
- j.land(s.core);
- },
+ .kind_job => s.queue.land(s.core, m),
else => m.deinit(s.gpa, s.lsp_allocator),
};
return s.batch.slice().len > 0;
@@ -2605,33 +2584,10 @@ const Shell = struct {
for (msgs.slice()) |m| switch (m) {
.output => |o| s.ptys.output(s.core, o),
.eof => |e| s.ptys.eof(s.core, e),
- .lsp, .lsp_status => s.queue.landLsp(s.core, m),
- .pipe => |response_value| {
- var response = response_value;
- s.core.update(.{ .pipe_resp = .{
- .id = response.id,
- .success = response.success,
- .outputs = response.outputs,
- .failure = response.failure,
- } });
- response.deinit(s.gpa);
- s.pipe_tasks.finish(s.io, response_value.id);
- },
- .search => |b| {
- s.core.update(.{ .search = b });
- b.deinit(s.gpa);
- },
- .handed => |h| {
- s.core.update(.{ .handed = .{ .seq = h.seq, .to = if (h.ok) h.words else "", .failure = if (h.ok) null else h.words } });
- s.gpa.free(h.words);
- },
- .kind_job => |j| {
- s.job_tasks.finish(s.io, j.id);
- j.land(s.core);
- },
.files_changed => check_files = true,
.fs_ready => {},
.adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd),
+ else => s.queue.land(s.core, m),
};
if (check_files) s.watches.reload(s.core);
}
@@ -3138,21 +3094,6 @@ fn guiNow(ctx: ?*anyopaque) u64 {
return s.test_clock orelse s.paced_ns orelse c.SDL_GetTicksNS();
}
-/// The daemon's thread: what it says, onto the queue (drainQueue).
-fn deliverNote(ctx: *anyopaque, note: daemon.Note) void {
- const s: *Shell = @ptrCast(@alignCast(ctx));
- const q = s.queue;
- switch (note) {
- .relinked => q.wake(),
- .adopted => |a| {
- for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| q.push(.{ .adopted = .{ .pid = pid, .fd = fd } });
- q.push(.{ .adopted = .{ .pid = 0, .fd = -1 } });
- },
- // Joined at the next step boundary (Peers, any thread).
- .replica => |j| s.peers.handed(j.fd, j.view),
- }
-}
-
fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void {
host_io.writeDump(shellOf(ctx).core, bytes);
}
@@ -3203,7 +3144,7 @@ fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void {
fn pipe(ctx: ?*anyopaque, id: u32) void {
const s = shellOf(ctx);
- if (s.threads_ok) return selection_pipe.start(s.io, s.gpa, s.core, s.pipe_tasks, id, s.queue, Queue.pushPipe);
+ if (s.threads_ok) return selection_pipe.start(s.io, s.gpa, s.core, &s.queue.pipe_tasks, id, s.queue, Queue.pushPipe);
s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } });
s.core.reportError(.at(s.core.view().active), "pipe", error.WorkersUnavailable);
}
@@ -3211,13 +3152,13 @@ fn pipe(ctx: ?*anyopaque, id: u32) void {
/// A draw (api.draw) on a worker, as a job is.
fn kindDraw(ctx: ?*anyopaque, j: *host_io.KindJob) bool {
const s = shellOf(ctx);
- return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.job_tasks, j, s.queue, Queue.pushJob);
+ return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.queue.job_tasks, j, s.queue, Queue.pushJob);
}
fn kindJob(ctx: ?*anyopaque, id: pardes.Pane.Id, serial: u32, token: u32) void {
const pane = id.index();
const s = shellOf(ctx);
- if (s.threads_ok) return host_io.KindJob.start(s.io, s.core, &s.job_tasks, pane, serial, token, s.queue, Queue.pushJob);
+ if (s.threads_ok) return host_io.KindJob.start(s.io, s.core, &s.queue.job_tasks, pane, serial, token, s.queue, Queue.pushJob);
host_io.KindJob.runHere(s.core, pane, serial, token);
}
@@ -6001,7 +5942,6 @@ test "GUI worker setup failures finish matching LSP and pipe requests" {
.lsp_allocator = failing.allocator(),
};
defer queue.deinit();
- var tasks: PipeTasks = .{};
core.lspRequest(core.view().active, .status, "");
const req: host_io.Lsp.Request = .{
.id = core.lsp_ask.wait.?.id,
@@ -6033,11 +5973,11 @@ test "GUI worker setup failures finish matching LSP and pipe requests" {
core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } });
core.update(.{ .key = .{ .cp = pardes.Key.enter } });
const pipe_id = core.pipe.wait.?.id;
- selection_pipe.start(failing_io, failing.allocator(), core, &tasks, pipe_id, &queue, Queue.pushPipe);
+ selection_pipe.start(failing_io, failing.allocator(), core, &queue.pipe_tasks, pipe_id, &queue, Queue.pushPipe);
try std.testing.expect(core.pipe.wait == null);
try std.testing.expectEqualStrings("abc", pane.file.?.content);
try std.testing.expect(queue.lsp_task == null);
- try std.testing.expectEqual(@as(usize, 0), tasks.len);
+ try std.testing.expectEqual(@as(usize, 0), queue.pipe_tasks.len);
try std.testing.expectEqual(@as(usize, 0), queue.len);
}
}
@@ -7701,9 +7641,8 @@ test "a detached GUI authority follows terminal directory changes with no window
const rcs: host_io.Shell.PromptFiles = .{};
var ptys: host_io.Ptys = .{ .queue = &queue, .prompt_rcs = &rcs, .gens = @splat(1) };
defer ptys.deinit();
- var pipes: PipeTasks = .{};
var no_peers: replica.Peers = .{};
- var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .ptys = &ptys, .queue = &queue, .pipe_tasks = &pipes, .watches = undefined, .peers = &no_peers };
+ var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .ptys = &ptys, .queue = &queue, .watches = undefined, .peers = &no_peers };
const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80);
ptys.slots[0] = .{ .fd = child.file.handle, .pid = child.pid };
try std.testing.expect(host_io.writeFd(child.file.handle, "cd child\n"));
diff --git a/dev/host_io.zig b/dev/host_io.zig
index 5465fc7a..a22bf5ce 100644
--- a/dev/host_io.zig
+++ b/dev/host_io.zig
@@ -1105,6 +1105,8 @@ pub fn takeExits(core: *pardes.Pardes, ptys: anytype, ctx: anytype, comptime clo
for (ptys, 0..) |*slot, id| {
const pt = slotPty(slot) orelse continue;
if (!pt.cmd.watched or !pt.cmd.due()) continue;
+ // Its output read and not yet applied (a host whose reader counts).
+ if (comptime @hasDecl(@TypeOf(ctx.*), "unapplied")) if (!pt.cmd.eof and ctx.unapplied(id)) continue;
pt.cmd.told = true;
const eof = pt.cmd.eof;
core.update(.{ .exited = .{ .pane = .at(id), .status = pt.cmd.status } });
@@ -2265,11 +2267,62 @@ test "PTY EOF reserve cannot evict terminal output" {
for (0..pardes.MAX_PANES) |pane| queue.push(.{ .eof = .{ .pane = .at(pane), .gen = 1 } });
var batch = queue.take();
defer for (batch.slice()) |msg| msg.deinit(gpa, gpa);
- try std.testing.expectEqual(Inbox.capacity, batch.len);
+ try std.testing.expectEqual(Inbox.output_capacity + pardes.MAX_PANES, batch.len);
for (batch.items[0..Inbox.output_capacity]) |msg| try std.testing.expectEqualStrings("before", msg.output.bytes);
for (batch.items[Inbox.output_capacity..batch.len], 0..) |msg, pane| try std.testing.expectEqual(pane, msg.eof.pane.index());
}
+test "a search's rows posted into a full queue wait for room: a take lets them in, a cancel ends the wait and frees them" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var queue: Inbox = .{ .io = io, .gpa = gpa, .lsp_allocator = gpa };
+ defer queue.deinit();
+ queue.acceptReader(.at(0), 1);
+ const Post = struct {
+ fn run(q: *Inbox, posted: *?bool) void {
+ const rows = std.testing.allocator.dupe(u8, "a.txt:1:1-2 hit\n") catch return;
+ posted.* = Inbox.pushSearch(q, .{ .gen = 1, .rows = rows });
+ }
+ };
+ for ([_]bool{ false, true }) |cancel| {
+ // The loop busy: its queue full of output.
+ for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = .at(0), .gen = 1, .bytes = try gpa.dupe(u8, "busy") } });
+ var posted: ?bool = null;
+ var worker = try io.concurrent(Post.run, .{ &queue, &posted });
+ try PtyTests.waitBlocked(&queue);
+ if (cancel) worker.cancel(io) else {
+ var batch = queue.take();
+ for (batch.slice()) |msg| msg.deinit(gpa, gpa);
+ worker.await(io);
+ }
+ try std.testing.expectEqual(!cancel, posted.?);
+ var rest = queue.take();
+ defer for (rest.slice()) |msg| msg.deinit(gpa, gpa);
+ try std.testing.expectEqual(@as(usize, if (cancel) Inbox.output_capacity else 1), rest.len);
+ if (!cancel) try std.testing.expectEqualStrings("a.txt:1:1-2 hit\n", rest.items[0].search.rows);
+ try std.testing.expectEqual(@as(usize, 0), queue.waiting);
+ }
+}
+
+test "an Adopt's shells are taken in whatever output fills the queue" {
+ const gpa = std.testing.allocator;
+ var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa };
+ defer queue.deinit();
+ queue.acceptReader(.at(0), 1);
+ for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = .at(0), .gen = 1, .bytes = try gpa.dupe(u8, "flood") } });
+ var fds: [2]c_int = undefined;
+ if (libc.pipe(&fds) != 0) return error.PipeFailed;
+ defer _ = libc.close(fds[1]);
+ queue.push(.{ .adopted = .{ .pid = 42, .fd = fds[0] } });
+ queue.push(.{ .adopted = .{ .pid = 0, .fd = -1 } });
+ var batch = queue.take();
+ defer for (batch.slice()) |msg| msg.deinit(gpa, gpa);
+ try std.testing.expectEqual(Inbox.output_capacity + 2, batch.len);
+ try std.testing.expectEqual(@as(libc.pid_t, 42), batch.items[Inbox.output_capacity].adopted.pid);
+ try std.testing.expectEqual(fds[0], batch.items[Inbox.output_capacity].adopted.fd);
+ try std.testing.expectEqual(@as(libc.pid_t, 0), batch.items[Inbox.output_capacity + 1].adopted.pid);
+}
+
test "completions retain their arrival order across LSP and pipes" {
const gpa = std.testing.allocator;
var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = 2 };
diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig
index a3889d28..72028b04 100644
--- a/dev/tui/tui.zig
+++ b/dev/tui/tui.zig
@@ -97,15 +97,14 @@ fn kittyShmProbe(w: *std.Io.Writer, feed: *Feed) void {
w.flush() catch {};
}
-/// What the loop's queue carries: a terminal's input, a pane's output, a
-/// worker's answer, a wake.
+/// What the loop's queue carries: a terminal's input, a wake, what a
+/// replica client's reader hands over. A pane's output, a worker's answer
+/// and the daemon's notes are the session's queue's (Inbox, `takeQueue`).
const Msg = union(enum) {
nop,
/// The terminal's input ended: its end of file, a hangup. A session
/// a daemon keeps carries on detached; any other ends.
quit,
- /// A shell a dead session left, its pty's master (daemon.Note.adopted).
- adopted: struct { pid: posix.pid_t, fd: posix.fd_t },
/// A timed wait ran out: the core's next wake has come.
wake,
/// A SIGWINCH: a terminal changed size (Shell.winched).
@@ -120,14 +119,7 @@ const Msg = union(enum) {
paste: []const u8,
paste_start,
paste_end,
- pipe_done: selection_pipe.Response,
- /// A streaming search's rows (pardes.Stream).
- search_rows: pardes.Stream.Batch,
- /// A kind's job done on a worker (host_io.KindJob).
- kind_job: *host_io.KindJob,
fs_ready,
- /// A replica's connection, handed over by the daemon (Peers).
- replica: daemon.Joining,
/// A replica's reader posted: the step boundary takes it in.
replica_mail,
/// A replica client's: what the session streamed (replica.Link).
@@ -369,8 +361,6 @@ const TestReader = struct {
}
};
-const PipeTasks = selection_pipe.Tasks;
-
/// A watched child exited: wake the loop, which takes it (`takeExits`).
fn wakeForExit(ctx: ?*anyopaque) void {
const loop: *Loop = @ptrCast(@alignCast(ctx.?));
@@ -760,7 +750,7 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8,
var c = try Client.init(&tty, &start);
defer c.link.deinit(gpa);
// A client has no clients of its own, and spawns nothing: its pty
- // table an empty one over an empty queue.
+ // table an empty one over a queue that carries its draws alone.
var no_peers: replica.Peers = .{};
var no_inbox: host_io.Inbox = .{ .io = io, .gpa = gpa, .lsp_allocator = start.allocs.lsp };
defer no_inbox.deinit();
@@ -783,6 +773,8 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8,
.ptys = &no_ptys,
};
tty = .{ .sh = &sh, .screen = &screen, .loop = &loop, .joins = &start };
+ no_inbox.wake_fn = Shell.wakeForQueue;
+ no_inbox.wake_ctx = &sh;
pardes.Kind.drawer = .{ .ctx = &sh, .go = Shell.draw };
defer pardes.Kind.drawer = null;
@@ -1007,19 +999,8 @@ const Own = struct {
stopInput(io, &o.screen.thread);
pardes.Kind.drawer = null;
host_io.setExitWake(null, null);
- sh.pipe_tasks.cancelAll(io);
- sh.job_tasks.cancelAll(io);
- // Its worker may be waiting on the loop's queue for room.
- sh.core.stream.cancelTask();
while (loop.tryEvent() catch null) |ev| switch (ev) {
.paste => |b| gpa.free(@constCast(b)),
- .pipe_done => |response_value| {
- var response = response_value;
- response.deinit(gpa);
- },
- .search_rows => |b| b.deinit(gpa),
- .kind_job => |j| j.drop(),
- .adopted => |a| _ = libc.close(a.fd),
else => {},
};
o.screen.art.deinit(gpa);
@@ -1055,14 +1036,9 @@ const Own = struct {
if (o.sh.upgrade_asked) |pane| o.sh.upgradeNow(pane);
}
- pub fn note(o: *Own, n: daemon.Note) void {
- deliverNote(o.loop, n);
- }
-
pub fn restoring(o: *Own, nc: *pardes.Pardes) void {
const sh = &o.sh;
const io = sh.io;
- sh.pipe_tasks.cancelAll(io);
// One view, the terminal's (host_io.restoreCore).
const live = o.screen;
stopInput(io, &live.thread);
@@ -1091,24 +1067,6 @@ fn clearNativeImages(
kitty_handles.clearRetainingCapacity();
}
-/// The daemon's thread: what it says, onto the loop's queue.
-fn deliverNote(ctx: *anyopaque, note: daemon.Note) void {
- const loop: *Loop = @ptrCast(@alignCast(ctx));
- switch (note) {
- // A full queue wakes it anyway.
- .relinked => _ = loop.tryPostEvent(.nop) catch false,
- .adopted => |a| {
- for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| loop.postEvent(.{ .adopted = .{ .pid = pid, .fd = fd } }) catch {
- _ = libc.close(fd);
- };
- loop.postEvent(.{ .adopted = .{ .pid = 0, .fd = -1 } }) catch {};
- },
- .replica => |j| loop.postEvent(.{ .replica = j }) catch {
- _ = libc.close(j.fd);
- },
- }
-}
-
/// A replica reader's post: the session's wait ends, and its step
/// boundary takes the post in.
fn wakeForReplica(ctx: ?*anyopaque) void {
@@ -1146,8 +1104,6 @@ const Shell = struct {
batch: host_io.Inbox.Batch = .{},
batch_at: usize = 0,
queue_woken: std.atomic.Value(bool) = .init(false),
- pipe_tasks: PipeTasks = .{},
- job_tasks: PipeTasks = .{},
threads_ok: bool = false,
check_files: bool = false,
in_paste: bool = false,
@@ -1521,11 +1477,9 @@ const Shell = struct {
// is held for the next wait: `split`).
s.takeQueue();
// An exit's wake (a .nop) or output an exit waited behind: told
- // here, inside the step, so the frame after it shows it; not while
- // reads taken off the queue wait their steps (`takeQueue`): one of
- // them may be the command's own last output, which its exit would
- // be drawn above (CommandWatch.due cannot see it).
- if (s.batch_at == s.batch.len) s.takeExits();
+ // here, inside the step, so the frame after it shows it (a read
+ // still to be applied holds it back: Ptys.unapplied).
+ s.takeExits();
s.reloadWatched();
}
@@ -1595,10 +1549,7 @@ const Shell = struct {
return true;
}
// The terminal went: a session the daemon keeps carries on
- // without it, to be attached again. Gone before the first
- // frame, the reader that takes the daemon's `ok` (kept
- // waits on it) is not started yet: started here.
- daemon.watch(s.loop, deliverNote);
+ // without it, to be attached again.
if (daemon.kept()) {
if (!s.detached()) s.leaveTerminal();
return true;
@@ -1606,11 +1557,6 @@ const Shell = struct {
core.quit = true;
return true;
},
- .adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd),
- .replica => |j| {
- s.peers.handed(j.fd, j.view);
- s.input_seen = true;
- },
.replica_mail => if (s.peers.urgent.swap(false, .acq_rel)) {
s.input_seen = true;
},
@@ -1666,27 +1612,6 @@ const Shell = struct {
s.paste_buf.clearRetainingCapacity();
},
.fs_ready => {},
- .pipe_done => |response_value| {
- var response = response_value;
- core.update(.{ .pipe_resp = .{
- .id = response.id,
- .success = response.success,
- .outputs = response.outputs,
- .failure = response.failure,
- } });
- response.deinit(s.gpa);
- s.pipe_tasks.finish(s.io, response_value.id);
- },
- .search_rows => |b| {
- core.update(.{ .search = b });
- b.deinit(s.gpa);
- },
- .kind_job => |j| {
- s.job_tasks.finish(s.io, j.id);
- j.land(core);
- // A client's draw done: its frame is its own to draw again.
- if (s.client) |cl| cl.link.dirty = true;
- },
}
return false;
}
@@ -1895,7 +1820,8 @@ const Shell = struct {
}
/// What the session's queue holds: its ptys' output (`waitInput`
- /// paces it; the focused pane's is its echo) and their ends of file.
+ /// paces it; the focused pane's is its echo), their ends of file and
+ /// the workers' answers.
/// A read a step, as the terminal's own queue gave them: the frame
/// after one shows it before what came after it (a command's last line
/// before its exit scrolls it away), the rest kept for the next wait.
@@ -1923,8 +1849,14 @@ const Shell = struct {
},
.eof => |e| s.ptys.eof(s.core, e),
.files_changed => s.check_files = true,
- .lsp, .lsp_status => s.ptys.queue.landLsp(s.core, m),
- else => m.deinit(s.gpa, s.lsp_gpa),
+ .kind_job => {
+ s.ptys.queue.land(s.core, m);
+ // A client's draw done: its frame is its own to draw again.
+ if (s.client) |cl| cl.link.dirty = true;
+ },
+ .adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd),
+ .fs_ready => {},
+ else => s.ptys.queue.land(s.core, m),
}
}
}
@@ -1979,50 +1911,29 @@ const Shell = struct {
s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } });
return s.core.reportError(.at(s.core.view().active), "pipe", error.WorkersUnavailable);
}
- selection_pipe.start(s.io, s.gpa, s.core, &s.pipe_tasks, id, s, deliverPipe);
+ const q = s.ptys.queue;
+ selection_pipe.start(s.io, s.gpa, s.core, &q.pipe_tasks, id, q, host_io.Inbox.pushPipe);
}
fn search(ctx: ?*anyopaque, gen: u32) void {
const s = of(ctx);
- if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s, deliverSearch);
+ if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s.ptys.queue, host_io.Inbox.pushSearch);
pardes.Stream.runHere(s.core, gen, true);
}
/// A draw (api.draw) on a worker, as a job is.
fn draw(ctx: ?*anyopaque, j: *host_io.KindJob) bool {
const s = of(ctx);
- return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.job_tasks, j, s, struct {
- fn deliver(c: ?*anyopaque, k: *host_io.KindJob) void {
- of(c).loop.postEvent(.{ .kind_job = k }) catch k.drop();
- }
- }.deliver);
+ const q = s.ptys.queue;
+ return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &q.job_tasks, j, q, host_io.Inbox.pushJob);
}
fn job(ctx: ?*anyopaque, id: pardes.Pane.Id, serial: u32, token: u32) void {
const pane = id.index();
const s = of(ctx);
if (!s.threads_ok) return host_io.KindJob.runHere(s.core, pane, serial, token);
- host_io.KindJob.start(s.io, s.core, &s.job_tasks, pane, serial, token, s, struct {
- fn deliver(c: ?*anyopaque, j: *host_io.KindJob) void {
- of(c).loop.postEvent(.{ .kind_job = j }) catch j.drop();
- }
- }.deliver);
- }
-
- /// The loop's queue waits for room (a wait the worker's cancel ends).
- fn deliverSearch(ctx: ?*anyopaque, batch: pardes.Stream.Batch) bool {
- const s = of(ctx);
- s.loop.postEvent(.{ .search_rows = batch }) catch {
- batch.deinit(s.gpa);
- return false;
- };
- return true;
- }
-
- fn deliverPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void {
- const s = of(ctx);
- var owned = response;
- s.loop.postEvent(.{ .pipe_done = owned }) catch owned.deinit(s.gpa);
+ const q = s.ptys.queue;
+ host_io.KindJob.start(s.io, s.core, &q.job_tasks, pane, serial, token, q, host_io.Inbox.pushJob);
}
};
@@ -2459,6 +2370,22 @@ test "an ESC read by itself is the Escape key at once" {
t.vx.caps.kitty_keyboard = false;
}
+test "an Escape read with the click after it is the Escape key, then the click" {
+ var t: TestInput = undefined;
+ try t.init();
+ defer t.deinit();
+ // A busy session reads them in one: no terminal sends Alt on a mouse
+ // report as an ESC before it (it is in the report's button).
+ var reader: TestReader = .{ .parts = &.{"\x1b\x1b[<1;105;9M"} };
+ try readInput(&t.loop, &reader, &t.vx, &t.feed);
+ try std.testing.expectEqual(.winsize, std.meta.activeTag((try t.loop.tryEvent()).?));
+ const escape = (try t.loop.tryEvent()).?.key_press;
+ try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint);
+ try std.testing.expect(!escape.mods.alt);
+ try std.testing.expectEqual(.mouse, std.meta.activeTag((try t.loop.tryEvent()).?));
+ try std.testing.expect(try t.loop.tryEvent() == null);
+}
+
test "a frame's answer is taken wherever the reads cut it, and never typed" {
const gpa = std.testing.allocator;
var t: TestInput = undefined;
@@ -2755,7 +2682,7 @@ test "TTY worker setup failures finish matching LSP and pipe requests" {
try std.testing.expect(core.pipe.wait == null);
try std.testing.expectEqualStrings("abc", pane.file.?.content);
try std.testing.expect(queue.lsp_task == null);
- try std.testing.expectEqual(@as(usize, 0), shell.pipe_tasks.len);
+ try std.testing.expectEqual(@as(usize, 0), queue.pipe_tasks.len);
}
}
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/9p_io.zig b/runtime/9p_io.zig
index bcb0f81b..aaca377d 100644
--- a/runtime/9p_io.zig
+++ b/runtime/9p_io.zig
@@ -1896,7 +1896,9 @@ pub const Client = struct {
/// same open, as /pane/new answers its own open: a session's last
/// answer, from another client, can never be what comes back. `exec
/// 3<>file`. `more` (`pardes -`'s text after its /pager line) goes in
- /// Twrites at rising offsets, each answer giving the next its budget.
+ /// Twrites at rising offsets. Untimed once connected: the answer comes
+ /// when the session's step has run, however long a loaded machine
+ /// takes over 256 MiB, and a session that died ends the connection.
pub fn ask(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, request: []const u8, more: []const u8) ![]u8 {
if (comptime !supported) return error.Unsupported;
var names: [max_depth][]const u8 = undefined;
@@ -1905,6 +1907,7 @@ pub const Client = struct {
errdefer said = remote;
const s = try startSession(dial, path);
defer endSession(s, false);
+ s.deadline = std.math.maxInt(i64);
const fid = try walkTo(s, names[0..n], &remote);
_ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote);
var written: usize = 0;
@@ -1914,7 +1917,6 @@ pub const Client = struct {
const count = (try s.ask(.{ .write = .{ .fid = fid, .offset = written, .data = chunk } }, &remote)).write;
if (count == 0 or count > chunk.len) return Error.Botch;
written += count;
- s.deadline = nowMs() +| write_budget_ms;
}
var out: std.ArrayList(u8) = .empty;
errdefer out.deinit(gpa);
diff --git a/runtime/daemon.zig b/runtime/daemon.zig
index a2e890f9..9b566e60 100644
--- a/runtime/daemon.zig
+++ b/runtime/daemon.zig
@@ -290,10 +290,11 @@ fn hello(fd: c_int, k: Kind, pid: libc.pid_t, named: []const u8, detached: bool)
/// This session's registration (`register`), which forkShell and the hosts
/// tell of their ptys; -1 with none (no daemon, or PARDES_DAEMON=off).
pub var link: c_int = -1;
-/// The daemon said `ok` to the hello, and the link has not ended since;
-/// `gone` once it has ended for good (`readNotes`).
-var up = std.atomic.Value(bool).init(false);
-var gone = std.atomic.Value(bool).init(false);
+/// The hello's answer, as the reader took it (`readNotes`): `up`, the
+/// daemon said `ok` and the link has not ended since; `gone`, it has ended
+/// for good; `asked` until either (and while a new daemon is dialled).
+const Answer = enum(u32) { asked, up, gone };
+var answer = std.atomic.Value(Answer).init(.asked);
/// The session is ending (`quit`): its link's end is no daemon's death.
var quitting = std.atomic.Value(bool).init(false);
/// A new daemon took the hello since the last one died: the rest of what
@@ -306,6 +307,8 @@ var detached_now = std.atomic.Value(bool).init(false);
var name_buf: [128]u8 = undefined;
var name_len: usize = 0;
var reader: ?std.Thread = null;
+/// Where the reader hands each note (`notesTo`).
+var notes: ?struct { ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void } = null;
pub fn name() []const u8 {
return name_buf[0..name_len];
@@ -314,12 +317,22 @@ pub fn name() []const u8 {
/// Whether a daemon keeps this session: what Detach, and a terminal's end,
/// need, or the session would be left where nothing can attach to it. A
/// daemon just started answers the hello once it runs, so this waits for
-/// that answer (up to 2 s): never on a startup's path, only on those two.
+/// that answer, or the link's end, whenever they come: never on a startup's
+/// path, only on those two. The reader takes it: started here if the first
+/// frame has not started it yet.
pub fn kept() bool {
if (link < 0) return false;
- var waited: u32 = 0;
- while (!up.load(.acquire) and !gone.load(.acquire) and waited < 2000) : (waited += 1) sleepMs(1);
- return up.load(.acquire);
+ watch();
+ if (reader == null) return false;
+ const io = std.Io.Threaded.global_single_threaded.io();
+ while (answer.load(.acquire) == .asked) io.futexWaitUncancelable(Answer, &answer.raw, .asked);
+ return answer.load(.acquire) == .up;
+}
+
+/// The reader's word on the hello's answer, to `kept` waiting on it.
+fn settle(a: Answer) void {
+ answer.store(a, .release);
+ std.Io.Threaded.global_single_threaded.io().futexWake(Answer, &answer.raw, 1);
}
/// The name a session goes by: its 9P socket's (`--9p=`, `--detach=`), else
@@ -438,11 +451,18 @@ pub const Note = union(enum) {
pub const Joining = struct { fd: c_int, view: ?u8 = null };
-/// Hands every note the daemon sends on to `deliver`, on a thread of its
+/// Where every note the daemon sends goes, once `watch` has started the
+/// reader: the session's, before its first step.
+pub fn notesTo(ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void {
+ notes = .{ .ctx = ctx, .deliver = deliver };
+}
+
+/// Hands every note the daemon sends on (`notesTo`), on a thread of its
/// own, until the link ends (`quit`). Called each loop: started once.
-pub fn watch(ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void {
+pub fn watch() void {
+ const n = notes orelse return;
if (link < 0 or reader != null) return;
- reader = std.Thread.spawn(.{}, readNotes, .{ link, ctx, deliver }) catch null;
+ reader = std.Thread.spawn(.{}, readNotes, .{ link, n.ctx, n.deliver }) catch null;
}
fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void {
@@ -452,7 +472,7 @@ fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, no
var words = std.mem.tokenizeScalar(u8, got.words, ' ');
const verb = words.next() orelse "";
if (std.meta.stringToEnum(enum { ok, replica, adopted }, verb)) |v| switch (v) {
- .ok => up.store(true, .release),
+ .ok => settle(.up),
.replica => {
const view = std.fmt.parseInt(u8, words.next() orelse "", 10) catch null;
if (got.nfds >= 1) deliver(ctx, .{ .replica = .{ .fd = got.fds[0], .view = view } });
@@ -482,12 +502,12 @@ fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, no
// link's end is what wakes this, never a timer. One that never took
// it (another build's daemon), or the session's own end, is not:
// an end begun while it dialled finds the new link (`quit`).
- if (!up.swap(false, .acq_rel) or quitting.load(.acquire) or !redial(fd) or quitting.load(.acquire)) break;
+ if (answer.swap(.asked, .acq_rel) != .up or quitting.load(.acquire) or !redial(fd) or quitting.load(.acquire)) break;
retell.store(true, .release);
deliver(ctx, .relinked);
}
// Not kept, until the session's end.
- gone.store(true, .release);
+ settle(.gone);
}
/// A new connection in the place of `fd`, the link (its number kept, so
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 bbe73a87..a21eb83f 100644
--- a/runtime/main.zig
+++ b/runtime/main.zig
@@ -1885,8 +1885,11 @@ fn attachClient(init: std.process.Init, opts: pardes.Options, where: []const u8,
Ssh.child = pid;
Ssh.path = here;
_ = atexit(Ssh.end);
+ // Its file is there a moment before ssh listens on it: until a
+ // connect answers.
var waited: u32 = 0;
- while (std.meta.isError(std.Io.Dir.cwd().access(io, here, .{}))) : (waited += 1) {
+ const probe = while (true) : (waited += 1) {
+ if (cloud9.transport.connectFd(.{ .unix = here }, cloud9.transport.nowMs() + 100)) |fd| break fd else |_| {}
var status: c_int = 0;
if (std.c.waitpid(pid, &status, std.c.W.NOHANG) == pid) {
Ssh.child = 0;
@@ -1895,7 +1898,8 @@ fn attachClient(init: std.process.Init, opts: pardes.Options, where: []const u8,
if (waited > 3000) die(io, "--attach: ssh to {s} set up no forward in 30 s", .{where});
const ts: std.c.timespec = .{ .sec = 0, .nsec = 10 * std.time.ns_per_ms };
_ = std.c.nanosleep(&ts, null);
- }
+ };
+ _ = std.c.close(probe);
clientOf(init, opts, here, name, true) catch |err| die(io, "--attach: {t}", .{err});
std.process.exit(0);
}
diff --git a/runtime/session.zig b/runtime/session.zig
index 0bd38c86..9c8446e3 100644
--- a/runtime/session.zig
+++ b/runtime/session.zig
@@ -6,10 +6,10 @@
//! posts, `Inbox`), its ptys (`Ptys`) and the files it watches
//! (`file_watch.Watches`): a step, its unit to the clients and theirs
//! taken in, an Upgrade or a Restore between steps; and the order its
-//! parts end in. Its other devices (the LSP's and the pipes' and addons'
-//! jobs, the session's own input) are still its frontend's (each `Shell`);
-//! the language servers' answers come through its queue (`Inbox.startLsp`).
-//! What a frontend does is:
+//! parts end in. Its workers (a language server's query, the pipes, the
+//! addons' jobs and draws, a search) answer through its queue, which holds
+//! their tasks and ends them (`Inbox.land`, `Inbox.deinit`); the session's
+//! own input is its frontend's (each `Shell`). What a frontend does is:
//!
//! - `options(o)`: before the core: what it gives the core it starts (a
//! window's size, for a dump's layout).
@@ -25,8 +25,6 @@
//! session's first wait (`l.watch`).
//! - `sent()`: after each step's unit went to the clients.
//! - `upgradeAsked()`: an Upgrade asked in the step, done (it execs).
-//! - `note(n)`: what the daemon says (an adopted shell, a client's
-//! connection, a new daemon's hello taken), onto its queue.
//! - `restoring(nc)`, `restored(l)`: a Restore's new core, before it
//! replaces the old one (its devices let go, what it is told of the
//! frontend) and after (its own view of it again).
@@ -75,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: {
@@ -90,6 +89,8 @@ pub fn Loop(comptime Frontend: type) type {
l.peers = .{ .gpa = l.gpa, .io = l.io, .name = daemon.name() };
l.inbox = .{ .io = l.io, .gpa = l.gpa, .lsp_allocator = l.allocs.lsp };
defer l.inbox.deinit();
+ // A search's worker may be waiting on the queue for room.
+ defer l.core.stream.cancelTask();
// The language servers' status lines, from the first effects on.
pardes.lsp.setStatusSink(&l.inbox, host_io.Inbox.lspStatus);
defer pardes.lsp.setStatusSink(null, null);
@@ -100,6 +101,7 @@ pub fn Loop(comptime Frontend: type) type {
l.host = try fe.open(&l);
defer fe.close(&l);
+ daemon.notesTo(&l, note);
defer l.peers.deinit();
// Before the core goes: each client sees its link end.
defer l.peers.dropAll(l.core);
@@ -156,17 +158,28 @@ pub fn Loop(comptime Frontend: type) type {
while (l.core.nextEffect()) |e| l.core.perform(e);
}
- /// What the daemon says, onto the frontend's queue (once: its
+ /// What the daemon says, onto the session's queue (once: its
/// reader is started by the first call); and a daemon started
/// since the last one died told the shells' masters it held.
pub fn watch(l: *L) void {
if (daemon.relinked()) l.ptys.tellDaemon();
- daemon.watch(l.fe, note);
+ daemon.watch();
}
+ /// The daemon's thread: an adopted shell onto the queue (taken
+ /// in the frontend's wait), a client's connection to `Peers`
+ /// (joined at the next step boundary), a new daemon's hello taken
+ /// a wake (`watch` tells it the rest).
fn note(ctx: *anyopaque, n: daemon.Note) void {
- const fe: *Frontend = @ptrCast(@alignCast(ctx));
- fe.note(n);
+ const l: *L = @ptrCast(@alignCast(ctx));
+ switch (n) {
+ .relinked => l.inbox.wake(),
+ .adopted => |a| {
+ for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| l.inbox.push(.{ .adopted = .{ .pid = pid, .fd = fd } });
+ l.inbox.push(.{ .adopted = .{ .pid = 0, .fd = -1 } });
+ },
+ .replica => |j| l.peers.handed(j.fd, j.view),
+ }
}
/// A Restore: the core its dump makes replaces this one, its clients
@@ -175,7 +188,9 @@ pub fn Loop(comptime Frontend: type) type {
fn restore(l: *L, path: []const u8) void {
const nc = host_io.restoreCore(l.gpa, l.core, path, &l.peers, l.watches.fd, &l.watches.table) orelse return;
l.fe.restoring(nc);
- // An answer to the old core's query is turned away.
+ // The old core's pipes end, and an answer to its query is
+ // turned away.
+ l.inbox.pipe_tasks.cancelAll(l.io);
l.inbox.discardCompletions();
l.ptys.stop();
nc.host = l.host;
diff --git a/test/daemon.py b/test/daemon.py
index 26508a0b..b28d16ea 100644
--- a/test/daemon.py
+++ b/test/daemon.py
@@ -30,7 +30,8 @@ private HOME and runtime directory:
python3 -B test/daemon.py --pair <pardes>
PARDES_PAIR: a terminal's session and its first client
python3 -B test/daemon.py --relink <pardes>
- the daemon killed: its sessions register again with the next
+ the daemon killed: its sessions register again with the next; and
+ one stopped: an Adopt waits for its answer to the hello
python3 -B test/daemon.py --far <pardes>
the far clients and their blob cache alone, and a file by its hash
python3 -B test/daemon.py --games <pardes> <lib> [seconds]
@@ -269,8 +270,11 @@ class Replica:
is read, whole. A daemon of another replica protocol (an older
build's, across an Upgrade) is dialled again in its own."""
name = session.encode()
- self.send(0x01, struct.pack('<HQH', wire or self.WIRE, build, len(name)) + name + b'\xff')
- self.send(0x06, b'\x00')
+ # Its first word (not far) in the same write, as a client's join
+ # sends it (core/replica.zig joinOn): a refused hello's connection
+ # is closed, and a second write after it would meet that.
+ hello = struct.pack('<HQH', wire or self.WIRE, build, len(name)) + name + b'\xff'
+ self.s.sendall(struct.pack('<BI', 0x01, len(hello)) + hello + struct.pack('<BIB', 0x06, 1, 0))
tag, body = self.read()
if tag == 0x01:
pid, n = struct.unpack_from('<IH', body)
@@ -972,6 +976,78 @@ def relink(binary):
shutil.rmtree(root, ignore_errors=True)
+def answer_late(binary):
+ """A session's Adopt asked at once, while its daemon has not answered
+ its hello (stopped 3 s, as a loaded machine can keep it), and before
+ the session's reader of the daemon has run: answered when the daemon
+ answers, never refused on a clock (daemon.zig `kept`)."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='ra-', 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')
+ started = []
+ terms = []
+ wake = None
+ try:
+ term = Term()
+ terms.append(term)
+ stub = term.spawn([binary, '--tty', '--9p=one'], env)
+ started.append(stub.pid)
+ wait_for('the first session', (root / 'pardes-9p-one.sock').exists)
+ one = Client(root / 'pardes-9p-one.sock')
+ session = int(dict(line.split(maxsplit=1) for line in one.read('/status').decode().splitlines())['pid'])
+ started.append(session)
+ shell_pid = int(run(one, terminals(one)[0], b'echo $$\n').split(b'\n')[1])
+ started.append(shell_pid)
+ daemon = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']][0]
+ started.append(daemon)
+ wait_for('its shell listed', lambda: f'shell {shell_pid}' in subprocess.run(
+ [binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode())
+ os.kill(session, signal.SIGKILL)
+ one.socket.close()
+ wait_for('the killed session gone', lambda: not alive(session))
+ os.kill(daemon, signal.SIGSTOP)
+ wake = threading.Timer(3, lambda: os.kill(daemon, signal.SIGCONT))
+ wake.start()
+ term = Term()
+ terms.append(term)
+ stub = term.spawn([binary, '--tty', '--9p=two'], env)
+ started.append(stub.pid)
+ wait_for('the next session', (root / 'pardes-9p-two.sock').exists)
+ two = Client(root / 'pardes-9p-two.sock', timeout=30)
+ started.append(int(dict(line.split(maxsplit=1) for line in two.read('/status').decode().splitlines())['pid']))
+ before = set(terminals(two))
+ asked = time.monotonic()
+ two.write(f'/pane/{min(before)}/exec', b'Adopt\n')
+ took = time.monotonic() - asked
+ pane = wait_for('the adopted pane', lambda: set(terminals(two)) - before).pop()
+ assert run(two, pane, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode()
+ print(f'answer late: an Adopt asked while the daemon was stopped waited {took:.1f} s for its answer, '
+ f'and shell {shell_pid} was adopted')
+ exit_session(two, pane)
+ two.socket.close()
+ wait_for('the shells hung up', lambda: not alive(shell_pid))
+ wait_for('the daemon gone once idle', lambda: not alive(daemon), timeout=5)
+ finally:
+ if wake:
+ wake.cancel()
+ for t in terms:
+ try:
+ t.close()
+ except OSError:
+ pass
+ for pid in started + processes(root):
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
class Window:
"""A pardes-gui in test mode, its window offscreen and hidden, its keys
written to its stdin (the test feed: Escape as `CSI 27 u`, which a
@@ -1419,12 +1495,13 @@ def far(binary):
f_join = joins(root / 'f.stats')[0]
assert f_join['from_disk'] > 0 and cached(cache) <= (1 << 20) + (64 << 10), (f_join, cached(cache))
far_joins(root / 'pardes-replica.sock', 'files', binary, 200)
- # Through ssh (a stand-in forwarding as `ssh -L` does): a client
- # refused and one detached each end their ssh and its socket (one
- # refused left both, 2026-10-30).
+ # Through ssh (a stand-in forwarding as `ssh -L` does, its socket
+ # bound 0.5 s before it listens: the client dials until it answers):
+ # a client refused and one detached each end their ssh and its
+ # socket (one refused left both, 2026-10-30).
fake = root / 'ssh'
fake.write_text('#!/bin/sh\nwhile [ $# -gt 0 ]; do case $1 in -L) fwd=$2; shift;; esac; shift; done\n'
- f'exec {sys.executable} -B {Path(__file__).parent / "delay_relay.py"} "${{fwd%%:*}}" "${{fwd#*:}}" --delay 0\n')
+ f'exec {sys.executable} -B {Path(__file__).parent / "delay_relay.py"} "${{fwd%%:*}}" "${{fwd#*:}}" --delay 0 --bound 500\n')
fake.chmod(0o755)
senv = dict(env, PARDES_SSH=str(fake), PARDES_REMOTE_RUNTIME=str(root), TMPDIR=str(root))
@@ -1508,7 +1585,10 @@ def by_hash(binary):
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')
+ # Each reply waited for as long as the opens it answers take: the
+ # 17 MiB file's Look took 1.6-6.6 s in a Debug build at a load of
+ # 35 (ninep.py's 5 s is a reply's whole wait).
+ nine = Client(root / 'pardes-9p-files.sock', timeout=60)
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'}
@@ -1661,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
@@ -1762,6 +1974,7 @@ def main(binary, cycles):
pair_rows(binary)
manage(binary)
relink(binary)
+ answer_late(binary)
shell = terminals(client)[0]
shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1])
started.append(shell_pid)
@@ -2436,10 +2649,15 @@ def upgrades(old, new):
sock = root / 'pardes-9p-again.sock'
wait_for('the next session', sock.exists)
client = Client(sock)
- started.append(int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid']))
- # Its reader of the daemon starts after its first frame: an Adopt
- # before that waits for an `ok` nobody reads, and is refused.
+ again = int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid'])
+ started.append(again)
+ # A build before daemon.zig's `kept` waited for the hello's answer
+ # (the new-to-old run) refused an Adopt before its reader of the
+ # daemon ran (after its first frame), or within 2 s of a slow `ok`:
+ # it is asked once the daemon lists it (answer_late tests the wait).
wait_for('the next session\'s first frame', lambda: b'\x1b[?1049h' in term.text())
+ wait_for('the next session listed by the daemon', lambda: f'session again {again} ' in subprocess.run(
+ [str(binary), '--ps'], env=env, capture_output=True, timeout=30).stdout.decode())
before = set(terminals(client))
client.write(f'/pane/{min(before)}/exec', b'Adopt\n')
pane = wait_for('the adopted pane', lambda: set(terminals(client)) - before).pop()
@@ -2691,11 +2909,17 @@ if __name__ == '__main__':
pair_rows(sys.argv[2])
elif sys.argv[1:2] == ['--relink']:
relink(sys.argv[2])
+ answer_late(sys.argv[2])
elif sys.argv[1:2] == ['--games']:
games(sys.argv[2], sys.argv[3], float(sys.argv[4]) if len(sys.argv) > 4 else 10)
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])
diff --git a/test/delay_relay.py b/test/delay_relay.py
index c600a3aa..b0d48e38 100644
--- a/test/delay_relay.py
+++ b/test/delay_relay.py
@@ -8,7 +8,7 @@ the ones before it have crossed at that rate, then waits out the delay. An
optional jitter adds up to that many ms more to each chunk's delay, at
random, its order kept (a chunk never overtakes the one before it).
- python3 -B test/delay_relay.py LISTEN TARGET --delay MS [--rate MB/s] [--jitter MS]
+ python3 -B test/delay_relay.py LISTEN TARGET --delay MS [--rate MB/s] [--jitter MS] [--bound MS]
python3 -B test/delay_relay.py --self-check
An address is a path (a Unix socket) or host:port (TCP). The one-way
@@ -46,7 +46,9 @@ def dial(address):
return s
-def listen(address):
+def listen(address, bound=0.0):
+ """Bound, then listening `bound` s later (an ssh -L's socket file is
+ there a moment before it answers)."""
family, addr = parse(address)
s = socket.socket(family)
if family == socket.AF_UNIX:
@@ -57,6 +59,7 @@ def listen(address):
else:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
+ time.sleep(bound)
s.listen(64)
return s
@@ -260,8 +263,9 @@ def main():
ap.add_argument('--delay', type=float, required=True, help='one-way delay, ms')
ap.add_argument('--rate', type=float, help='a bandwidth cap, MB/s')
ap.add_argument('--jitter', type=float, default=0, help='up to this many ms more a chunk, at random')
+ ap.add_argument('--bound', type=float, default=0, help='ms between the bind and the listen')
a = ap.parse_args()
- listener = listen(a.listen)
+ listener = listen(a.listen, a.bound / 1000)
print(f'relaying {a.listen} -> {a.target}, {a.delay} ms each way'
+ (f', {a.rate} MB/s' if a.rate else '') + (f', jitter {a.jitter} ms' if a.jitter else ''), flush=True)
try:
diff --git a/test/e2e_harness.zig b/test/e2e_harness.zig
index f7d65b03..26e942e7 100644
--- a/test/e2e_harness.zig
+++ b/test/e2e_harness.zig
@@ -149,9 +149,25 @@ pub const Harness = struct {
return true;
}
+ /// The app ended as closing its terminal ends it: the master closed (its
+ /// hangup), the app given `end_ms` to end, SIGKILLed only after, and
+ /// reaped: what it ends at its own end (its shells, its language servers'
+ /// groups) does not outlive the case.
pub fn deinit(self: *Harness) void {
- posix.kill(self.pid, posix.SIG.KILL) catch {};
_ = libc.close(self.master);
+ const end_ms = 5000;
+ const until = nowMs() + end_ms;
+ var status: c_int = 0;
+ var none: [0]posix.pollfd = .{};
+ while (libc.waitpid(self.pid, &status, libc.W.NOHANG) == 0) {
+ if (nowMs() < until) {
+ _ = posix.poll(&none, 5) catch 0;
+ continue;
+ }
+ posix.kill(self.pid, posix.SIG.KILL) catch {};
+ _ = libc.waitpid(self.pid, &status, 0);
+ break;
+ }
self.stream.deinit();
self.gpa.destroy(self.raw);
self.term.deinit(self.gpa);
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/process/terminals.zig b/test/process/terminals.zig
index 24772ced..d9c3bcca 100644
--- a/test/process/terminals.zig
+++ b/test/process/terminals.zig
@@ -262,7 +262,9 @@ fn rawKey(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
/// thousand: nothing printed is nothing kept), then a probe typed and
/// taken back with ^U.
fn drive(gpa: std.mem.Allocator, exe: [:0]const u8, script: []const u8, key: ?u8, rows: usize) !void {
- var d = try process.Detached.start(gpa, exe, "agent", .{});
+ // No builtin announces itself: Term's name would linger on the screen
+ // (MessageLinger, 800 ms) and go between `before` and ^U's answer.
+ var d = try process.Detached.start(gpa, exe, "agent", .{ .init = "Verbose off\n" });
defer d.deinit();
const f = &d.files;
try d.put("command.sh", f.at("exec /bin/sh -c '{s}'\n", .{script}));
@@ -300,7 +302,10 @@ fn drive(gpa: std.mem.Allocator, exe: [:0]const u8, script: []const u8, key: ?u8
try f.write(data, "\x15");
const back_by = eh.nowMs() + 10_000;
while (!std.mem.eql(u8, try f.screen(), before)) {
- if (eh.nowMs() > back_by) return error.ScreenNotRestored;
+ if (eh.nowMs() > back_by) {
+ std.debug.print("before:\n{s}\nafter ^U:\n{s}\n", .{ before, try f.screen() });
+ return error.ScreenNotRestored;
+ }
sleepMs(10);
}
}
diff --git a/test/process/tty_terminals.zig b/test/process/tty_terminals.zig
index d5540818..dfb027e2 100644
--- a/test/process/tty_terminals.zig
+++ b/test/process/tty_terminals.zig
@@ -844,7 +844,9 @@ fn exec_bigdrag(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
try t.drag("middle", "150", 31);
try t.drag("middle", "198", 59);
try t.release("middle", "198", 59);
- try t.stable(500, 8000);
+ // Bash fails each swept chunk as a command, one by one: under load
+ // that runs well past 8 s, so the quiet is waited for once, with the
+ // cap the sweep's other waits have.
try t.stable(800, 30000);
// still alive: type and execute a marker command
try t.press("left", "105", 41);
diff --git a/test/replicas.zig b/test/replicas.zig
index e07949fb..6a6d43b4 100644
--- a/test/replicas.zig
+++ b/test/replicas.zig
@@ -1120,7 +1120,6 @@ const Soak = struct {
}
pub fn upgradeAsked(_: *Soak) void {}
- pub fn note(_: *Soak, _: anytype) void {}
pub fn restoring(_: *Soak, _: *pardes.Pardes) void {}
pub fn restored(_: *Soak, _: *SessionLoop) void {}
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);