diff options
Diffstat (limited to 'core')
| -rw-r--r-- | core/CHANGELOG.md | 17 | ||||
| -rw-r--r-- | core/Core.zig | 37 | ||||
| -rw-r--r-- | core/File.zig | 15 | ||||
| -rw-r--r-- | core/Handover.zig | 14 | ||||
| -rw-r--r-- | core/Names.zig | 20 | ||||
| -rw-r--r-- | core/Pipe.zig | 36 | ||||
| -rw-r--r-- | core/Places.zig | 21 | ||||
| -rw-r--r-- | core/Plumb.zig | 4 | ||||
| -rw-r--r-- | core/Query.zig | 20 | ||||
| -rw-r--r-- | core/Store.zig | 8 | ||||
| -rw-r--r-- | core/Stream.zig | 2 | ||||
| -rw-r--r-- | core/Turn.zig | 10 | ||||
| -rw-r--r-- | core/body_layer.zig | 5 | ||||
| -rw-r--r-- | core/builtins.zig | 4 | ||||
| -rw-r--r-- | core/colors.zig | 7 | ||||
| -rw-r--r-- | core/dump.zig | 12 | ||||
| -rw-r--r-- | core/echo.zig | 2 | ||||
| -rw-r--r-- | core/edit_cmd.zig | 4 | ||||
| -rw-r--r-- | core/exec.zig | 2 | ||||
| -rw-r--r-- | core/fs.zig | 78 | ||||
| -rw-r--r-- | core/layout.zig | 90 | ||||
| -rw-r--r-- | core/lsp/Ask.zig | 39 | ||||
| -rw-r--r-- | core/ninep/events.zig | 4 | ||||
| -rw-r--r-- | core/ninep/pane.zig | 22 | ||||
| -rw-r--r-- | core/ninep/pty.zig | 1 | ||||
| -rw-r--r-- | core/ninep/tree.zig | 94 | ||||
| -rw-r--r-- | core/panes.zig | 13 | ||||
| -rw-r--r-- | core/replica.zig | 570 | ||||
| -rw-r--r-- | core/rollback.zig | 16 | ||||
| -rw-r--r-- | core/syntax.zig | 47 | ||||
| -rw-r--r-- | core/tape.zig | 128 | ||||
| -rw-r--r-- | core/walk.zig | 6 |
32 files changed, 1017 insertions, 331 deletions
diff --git a/core/CHANGELOG.md b/core/CHANGELOG.md index faa02ade..49bc105f 100644 --- a/core/CHANGELOG.md +++ b/core/CHANGELOG.md @@ -2,6 +2,17 @@ ## Unreleased +- An experiment, behind `PARDES_PAIR=1` until it is the default: `pardes + FILE` in a terminal and `pardes-gui FILE` fork a session with no + frontend of its own and are its first client. Such a session is kept + (started with `new --detach`, or a Detach typed in any client since) or + not: closing a client's window or terminal, or a TERM to it, ends a + session not kept when that was its last client; a client killed outright + leaves it running. `pardes ps` says `(tty, kept)` or `(tty)` of it. + Without the variable nothing changes, but a terminal client (`pardes + attach`) ended by a TERM now says goodbye and exits 0, its terminal put + back, where it died of the signal. + - `pardes new --detach[=NAME]` returns once the session runs (registered and listening), printing its name, exit 0; the session runs on in a session of its own. `pardes --detach=NAME` without `new` is still the @@ -238,9 +249,9 @@ editor has them, for a program that draws source text itself. Every dependency but tree-sitter's runtime is lazy in the manifest, so such a package fetches the runtime and the grammars of its `grammars` set - and nothing else; `zig build lib-test`, which `unit-test` runs, builds - one (`test/consumer`). The markdown grammar is pinned by its commit: its - branch has moved, and a fresh checkout could not fetch it. + and nothing else; `zig build consumer-test`, which `unit-test` runs, + builds one (`test/consumer`). The markdown grammar is pinned by its + commit: its branch has moved, and a fresh checkout could not fetch it. - Enter, `o` and `O` give the new line helix's indent where the file's grammar has an indent query (bash, C, C#, C++, Clojure, CSS, Elixir, diff --git a/core/Core.zig b/core/Core.zig index de911469..d2cfadfc 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -303,7 +303,7 @@ theme_file_path: config.Settings.Text(limits.host_path_cap) = .{}, /// what a failed ThemeFile goes back to (colors.revertThemeFile). theme_file_loaded: config.Settings.Text(limits.host_path_cap) = .{}, theme_file_generation: u32 = 0, -theme_file_pane: u8 = 0, +theme_file_pane: Pane.Id = .at(0), chrome: colors.ChromeTheme = colors.initial_chrome, /// Every drawn frame's timings (FrameStats: the Debug box, PARDES_FRAMES): /// its runner's (`Options.frames`), which its frontend writes as it draws @@ -472,11 +472,11 @@ pub const replica = .{ "tape", }, .derived = .{ "shell_rows", "diff_output", "locations_cache", "retired_panes", "tty_filter_palette", "body_chrome" }, - // The host's handles, the 9P server's fids and log, the state file - // every session of the user shares (and Recent read from it), this - // session's closed panes, and the files of a host with no file - // system of its own. - .authority = .{ "host", "fs", "store", "recent", "db", "fallback" }, + // The host's handles, the state file every session of the user + // shares (and Recent read from it), this session's closed panes, and + // the files of a host with no file system of its own. (The 9P + // server's own part of `fs` says so in fs.Namespace.) + .authority = .{ "host", "store", "recent", "db", "fallback" }, .len = .{ .{ "look_src", "n_look_src" }, .{ "session_dir", "session_dir_len" }, .{ "session_home", "session_home_len" }, .{ "session_shell", "session_shell_len" } }, }; @@ -531,9 +531,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, @@ -564,10 +564,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; @@ -824,8 +823,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. @@ -1581,12 +1580,6 @@ fn stepInner(p: *Pardes) void { /// local socket costs microseconds and not a vsync. pub const serveFs = pardes.tape.taped(serveFsInner); fn serveFsInner(p: *Pardes, req: ctlfs.Req) ctlfs.Reply { - // The held write of an Edit whose commands run, asked again by a - // retry of its park: still waiting, or its answer, never run twice. - if (p.fs.edit_hold) |*h| if (h.names(req)) { - if (!h.done) return .{ .tag = req.tag, .status = .again }; - return filesystem.EditHold.answer(&p.fs); - }; defer pardes.panes.File.syncTwins(p); if (!ctlfs.changesPane(p, req)) return ctlfs.handle(p, req); // An address, a limit or the mark flag is nothing drawn: a script's @@ -2293,6 +2286,10 @@ pub const Options = struct { /// first effects (runtime/session.zig); a client's session is on it, /// its first join made there with no hello (replica.join). pair: ?c_int = null, + /// A client exec'd at an Upgrade (runtime/client.zig `execAgain`, + /// PARDES_JOIN_VIEW): the view it had, which the session kept for it + /// (views.away), joined again for as a rejoin dials (replica.join). + join_view: ?u8 = null, mounts: []const filesystem.Mount = &.{}, config_dir: ?[]const u8 = null, /// Where what outlives the session is kept (Db.zig): the user's state @@ -2308,7 +2305,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..8a8c05de 100644 --- a/core/File.zig +++ b/core/File.zig @@ -2312,6 +2312,7 @@ test "a pager's text is a diff when it holds a diff header or a unified hunk" { } test "a long line is painted only around the caret" { + if (comptime !syntax.full_grammars) return error.SkipZigTest; // JSON's const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); const line = try std.testing.allocator.alloc(u8, 600 << 10); @@ -2356,6 +2357,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/Handover.zig b/core/Handover.zig index dde31f8b..6f7340b2 100644 --- a/core/Handover.zig +++ b/core/Handover.zig @@ -33,7 +33,7 @@ const MAX_PANES = pardes.MAX_PANES; /// libc: fork and exec of a window, and file calls in the cancelable carry task that must not see its cancel (its defer's unlink). const libc = std.c; -/// What a grip carries out of its window: one pane with the panes attached +/// What a grip carries out of its window: one pane with the panes docked /// to it, or a whole column. pub const Kind = enum { pane, column }; @@ -46,7 +46,7 @@ const Carried = struct { /// Each pane as dump.savePane makes it, top to bottom. panes: []const []const u8, weights: []const f32, - /// Which of them each one is attached to (layout.zig, "Attached panes"). + /// Which of them each one is docked to (layout.zig, "Docked panes"). owners: []const ?u32, }; pub const carried_magic = "pardes-carried\n"; @@ -84,8 +84,8 @@ pub fn deinit(h: *Handover, gpa: std.mem.Allocator) void { h.bytes = null; } -/// Pane slot `at` (with what is attached to it, or alone when it is itself -/// an attachment), or column `at`, released past the window's edge: dumped, +/// Pane slot `at` (with what is docked to it, or alone when it is itself +/// a docked pane), or column `at`, released past the window's edge: dumped, /// and the host asked to carry it. Only text panes travel: a terminal's /// shell is this process's child and would die with the pane here. pub fn begin(h: *Handover, p: *Pardes, carried: Kind, at: usize) void { @@ -273,7 +273,7 @@ pub fn adopt(p: *Pardes, bytes: []const u8) !usize { n += 1; if (pane.file == null) return error.NotText; } - // An attachment names its owner by its place in the dump. + // A docked pane names its owner by its place in the dump. for (st.owners, 0..) |owner, k| { const at = owner orelse continue; if (at >= n) continue; @@ -299,7 +299,7 @@ pub fn adopt(p: *Pardes, bytes: []const u8) !usize { for (0..p.view().ncol) |c| for (p.view().cols[c].panes[0..p.view().cols[c].n]) |id| { heights[id] = p.view().rects[id].h; }; - // The group under the pointer (a pane with what is attached to it): the + // The group under the pointer (a pane with what is docked to it): the // new panes go under all of it, out of its owner's rows. var after: usize = p.view().cols[tc].n; var root: ?usize = null; @@ -315,7 +315,7 @@ pub fn adopt(p: *Pardes, bytes: []const u8) !usize { } if (root) |owner| { const r = p.view().rects[owner]; - // Down to the pointer's row; let go over one of its attachments, + // Down to the pointer's row; let go over one of its docked panes, // half of it. const keeps = @max(layout.minRows(p, owner), if (y >= r.y and y < r.y + r.h) (y - r.y) + 1 else r.h / 2); const give = heights[owner] -| keeps; 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/Pipe.zig b/core/Pipe.zig index cf61b78f..012ce689 100644 --- a/core/Pipe.zig +++ b/core/Pipe.zig @@ -52,7 +52,7 @@ pub const PendingPipe = struct { /// The digest's walk (core/walk.zig) of the ranges, as far as they go. pub const replica = .{ .len = .{.{ "ranges", "nranges" }} }; id: u32, - pane: usize, + pane: Pane.Id, serial: u32, /// The text piped: the pane's body or tag, or a header (`column` /// names which). @@ -133,7 +133,7 @@ pub fn submitPipe(p: *Pardes, id: usize) void { if (p.pipe.wait) |*old| old.deinit(); p.pipe.wait = .{ .id = p.pipe.seq, - .pane = id, + .pane = .at(id), .serial = pane.serial, .what = t.what, .column = p.headerColumn() orelse 0, @@ -166,16 +166,16 @@ fn pipeFailed(p: *Pardes, wait: *const PendingPipe, failure: ?selection_pipe.Fai var out: std.Io.Writer.Allocating = .init(p.gpa); defer out.deinit(); const w = &out.writer; - w.print("| {s}\n\n", .{wait.command}) catch |err| return p.reportError(.at(wait.pane), "pipe", err); + w.print("| {s}\n\n", .{wait.command}) catch |err| return p.reportError(wait.pane, "pipe", err); if (wait.inputs.len > 1) if (failure) |fail| - w.print("selection {d} of {d}: ", .{ fail.index + 1, wait.inputs.len }) catch |err| return p.reportError(.at(wait.pane), "pipe", err); - writeFailure(w, failure) catch |err| return p.reportError(.at(wait.pane), "pipe", err); - const content = out.toOwnedSlice() catch |err| return p.reportError(.at(wait.pane), "pipe", err); + w.print("selection {d} of {d}: ", .{ fail.index + 1, wait.inputs.len }) catch |err| return p.reportError(wait.pane, "pipe", err); + writeFailure(w, failure) catch |err| return p.reportError(wait.pane, "pipe", err); + const content = out.toOwnedSlice() catch |err| return p.reportError(wait.pane, "pipe", err); const was = p.view().active; - panes.Output.openErrors(p, wait.pane, content) catch |err| { + panes.Output.openErrors(p, wait.pane.index(), content) catch |err| { p.gpa.free(content); // Nowhere to put the report is itself worth one line. - p.reportError(.at(wait.pane), "pipe", err); + p.reportError(wait.pane, "pipe", err); return; }; if (p.panes[was] != null) p.view().active = was; @@ -250,7 +250,7 @@ pub fn pipeResponse( if (!success or outputs.len != wait.inputs.len) return pipeFailed(p, &wait, failure); - const pane = p.panes[wait.pane] orelse return; + const pane = p.panes[wait.pane.index()] orelse return; if (pane.serial != wait.serial) return; const t: *Text = switch (wait.what) { .body => &pane.body, @@ -259,13 +259,13 @@ pub fn pipeResponse( .workspace => &p.global_tag, .input => return, }; - const content = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(.at(wait.pane), "pipe", err); + const content = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(wait.pane, "pipe", err); const changed = if (t.what == .body) changed: { const f = pane.file orelse return; if (!panes.Output.fileTraits(f.output).saves) return; break :changed f.revision != wait.revision; } else std.hash.Wyhash.hash(0, content) != wait.sum; - if (changed) return p.reportError(.at(wait.pane), "pipe", error.FileChangedWhileFiltering); + if (changed) return p.reportError(wait.pane, "pipe", error.FileChangedWhileFiltering); if (wait.how == .ignore) return; if (wait.how == .keep) { @@ -296,14 +296,14 @@ pub fn pipeResponse( const cut = pipeCut(&wait, content, i) orelse return; const output = pipeOutput(&wait, outputs, content, i); if (output.len > selection_pipe.max_stdout_bytes) - return p.setMessage(.at(wait.pane), std.fmt.bufPrint(&said, "pipe: an output of {d} bytes, past {d}: the text is left as it was", .{ output.len, selection_pipe.max_stdout_bytes }) catch unreachable); // two numbers fit 128 + return p.setMessage(wait.pane, std.fmt.bufPrint(&said, "pipe: an output of {d} bytes, past {d}: the text is left as it was", .{ output.len, selection_pipe.max_stdout_bytes }) catch unreachable); // two numbers fit 128 total_output += output.len; // each under 1 MiB, at most max_selections of them if (total_output > selection_pipe.max_total_stdout_bytes) - return p.setMessage(.at(wait.pane), std.fmt.bufPrint(&said, "pipe: {d} bytes of output in all, past {d}: the text is left as it was", .{ total_output, selection_pipe.max_total_stdout_bytes }) catch unreachable); // two numbers fit 128 - if (i > 0 and cut.lo < ops[i - 1].q1) return p.setMessage(.at(wait.pane), "pipe: the selections overlap: the text is left as it was"); + return p.setMessage(wait.pane, std.fmt.bufPrint(&said, "pipe: {d} bytes of output in all, past {d}: the text is left as it was", .{ total_output, selection_pipe.max_total_stdout_bytes }) catch unreachable); // two numbers fit 128 + if (i > 0 and cut.lo < ops[i - 1].q1) return p.setMessage(wait.pane, "pipe: the selections overlap: the text is left as it was"); ops[i] = .{ .q0 = @intCast(cut.lo), .q1 = @intCast(cut.hi), .text = output }; } - const replacement = sam.apply(p.gpa, content, ops[0..n]) catch |err| return p.reportError(.at(wait.pane), "pipe", err); + const replacement = sam.apply(p.gpa, content, ops[0..n]) catch |err| return p.reportError(wait.pane, "pipe", err); var new_ranges: [panes.Text.max_selections]modal.Selection = undefined; var delta: isize = 0; for (ops[0..n], wait.ranges[0..n], new_ranges[0..n]) |op, range, *moved| { @@ -316,10 +316,10 @@ pub fn pipeResponse( // One async request is one history transaction, even at 64 cursors. edit.pushUndo(p.editor(), t) catch |err| { p.gpa.free(replacement); - return p.reportError(.at(wait.pane), "pipe", err); + return p.reportError(wait.pane, "pipe", err); }; - edit.setEditText(p.editor(), t, replacement) catch |err| return p.reportError(.at(wait.pane), "pipe", err); - const now = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(.at(wait.pane), "pipe", err); + edit.setEditText(p.editor(), t, replacement) catch |err| return p.reportError(wait.pane, "pipe", err); + const now = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(wait.pane, "pipe", err); t.setRanges(p.settings.tab, now, new_ranges[0..n], &.{}, wait.primary, wait.explicit); t.select = false; t.show(p.settings.tab); 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/Plumb.zig b/core/Plumb.zig index f51ddace..e1b09e69 100644 --- a/core/Plumb.zig +++ b/core/Plumb.zig @@ -593,7 +593,7 @@ pub fn portName(p: *const Pardes, index: u8) ?[]const u8 { /// Whether a program reads port `index` (an open of its file): the /// authority's 9P state, asked through the tape. fn portRead(p: *Pardes, index: u8) bool { - for (&p.fs.opens) |*o| if (o.node != 0 and o.what == .port and o.what.port.index == index) return true; + for (p.fs.opens[0..p.fs.opens_len]) |*o| if (o.node != 0 and o.what == .port and o.what.port.index == index) return true; return false; } @@ -611,7 +611,7 @@ fn enqueue(p: *Pardes, q: *events.Queue, lead: []const u8, m: *const Msg) bool { /// A copy of `m` to every reader of port `index` (plumber(4)'s queuesend: /// every fid open when it was sent), each read held for one answered. fn fanOut(p: *Pardes, index: u8, m: *const Msg) void { - for (&p.fs.opens) |*o| if (o.node != 0 and o.what == .port and o.what.port.index == index) { + for (p.fs.opens[0..p.fs.opens_len]) |*o| if (o.node != 0 and o.what == .port and o.what.port.index == index) { if (!enqueue(p, &o.what.port.queue, "", m)) { var said: Kind.Buf(160) = .{}; events.notePath(p, "err -", said.print("plumb/{s}: a message of {d} bytes is over a reader's {d} KiB, not sent to it", .{ portName(p, index).?, m.data.len, events.queue_cap / 1024 })); diff --git a/core/Query.zig b/core/Query.zig index f0e9ee1a..e2f59028 100644 --- a/core/Query.zig +++ b/core/Query.zig @@ -1,5 +1,5 @@ -//! The query pane: the one pane search is. A +Search attached under the -//! pane that asked (its owner, layout.zig "Attached panes"), born at a +//! The query pane: the one pane search is. A +Search docked under the +//! pane that asked (its owner, layout.zig "Docked panes"), born at a //! fixed height, whose body's line 1 is the query, editable text, and //! whose rows below are made live from a source, read-only while live. //! Line 1's first word names the source: `/pat` the owner's text (smart- @@ -18,7 +18,7 @@ //! text: B3 on one looks, B2 on line 1 runs it again. Wherever a row points into //! an open pane's text, that pane's places (Places.zig) show the set: //! tints, rail ticks, the current one selected. A row pointing at a file -//! no pane shows is shown in the +Preview attached under this pane; Enter +//! no pane shows is shown in the +Preview docked under this pane; Enter //! promotes the preview to the file's pane where it stands. //! //! Nothing moves while you type: the pane never closes, resizes or @@ -319,7 +319,7 @@ fn create(p: *Pardes, owner_id: usize, line: []const u8, source: Source) ?usize preview_rows = spare -| want; } } - if (!layout.attachFrom(p, owner_id, free, want, owner_id)) { + if (!layout.dockFrom(p, owner_id, free, want, owner_id)) { // An owner too short to give a query pane its rows: placed as any // new pane is, the one place a search moves another pane. layout.placeNew(p, owner_id, owner_id, free, .doc); @@ -1644,7 +1644,7 @@ fn makePreview(p: *Pardes, qid: usize, rows: u16, giver: usize) ?usize { return null; }; layout.compute(p); - if (!layout.attachFrom(p, qid, free, rows, giver)) { + if (!layout.dockFrom(p, qid, free, rows, giver)) { p.removePane(free, qid) catch |err| p.reportError(.at(qid), "query", err); return null; } @@ -1732,7 +1732,7 @@ fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void /// The +Preview becomes the file's pane where it stands: same slot, same /// serial, same rect, its scroll and selection as the preview left them. /// It is a file pane from here: an empty undo history, the Recent entry, -/// the watch, a file's tag; and a pane of its own, no longer attached (it +/// the watch, a file's tag; and a pane of its own, no longer docked (it /// stays when its query pane goes). fn promote(p: *Pardes, qid: usize, id: usize) void { const pane = p.panes[id] orelse return; @@ -1911,10 +1911,10 @@ pub fn cancel(p: *Pardes, id: usize) void { if (owner_id) |oid| p.view().active = oid; return; } - // Attached, its rows go back to its owner; else to its own column's. - const attached = layout.ownerOf(p, id) != null; + // Docked, its rows go back to its owner; else to its own column's. + const docked = layout.ownerOf(p, id) != null; if (owner_id) |oid| { - p.removePane(id, if (attached) oid else null) catch |err| p.reportError(.at(id), "query", err); + p.removePane(id, if (docked) oid else null) catch |err| p.reportError(.at(id), "query", err); p.view().active = oid; if (layout.findPane(p, oid)) |at| p.setActiveColumn(at.col); } else p.removePane(id, null) catch |err| p.reportError(.at(id), "query", err); @@ -2399,6 +2399,7 @@ test "Grep: lines of the files under the owner's directory, under their file; Al } test "* seeds line 1 and keeps the keyboard; SPC b b picks a pane, SPC s s a declaration" { + if (comptime !syntax.minimal_grammars) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); defer p.deinit(); const pane = try p.setTestFile("const alpha = 1;\nfn beta() void {\n _ = alpha;\n}\nfn gamma() void {}\n"); @@ -2633,6 +2634,7 @@ test "a query row's place is its text: the match tinted after it, B3 on it opens } test "the +Preview: the query's hits in its file are its places, the row's one current and selected, coloured as the file is" { + if (comptime !syntax.minimal_grammars) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const text = "const needle = 1;\nconst hay = 2;\nfn f() void {\n _ = needle;\n}\npub const needle_too = needle;\n"; diff --git a/core/Store.zig b/core/Store.zig index 82e3c5bf..ac9387cb 100644 --- a/core/Store.zig +++ b/core/Store.zig @@ -28,7 +28,7 @@ pub const Closed = struct { /// brought back, it takes them from that pane alone. gainer: u32, below: bool, - /// The pane it was attached to, by serial (0 none). + /// The pane it was docked to, by serial (0 none). owner: u32, rows: u16, /// What its Panes row shows: its file, command or directory. @@ -78,7 +78,7 @@ pub fn clone(s: *const Store, gpa: std.mem.Allocator) Store { // ---- the closed panes ---- /// Pane `id`, about to close, kept: what it was (a one-pane Dump) and -/// where (its column, its rows, what it was attached to). Null for a pane +/// where (its column, its rows, what it was docked to). Null for a pane /// that is no pane of the user's: a query pane, a preview, one carried to /// another window (`away`), one made and refused in the same step (never /// announced), or one whose dump fails or is too big. `close` finishes it @@ -186,7 +186,7 @@ pub fn closedBySerial(s: *const Store, serial: u32) ?*Closed { } /// Closed pane `serial` of this session made again, where it was: beside -/// the pane its rows went to, taking them from that pane alone (attached +/// the pane its rows went to, taking them from that pane alone (docked /// again to its owner when that is still open), else placed as a new pane /// from `from`. False when it is not this session's, or its dump will not /// load; the keyboard on it otherwise. @@ -204,7 +204,7 @@ pub fn reopen(s: *Store, p: *Pardes, serial: u32, from: usize) bool { const owner = if (place.owner != 0) p.paneBySerial(place.owner) else null; const gainer = if (place.gainer != 0) p.paneBySerial(place.gainer) else null; const placed = if (owner) |o| - layout.attachFrom(p, o, free, place.rows, o) + layout.dockFrom(p, o, free, place.rows, o) else if (gainer) |g| layout.giveBack(p, free, g, place.below, place.rows) else diff --git a/core/Stream.zig b/core/Stream.zig index 78f6ef41..f65d0683 100644 --- a/core/Stream.zig +++ b/core/Stream.zig @@ -1269,6 +1269,7 @@ test "Stream: the listing of files for Find on a worker, a cap of hits stops the } test "Stream: a big text's declarations are parsed on a worker, never the loop, and the rows of its / regroup under them" { + if (comptime !syntax.minimal_grammars) return error.SkipZigTest; const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); defer p.deinit(); var text: std.ArrayList(u8) = .empty; @@ -1307,6 +1308,7 @@ test "Stream: a big text's declarations are parsed on a worker, never the loop, } test "Stream: a scroll's colours are painted ahead on a worker, so PageDown after PageDown parses nothing on the frame" { + if (comptime !syntax.minimal_grammars) return error.SkipZigTest; const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); defer p.deinit(); var text: std.ArrayList(u8) = .empty; 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/builtins.zig b/core/builtins.zig index 894478fd..7ad70e7c 100644 --- a/core/builtins.zig +++ b/core/builtins.zig @@ -1017,11 +1017,11 @@ pub const Del = struct { // acme's Del asks winclean first (exec.c del): unsaved text is warned // about once, and the same Del again, nothing edited since, closes. if (warnModifiedIn(c, .Del, .{ .pane = c.id })) return; - // An attachment's rows go back to its owner: nothing to ask. + // A docked pane's rows go back to its owner: nothing to ask. if (layout.ownerOf(c.p, c.id)) |owner| return c.p.removePane(c.id, owner) catch |err| c.p.reportError(.at(c.id), "close", err); const at = layout.findPane(c.p, c.id); const above = if (at) |f| layout.expandedNeighbor(c.p, f.col, f.idx, .above) else null; - // An owner's attachments close with it: below is past them. + // An owner's docked panes close with it: below is past them. const below = if (at) |f| layout.expandedNeighbor(c.p, f.col, layout.groupEnd(c.p, f.col, f.idx) - 1, .below) else null; const to: ?usize = if (std.mem.eql(u8, side, "k")) above orelse below diff --git a/core/colors.zig b/core/colors.zig index 4825ea3f..7e692fe5 100644 --- a/core/colors.zig +++ b/core/colors.zig @@ -8,7 +8,6 @@ const Color = @import("surface.zig").Color; const FontRole = @import("surface.zig").FontRole; const config = @import("config.zig"); const platform = pardes.platform; -const MAX_PANES = pardes.MAX_PANES; const BOX_H = pardes.BOX_H; const Pardes = pardes.Pardes; @@ -630,7 +629,7 @@ pub fn requestThemeFile(p: *Pardes, id: usize, argument: []const u8) void { p.reportError(.at(id), "theme file", error.PathTooLong); return; } - p.theme_file_pane = @intCast(@min(id, MAX_PANES - 1)); + p.theme_file_pane = .at(id); const generation = nextThemeFileGeneration(p); p.emit(.{ .theme_file = .{ .generation = generation, .on = true } }); } @@ -645,7 +644,7 @@ pub fn loadedThemeFile(p: *const Pardes) ?[]const u8 { pub const ThemeFileRequest = struct { path: []const u8, - pane: u8, + pane: pardes.Pane.Id, }; /// Borrow the current request while a native host performs its synchronous @@ -673,7 +672,7 @@ fn themeFileFailure(p: *Pardes, request: ThemeFileRequest, why: []const u8) void var said: pardes.Kind.Buf(520) = .{}; var cut: [200]u8 = undefined; const path = @import("ninep/tree.zig").fitErr(request.path, &cut); - p.reportFailure(request.pane, said.print("theme file {s}: {s}", .{ path, why })); + p.reportFailure(request.pane.index(), said.print("theme file {s}: {s}", .{ path, why })); revertThemeFile(p); } diff --git a/core/dump.zig b/core/dump.zig index c348dec2..4fc7fc4d 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; @@ -574,6 +577,10 @@ fn loadAndRevive(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, previ var on_disk: OnDisk = @splat(false); const p = try loadKnowing(gpa, opts, bytes, ¬es, &on_disk); errdefer p.deinit(); + // The 9P state its requests made was its connections', which do not + // come with it (a client's join loads alone, and keeps it). + p.fs.forget(gpa); + for (p.panes) |slot| if (slot) |pane| pane.fs.deinit(gpa); // Its kinds are this process's, not the dump's: the session's it // replaces, or what the scan found (a dump of another session's). p.kinds = if (previous) |old| old.kinds else .started(p.tape, opts.addons); @@ -750,6 +757,7 @@ pub fn loadPane(p: *Pardes, id: usize, bytes: []const u8) !*pardes.panes.Pane { pane.command_from = 0; pane.places.from = 0; pane.collapsed = false; + pane.fs.deinit(p.gpa); pane.prompt_view = p.live; try ensureKind(p, pane); p.installPane(id, pane); diff --git a/core/echo.zig b/core/echo.zig index 40200696..f35c9f9d 100644 --- a/core/echo.zig +++ b/core/echo.zig @@ -614,7 +614,7 @@ const Rig = struct { for (msgs.items) |m| gpa.free(m); msgs.deinit(gpa); } - try g.screens.flush(g.a.core, g.peer, g.r.view, &msgs); + try g.screens.flush(g.a.core, g.peer, &msgs); for (msgs.items) |m| if (g.r.screen(m)) |reply| { _ = try g.screens.take(g.a.core, g.peer, reply); }; diff --git a/core/edit_cmd.zig b/core/edit_cmd.zig index 9a5c6865..ab4f2b5d 100644 --- a/core/edit_cmd.zig +++ b/core/edit_cmd.zig @@ -533,11 +533,11 @@ test "the held write asked again is parked again, then answered once, and a flus // As 9p_io holds it. p.fs.edit_hold = .{ .asker = @ptrCast(p), .slot = 0, .seq = 1, .tag = 7, .node = ctl, .handle = 0, .written = @intCast(req.data.len) }; // A retry of its park: still waiting, never run a second time. - try testing.expectEqual(tree.Status.again, p.serveFs(req).status); + try testing.expectEqual(tree.Status.again, filesystem.EditHold.retried(&p.fs, req).?.status); try testing.expect(p.pipe.edit_run != null); answer(p, &.{"a\nb\n"}); try testing.expect(p.fs.edit_hold.?.done); - const done = p.serveFs(req); + const done = filesystem.EditHold.retried(&p.fs, req).?; try testing.expectEqual(tree.Status.ok, done.status); try testing.expectEqual(@as(u32, @intCast(req.data.len)), done.written); try testing.expect(p.fs.edit_hold == null); diff --git a/core/exec.zig b/core/exec.zig index 18b519ff..52f54541 100644 --- a/core/exec.zig +++ b/core/exec.zig @@ -799,7 +799,7 @@ pub fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { /// Whether an open of a look or exec file holds `serial` from its own write /// (tree.Open.results): its client is reading that pane. fn leased(p: *const Pardes, serial: u32) bool { - for (p.fs.opens) |o| if (o.node != 0 and o.results.wrote) { + for (p.fs.opens[0..p.fs.opens_len]) |o| if (o.node != 0 and o.results.wrote) { if (std.mem.indexOfScalar(u32, o.results.list[0..o.results.len], serial) != null) return true; }; return false; diff --git a/core/fs.zig b/core/fs.zig index 6e5829e1..6b43ba67 100644 --- a/core/fs.zig +++ b/core/fs.zig @@ -830,6 +830,16 @@ pub const EditHold = struct { return req.op == .write and req.tag == h.tag and req.node == h.node and req.handle == h.handle; } + /// The held write asked again by a retry of its park, as the listener + /// answers it, never a step (no replica holds it): still waiting, or + /// its answer; null for any other request. + pub fn retried(ns: *Namespace, req: tree.Req) ?tree.Reply { + const h = if (ns.edit_hold) |*held| held else return null; + if (!h.names(req)) return null; + if (!h.done) return .{ .tag = req.tag, .status = .again }; + return answer(ns); + } + /// Its answer, the held record let go: the words copied out first. pub fn answer(ns: *Namespace) tree.Reply { const h = ns.edit_hold.?; @@ -841,6 +851,32 @@ pub const EditHold = struct { }; pub const Namespace = struct { + /// What a step reads that 9P requests made (every request an input + /// each replica replays) is the core's like any state: the open + /// records (a command pane a script reads is not taken again: + /// exec.leased), the panes the last look or exec touched (a new open's + /// own), the writes held to go in as one edit and a header tag's + /// truncation, digested and dumped (a client's join takes them from + /// the dump; a session revived from one drops the opens with the + /// connections that held them: dump.zig `loadAndRevive`). The rest is + /// the server's (core/walk.zig): its sockets and the mounts (dumped + /// on their own), the log and what a reader or a listener is answered + /// with, and the request being served's own flags, set and read in + /// its step, and `edit_hold`: the listener's, which answers a retry + /// of the held write from it, no step (`EditHold.retried`). + pub const replica = .{ + .authority = .{ + "socket_path", "tcp_address", "mounts", "node_name", "os_paths", "out", + "listeners", "origin", "no_prompt", "session_write", "unlogged", "capturing", + "serving", "refused", "failure", "failure_len", "no_pane_slot", "no_pane_slot_len", + "said", "said_len", "said_at", "late_failure", "late_failure_len", + "lsp_answer_at", "edit_started", "edit_hold", "edit_said", "lsp_result", "write_room", + "write_waits", "log_full_hash", "pages", "closed_lines", "ran_at", "refilled", + "failures", "ename", "news", "hanging_up", "log", "plumb_held", + "started", + }, + .len = .{ .{ "opens", "opens_len" }, .{ "results", "results_len" } }, + }; socket_path: []const u8 = "", tcp_address: ?std.Io.net.IpAddress = null, mounts: std.ArrayList(Mount) = .empty, @@ -848,6 +884,11 @@ pub const Namespace = struct { os_paths: std.ArrayList(OsPath) = .empty, /// What each open holds between its open and its release. opens: [tree.open_slots]tree.Open = @splat(.{}), + /// The records past it are nothing: a digest, a dump and a replica's + /// rollback copy take the opens this far (an idle session's none), and + /// nothing reads or frees one past it (a rollback leaves there what + /// its epoch freed). + opens_len: u8 = 0, out: std.ArrayList(u8) = .empty, listeners: u16 = 0, origin: u8 = 'K', @@ -902,7 +943,7 @@ pub const Namespace = struct { /// commands run off the loop (edit_cmd.zig): the listener holds it. edit_started: bool = false, /// That write, held: answered once `done` (9p_io answerHeld), or - /// asked again by a retry of its park (Pardes.serveFs); a flush or a + /// asked again by a retry of its park (`EditHold.retried`); a flush or a /// hang-up stops the Edit (9p_io watchEdit). edit_hold: ?EditHold = null, /// The words a held Edit write was refused with, kept for its answer. @@ -985,7 +1026,7 @@ pub const Namespace = struct { st.mounts.deinit(gpa); for (st.os_paths.items) |entry| gpa.free(entry.path); st.os_paths.deinit(gpa); - for (&st.opens) |*o| o.deinit(gpa); + for (st.opens[0..st.opens_len]) |*o| o.deinit(gpa); for (st.pages.items) |*page| page.bytes.deinit(gpa); st.pages.deinit(gpa); for (st.closed_lines.items) |*line| line.bytes.deinit(gpa); @@ -995,6 +1036,39 @@ pub const Namespace = struct { st.out.deinit(gpa); } + /// Its digest (core/walk.zig): the opens in use, and writes held by + /// their length (their bytes are the same writes on every side; a + /// stream of 8 KB appends hashed whole cost each its length again; + /// none held, the rest of `batch` is nothing a step reads), the panes + /// the last look or exec touched, a header's truncation. Nothing at + /// all for a session no script holds anything of. + pub fn digest(st: *const Namespace, h: *pardes.walk.Hasher) void { + comptime if (pardes.walk.fieldNames(Namespace).len != 8) @compileError("Namespace.digest: hash every field the walk does not leave out"); + for (st.opens[0..st.opens_len]) |*o| pardes.walk.hash(tree.Open, o, h); + h.update(std.mem.sliceAsBytes(st.results[0..st.results_len])); + if (st.header_rewrite != null or st.header_trunc_pending != null or st.header_held) { + const words = [_]u64{ st.header_rewrite orelse std.math.maxInt(u64), st.header_trunc_pending orelse std.math.maxInt(u64), @intFromBool(st.header_held) }; + h.update(std.mem.asBytes(&words)); + } + const b = &st.batch; + if (b.bytes.items.len == 0) return; + const words = [_]u64{ b.serial, b.node, b.handle, b.at, b.bytes.items.len, b.last_ns }; + h.update(std.mem.asBytes(&words)); + } + + /// What the requests of connections gone made, let go: a session + /// revived from a dump has none of the connections that held its opens. + pub fn forget(st: *Namespace, gpa: std.mem.Allocator) void { + for (st.opens[0..st.opens_len]) |*o| o.deinit(gpa); + st.opens_len = 0; + st.results_len = 0; + st.batch.bytes.deinit(gpa); + st.batch = .{}; + st.header_rewrite = null; + st.header_trunc_pending = null; + st.header_held = false; + } + pub fn mount(st: *Namespace, gpa: std.mem.Allocator, name: []const u8, dial: []const u8) !void { if (!validMountName(name)) return error.BadMountName; try ninep_io.Client.validateDial(dial); diff --git a/core/layout.zig b/core/layout.zig index 9c99dc7d..4c7d6afb 100644 --- a/core/layout.zig +++ b/core/layout.zig @@ -249,8 +249,8 @@ fn splitRowFor(y: u16, h: u16, cur_y: u16, least: ?u16) ?u16 { } /// Where pane `id` dragged by its grip to (`cur_x`, `cur_y`) lands. An -/// owner's grip drags its group; an attachment's drags it alone, which -/// within its group resizes it and anywhere else detaches it (movePane). +/// owner's grip drags its group; a docked pane's drags it alone, which +/// within its group resizes it and anywhere else undocks it (movePane). /// Another group is one place: a pane dropped on it lands under all of it. pub fn movePlacement(p: *Pardes, id: usize, cur_x: u16, cur_y: u16) ?MovePlacement { const v = p.view(); @@ -285,8 +285,8 @@ pub fn movePlacement(p: *Pardes, id: usize, cur_x: u16, cur_y: u16) ?MovePlaceme k += 1; continue; } - // Its own group's panes are places of their own: that is how an - // attachment's grip resizes it against its owner. + // Its own group's panes are places of their own: that is how a + // docked pane's grip resizes it against its owner. const unit_end = if (groupRoot(p, v.cols[tc].panes[k]) == own_root) k + 1 else groupEnd(p, tc, k); var h: u16 = 0; for (k..unit_end) |j| { @@ -313,8 +313,8 @@ pub fn movePlacement(p: *Pardes, id: usize, cur_x: u16, cur_y: u16) ?MovePlaceme return last; } -/// Move pane `id`, and the group it owns, where movePlacement says. An -/// attachment moved anywhere but within its own group is detached there. +/// Move pane `id`, and the group it owns, where movePlacement says. A +/// docked pane moved anywhere but within its own group is undocked there. pub fn movePane(p: *Pardes, id: usize, cur_x: u16, cur_y: u16) void { const v = p.view(); const placement = movePlacement(p, id, cur_x, cur_y) orelse return; @@ -549,7 +549,7 @@ pub fn acmePlace(p: *Pardes, c: usize, origin: ?usize, id: usize) void { var empty: ?usize = null; for (p.view().cols[c].panes[0..n]) |k| { const pane = p.panes[k] orelse continue; - // An attachment is its owner's: never halved for another pane. + // A docked pane is its owner's: never halved for another pane. if (pane.collapsed or ownerOf(p, k) != null) continue; // `>=`: at a tie the one nearer the bottom, as acme picks. if (big == null or bodyRows(p, k) >= bodyRows(p, big.?)) big = k; @@ -1076,7 +1076,7 @@ pub fn absorbVWeight(p: *Pardes, id: usize, to: ?usize) ?usize { var k = f.idx; while (to == null and k > 0) : (k -= 1) { sib = v.cols[f.col].panes[k - 1]; - // nor to a pane attached to another: rows go to owners + // nor to a pane docked to another: rows go to owners if (p.panes[sib]) |pp| if (if (pp.file) |ff| panes.Output.fileTraits(ff.output).doc else true) if (ownerOf(p, sib) == null) break; } const s = p.panes[sib] orelse return null; @@ -1112,26 +1112,26 @@ pub fn splitBelow(p: *Pardes, src_id: usize, nw: *Pane) void { }; } -// ---- Attached panes ---- +// ---- Docked panes ---- // -// A results pane (+Search, +Callstack, +Diff, +Errors) is ATTACHED to the +// A results pane (+Search, +Callstack, +Diff, +Errors) is DOCKED to the // pane it answers for, its owner (Pane.docked_to). The owner and what is -// attached to it, and what is attached to those (a preview under a +// docked to it, and what is docked to those (a preview under a // +Search), are a GROUP: contiguous in one column, the owner first. A group // is one place to everything else in the layout: an unrelated pane is never // put inside it (acmePlace, splitAt, splitTallest), a pane dragged onto it // lands under all of it (movePlacement), and its owner's grip, Collapse and -// Del take all of it (movePane, toggleCollapse, Pardes.removePane). An -// attachment's rows come from its owner and go back to it, nobody else's. +// Del take all of it (movePane, toggleCollapse, Pardes.removePane). A +// docked pane's rows come from its owner and go back to it, nobody else's. -/// The slot of `id`'s owner, when `id` is attached to a live pane. +/// The slot of `id`'s owner, when `id` is docked to a live pane. pub fn ownerOf(p: *const Pardes, id: usize) ?usize { const serial = (p.panes[id] orelse return null).docked_to orelse return null; for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.serial == serial and i != id) return i; return null; } -/// The owner at the top of `id`'s group: `id` itself when it is attached to +/// The owner at the top of `id`'s group: `id` itself when it is docked to /// nothing. Bounded: a dump could name a ring of owners. pub fn groupRoot(p: *const Pardes, id: usize) usize { var at = id; @@ -1139,7 +1139,7 @@ pub fn groupRoot(p: *const Pardes, id: usize) usize { return at; } -/// Whether `id` is `root` or attached to it through any number of owners. +/// Whether `id` is `root` or docked to it through any number of owners. fn descends(p: *const Pardes, id: usize, root: usize) bool { var at = id; for (0..MAX_PANES) |_| { @@ -1150,7 +1150,7 @@ fn descends(p: *const Pardes, id: usize, root: usize) bool { } /// One past the last pane of the group that pane `idx` of column `c` is -/// in: `idx + 1` for a pane with nothing attached. +/// in: `idx + 1` for a pane with nothing docked. pub fn groupEnd(p: *const Pardes, c: usize, idx: usize) usize { const v = p.view(); const root = groupRoot(p, v.cols[c].panes[idx]); @@ -1159,11 +1159,11 @@ pub fn groupEnd(p: *const Pardes, c: usize, idx: usize) usize { return k; } -/// The attachments kept where they are attached: one whose owner is gone, +/// The docked panes kept where they are docked: one whose owner is gone, /// or that something (a 9P move, a pane split into a column of its own, an /// owner moved by a route that does not carry its group) left anywhere but /// right under its owner's group, is an ordinary pane from then on, where -/// it stands. Nothing moves. Top to bottom, so a nested attachment is +/// it stands. Nothing moves. Top to bottom, so a nested docked pane is /// judged after the one it hangs from. pub fn keepGroups(p: *Pardes) void { for (0..p.view().ncol) |c| for (p.view().cols[c].panes[0..p.view().cols[c].n], 0..) |id, k| { @@ -1175,17 +1175,17 @@ pub fn keepGroups(p: *Pardes) void { }; } -/// Attach new pane `id`, in no column yet, to `owner`: under the owner's +/// Dock new pane `id`, in no column yet, to `owner`: under the owner's /// group, `rows` of the owner's rows (tag included), from the owner and /// from no other pane. The owner keeps its own minimum, else its tag (acme -/// lets a window shrink to it), so the attachment may get fewer. A folded -/// owner is unfolded first. The rows are the attachment's from then on: +/// lets a window shrink to it), so the docked pane may get fewer. A folded +/// owner is unfolded first. The rows are the docked pane's from then on: /// nothing here ever resizes it again; the seam is the user's to drag. /// False, `id` in no column, when the owner has not the rows for its tag -/// and the attachment's minimum. The rows are given by `giver`: the owner +/// and the docked pane's minimum. The rows are given by `giver`: the owner /// itself or a pane of its group (a +Preview added under a query pane later /// takes the text's rows, so the query pane, typed into, keeps its own). -pub fn attachFrom(p: *Pardes, owner: usize, id: usize, rows: u16, giver: usize) bool { +pub fn dockFrom(p: *Pardes, owner: usize, id: usize, rows: u16, giver: usize) bool { const v = p.view(); const o = p.panes[owner] orelse return false; const g = p.panes[giver] orelse return false; @@ -1238,10 +1238,10 @@ pub fn giveBack(p: *Pardes, id: usize, gainer: usize, below: bool, rows: u16) bo return true; } -/// Collapse on an owner with attachments: the whole group folds to its +/// Collapse on an owner with docked panes: the whole group folds to its /// tags, every row it gave up to the one unfolded neighbour outside it, /// and unfolds again from that neighbour, as one pane's Collapse does. -/// ponytail: unfolding opens every attachment, one folded alone before +/// ponytail: unfolding opens every docked pane, one folded alone before /// included; remembering which were is a bit a pane. fn collapseGroup(p: *Pardes, c: usize, start: usize, end: usize) void { const v = p.view(); @@ -1281,7 +1281,7 @@ pub fn toggleCollapse(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; const at = findPane(p, id) orelse return; compute(p); - // An owner folds and unfolds with what is attached to it. + // An owner folds and unfolds with what is docked to it. if (ownerOf(p, id) == null) { const end = groupEnd(p, at.col, at.idx); if (end > at.idx + 1) return collapseGroup(p, at.col, at.idx, end); @@ -1635,8 +1635,8 @@ pub fn reprojectTagHit(p: *const Pardes, tag_hit: TagHit) ?TagHit { return Layer.tagAgain(tag_hit); } -/// A test's attachment: an empty +Search in a new slot, in no column. -fn testAttachment(p: *Pardes) !usize { +/// A test's docked pane: an empty +Search in a new slot, in no column. +fn testDocking(p: *Pardes) !usize { const free = p.freeSlot().?; _ = try panes.Output.open(p, free, "/tmp", .search, "", try p.gpa.dupe(u8, "q\n")); return free; @@ -1884,7 +1884,7 @@ test "column reorder moves only crossed state and preserves weights" { try std.testing.expectEqual(@as(i32, 21), p.view().col_tags[1].cur_col); } -test "an attachment takes its rows from its owner alone, keeps them, and moves, folds and closes with it" { +test "a docked pane takes its rows from its owner alone, keeps them, and moves, folds and closes with it" { const exec = pardes.exec; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 48 }); defer p.deinit(); @@ -1900,8 +1900,8 @@ test "an attachment takes its rows from its owner alone, keeps them, and moves, const unrelated = [_]usize{ below, other_col }; // Under its owner, the rows asked for, the owner's and nobody else's. - const s = try testAttachment(p); - try std.testing.expect(attachFrom(p, 0, s, 9, 0)); + const s = try testDocking(p); + try std.testing.expect(dockFrom(p, 0, s, 9, 0)); try std.testing.expectEqual(@as(?usize, 0), ownerOf(p, s)); try std.testing.expectEqual(s, p.view().cols[0].panes[1]); for (unrelated) |k| try std.testing.expectEqualDeep(before[k], p.view().rects[k]); @@ -1909,8 +1909,8 @@ test "an attachment takes its rows from its owner alone, keeps them, and moves, try std.testing.expectEqual(before[0].y, p.view().rects[0].y); try std.testing.expectEqual(@as(u16, 9), p.view().rects[s].h); // A second level (a preview under a query pane): out of the first's rows. - const pv = try testAttachment(p); - try std.testing.expect(attachFrom(p, s, pv, 4, s)); + const pv = try testDocking(p); + try std.testing.expect(dockFrom(p, s, pv, 4, s)); try std.testing.expectEqual(pv, p.view().cols[0].panes[2]); try std.testing.expectEqual(@as(usize, 0), groupRoot(p, pv)); try std.testing.expectEqual(@as(usize, 3), groupEnd(p, 0, 0)); @@ -1925,7 +1925,7 @@ test "an attachment takes its rows from its owner alone, keeps them, and moves, compute(p); try std.testing.expectEqual(@as(u16, 5), p.view().rects[s].h); - // An unrelated New, from the owner or from its attachment, never lands + // An unrelated New, from the owner or from its docked pane, never lands // inside the group. exec.runBuiltin(p, .New, 0, "", null); exec.runBuiltin(p, .New, s, "", null); @@ -1933,7 +1933,7 @@ test "an attachment takes its rows from its owner alone, keeps them, and moves, try std.testing.expectEqual(s, p.view().cols[at.col].panes[at.idx + 1]); try std.testing.expectEqual(pv, p.view().cols[at.col].panes[at.idx + 2]); - // The seam between owner and attachment is the user's: the pair alone. + // The seam between owner and docked pane is the user's: the pair alone. compute(p); const pre_drag = p.view().rects; applyRowSplit(p, at.col, at.idx, p.view().rects[s].y - 3); @@ -1965,7 +1965,7 @@ test "an attachment takes its rows from its owner alone, keeps them, and moves, try std.testing.expect(p.panes[pv] == null); compute(p); try std.testing.expectEqual(pair[s].h + pair[pv].h, p.view().rects[s].h); - // Del of the attachment gives its rows back to the owner, nobody else. + // Del of the docked pane gives its rows back to the owner, nobody else. pair = p.view().rects; exec.runBuiltin(p, .Del, s, "", null); try std.testing.expect(p.panes[s] == null); @@ -1973,19 +1973,19 @@ test "an attachment takes its rows from its owner alone, keeps them, and moves, try std.testing.expectEqual(pair[0].h + pair[s].h, p.view().rects[0].h); for (p.view().cols[1].panes[0..p.view().cols[1].n]) |k| if (k != 0) try std.testing.expectEqualDeep(pair[k], p.view().rects[k]); - // Del of the owner closes what is attached to it. - const again = try testAttachment(p); - try std.testing.expect(attachFrom(p, 0, again, 6, 0)); + // Del of the owner closes what is docked to it. + const again = try testDocking(p); + try std.testing.expect(dockFrom(p, 0, again, 6, 0)); exec.runBuiltin(p, .Del, 0, "", null); try std.testing.expect(p.panes[0] == null and p.panes[again] == null); } -test "an attachment survives Dump and Restore, and one left away from its owner is a pane of its own" { +test "a docked pane survives Dump and Restore, and one left away from its owner is a pane of its own" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); defer p.deinit(); _ = try p.setTestFile("alpha\nbeta\nalphabet\n"); - const s = try testAttachment(p); - try std.testing.expect(attachFrom(p, 0, s, 8, 0)); + const s = try testDocking(p); + try std.testing.expect(dockFrom(p, 0, s, 8, 0)); try std.testing.expectEqual(@as(?usize, 0), ownerOf(p, s)); try dump.dumpState(p); const restored = try dump.initFromDump(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }, p.dump_out.?); @@ -1995,8 +1995,8 @@ test "an attachment survives Dump and Restore, and one left away from its owner pardes.exec.runBuiltin(p, .Undock, s, "", null); try std.testing.expect(p.panes[s].?.docked_to == null); // Put above its owner by a route that does not carry groups: detached. - const t = try testAttachment(p); - try std.testing.expect(attachFrom(p, 0, t, 8, 0)); + const t = try testDocking(p); + try std.testing.expect(dockFrom(p, 0, t, 8, 0)); try std.testing.expectEqual(@as(?usize, 0), ownerOf(p, t)); removePane(p, t); insert(p, 0, 0, t); diff --git a/core/lsp/Ask.zig b/core/lsp/Ask.zig index 376b093d..500f02b5 100644 --- a/core/lsp/Ask.zig +++ b/core/lsp/Ask.zig @@ -29,7 +29,7 @@ last: ?struct { kind: lsp.Kind, arg: Effect.Buf(128), serial: u32, offset: u32 } wait: ?struct { id: u32, kind: lsp.Kind, - pane: usize, + pane: Pane.Id, serial: u32, revision: u32, arg: Effect.Buf(128), @@ -103,7 +103,7 @@ pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8) p.lsp_ask.wait = .{ .id = p.lsp_ask.seq, .kind = kind, - .pane = id, + .pane = .at(id), .serial = pane.serial, .revision = if (pane.file) |f| f.revision else 0, .arg = .from(arg), @@ -270,24 +270,25 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { const w = p.lsp_ask.wait orelse return; if (w.id != id) return; // superseded by a newer press, or the pane died p.lsp_ask.wait = null; - const pane = p.panes[w.pane] orelse return; + const asked = w.pane.index(); + const pane = p.panes[asked] orelse return; if (pane.serial != w.serial) return; // Whatever fails from here -- no answer, nothing found, no room for // its pane -- fails a 9P write that asked it too. const failures = p.fs.failures; - defer if (p.fs.failures != failures) p.noteLateFailure(.at(w.pane)); + defer if (p.fs.failures != failures) p.noteLateFailure(w.pane); var said: pardes.Kind.Buf(256) = .{}; const rows = response orelse - return p.reportFailure(w.pane, said.print("{s}: the language server did not answer", .{lspWord(w.kind)})); + return p.reportFailure(asked, said.print("{s}: the language server did not answer", .{lspWord(w.kind)})); // A backend that cannot answer it says why (`@none <why>`). if (std.mem.startsWith(u8, rows, "@none ")) { const why = std.mem.trimEnd(u8, rows["@none ".len..], "\n"); - return p.reportFailure(w.pane, said.print("{s}: {s}", .{ lspWord(w.kind), why })); + return p.reportFailure(asked, said.print("{s}: {s}", .{ lspWord(w.kind), why })); } // Index's answer is its indexer's command line, run in a command // pane (lsp_client.indexCommand). if (w.kind == .index) { - if (std.mem.startsWith(u8, rows, "@run ")) _ = exec.execute(p, w.pane, std.mem.trimEnd(u8, rows["@run ".len..], "\n")); + if (std.mem.startsWith(u8, rows, "@run ")) _ = exec.execute(p, asked, std.mem.trimEnd(u8, rows["@run ".len..], "\n")); return; } if (w.kind == .rename or w.kind == .format) { @@ -296,7 +297,7 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { if (applyLspEdits(p, pane, w.revision, edits)) { var buf: pardes.Kind.Buf(64) = .{}; const verb: []const u8 = if (w.kind == .rename) "renamed" else "formatted"; - p.setMessage(.at(w.pane), buf.print("{s} {d} range(s)", .{ verb, edits.len })); + p.setMessage(w.pane, buf.print("{s} {d} range(s)", .{ verb, edits.len })); } return; } @@ -308,19 +309,19 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { } if (rows.len == 0) { if (w.kind == .completion and pane.body.mode == .insert and pane.body.nsel == 0 and - pane.body.cur_row == w.row and pane.body.cur_col == w.col) edit.insertTab(p.editor(), &pane.body) catch |err| return p.reportError(.at(w.pane), "complete", err); + pane.body.cur_row == w.row and pane.body.cur_col == w.col) edit.insertTab(p.editor(), &pane.body) catch |err| return p.reportError(w.pane, "complete", err); // Nothing found fails, but for a file with no diagnostics, // which is no failure, and a completion's Tab. const none: ?[]const u8 = switch (w.kind) { .completion, .format => null, .rename => "nothing here to rename", - .diagnostics, .workspace_diagnostics => return p.setMessage(.at(w.pane), said.print("{s}: none", .{lspWord(w.kind)})), + .diagnostics, .workspace_diagnostics => return p.setMessage(w.pane, said.print("{s}: none", .{lspWord(w.kind)})), .incoming_calls => "callers not found", .outgoing_calls => "callees not found", .hover => "nothing to show: not found", else => "not found", }; - if (none) |text| p.reportFailure(w.pane, said.print("{s}: {s}", .{ lspWord(w.kind), text })); + if (none) |text| p.reportFailure(asked, said.print("{s}: {s}", .{ lspWord(w.kind), text })); return; } @@ -330,7 +331,7 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { const ln = std.mem.trimEnd(u8, rows, "\n"); const place = ln[0..panes.Output.location(ln).end]; p.look_missed = false; - look.lookAt(p, w.pane, place); + look.lookAt(p, asked, place); // The one place is the text's places, as a list's would be: tinted, // and n and N step it. const spot = look.parsePathLine(place); @@ -367,16 +368,16 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { }; if (listed) |source| if (pane.file != null and pane.query == null and !p.exec_header) { p.fs.refilled = null; - panes.Query.fillList(p, w.pane, source, rows); + panes.Query.fillList(p, asked, source, rows); p.fs.lsp_result = if (panes.Query.ofOwner(p, pane.serial)) |qid| p.panes[qid].?.serial else null; return; }; const dir = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice(); - const content = p.gpa.dupe(u8, rows) catch |err| return p.reportError(.at(w.pane), lspWord(w.kind), err); + const content = p.gpa.dupe(u8, rows) catch |err| return p.reportError(w.pane, lspWord(w.kind), err); const serial_before = p.next_serial; p.fs.refilled = null; - panes.Output.fillResults(p, w.pane, dir, from, w.arg.slice(), content, null) catch |err| { - p.reportError(.at(w.pane), "language response", err); + panes.Output.fillResults(p, asked, dir, from, w.arg.slice(), content, null) catch |err| { + p.reportError(w.pane, "language response", err); return; }; if (rows.len >= 1 << 20) memory.trim(); @@ -390,7 +391,7 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { if (p.next_serial != serial_before) { const report_rows = std.mem.count(u8, result_pane.file.?.content, "\n"); const wanted: u16 = @intCast(@min(v.screen_h, report_rows + result_pane.tag_rows)); - layout.givePaneRows(p, result_id, wanted, w.pane); + layout.givePaneRows(p, result_id, wanted, asked); } look.focusPaneLine(p, result_id, .{ .line = 1, .col = 1 }, .keep); break; @@ -401,7 +402,7 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { // Rows that only name a file the server left alone (lsp_client // renameEdits) are no edits. const unrenamed = std.mem.count(u8, rows, ", which the server did not rename\n"); - p.setMessage(.at(w.pane), if (unrenamed > 0) + p.setMessage(w.pane, if (unrenamed > 0) said_buf.print("Rename: previewed, not applied: the server renamed in this file only, and {d} other open file(s) say the name", .{unrenamed}) else said_buf.print("Rename: {d} edit(s) across files, previewed, not applied", .{nrows})); @@ -413,7 +414,7 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { .line = @as(usize, @intCast(@max(0, w.row))) + 1, .col = @as(usize, @intCast(@max(0, w.col))) + 1, }); - _ = look.jumpResult(p, w.pane, row); + _ = look.jumpResult(p, asked, row); } } diff --git a/core/ninep/events.zig b/core/ninep/events.zig index 1951a434..1fd05b54 100644 --- a/core/ninep/events.zig +++ b/core/ninep/events.zig @@ -332,7 +332,7 @@ fn newest(p: *Pardes) ?struct { at: usize, seq: u64, text: []const u8 } { /// Whether a follower has read the record `seq`, or is part way through it. fn followerRead(p: *Pardes, seq: u64) bool { - for (p.fs.opens) |o| if (o.node != 0 and o.what == .log) { + for (p.fs.opens[0..p.fs.opens_len]) |o| if (o.node != 0 and o.what == .log) { const l = o.what.log; if (l.follow and (l.next > seq or (l.next == seq and l.part > 0))) return true; }; @@ -437,6 +437,8 @@ fn pushLog(p: *Pardes, raw: []u8) void { /// What an open of /log holds. pub const LogOpen = struct { + /// Its reader's alone: what it is answered with (the log is the session's). + pub const replica = .{ .authority = .{ "bytes", "follow", "next", "part", "pos" } }; /// The ring's text when it was opened. bytes: []const u8 = &.{}, /// This open waits for records after `bytes`, from `next`. diff --git a/core/ninep/pane.zig b/core/ninep/pane.zig index 1d514a3c..d47b637b 100644 --- a/core/ninep/pane.zig +++ b/core/ninep/pane.zig @@ -30,6 +30,28 @@ const Node = tree.Node; /// Filesystem state a pane carries beside its editor state. pub const State = struct { + /// What a step reads of it is digested and dumped (fs.Namespace); the + /// readers' records and the server's say of them are the session's. + pub const replica = .{ .authority = .{ "readers", "event_reader", "events", "tag_snap", "pty_reader", "pty_out", "winsize", "unannounced" } }; + + /// Its digest (core/walk.zig): nothing for a pane no script has set + /// anything of (most of them, at every unit a replica confirms); the + /// rest's fields as one run of bytes, not a hash's call a field. + pub fn digest(st: *const State, h: *pardes.walk.Hasher) void { + const untouched: State = .{}; + var touched = false; + inline for (comptime pardes.walk.fieldNames(State)) |name| touched = touched or !std.meta.eql(@field(st, name), @field(untouched, name)); + if (!touched) return; + var buf: [256]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + // Longer than the room (a chord's text): field by field. + if (encoded(st, &w)) |_| h.update(w.buffered()) else |_| inline for (comptime pardes.walk.fieldNames(State)) |name| pardes.walk.hash(@FieldType(State, name), &@field(st, name), h); + } + + fn encoded(st: *const State, w: *std.Io.Writer) std.Io.Writer.Error!void { + inline for (comptime pardes.walk.fieldNames(State)) |name| try pardes.walk.encode(@FieldType(State, name), &@field(st, name), w); + } + /// The range `data` and `xdata` read and write through. acme clears it /// when the first client opens `addr` (editors/acme/xfid.c:105-108), /// which suits a client that holds the fid open; a shell cannot, and diff --git a/core/ninep/pty.zig b/core/ninep/pty.zig index 4b0cee66..ec752311 100644 --- a/core/ninep/pty.zig +++ b/core/ninep/pty.zig @@ -164,6 +164,7 @@ pub const output_rows = output_cap / 8; /// What an open of run holds (tree.zig's open records). pub const Run = struct { + pub const replica = .{ .len = .{.{ "answer", "len" }} }; /// `waiting`: the line is kept until the shell's first prompt (a new /// terminal's shell takes a moment to draw it), then sent. phase: enum { idle, waiting, sent, done } = .idle, diff --git a/core/ninep/tree.zig b/core/ninep/tree.zig index 1eaaa8cb..2c0ce1b0 100644 --- a/core/ninep/tree.zig +++ b/core/ninep/tree.zig @@ -124,9 +124,45 @@ pub const out_reserve = 4 * 1024; /// (editors/acme/dat.h:373-385). An open that holds something answers its /// record's index plus one as the handle; one that holds nothing answers 0. pub const Open = struct { + /// A client's join carries it and the digest covers it (fs.Namespace), + /// but what only its reader is answered with: the listener's held + /// read and the stream's last answer. + pub const replica = .{ .authority = .{ "held", "replay" } }; /// The node it was opened on, which every use checks; 0 is a free record. node: u64 = 0, - what: union(enum) { + what: What = .{ .snapshot = null }, + /// What a write to a file of command lines left unfinished: a last line + /// with no newline yet, or an Edit block still open. A write through a + /// mount is cut at the 9P message size, so one `echo` of many lines may + /// come as several writes, cut anywhere; the rest waits for the open's + /// next write, or its release, and never runs as a fragment. + pending: std.ArrayList(u8) = .empty, + /// The panes this open's last write touched, which a read of look or + /// exec on it answers, as /net/tcp/clone answers on the open that + /// asked; a fresh open holds the session's last, from before it opened. + results: Results = .{}, + /// A read that found nothing yet (`.again`), kept to be answered when + /// this open's file has something, the way factotum keeps its log's + /// waiting reads and answers them on append (security/auth/factotum/ + /// log.c:4-52) and acme an event read (editors/acme/xfid.c:994). One at a + /// time, as acme's window keeps one `eventx`: a newer read takes the + /// place of the older. The listener fills it in and answers it + /// (runtime/9p_io.zig, `answerHeld`). + held: ?Held = null, + /// The last answer a stream open (a followed log, event, pty/data) gave, + /// and the offset it was read at. A read at an offset inside it is + /// answered from it again: bash's `read` takes a chunk, keeps a line and + /// lseeks back to just past it, and a stream has already moved on. + replay: ?Replay = null, + /// A `name` open has named its pane: one name an open, so a second line + /// on it (bash writes `printf 'a\nb\n'` a line at a time) is refused. + named: bool = false, + /// A line over 1 MiB was refused: what follows of it, through its + /// newline, is dropped rather than run as a line of its own. + discarding: bool = false, + + /// What it is an open of, and what that holds. + pub const What = union(enum) { /// /screen's frame from the open, a terminal body's history from its /// first read. snapshot: ?[]const u8, @@ -160,40 +196,27 @@ pub const Open = struct { /// An open reading a plumb port (Plumb.zig's ports, plumber(4)'s): /// the messages sent to it since the open, packed, a read each. port: struct { index: u8, queue: events.Queue = .{} }, - } = .{ .snapshot = null }, - /// What a write to a file of command lines left unfinished: a last line - /// with no newline yet, or an Edit block still open. A write through a - /// mount is cut at the 9P message size, so one `echo` of many lines may - /// come as several writes, cut anywhere; the rest waits for the open's - /// next write, or its release, and never runs as a fragment. - pending: std.ArrayList(u8) = .empty, - /// The panes this open's last write touched, which a read of look or - /// exec on it answers, as /net/tcp/clone answers on the open that - /// asked; a fresh open holds the session's last, from before it opened. - results: Results = .{}, - /// A read that found nothing yet (`.again`), kept to be answered when - /// this open's file has something, the way factotum keeps its log's - /// waiting reads and answers them on append (security/auth/factotum/ - /// log.c:4-52) and acme an event read (editors/acme/xfid.c:994). One at a - /// time, as acme's window keeps one `eventx`: a newer read takes the - /// place of the older. The listener fills it in and answers it - /// (runtime/9p_io.zig, `answerHeld`). - held: ?Held = null, - /// The last answer a stream open (a followed log, event, pty/data) gave, - /// and the offset it was read at. A read at an offset inside it is - /// answered from it again: bash's `read` takes a chunk, keeps a line and - /// lseeks back to just past it, and a stream has already moved on. - replay: ?Replay = null, - /// A `name` open has named its pane: one name an open, so a second line - /// on it (bash writes `printf 'a\nb\n'` a line at a time) is refused. - named: bool = false, - /// A line over 1 MiB was refused: what follows of it, through its - /// newline, is dropped rather than run as a line of its own. - discarding: bool = false, + + /// What a step reads of it: not the text a reader is answered from + /// (a screen, a listing, the log, a port's messages), which each + /// process makes of its own state, and a replica never answers. + pub fn digest(w: *const What, h: *pardes.walk.Hasher) void { + const tag = std.meta.activeTag(w.*); + pardes.walk.hash(@TypeOf(tag), &tag, h); + switch (w.*) { + .run => |*run| pardes.walk.hash(pty.Run, run, h), + .event => |*reader| pardes.walk.hash(bool, reader, h), + .pager => |*serial| pardes.walk.hash(u32, serial, h), + .port => |*port| pardes.walk.hash(u8, &port.index, h), + .snapshot, .log, .frozen, .pty_data, .ctl, .lines, .writes, .plumb => {}, + } + } + }; pub const Replay = struct { off: u64, bytes: []u8 }; pub const Results = struct { + pub const replica = .{ .len = .{.{ "list", "len" }} }; list: [pardes.MAX_PANES]u32 = undefined, len: u8 = 0, /// Written on: reads are a stream from the write on, whatever @@ -230,7 +253,7 @@ pub const open_slots = 64; /// The record a request's handle names, when it was opened on that node. pub fn openOf(p: *Pardes, req: Req) ?*Open { - if (req.handle == 0 or req.handle > p.fs.opens.len) return null; + if (req.handle == 0 or req.handle > p.fs.opens_len) return null; const o = &p.fs.opens[req.handle - 1]; return if (o.node == req.node) o else null; } @@ -614,7 +637,7 @@ fn runAttr(p: *Pardes, req: Req, target: Target) ?Reply.Attr { .top, .col, .port => return null, }; if (t.file != .pty_run) return null; - const run = if (req.handle != 0) openOf(p, req) else for (&p.fs.opens) |*o| { + const run = if (req.handle != 0) openOf(p, req) else for (p.fs.opens[0..p.fs.opens_len]) |*o| { if (o.node == req.node and o.what == .run) break o; } else null; if ((run orelse return null).what != .run) return null; @@ -895,7 +918,7 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { .ctl => if (linesOpen(target, req)) .lines else .{ .frozen = &.{} }, // One writer of the rules at a time, as plumber(4)'s. .rules, .send => if (req.omode & 3 == 0) return .{ .tag = req.tag } else plumb: { - if (f == .rules) for (p.fs.opens) |o| if (o.node == req.node and o.what == .plumb) return failText(req.tag, E.BUSY, e_in_use); + if (f == .rules) for (p.fs.opens[0..p.fs.opens_len]) |o| if (o.node == req.node and o.what == .plumb) return failText(req.tag, E.BUSY, e_in_use); break :plumb .plumb; }, else => if (linesOpen(target, req)) .lines else return .{ .tag = req.tag }, @@ -934,7 +957,9 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { // record would be another than the session's. const i = p.tape.authority(freeOpen, .{p}) orelse return Reply.fail(req.tag, E.NFILE); const o = &p.fs.opens[i]; + // Past `opens_len` a record is nothing: written over, never freed. o.* = .{ .node = req.node, .what = what }; + p.fs.opens_len = @max(p.fs.opens_len, @as(u8, @intCast(i + 1))); if (resultsFile(target)) { @memcpy(o.results.list[0..p.fs.results_len], p.fs.results[0..p.fs.results_len]); o.results.len = p.fs.results_len; @@ -1074,6 +1099,7 @@ fn releaseHandle(p: *Pardes, req: Req) void { .snapshot, .log, .lines, .writes, .frozen, .pager, .plumb, .port => {}, }; o.deinit(p.gpa); + while (p.fs.opens_len > 0 and p.fs.opens[p.fs.opens_len - 1].node == 0) p.fs.opens_len -= 1; } fn setattr(p: *Pardes, req: Req, target: Target) Reply { diff --git a/core/panes.zig b/core/panes.zig index 89d9f309..15e1db50 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -27,12 +27,11 @@ pub const EditText = struct { text: []u8, row0: i32 }; pub const Pane = struct { /// What the replay digest leaves out (core/walk.zig): the view's geometry, - /// made again from the rest (File.geometry); the 9P server's record of - /// the pane's opens and readers; the other views' share of it (views.zig). + /// made again from the rest (File.geometry); the other views' share of + /// it (views.zig). (The 9P server's part of `fs` says so in its type.) pub const replica = .{ .local = .{ "pv", "pv_known" }, .derived = .{ "wrap_line", "wrap_col", "wrap_pad", "wrap_n", "body_wrapped", "context_rows", "body_rows", "body_visible_rows", "context_row_limit", "geometry_key", "geometry_len", "notices", "pan" }, - .authority = .{"fs"}, .len = .{ .{ "msg", "msg_len" }, .{ "msg_older", "msg_older_len" }, .{ "question", "question_len" }, .{ "shell_tail", "shell_tail_len" }, .{ "sel_snap", "nsel_snap" } }, // A picture's memory is its own allocator's (a dump loaded makes // it there). @@ -148,10 +147,10 @@ pub const Pane = struct { vweight: f32 = 1, /// A folded pane keeps its expansion weight, but occupies only its tag row. collapsed: bool = false, - /// The serial of the pane this one is attached to, its owner: a query + /// The serial of the pane this one is docked to, its owner: a query /// pane or its +Preview sits right under its owner in the owner's /// column, takes its rows from the owner alone, and moves, folds and - /// closes with it (layout.zig, "Attached panes"). An owner that is + /// closes with it (layout.zig, "Docked panes"). An owner that is /// gone, or a pane no longer right under its owner's group, leaves it /// an ordinary pane (layout.keepGroups). docked_to: ?u32 = null, @@ -1485,14 +1484,14 @@ pub fn paneDir(pane: *const Pane) []const u8 { pub fn removePane(p: *Pardes, id: usize, to: ?usize) error{OutOfMemory}!void { const v = p.view(); const pane = p.panes[id] orelse return; - // What is attached to it closes with it, first, each giving its rows + // What is docked to it closes with it, first, each giving its rows // back to it: then its rows, theirs among them, go where a pane's go. for (0..p.panes.len) |k| if (p.panes[k]) |other| if (k != id and other.docked_to == pane.serial) { if (layout.ownerOf(p, k) != id) continue; try p.removePane(k, id); layout.compute(p); }; - // An attachment's rows go back to its owner and nobody else. + // A docked pane's rows go back to its owner and nobody else. const owner = layout.ownerOf(p, id); const place = layout.findPane(p, id); const emptied = if (place) |f| (if (v.cols[f.col].n == 1) f.col else null) else null; diff --git a/core/replica.zig b/core/replica.zig index e05cf79e..39ee53b2 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -157,7 +157,7 @@ pub const Authority = struct { seq: u32 = 0, /// Each client's view (core/views.zig): its own layout, focus and /// cursors over the session's text. The first client has the session's. - view_of: [64]u8 = @splat(0), + view_of: [64]Pardes.View.Id = @splat(.at(0)), /// Steps of its own taken since the last unit (`output`): one unit, /// `pending`, sent before the next input it steps and at a frame. batched: u32 = 0, @@ -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); @@ -278,7 +279,7 @@ pub const Authority = struct { }; a.core.pump(a.host) catch {}; was.end(); - a.view_of[client] = k.index(); + a.view_of[client] = k; a.seq += 1; return .{ .view = k.index(), .unit = try a.unit(0, a.seq) }; } @@ -295,7 +296,7 @@ pub const Authority = struct { const again = if (back) |v| a.core.rejoinView(.at(v)) else false; const k = (if (again) back else if (a.core.openView()) |o| o.index() else null) orelse return null; a.core.undrawn |= @as(u8, 1) << @intCast(k); - a.view_of[client] = k; + a.view_of[client] = .at(k); a.seq += 1; const u = try a.unit(0, a.seq); var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; @@ -321,8 +322,8 @@ pub const Authority = struct { std.debug.assert(a.batched == 0); const was = Stepping.begin(&a.t, null); const k = a.view_of[client]; - a.core.undrawn &= ~(@as(u8, 1) << @intCast(k)); - if (again) a.core.awayView(.at(k)) else a.core.closeView(.at(k)); + a.core.undrawn &= ~(@as(u8, 1) << @intCast(k.index())); + if (again) a.core.awayView(k) else a.core.closeView(k); was.end(); a.seq += 1; return a.unit(0, a.seq); @@ -332,7 +333,7 @@ pub const Authority = struct { pub fn closeView(a: *Authority, client: u16) ![]const u8 { std.debug.assert(a.batched == 0); const was = Stepping.begin(&a.t, null); - a.core.closeView(.at(a.view_of[client])); + a.core.closeView(a.view_of[client]); was.end(); a.seq += 1; return a.unit(0, a.seq); @@ -344,7 +345,7 @@ pub const Authority = struct { std.debug.assert(a.batched == 0); const in = parseInput(msg) orelse return error.BadInput; const was = Stepping.begin(&a.t, null); - a.core.toView(.at(a.view_of[in.client])); + a.core.toView(a.view_of[in.client]); a.t.stamp = stampOf(in); a.core.update(in.event); a.core.step(); @@ -449,7 +450,7 @@ pub const Screens = struct { /// What `peer` is owed of every terminal, each a message onto `out` /// (owned): nothing for one it has as it is, or with `bound` in flight. - pub fn flush(s: *Screens, core: *Pardes, peer: u16, _: u8, out: *std.ArrayListUnmanaged([]u8)) !void { + pub fn flush(s: *Screens, core: *Pardes, peer: u16, out: *std.ArrayListUnmanaged([]u8)) !void { const t0 = nowNs(); defer s.encode_ns += nowNs() - t0; for (core.panes, 0..) |slot, id| { @@ -1667,12 +1668,14 @@ pub const Peer = struct { peers: *Peers, fd: c_int, id: u16, - view: u8, + view: Pardes.View.Id, /// Its process (its socket's peer), for `--ps`; 0 not known. pid: libc.pid_t = 0, /// Its bye said it joins again for its view (a divergence's rejoin): /// kept for it (views.away), not closed. Its reader's, read after its end. again: bool = false, + /// ...or that its window was closed (Peers.closed). + close: bool = false, /// Its number in the session's `Screens`. sid: u16 = 0, /// Inputs read (each one's seq, as the client numbered them). @@ -1943,7 +1946,9 @@ pub const Peer = struct { switch (t) { .hello => return false, .bye => { - peer.again = (wire.decodeClient(tag, payload) catch return false).bye.again; + const b = (wire.decodeClient(tag, payload) catch return false).bye; + peer.again = b.again; + peer.close = b.close; return false; }, .ping => { @@ -2066,6 +2071,10 @@ pub const Peers = struct { /// No frontend of its own (the host says): with no client either, the /// session is unattended. detached: bool = false, + /// Its last client left with a close (its window closed, its terminal + /// hung up) and the session is a pair's not kept (daemon.sessionState): it + /// ends there (runtime/session.zig). + closed: bool = false, /// The worst a join cost the session's step, and the last one's dump. join_ns: u64 = 0, each_join: std.ArrayListUnmanaged(u64) = .empty, @@ -2204,7 +2213,7 @@ pub const Peers = struct { // The terminals as this step reads them, then the step, the rows // it read, its unit (part B terminal notes' order). ps.screensOut(core, .flush); - core.toView(.at(peer.view)); + core.toView(peer.view); ps.t.stamp = stampOf(in); core.update(in.event); core.step(); @@ -2242,7 +2251,7 @@ pub const Peers = struct { ps.msgs.clearRetainingCapacity(); } (switch (what) { - .flush => ps.screens.flush(core, peer.sid, peer.view, &ps.msgs), + .flush => ps.screens.flush(core, peer.sid, &ps.msgs), .fill => ps.screens.fill(core, peer.sid, &ps.msgs), }) catch return; if (what == .flush) if (ps.flushed) |h| h.f(h.ctx, core, &ps.screens); @@ -2328,12 +2337,12 @@ pub const Peers = struct { core.gpa.free(bytes); return daemon.refuseReplica(fd, "out of memory"); }; - peer.* = .{ .peers = ps, .fd = fd, .id = ps.next_id, .view = k, .dump = bytes, .blobs = blobs, .dump_gpa = core.gpa }; + peer.* = .{ .peers = ps, .fd = fd, .id = ps.next_id, .view = .at(k), .dump = bytes, .blobs = blobs, .dump_gpa = core.gpa }; ps.next_id +%= 1; if (ps.next_id == 0) ps.next_id = 1; // The session's digest as dumped, for the joiner to check its load by. const digest = tape.digestOf(core); - peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = @intCast(libc.getpid()), .session = ps.name[0..@min(ps.name.len, wire.max_name)], .client = peer.id, .view = .at(k), .dump_len = whole, .gmtoff = gmtoff(), .digest = digest, .semantics = wire.semantics, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len; + peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = @intCast(libc.getpid()), .session = ps.name[0..@min(ps.name.len, wire.max_name)], .client = peer.id, .view = peer.view, .dump_len = whole, .gmtoff = gmtoff(), .digest = digest, .semantics = wire.semantics, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len; if (ps.threads) peer.writer = std.Thread.spawn(.{}, Peer.writeLoop, .{peer}) catch null; if (ps.threads) peer.reader = std.Thread.spawn(.{}, Peer.readLoop, .{peer}) catch null; if (ps.threads and (peer.writer == null or peer.reader == null)) { @@ -2362,11 +2371,12 @@ pub const Peers = struct { log.info("client {d} left '{s}'", .{ peer.id, ps.name }); ps.tellClients(); ps.screens.dropPeer(peer.sid); - core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view)); + core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view.index())); // Cut off, it joins again after the words why (`send`); its reader // has ended and no other thread sets `cut` now. ps.closeViewOf(core, peer, peer.again or peer.cut); if (ps.count() == 0) core.unattended = ps.detached; + if (ps.count() == 0 and peer.close and daemon.sessionState() == .pair) ps.closed = true; ps.seq += 1; ps.unit(0, ps.seq); ps.letGo(peer); @@ -2378,7 +2388,7 @@ pub const Peers = struct { /// session no one else watches leaves the session its layout, for a /// client that comes after to find. fn closeViewOf(ps: *Peers, core: *Pardes, peer: *Peer, again: bool) void { - if (again) core.awayView(.at(peer.view)) else if (ps.count() == 0 and ps.detached) core.leaveView(.at(peer.view)) else core.closeView(.at(peer.view)); + if (again) core.awayView(peer.view) else if (ps.count() == 0 and ps.detached) core.leaveView(peer.view) else core.closeView(peer.view); } /// Its threads ended and joined, its link closed. @@ -2470,7 +2480,8 @@ pub const Peers = struct { /// Detach typed in client view `k`'s: told it left the session running /// (`left`), its last word; the client goes, and its reader says so. pub fn detach(ps: *Peers, k: u8) bool { - for (ps.list) |slot| if (slot) |peer| if (peer.view == k) { + for (ps.list) |slot| if (slot) |peer| if (peer.view.index() == k) { + daemon.keepSession(); var out: [wire.max_name + 8]u8 = undefined; peer.last(wire.encodeServer(&out, .{ .left = ps.name[0..@min(ps.name.len, wire.max_name)] }) catch unreachable); return true; @@ -2507,7 +2518,7 @@ pub const Peers = struct { fn drop(ps: *Peers, core: *Pardes, again: bool) void { for (&ps.list) |*slot| if (slot.*) |peer| { slot.* = null; - core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view)); + core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view.index())); ps.closeViewOf(core, peer, again); ps.screens.dropPeer(peer.sid); ps.letGo(peer); @@ -2941,10 +2952,11 @@ pub fn askCheck(fd: c_int) bool { return writeAll(fd, wire.encodeClient(&out, .check) catch unreachable); } -/// The client's last word: `again`, it joins again for its view at once. -pub fn bye(fd: c_int, again: bool) void { +/// The client's last word: `again`, it joins again for its view at once; +/// `close`, its window was closed. +pub fn bye(fd: c_int, how: @FieldType(wire.ClientMsg, "bye")) void { var out: [16]u8 = undefined; - if (wire.encodeClient(&out, .{ .bye = .{ .again = again } })) |b| _ = writeAll(fd, b) else |_| {} + if (wire.encodeClient(&out, .{ .bye = how })) |b| _ = writeAll(fd, b) else |_| {} } /// What the session streams a client after its dump, as its frontend's loop @@ -2998,6 +3010,13 @@ pub fn ended(why: []const u8) bool { /// The words a client goes with when its session runs another build now. const upgrade_words = "session upgraded to a newer pardes: upgrade this client too"; +/// A join's failure that is its session's running another build now: a +/// client whose own start path holds a newer one execs that instead +/// (runtime/client.zig). +pub fn otherBuild(why: []const u8) bool { + return std.mem.endsWith(u8, std.mem.sliceTo(why, 0), upgrade_words); +} + /// A replica client's join, the terminal's and the window's alike (their /// `runClient`): the session at `path` dialled (or, first, the one on its /// pair, `o.pair`), its build checked to be this @@ -3022,7 +3041,10 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o }; if (have) |h| h.left(); prev.deinit(); - } else j.* = sameBuild(gpa, (if (o.pair) |fd| joinOn(gpa, fd, null, why, have, null) else dial(gpa, path, session, why, have, null)) orelse return null, why) orelse return null; + } else j.* = (if (o.join_view) |v| + redial(gpa, path, session, why, have, true, v) + else + sameBuild(gpa, (if (o.pair) |fd| joinOn(gpa, fd, null, why, have, null) else dial(gpa, path, session, why, have, null)) orelse return null, why)) orelse return null; defer { if (have) |h| h.store(gpa, j) else gpa.free(j.dump); j.dump = &.{}; @@ -3057,7 +3079,7 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o /// an upgrade under way may not have said yet. fn sameBuild(gpa: Allocator, j: Joined, why: []u8) ?Joined { if (j.semantics == wire.semantics) return j; - bye(j.fd, false); + bye(j.fd, .{}); _ = libc.close(j.fd); var jj = j; jj.rest.deinit(gpa); @@ -3078,7 +3100,10 @@ fn redial(gpa: Allocator, path: []const u8, session: []const u8, why: *[600]u8, while (true) : (tries += 1) { why.* = @splat(0); if (dial(gpa, path, session, why, have, view)) |j| return sameBuild(gpa, j, why); - if (std.mem.indexOf(u8, std.mem.sliceTo(why, 0), "runs another build") != null) { + // Another build, or another protocol (the daemon moved with its + // session): no dial again will do. + const words = std.mem.sliceTo(why, 0); + if (std.mem.indexOf(u8, words, "runs another build") != null or std.mem.indexOf(u8, words, "run the same pardes at both ends") != null) { _ = std.fmt.bufPrint(why, "{s}\x00", .{upgrade_words}) catch {}; return null; } @@ -3099,6 +3124,8 @@ pub const Link = struct { r: *Replica, fd: c_int, quit: bool = false, + /// ...because its window was closed: said in its bye. + close: bool = false, /// The session hung up. gone: bool = false, /// Something to draw: an input applied, a unit taken. @@ -3501,7 +3528,7 @@ fn deliver(a: *Authority, screens: *Screens, peer: u16, r: *Replica, comptime wh msgs.deinit(gpa); } switch (what) { - .flush => try screens.flush(a.core, peer, r.view, &msgs), + .flush => try screens.flush(a.core, peer, &msgs), .fill => { try screens.fill(a.core, peer, &msgs); screens.filled(a.core); @@ -3534,7 +3561,7 @@ fn farJoinOnce(ps: *Peers, core: *Pardes, have: ?*Have) !Joined { var whole = state.len; for (blobs.items) |b| whole += b.bytes.len; const peer = try ps.gpa.create(Peer); - peer.* = .{ .peers = ps, .fd = fds[0], .id = 1, .view = 0, .dump = state, .blobs = blobs, .dump_gpa = core.gpa }; + peer.* = .{ .peers = ps, .fd = fds[0], .id = 1, .view = .at(0), .dump = state, .blobs = blobs, .dump_gpa = core.gpa }; peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = 1, .session = "t", .dump_len = whole, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len; const Serve = struct { fn run(p: *Peer) void { @@ -5289,7 +5316,7 @@ test "a client that diverged joins again for its view: kept for it meanwhile, it const back = try joinedNow(a, 3, opened.view); defer back.deinit(); try std.testing.expectEqual(digestOf(a), back.digest()); - a.view_of[3] = opened.view; + a.view_of[3] = .at(opened.view); const u = try gpa.dupe(u8, try a.take(try back.input(.{ .key = .{ .cp = 'l', .text = "l" } }))); defer gpa.free(u); old.confirm(u); @@ -5391,13 +5418,13 @@ test "a client cut off for what it left unread is told why and joins again for i // ...once its old link's end is heard: its view kept for it meanwhile. ps.post(.{ .gone = first.peer }); ps.boundary(core); - try std.testing.expect(pardes.views.isAway(core, view)); + try std.testing.expect(pardes.views.isAway(core, view.index())); first.r.deinit(); _ = libc.close(fd); - const back = try MemoryLinks.join(&ps, core, view, &fd); + const back = try MemoryLinks.join(&ps, core, view.index(), &fd); defer back.r.deinit(); try std.testing.expectEqual(view, back.peer.view); - link.reset(back.r, &.{ .fd = fd, .pid = 0, .client = back.r.id, .view = view, .gmtoff = 0, .dump = &.{} }); + link.reset(back.r, &.{ .fd = fd, .pid = 0, .client = back.r.id, .view = view.index(), .gmtoff = 0, .dump = &.{} }); core.update(.{ .paste = "back" }); try core.pump(core.host); ps.boundary(core); @@ -5462,7 +5489,7 @@ test "a client's writer, the client cut off while it waits on the socket, writes if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; defer _ = libc.close(fds[1]); const peer = try gpa.create(Peer); - peer.* = .{ .peers = &ps, .fd = fds[0], .id = 1, .view = 0, .dump_gpa = gpa, .far = false, .limit = 256 << 10 }; + peer.* = .{ .peers = &ps, .fd = fds[0], .id = 1, .view = .at(0), .dump_gpa = gpa, .far = false, .limit = 256 << 10 }; peer.welcome_len = (try wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = 1, .session = "t" } })).len; peer.writer = try std.Thread.spawn(.{}, Peer.writeLoop, .{peer}); defer ps.letGo(peer); @@ -7222,9 +7249,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); } @@ -7476,6 +7500,111 @@ test "a client of screen-state terminals takes a 9P pty/run in a shell as the se try agrees(a, late); } +// daemon.py --clients' client C (2026-11-20): idle, a copy taken ahead; the +// session's script opens pty/run and its command prints, replayed over the +// copy and kept; the client types into the shell, its speculation stops at +// the pty write, and the rollback replays the open again over a record the +// copy never held (it holds the opens as far as `opens_len`), whose line +// and output the epoch had freed: freed again there, the client's C heap +// was corrupt. +test "a 9P open the session made over a copy taken ahead, replayed after a rollback: the record past the opens the copy holds is written over, never freed again" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const RunHost = struct { + fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool { + return false; + } + fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {} + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write }; + }; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &RunHost.vtable }, true); + defer a.deinit(); + var screens: Screens = .init(gpa); + defer screens.deinit(a.core); + const peer = try screens.addPeer(); + const r = try Replica.init(gpa, 1, try a.unit(0, 0), true); + defer r.deinit(); + const shell: u8 = for (a.core.panes, 0..) |slot, id| { + if (slot) |pane| if (pane.isTerminal()) break @intCast(id); + } else return error.NoShell; + const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; + a.output(.{ .output = .{ .pane = .at(shell), .bytes = prompt } }); + r.confirm((try a.pending()).?); + try deliver(a, &screens, peer, r, .flush); + r.ready(); + try std.testing.expect(r.copy.held and r.core().fs.opens_len == 0); + const node = pardes.ctlfs.Node.of(a.core.panes[shell].?.serial, .pty_run); + const Serve = struct { + fn serve(s: *Authority, x: *Replica, req: pardes.ctlfs.Req) !pardes.ctlfs.Reply { + const was = Stepping.begin(&s.t, null); + const reply = s.core.serveFs(req); + s.core.pump(s.host) catch {}; + was.end(); + s.seq += 1; + const u = try std.testing.allocator.dupe(u8, try s.unit(0, s.seq)); + defer std.testing.allocator.free(u); + x.confirm(u); + x.settle(); + return reply; + } + }; + const h = (try Serve.serve(a, r, .{ .tag = 1, .op = .open, .node = node, .omode = 2 })).handle; + _ = try Serve.serve(a, r, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "echo x\n" }); + a.output(.{ .output = .{ .pane = .at(shell), .bytes = "echo x\r\n\x1b]133;C;aid=pardes\x07x\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt } }); + r.confirm((try a.pending()).?); + r.settle(); + // Kept over the copy: the record past its opens holds the run's output. + try std.testing.expect(r.copy.held and r.since.items.len > 0); + try std.testing.expectEqualStrings("x\n", r.core().fs.opens[h - 1].what.run.output); + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| gpa.free(m); + sent.deinit(gpa); + } + // A key into the shell: its speculation stops at the pty write, and + // the copy is put back, the units since replayed (the open again). + try key(r, 'e', &sent); + try std.testing.expect(r.applied == 0 and r.stats.stopped > 0); + r.confirm(try a.take(sent.items[0])); + r.settle(); + try deliver(a, &screens, peer, r, .flush); + _ = try Serve.serve(a, r, .{ .tag = 3, .op = .release, .node = node, .handle = h, .opened = true }); + if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); + try std.testing.expect(r.diverged == null and r.quiet()); + try agrees(a, r); +} + +test "a script's half line held over a copy taken ahead, its next write run and its rest moved to the front in place, put back by a rollback: the line replayed is the session's" { + var n = try NinepJoin.init("one\n", TestHost.host()); + defer n.deinit(); + try n.join(); + const r = n.late.?; + const exec = n.node(.exec); + const h = (try n.serve(.{ .tag = 1, .op = .open, .node = exec, .omode = 1 }, true)).handle; + _ = try n.serve(.{ .tag = 2, .op = .write, .node = exec, .handle = h, .data = "Ta" }, true); + r.ready(); + // Replayed over the copy and kept: `Tab 8` runs, `Un` is held where + // `Ta` was, in the buffer the copy holds. + _ = try n.serve(.{ .tag = 3, .op = .write, .node = exec, .handle = h, .data = "b 8\nUn" }, true); + try std.testing.expect(r.copy.held and r.since.items.len > 0); + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| std.testing.allocator.free(m); + sent.deinit(std.testing.allocator); + } + try key(r, 'l', &sent); + try std.testing.expectEqual(@as(usize, 1), r.applied); + // The session's key first: a rollback, the write replayed again. + try n.send(try n.a.local(.{ .key = .{ .cp = 'j', .text = "j" } })); + try std.testing.expect(r.stats.foreign > 0); + try n.send(try n.a.take(sent.items[0])); + _ = try n.serve(.{ .tag = 4, .op = .write, .node = exec, .handle = h, .data = "do\n" }, true); + _ = try n.serve(.{ .tag = 5, .op = .release, .node = exec, .handle = h, .opened = true }, true); + if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); + try std.testing.expect(r.diverged == null and r.quiet()); + try n.agree(); +} + // Del with a pane above and below asks which way the space goes, its // question shown once a delay is up (builtins.zig): its time was the // host's clock read in the step, an answering entry a speculation stops at. @@ -7523,3 +7652,376 @@ test "a far client's Del with panes above and below is applied at once, and its try agrees(a, r); try std.testing.expectEqual(Clocked.now_ns + pardes.config.del_question_delay_ns, r.core().panes[mid].?.question_due_ns); } + +// ---- a client that joins a session with 9P work under way ---- +// +// A 9P request is an input every replica replays, so the state the 9P +// tree builds from the requests (the open records, each pane's `fs`) is +// a client's for everything after its join: what was made before it +// comes in the join's dump, or the client steps the next request +// otherwise than its session. + +/// A session with a file pane and its 9P server, and a client joined +/// from its dump (`join`) that takes every unit after. +const NinepJoin = struct { + a: *Authority, + late: ?*Replica = null, + serial: u32, + + fn init(text: []const u8, host: pardes.Host) !NinepJoin { + const a = try Authority.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, host, false); + errdefer a.deinit(); + const was = Stepping.begin(&a.t, null); + const pane = try a.core.setTestFile(text); + was.end(); + _ = try a.unit(0, 0); + return .{ .a = a, .serial = pane.serial }; + } + + fn deinit(n: *NinepJoin) void { + if (n.late) |r| r.deinit(); + n.a.deinit(); + } + + fn node(n: *const NinepJoin, file: pardes.ctlfs.PaneFile) u64 { + return pardes.ctlfs.Node.of(n.serial, file); + } + + /// One request as the session's 9P server serves it, a step of its + /// own, then (`pumped`) its loop's pass: a join can come between the + /// two, the session's loop being elsewhere. Its unit to the client. + fn serve(n: *NinepJoin, req: pardes.ctlfs.Req, pumped: bool) !pardes.ctlfs.Reply { + const a = n.a; + const was = Stepping.begin(&a.t, null); + const reply = a.core.serveFs(req); + if (pumped) a.core.pump(a.host) catch {}; + was.end(); + a.seq += 1; + try n.send(try a.unit(0, a.seq)); + return reply; + } + + /// A pass of the session's loop with no request: its unit. + fn pump(n: *NinepJoin) !void { + n.a.pump(); + try n.send((try n.a.pending()).?); + } + + fn send(n: *NinepJoin, u: []const u8) !void { + const r = n.late orelse return; + const kept = try std.testing.allocator.dupe(u8, u); + defer std.testing.allocator.free(kept); + r.confirm(kept); + r.settle(); + } + + /// A client joins now, from the session's dump, at the digest the + /// session had. + fn join(n: *NinepJoin) !void { + const joined = (try n.a.join(1, null)).?; + defer std.testing.allocator.free(joined.dump); + const r = try Replica.initDump(std.testing.allocator, 1, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); + r.t.screen_state = false; + r.core().echo = null; + n.late = r; + try std.testing.expectEqual(joined.digest, r.digest()); + } + + fn agree(n: *NinepJoin) !void { + try agrees(n.a, n.late.?); + } +}; + +test "a client joined while a script's open of a pane's exec holds half a line runs the line its session runs" { + var n = try NinepJoin.init("one\n", TestHost.host()); + defer n.deinit(); + const exec = n.node(.exec); + const h = (try n.serve(.{ .tag = 1, .op = .open, .node = exec, .omode = 1 }, true)).handle; + _ = try n.serve(.{ .tag = 2, .op = .write, .node = exec, .handle = h, .data = "Ne" }, true); + try n.join(); + _ = try n.serve(.{ .tag = 3, .op = .write, .node = exec, .handle = h, .data = "w\n" }, true); + _ = try n.serve(.{ .tag = 4, .op = .release, .node = exec, .handle = h, .opened = true }, true); + try n.agree(); +} + +test "a client joined between two writes of one open to a body makes them one undo step, as its session does" { + var n = try NinepJoin.init("one\n", TestHost.host()); + defer n.deinit(); + const body = n.node(.body); + const h = (try n.serve(.{ .tag = 1, .op = .open, .node = body, .omode = 1 }, true)).handle; + _ = try n.serve(.{ .tag = 2, .op = .write, .node = body, .handle = h, .data = "a\n" }, true); + try n.join(); + _ = try n.serve(.{ .tag = 3, .op = .write, .node = body, .handle = h, .data = "b\n" }, true); + _ = try n.serve(.{ .tag = 4, .op = .release, .node = body, .handle = h, .opened = true }, true); + _ = try n.serve(.{ .tag = 5, .op = .write, .node = n.node(.ctl), .data = "Undo" }, true); + try n.agree(); +} + +test "a client joined while a script's ctl open holds a pane's lock refuses another open's lock, as its session does" { + var n = try NinepJoin.init("one\n", TestHost.host()); + defer n.deinit(); + const ctl = n.node(.ctl); + const h = (try n.serve(.{ .tag = 1, .op = .open, .node = ctl, .omode = 1 }, true)).handle; + _ = try n.serve(.{ .tag = 2, .op = .write, .node = ctl, .handle = h, .data = "lock\n" }, true); + try n.join(); + const g = (try n.serve(.{ .tag = 3, .op = .open, .node = ctl, .omode = 1 }, true)).handle; + try std.testing.expectEqual(pardes.ctlfs.Status.err, (try n.serve(.{ .tag = 4, .op = .write, .node = ctl, .handle = g, .data = "lock\n" }, true)).status); + // Who holds it, by name: on the base no digest covered it. + const id = n.a.core.paneBySerial(n.serial).?; + try std.testing.expectEqual(n.a.core.panes[id].?.fs.lock, n.late.?.core().panes[id].?.fs.lock); + try n.agree(); + _ = try n.serve(.{ .tag = 5, .op = .release, .node = ctl, .handle = g, .opened = true }, true); + _ = try n.serve(.{ .tag = 6, .op = .release, .node = ctl, .handle = h, .opened = true }, true); + try n.agree(); +} + +test "a client joined after a script set a pane's addr, its limit, or truncated its dot writes where its session writes" { + // addr: the next data write replaces what it says. + { + var n = try NinepJoin.init("one two\nthree\n", TestHost.host()); + defer n.deinit(); + _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.addr), .data = "/two/" }, true); + try n.join(); + _ = try n.serve(.{ .tag = 2, .op = .write, .node = n.node(.data), .data = "2" }, true); + try n.agree(); + } + // limit: an address is looked for inside it. + { + var n = try NinepJoin.init("one two\nthree\n", TestHost.host()); + defer n.deinit(); + _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.limit), .data = "#0,#3" }, true); + try n.join(); + _ = try n.serve(.{ .tag = 2, .op = .write, .node = n.node(.addr), .data = "/two/" }, true); + _ = try n.serve(.{ .tag = 3, .op = .write, .node = n.node(.data), .data = "2" }, true); + try n.agree(); + } + // dot truncated: its open's release with no write empties it. + { + var n = try NinepJoin.init("one two\nthree\n", TestHost.host()); + defer n.deinit(); + const dot = n.node(.dot); + _ = try n.serve(.{ .tag = 1, .op = .write, .node = dot, .data = "#0,#3" }, true); + const h = (try n.serve(.{ .tag = 2, .op = .open, .node = dot, .omode = 1 }, true)).handle; + _ = try n.serve(.{ .tag = 3, .op = .setattr, .node = dot, .handle = h, .truncate = true }, true); + try n.join(); + _ = try n.serve(.{ .tag = 4, .op = .release, .node = dot, .handle = h, .opened = true }, true); + try n.agree(); + } +} + +test "a client joined between two writes of one open to a pane's sel runs the second on from the first, as its session does" { + var n = try NinepJoin.init("one two\n", TestHost.host()); + defer n.deinit(); + const sel = n.node(.sel); + const h = (try n.serve(.{ .tag = 1, .op = .open, .node = sel, .omode = 1 }, true)).handle; + _ = try n.serve(.{ .tag = 2, .op = .write, .node = sel, .handle = h, .data = "a" }, true); + try n.join(); + _ = try n.serve(.{ .tag = 3, .op = .write, .node = sel, .handle = h, .data = "b" }, true); + _ = try n.serve(.{ .tag = 4, .op = .release, .node = sel, .handle = h, .opened = true }, true); + try n.agree(); +} + +test "a client joined after a script's nomark or noscroll writes as its session does" { + // nomark: writes under it are one undo step. + { + var n = try NinepJoin.init("one\n", TestHost.host()); + defer n.deinit(); + _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.ctl), .data = "nomark" }, true); + try n.join(); + // Two opens' writes, each its own undo step but for nomark. + const body = n.node(.body); + for ([_][]const u8{ "two\n", "three\n" }) |text| { + const h = (try n.serve(.{ .tag = 2, .op = .open, .node = body, .omode = 1 }, true)).handle; + _ = try n.serve(.{ .tag = 3, .op = .write, .node = body, .handle = h, .data = text }, true); + _ = try n.serve(.{ .tag = 4, .op = .release, .node = body, .handle = h, .opened = true }, true); + } + _ = try n.serve(.{ .tag = 5, .op = .write, .node = n.node(.ctl), .data = "mark" }, true); + _ = try n.serve(.{ .tag = 6, .op = .write, .node = n.node(.ctl), .data = "Undo" }, true); + try n.agree(); + } + // noscroll: a write past the screen leaves the view where it was. + { + var n = try NinepJoin.init("one\n", TestHost.host()); + defer n.deinit(); + _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.scroll), .data = "0" }, true); + try n.join(); + _ = try n.serve(.{ .tag = 2, .op = .write, .node = n.node(.body), .data = &@as([100]u8, @splat('\n')) }, true); + try n.agree(); + } +} + +test "a client joined after a script truncated a pane's tag writes the tag its session writes" { + var n = try NinepJoin.init("one\n", TestHost.host()); + defer n.deinit(); + const tag = n.node(.tag); + const h = (try n.serve(.{ .tag = 1, .op = .open, .node = tag, .omode = 1 }, true)).handle; + _ = try n.serve(.{ .tag = 2, .op = .setattr, .node = tag, .handle = h, .truncate = true }, true); + try n.join(); + _ = try n.serve(.{ .tag = 3, .op = .write, .node = tag, .handle = h, .data = "Get Put\n" }, true); + _ = try n.serve(.{ .tag = 4, .op = .release, .node = tag, .handle = h, .opened = true }, true); + try n.agree(); +} + +test "a client joined after a script truncated the workspace's tag writes the tag its session writes" { + var n = try NinepJoin.init("one\n", TestHost.host()); + defer n.deinit(); + const tag: u64 = @backingInt(pardes.ctlfs.TopFile.tag); + const h = (try n.serve(.{ .tag = 1, .op = .open, .node = tag, .omode = 1 }, true)).handle; + _ = try n.serve(.{ .tag = 2, .op = .setattr, .node = tag, .handle = h, .truncate = true }, true); + try n.join(); + _ = try n.serve(.{ .tag = 3, .op = .write, .node = tag, .handle = h, .data = "Exit\n" }, true); + _ = try n.serve(.{ .tag = 4, .op = .release, .node = tag, .handle = h, .opened = true }, true); + try n.agree(); +} + +test "a client joined while a chorded exec waits for its event reader's write-back runs it with its argument, as its session does" { + var n = try NinepJoin.init("Msg said\narg-text\n", TestHost.host()); + defer n.deinit(); + const event = n.node(.event); + const h = (try n.serve(.{ .tag = 1, .op = .open, .node = event, .omode = 2 }, true)).handle; + // The session's chorded click, told to the reader, its argument kept. + { + const was = Stepping.begin(&n.a.t, null); + const id = n.a.core.paneBySerial(n.serial).?; + try std.testing.expect(pardes.mouse.reportRange(n.a.core, id, pardes.config.exec_cmd, "Msg", false, .{ .q0 = 0, .q1 = 3 }, "arg-text")); + was.end(); + n.a.seq += 1; + _ = try n.a.unit(0, n.a.seq); + } + try n.join(); + // The command's record written back alone: its argument is the one kept. + _ = try n.serve(.{ .tag = 2, .op = .write, .node = event, .handle = h, .data = "MX0 3 9 3 Msg\n" }, true); + _ = try n.serve(.{ .tag = 3, .op = .release, .node = event, .handle = h, .opened = true }, true); + try n.agree(); +} + +test "a client joined while a script's writes to a body are held to go in as one edit puts them in as its session does" { + // A host with a clock: held writes go in once they have paused + // (pane.batch_pause_ns), and the join came before that. + const Clock = struct { + var now_ns: u64 = 5 * std.time.ns_per_s; + fn now(_: ?*anyopaque) u64 { + return now_ns; + } + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .now = now }; + }; + var n = try NinepJoin.init("one\n", .{ .vtable = &Clock.vtable }); + defer n.deinit(); + const body = n.node(.body); + const h = (try n.serve(.{ .tag = 1, .op = .open, .node = body, .omode = 1 }, true)).handle; + _ = try n.serve(.{ .tag = 2, .op = .write, .node = body, .handle = h, .data = "two\n" }, true); + try std.testing.expect(n.a.core.fs.batch.bytes.items.len > 0); + try n.join(); + Clock.now_ns += std.time.ns_per_s; + try n.pump(); + try n.agree(); + _ = try n.serve(.{ .tag = 3, .op = .release, .node = body, .handle = h, .opened = true }, true); + try n.agree(); +} + +test "a client runs an Edit a script's write started once, as its session does, when the held write is asked again" { + var n = try NinepJoin.init("b\na\n", TestHost.host()); + defer n.deinit(); + try n.join(); + const ctl = n.node(.ctl); + const req: pardes.ctlfs.Req = .{ .tag = 7, .op = .write, .node = ctl, .data = "Edit , | sort\n" }; + // The step alone: its loop's pass would run the command (here, with no + // host to run it, fail it). + const first = try n.serve(req, false); + try std.testing.expectEqual(pardes.ctlfs.Status.ok, first.status); + // The write held as the session's listener holds it (runtime/9p_io.zig). + n.a.core.fs.edit_hold = .{ .asker = @ptrCast(n.a.core), .slot = 0, .seq = 1, .tag = req.tag, .node = ctl, .handle = 0, .written = first.written }; + // Its command answers: the Edit is done. + n.a.apply(.{ .pipe_resp = .{ .id = n.a.core.pipe.edit_run.?.id, .success = true, .outputs = &.{"a\nb\n"} } }); + n.a.seq += 1; + try n.send(try n.a.unit(0, n.a.seq)); + try n.agree(); + // A retry of the held write's park, as the listener serves it: its + // answer from the hold, no step, the Edit not run again by anyone. + const again = pardes.filesystem.EditHold.retried(&n.a.core.fs, req) orelse try n.serve(req, true); + try std.testing.expectEqual(pardes.ctlfs.Status.ok, again.status); + try std.testing.expect(n.a.core.pipe.edit_run == null); + try n.agree(); +} + +test "an Edit's stop token is each process's own (selection_pipe.next_token): a client's differs from its session's, and they agree" { + var n = try NinepJoin.init("b\na\n", TestHost.host()); + defer n.deinit(); + try n.join(); + _ = try n.serve(.{ .tag = 1, .op = .write, .node = n.node(.ctl), .data = "Edit , | sort\n" }, false); + const session = n.a.core.pipe.edit_run.?.request.token; + const client = n.late.?.core().pipe.edit_run.?.request.token; + try std.testing.expect(session != client); + try n.agree(); +} + +/// A session with a shell, for a run's 9P state across a join: a host +/// whose pty takes the line and whose tty nobody else holds. +const RunJoin = struct { + fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool { + return false; + } + fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {} + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write }; + const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; + + /// The session at its shell's first prompt, and the shell's slot. + fn init(n: *NinepJoin) !u8 { + const a = try Authority.init(std.testing.allocator, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &vtable }, false); + n.* = .{ .a = a, .serial = 0 }; + _ = try a.unit(0, 0); + const shell: u8 = for (a.core.panes, 0..) |slot, id| { + if (slot) |pane| if (pane.isTerminal()) break @intCast(id); + } else return error.NoShell; + n.serial = a.core.panes[shell].?.serial; + return shell; + } + + fn output(n: *NinepJoin, shell: u8, bytes: []const u8) !void { + n.a.output(.{ .output = .{ .pane = .at(shell), .bytes = bytes } }); + try n.send((try n.a.pending()).?); + } +}; + +test "a client joined while a script's pty/run waits on the command it sent ends the run as its session does" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + var n: NinepJoin = undefined; + const shell = try RunJoin.init(&n); + defer n.deinit(); + // The shell's greeting (`ls`) run at its first prompt, done. + try RunJoin.output(&n, shell, RunJoin.prompt ++ "ls\r\n\x1b]133;C;aid=pardes\x07a b\r\n\x1b]133;D;0;aid=pardes\x07" ++ RunJoin.prompt); + const run = n.node(.pty_run); + const h = (try n.serve(.{ .tag = 1, .op = .open, .node = run, .omode = 2 }, true)).handle; + _ = try n.serve(.{ .tag = 2, .op = .write, .node = run, .handle = h, .data = "true\n" }, true); + try n.join(); + try RunJoin.output(&n, shell, "true\r\n\x1b]133;C;aid=pardes\x07\x1b]133;D;0;aid=pardes\x07" ++ RunJoin.prompt); + const answer = try n.serve(.{ .tag = 3, .op = .read, .node = run, .handle = h, .size = 64 }, true); + try std.testing.expectEqualStrings("exit 0\n", n.a.core.fsPayload(answer)); + // The open's next line, sent at the prompt the first left. + _ = try n.serve(.{ .tag = 4, .op = .write, .node = run, .handle = h, .data = "false\n" }, true); + try RunJoin.output(&n, shell, "false\r\n\x1b]133;C;aid=pardes\x07\x1b]133;D;1;aid=pardes\x07" ++ RunJoin.prompt); + _ = try n.serve(.{ .tag = 5, .op = .release, .node = run, .handle = h, .opened = true }, true); + try n.agree(); +} + +test "a client joined after its session's shell was found to have no prompt marks answers a pty/run as its session does" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + var n: NinepJoin = undefined; + const shell = try RunJoin.init(&n); + defer n.deinit(); + { + const was = Stepping.begin(&n.a.t, null); + n.a.core.acknowledgeShell(.at(shell), "/bin/sh", false); + was.end(); + n.a.seq += 1; + _ = try n.a.unit(0, n.a.seq); + } + try n.join(); + const run = n.node(.pty_run); + const h = (try n.serve(.{ .tag = 1, .op = .open, .node = run, .omode = 2 }, true)).handle; + _ = try n.serve(.{ .tag = 2, .op = .write, .node = run, .handle = h, .data = "true\n" }, true); + const answer = try n.serve(.{ .tag = 3, .op = .read, .node = run, .handle = h, .size = 64 }, true); + try std.testing.expectEqualStrings("error no prompt marks\n", n.a.core.fsPayload(answer)); + _ = try n.serve(.{ .tag = 4, .op = .release, .node = run, .handle = h, .opened = true }, true); + try n.agree(); +} diff --git a/core/rollback.zig b/core/rollback.zig index c7d0a4e8..a55d3c87 100644 --- a/core/rollback.zig +++ b/core/rollback.zig @@ -404,9 +404,7 @@ pub const Copy = struct { }, .@"struct" => |s| { if (comptime walk.machinery(T)) return; - // A terminal: the authority's (its emulator is never written - // by a speculation: terminal.zig's guards). - if (comptime @hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *walk.Hasher) void) return; + if (comptime unwalked(T)) return; if (s.layout == .@"packed") return; // std's lists (a safe build's have a third field, a lock). if (comptime walk.isList(T)) { @@ -467,7 +465,7 @@ pub const Copy = struct { if (comptime walk.machinery(P)) return; const addr = @intFromPtr(ptr); if (try c.reached(P, addr)) return; - if (comptime @hasDecl(P, "digest") and @TypeOf(P.digest) == fn (*const P, *walk.Hasher) void) return; + if (comptime unwalked(P)) return; if (c.epoch.?.owns(addr) != null) { _ = try c.reached(void, addr); try c.fields(P, ptr); @@ -513,6 +511,16 @@ pub const Copy = struct { } }; +/// A type that hashes itself and says nothing of its fields (`replica`): +/// a terminal, the authority's (its emulator is never written by a +/// speculation: terminal.zig's guards), or a location row, made again and +/// never written. One that says its fields' kinds is walked by them, +/// whatever digest it has (the 9P state, fs.Namespace and a pane's: a +/// replayed request writes its buffers in place). +fn unwalked(comptime T: type) bool { + return @hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *walk.Hasher) void and !@hasDecl(T, "replica"); +} + fn annotatedStruct(comptime T: type) bool { return @typeInfo(T) == .@"struct" and @hasDecl(T, "replica"); } diff --git a/core/syntax.zig b/core/syntax.zig index 19831ec2..00ee497f 100644 --- a/core/syntax.zig +++ b/core/syntax.zig @@ -7,8 +7,10 @@ const regexp = @import("regexp.zig"); const c_heap = @import("c_heap"); const diff = @import("diff.zig"); -const minimal_grammars = config.grammars != .none; -const full_grammars = config.grammars == .full; +/// The grammar sets built (`-Dgrammars`): a test that needs a grammar +/// not built skips. +pub const minimal_grammars = config.grammars != .none; +pub const full_grammars = config.grammars == .full; pub const ts = @import("tree-sitter"); const ts_queries = @import("ts_queries"); @@ -1260,6 +1262,7 @@ test "every vendored textobject and indent query compiles against its grammar" { } test "syntax context nested Zig containers and multiline function signatures" { + if (comptime !minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1291,7 +1294,7 @@ test "syntax context nested Zig containers and multiline function signatures" { } test "syntax context Python class and function body excludes first statement" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1304,6 +1307,7 @@ test "syntax context Python class and function body excludes first statement" { } test "syntax context multiline bindings and C++ namespaces preserve declaration starts" { + if (comptime !minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1313,7 +1317,7 @@ test "syntax context multiline bindings and C++ namespaces preserve declaration try std.testing.expectEqual(@as(usize, 1), zig_declarations.len); try std.testing.expectEqual(@as(usize, 0), zig_declarations[0].start_line); try std.testing.expectEqual(@as(usize, 1), zig_declarations[0].header_end_line); - if (!minimal_grammars) return; + if (!minimal_grammars) return error.SkipZigTest; const cpp_source = "namespace example {\nstruct Outer {\n int run() {\n return 1;\n }\n};\n}\n"; const cpp_declarations = try contextDeclarations(gpa, "nested.cpp", cpp_source); defer gpa.free(cpp_declarations); @@ -1325,7 +1329,7 @@ test "syntax context multiline bindings and C++ namespaces preserve declaration } test "syntax context Rust modules impls and methods remain nested" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1341,7 +1345,7 @@ test "syntax context Rust modules impls and methods remain nested" { } test "syntax formatted locations color hidden context and preserve multiline source" { - if (!minimal_grammars) return; + if (!minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1366,7 +1370,7 @@ test "syntax formatted locations color hidden context and preserve multiline sou } test "syntax formatted locations separate alignment from Markdown indentation" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1382,6 +1386,7 @@ test "syntax formatted locations separate alignment from Markdown indentation" { } test "syntax a results row is coloured by the file its location names" { + if (comptime !minimal_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); const gpa = std.testing.allocator; @@ -1431,7 +1436,7 @@ test "syntax codeAfterLocation takes whole-token locations and nothing else" { } test "syntax default full grammar set highlights Typst source" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); @@ -1454,7 +1459,7 @@ test "syntax default full grammar set highlights Typst source" { } test "syntax Typst markup constructs paint and raw blocks inject their language" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); @@ -1498,7 +1503,7 @@ test "syntax Typst markup constructs paint and raw blocks inject their language" } test "syntax markdown highlights markup, injects inline spans and fenced code blocks" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); @@ -1530,7 +1535,7 @@ test "syntax markdown highlights markup, injects inline spans and fenced code bl } test "syntax inline fast path agrees with full Markdown query" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); const selected = (try forLang("markdown_inline")).?; @@ -1577,7 +1582,7 @@ test "syntax inline fast path agrees with full Markdown query" { } test "syntax plain Markdown keeps block styles without starting the inline parser" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); const source = "# Heading\n\nPlain prose.\n\n indented code\n"; @@ -1619,6 +1624,7 @@ test "syntax highlightDiff colors unified diff lines by prefix" { } test "syntax a Zig hunk is coloured as Zig, each side parsed whole" { + if (comptime !minimal_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); const diff_text = @@ -1659,7 +1665,7 @@ test "syntax a Zig hunk is coloured as Zig, each side parsed whole" { } test "syntax a Python hunk is coloured as Python" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); const diff_text = @@ -1680,6 +1686,7 @@ test "syntax a Python hunk is coloured as Python" { } test "syntax a deleted file's lines are coloured in its language" { + if (comptime !minimal_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); const diff_text = @@ -1715,6 +1722,7 @@ test "syntax a hunk in no known language keeps the line colours" { } test "syntax git diff output in a command pane is told and coloured by its rows" { + if (comptime !minimal_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); // A command pane's rows: its command line, then git's output, with one @@ -1747,6 +1755,7 @@ test "syntax git diff output in a command pane is told and coloured by its rows" } test "syntax a section's small hunks share one parse" { + if (comptime !minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1768,6 +1777,7 @@ test "syntax a section's small hunks share one parse" { } test "syntax a hunk painted once is kept, and a long one is parsed in pieces" { + if (comptime !minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1856,6 +1866,7 @@ test "syntax query filtering preserves upstream colors" { } test "syntax Zig keyword captures cover both bytes beyond line ten thousand" { + if (comptime !minimal_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); const code = "pub fn main() void {\n if (true) return;\n}\n"; @@ -1873,6 +1884,7 @@ test "syntax Zig keyword captures cover both bytes beyond line ten thousand" { } test "syntax allocator switching clears default-runtime caches" { + if (comptime !minimal_grammars) return error.SkipZigTest; const source = "fn main() void {}"; const initial = try highlightFileRange(std.testing.allocator, "a.zig", source, 0, source.len); std.testing.allocator.free(initial); @@ -1888,7 +1900,7 @@ test "syntax allocator switching clears default-runtime caches" { } test "syntax location context snapshots retain omitted multiline comment scope" { - if (!minimal_grammars) return; + if (!minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1914,6 +1926,7 @@ test "syntax location context snapshots retain omitted multiline comment scope" } test "syntax declaration locations clear snapshots without muting ordinary context" { + if (comptime !minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1933,7 +1946,7 @@ test "syntax declaration locations clear snapshots without muting ordinary conte } test "syntax stacked addresses do not split multiline source groups" { - if (!minimal_grammars) return; + if (!minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -2018,7 +2031,7 @@ test "syntax source analysis preserves declarations and injected colors" { } test "tables are the pipe_tables tree-sitter finds" { - if (!full_grammars) return; + if (!full_grammars) return error.SkipZigTest; start(std.testing.allocator); defer stop(); const Tables = @import("Tables.zig"); @@ -2087,6 +2100,7 @@ test "tables are the pipe_tables tree-sitter finds" { } test "a kept tree told its edits parses to the fresh parse's tree, places and all" { + if (comptime !minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; const a = "const std = @import(\"std\");\n\nfn f(x: u32) u32 {\n return x;\n}\n\ntest \"t\" {\n _ = f(1);\n}\n"; const old_tree = parseTree("a.zig", a, null) orelse return error.NoTree; @@ -2126,6 +2140,7 @@ test "a kept tree told its edits parses to the fresh parse's tree, places and al } test "syntax: a grammar handed in at run time colours and walks as the one compiled in" { + if (comptime !minimal_grammars) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); diff --git a/core/tape.zig b/core/tape.zig index 88a7047b..6af332a3 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; @@ -1592,19 +1583,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 @@ -1661,16 +1654,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" { @@ -1700,7 +1696,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/core/walk.zig b/core/walk.zig index 6d7c594d..9b760144 100644 --- a/core/walk.zig +++ b/core/walk.zig @@ -31,8 +31,9 @@ //! .blob = .{ "content" }, //! }; //! -//! None of the three kinds is in a digest or a dump. A type with a `pub fn -//! digest(*const T, *Hasher) void` of its own hashes itself; one with +//! None of the three kinds is in a digest or a dump. A type (a struct or a +//! tagged union) with a `pub fn digest(*const T, *Hasher) void` of its own +//! hashes itself; one with //! `dumpWrite`, `dumpRead` (and `dumpFree`) dumps itself as bytes. const std = @import("std"); const xitdb = @import("xitdb"); @@ -242,6 +243,7 @@ pub fn hash(comptime T: type, v: *const T, h: *Hasher) void { }, .@"union" => |u| { if (u.tag_type == null) @compileError("walk: an untagged union: " ++ @typeName(T)); + if (comptime @hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *Hasher) void) return v.digest(h); const tag: u.tag_type.? = v.*; hash(u.tag_type.?, &tag, h); switch (v.*) { |
