diff options
| -rw-r--r-- | abi/wire.zig | 4 | ||||
| -rw-r--r-- | core/Core.zig | 8 | ||||
| -rw-r--r-- | core/Jump.zig | 2 | ||||
| -rw-r--r-- | core/Term.zig | 72 | ||||
| -rw-r--r-- | core/dump.zig | 4 | ||||
| -rw-r--r-- | core/edit.zig | 1 | ||||
| -rw-r--r-- | core/keys.zig | 2 | ||||
| -rw-r--r-- | core/ninep/pty.zig | 6 | ||||
| -rw-r--r-- | core/panes.zig | 48 | ||||
| -rw-r--r-- | core/replica.zig | 113 | ||||
| -rw-r--r-- | core/tape.zig | 36 | ||||
| -rw-r--r-- | test/kitty.zig | 4 | ||||
| -rw-r--r-- | test/perf.zig | 5 | ||||
| -rw-r--r-- | test/terminal.zig | 8 |
14 files changed, 170 insertions, 143 deletions
diff --git a/abi/wire.zig b/abi/wire.zig index 55a08909..8949edff 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -12,7 +12,9 @@ const build_info = @import("build_info"); /// 31: where a view stands in a terminal's history is the view's: a pane's /// `scrolled_to` (and its share's in each view) in the dump and the digest, -/// the emulator's own view out of both (its `Parts.view` gone); +/// the emulator's own view out of both (its `Parts.view` gone); and the +/// core's count of its emulators' writes (`outside`) in both, which the +/// replica engine's one question of a unit reads; /// 30: the terminals' one road: the screen-state messages are retired (a /// replica's `screen_ack`, 0x04, and the session's `screen`, 0x06: gaps), /// a welcome says no road (its `bytes` byte gone), and a pane's diff --git a/core/Core.zig b/core/Core.zig index a35cea8e..2c6567ed 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -258,6 +258,10 @@ n_look_src: usize = 0, look_walk_owner: ?u32 = null, /// hands out Pane.serial; monotonic, never reused next_serial: u32 = 0, +/// The writes of its terminals' emulators, which no rollback copy holds +/// (Term.Outside): digested, dumped and copied as any field, so the same on +/// every side; the replica engine's one question of a unit reads it. +outside: pardes.Term.Outside = .{}, /// The column whose tag the running command came from, while it runs: /// the column acme's commands take from their Text's col. exec_column: ?usize = null, @@ -1908,7 +1912,7 @@ pub fn sync(p: *Pardes) void { // What the terminal answers its program (a cursor report, its // attributes) goes as typed bytes go: behind whatever is still // queued for its pty, never ahead of it nor dropped. - if (pane.terminal) |state| p.emitWrite(id, pardes.Term.replies(state)); + if (pane.terminal) |state| p.emitWrite(id, pardes.Term.replies(&p.outside, state)); const r = v.rects[id]; // The session's part of the pane's view geometry (File.geometry), // and its context declarations. @@ -1974,7 +1978,7 @@ pub fn sync(p: *Pardes) void { // doc panes have no pty/emulator grid to reflow; just record // the size so bodyText renders the right number of rows if (pane.isTerminal()) { - pane.resizeGrid(p.live, cols, rows); + pane.resizeGrid(p, cols, rows); p.shell_rows.markStale(pane); // reflow moved every row p.emit(.{ .resize_pty = .{ .pane = .at(id), .cols = cols, .rows = rows } }); pane.fs.winsize = null; diff --git a/core/Jump.zig b/core/Jump.zig index aa633044..b68da32d 100644 --- a/core/Jump.zig +++ b/core/Jump.zig @@ -410,7 +410,7 @@ test "jump history terminal rectangle follows output and clears on reflow" { try std.testing.expectEqualStrings("alpha", try edit.selectionText(p, pane, pane.sel[0])); for (0..40) |_| p.update(.{ .output = .{ .pane = .at(0), .bytes = "more output\r\n" } }); try std.testing.expectEqualStrings("alpha", try edit.selectionText(p, pane, pane.sel[0])); - pane.resizeGrid(p.live, pane.cols - 1, pane.rows); + pane.resizeGrid(p, pane.cols - 1, pane.rows); try std.testing.expect(pane.pointerSelection(pane.sel[0]) == null); try std.testing.expectEqual(.none, pane.sel[0].state); } diff --git a/core/Term.zig b/core/Term.zig index b82017f6..d1065b49 100644 --- a/core/Term.zig +++ b/core/Term.zig @@ -14,11 +14,15 @@ const dump = @import("dump.zig"); const File = @import("File.zig"); const iface = plain.term; -/// Writes into this process's emulators (a read fed, a grid reflowed, one -/// opened, closed, loaded or made again): whether a unit's -/// replay made one, the replica engine's one rule (core/replica.zig -/// `confirm`) reads across that replay, on its one thread. -pub var writes: u32 = 0; +/// The writes of a core's emulators, which live outside its rollback copy +/// (`Pardes.outside`): a field of the core, so copied with a speculation, +/// digested and dumped, a function of the tape, the same on every side (one +/// side's emulator written where the others' are not is a digest that says +/// `outside`). Every write below takes it and counts, and so does a write a +/// speculation owes (`resize`): over an input's apply, the count moved is +/// "this input wrote, or owes, state outside the copy", the one question +/// core/replica.zig `confirm` asks a unit. A load sets it from the dump. +pub const Outside = struct { n: u64 = 0 }; /// The reloads this process made (a join's, on every side) and their time, /// for the soak's join line (test/replicas.zig `--bytes`). pub var reloads: struct { n: u32 = 0, ns: u64 = 0, worst_ns: u64 = 0 } = .{}; @@ -96,7 +100,6 @@ pub const State = struct { const parts = try walk.load(iface.Parts, arena.allocator(), bytes[8..][0..n], null); o.media(media); out.* = .{ .impl = try o.load(gpa, bytes[8 + n ..], &parts) }; - writes +%= 1; } }; @@ -112,13 +115,13 @@ pub fn emulatorOf(s: *State) *@import("term").terminal.State { /// A new terminal, `cols` by `rows`, allocated with `gpa` (its own from /// then on). Refused in a core without one: `error.NoTerminal`, which a /// word reports as `none` says it. -pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State { +pub fn open(outside: *Outside, gpa: std.mem.Allocator, cols: u16, rows: u16) !*State { const o = ops orelse return error.NoTerminal; const s = try gpa.create(State); errdefer gpa.destroy(s); o.media(media); s.* = .{ .impl = try o.open(gpa, cols, rows) }; - writes +%= 1; + outside.n +%= 1; return s; } @@ -137,9 +140,9 @@ fn readMedium(read: *const fn (*const anyopaque) iface.MediumError![]u8, ctx: *c /// It and what it holds, freed, all of it with its own allocator (the /// one it was opened with): the allocator a caller hands is not used. -pub fn close(s: *State, _: std.mem.Allocator) void { +pub fn close(outside: *Outside, s: *State) void { const own = the().gpa(s.impl); - writes +%= 1; + outside.n +%= 1; the().close(s.impl); own.destroy(s); } @@ -148,8 +151,8 @@ pub fn close(s: *State, _: std.mem.Allocator) void { /// every side does it, so that all hold the same pages (ghostty prunes its /// history a page at a time, and a snapshot does not say how its rows were /// cut into pages). The snapshot's hash, which every side compares. -pub fn reload(s: *State) !u64 { - writes +%= 1; +pub fn reload(outside: *Outside, s: *State) !u64 { + outside.n +%= 1; const t0 = @import("FrameStats.zig").nowNs(); defer { reloads.n += 1; @@ -170,8 +173,8 @@ pub fn due(s: *const State) ?u64 { /// Loaded from a dump without its shell: its program's modes reset, its /// history marked off from what the next shell prints. -pub fn revive(s: *State) void { - writes +%= 1; +pub fn revive(outside: *Outside, s: *State) void { + outside.n +%= 1; s.written = true; the().revive(s.impl); } @@ -190,8 +193,8 @@ pub fn stop() void { /// One read of its program's output (`Told` says where the tracked rows /// went), every view's place in its history carried through it (`resize`). -pub fn feed(s: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool, places: []?usize) Told { - writes +%= 1; +pub fn feed(outside: *Outside, s: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool, places: []?usize) Told { + outside.n +%= 1; s.written = true; return the().feed(s.impl, bytes, tracked, rows, erased, places); } @@ -205,8 +208,11 @@ pub fn grid(s: ?*const State) Grid { /// Its grid reflowed, every view's place in its history (Pane.scrolled_to, /// each view's) carried through it as ghostty carries a view of its own. -pub fn resize(s: *State, cols: u16, rows: u16, places: []?usize) void { - writes +%= 1; +/// A speculation owes it (counted, not made): its input is replayed when it +/// is confirmed (core/replica.zig `confirm`), never taken as speculated. +pub fn resize(outside: *Outside, s: *State, cols: u16, rows: u16, places: []?usize) void { + outside.n +%= 1; + if (tape.speculating()) return; s.written = true; the().resize(s.impl, cols, rows, places); } @@ -218,8 +224,10 @@ pub fn cellPixels(s: *State, w: u32, h: u32) void { /// What it answered its program since the last call, to be written to its /// pty. -pub fn replies(s: *State) []const u8 { - return the().replies(s.impl); +pub fn replies(outside: *Outside, s: *State) []const u8 { + const r = the().replies(s.impl); + if (r.len > 0) outside.n +%= 1; + return r; } // ---- input ---- @@ -277,7 +285,8 @@ pub fn commandOutput(s: ?*State, gpa: std.mem.Allocator, max_rows: usize) !Comma /// The shell exited in the middle of a command: its output ends at the /// cursor. -pub fn endOutputHere(s: *State) void { +pub fn endOutputHere(outside: *Outside, s: *State) void { + outside.n +%= 1; the().endOutputHere(s.impl); } @@ -399,14 +408,14 @@ pub fn hasImages(s: ?*const State) bool { /// and pardes-image-loop's tables, kept as a test). pub const calls = [_]struct { []const u8, []const u8, []const u8 }{ // ---- writes: outside the copy ---- - .{ "open", "dump.zig:1 panes.zig:1", "WRITE: a terminal made by a step (a shell's pane) or a load; a copy held across a pane's opening is let go (replica.zig `confirm`: serials)" }, - .{ "close", "panes.zig:1", "WRITE: let go by a step that closes its pane: a copy held across it is let go (retiring panes); a unit that closes one is never kept over a copy" }, + .{ "open", "dump.zig:1 panes.zig:1", "WRITE: a terminal made by a step (a shell's pane) or a load, counted (`Outside`); a speculation is refused it" }, + .{ "close", "panes.zig:1", "WRITE: let go by a step that closes its pane, counted; a speculation is refused it" }, .{ "revive", "dump.zig:1", "WRITE: a load's (a join's dump, a Restore): no copy is held" }, .{ "reload", "panes.zig:1", "WRITE: a join's step remakes each terminal written since its last reload, on every side (panes.reloadTerminals, the session's choice taped, the snapshot's hash compared)" }, - .{ "feed", "keys.zig:1 panes.zig:3", "WRITE: the pty's bytes in a unit, every side in the tape's order, every view's place (Pane.scrolled_to, in the copy) carried through it; a unit that feeds lets a copy held ahead go (`Term.writes`), so none is replayed (keys.zig's: a test's)" }, - .{ "resize", "panes.zig:1", "WRITE: a step's reflow, every view's place carried through it; a speculation owes it (`touchTerminal`): its input is taken when confirmed, never as speculated" }, + .{ "feed", "keys.zig:1 panes.zig:3 replica.zig:1", "WRITE: the pty's bytes in a unit, every side in the tape's order, every view's place (Pane.scrolled_to, in the copy) carried through it, counted: a unit that moved the count is applied once, to the confirmed core (replica.zig `confirm`); a speculation is refused it (keys.zig's, replica.zig's: tests')" }, + .{ "resize", "panes.zig:1", "WRITE: a step's reflow, every view's place carried through it, counted; a speculation owes it (counted, not made): its input is taken when confirmed, never as speculated" }, .{ "endOutputHere", "ninep/pty.zig:1", "WRITE: a 9P pty/run's step ends a command's output at the cursor: the session's step, replayed as such" }, - .{ "replies", "Core.zig:1", "WRITE: a step drains the reply buffer (in the digest); only the session writes it to the pty (pty_write is off the tape)" }, + .{ "replies", "Core.zig:1", "WRITE: a step drains the reply buffer (in the digest), counted when it held any (the feed's own unit, which filled it); only the session writes it to the pty (pty_write is off the tape)" }, // ---- reads by a step: in the digest ---- .{ "grid", "Core.zig:2 ansi.zig:3 body_layer.zig:3 draw.zig:2 dump.zig:4 echo.zig:8 exec.zig:2 layout.zig:2 panes.zig:5 replica.zig:2", "READ: the size, the history's length, the cursor: in the digest (a view's place is its pane's; ansi.zig, body_layer.zig, draw.zig, echo.zig: a draw's)" }, .{ "modes", "Core.zig:5 draw.zig:1 dump.zig:2 echo.zig:3 exec.zig:3 mouse.zig:4 ninep/pty.zig:3 panes.zig:2 replica.zig:1", "READ: the program's modes (mouse, focus, bracketed paste, the alternate screen): in the digest (draw.zig, echo.zig: a draw's; panes.zig: a view scrolls no history on the alternate screen)" }, @@ -502,6 +511,17 @@ test "every call of the core's into a terminal is listed with its rule (S1): a n try std.testing.expectEqual(@as(usize, 0), wrong); } +// Every WRITE above takes its core's count first (`Outside`): a call +// cannot be written without one, so the count cannot be forgotten at a call +// site (the compiler holds that); that a new op is listed as a WRITE is the +// test's above and a reviewer's. +comptime { + for (calls) |c| if (std.mem.startsWith(u8, c[2], "WRITE")) { + const params = @typeInfo(@TypeOf(@field(@This(), c[0]))).@"fn".param_types; + if (params.len == 0 or params[0] != *Outside) @compileError("Term." ++ c[0] ++ " writes an emulator: it takes its core's count (`*Outside`) first"); + }; +} + fn listedCall(name: []const u8, file: []const u8) bool { for (calls) |c| { if (!std.mem.eql(u8, c[0], name)) continue; diff --git a/core/dump.zig b/core/dump.zig index c3742a21..5fd933b9 100644 --- a/core/dump.zig +++ b/core/dump.zig @@ -500,7 +500,7 @@ fn loadImage(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: ?* fn ensureKind(p: *Pardes, pane: *pardes.panes.Pane) !void { if (pane.terminal != null or pane.file != null or pane.addon != null or pane.pdf != null) return; if (p.tape.authorityOnly("open a terminal")) return error.OutOfMemory; - pane.terminal = try pardes.Term.open(pardes.panes.emulatorGpa(p.gpa), @max(1, pane.cols), @max(1, pane.rows)); + pane.terminal = try pardes.Term.open(&p.outside, pardes.panes.emulatorGpa(p.gpa), @max(1, pane.cols), @max(1, pane.rows)); } /// The panes a column lists that are not there (another build's dump left @@ -674,7 +674,7 @@ fn revivePane(p: *Pardes, id: usize, pane: *pardes.panes.Pane, was_on_disk: bool // shell was, ran and said is gone with it (the REPL it ran, the // Term+ word naming it), and the pane waits for the new one like // any new terminal (a line queued for the old one goes to it). - pardes.Term.revive(pane.terminal.?); + pardes.Term.revive(&p.outside, pane.terminal.?); pane.shell_spoke = false; pane.had_shell = false; pane.shell_failed = false; diff --git a/core/edit.zig b/core/edit.zig index f3a87e57..129b004c 100644 --- a/core/edit.zig +++ b/core/edit.zig @@ -470,7 +470,6 @@ const empty_grid = [1][]const u8{""}; /// in `Pardes.shell_rows` while its grid holds still. pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 { const state = pane.terminal orelse return &empty_grid; - pardes.tape.touchTerminal(); const c = &p.shell_rows; if (!c.stale and c.pane == pane) return c.rows; // Another pane's rows, or a dropped pane's still waiting for the step's diff --git a/core/keys.zig b/core/keys.zig index 91cb2724..9afb983b 100644 --- a/core/keys.zig +++ b/core/keys.zig @@ -804,7 +804,7 @@ test "raw tty forwards Ctrl letters and former global shortcuts to the child" { } p.update(.{ .key = .{ .cp = Key.up } }); try std.testing.expectEqualStrings("\x1b[A", test_api.ptyBytes(p, null, &buf)); - _ = pardes.Term.feed(p.panes[0].?.terminal.?, "\x1b[?1h", &.{}, &.{}, &.{}, &.{}); // DECCKM + _ = pardes.Term.feed(&p.outside, p.panes[0].?.terminal.?, "\x1b[?1h", &.{}, &.{}, &.{}, &.{}); // DECCKM p.update(.{ .key = .{ .cp = Key.up } }); try std.testing.expectEqualStrings("\x1bOA", test_api.ptyBytes(p, null, &buf)); p.update(.{ .key = .{ .cp = Key.left, .ctrl = true } }); diff --git a/core/ninep/pty.zig b/core/ninep/pty.zig index 923dab88..43973491 100644 --- a/core/ninep/pty.zig +++ b/core/ninep/pty.zig @@ -422,7 +422,7 @@ pub fn shellExited(p: *Pardes, pane: *Pane, status: ?u8) void { const code = status orelse return; if (waitingRun(p, pane)) |slot| if (slot.phase == .sent) { pane.fs.run = null; - if (pane.terminal) |state| pardes.Term.endOutputHere(state); + if (pane.terminal) |state| pardes.Term.endOutputHere(&p.outside, state); finish(p, slot, pane, code); }; var buf: [4]u8 = undefined; @@ -1015,10 +1015,10 @@ test "a run's answer says cut when its output's start is gone, and reads a bound // A resize between its start and end reflows the pins with the text. h = sh.send(p, node); sh.put(p, c ++ "one\r\ntwo\r\n"); - pane.resizeGrid(p.live, 50, 20); + pane.resizeGrid(p, 50, 20); sh.put(p, d ++ prompt); try testing.expectEqualStrings("exit 0\none\ntwo\n", sh.answered(p, node, h, into)); - pane.resizeGrid(p.live, pane.cols, pane.rows); + pane.resizeGrid(p, pane.cols, pane.rows); // A full-screen program leaves nothing on the primary screen, and a D // with no status is not a success. diff --git a/core/panes.zig b/core/panes.zig index 032cb4db..5bf6992a 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -762,8 +762,8 @@ pub const Pane = struct { var scrolled: Scrolled = .of(pane, p.live); defer scrolled.put(pane, p.live); if (!has_positions) { - _ = Term.feed(state, bytes, &.{}, &.{}, &.{}, scrolled.places()); - } else if (pane.followRows(state, bytes, scrolled.places())) if (paneIdOf(p, pane)) |id| p.setMessage(.at(id), positions_lost); + _ = Term.feed(&p.outside, state, bytes, &.{}, &.{}, &.{}, scrolled.places()); + } else if (pane.followRows(&p.outside, state, bytes, scrolled.places())) if (paneIdOf(p, pane)) |id| p.setMessage(.at(id), positions_lost); p.shell_rows.markStale(pane); } @@ -802,7 +802,7 @@ pub const Pane = struct { /// (the edit copy, the cursors and selections, their undo, the /// pointer's rows) moved as the rows move (`Term.Told`). True when one /// could not be kept (no memory for its pin). - fn followRows(pane: *Pane, state: *Term.State, bytes: []const u8, places: []?usize) bool { + fn followRows(pane: *Pane, outside: *Term.Outside, state: *Term.State, bytes: []const u8, places: []?usize) bool { const Group = struct { overlay: ?*Text.EditBuffer, cursor: *i32, selection: *Text.CharSel }; var groups: [Text.history_max * 2 + 1]Group = undefined; groups[0] = .{ @@ -898,11 +898,11 @@ pub const Pane = struct { var rows_buf: [512]i32 = undefined; var erased_buf: [512]bool = undefined; // Out of memory for them, the read is parsed and nothing moves. - const track = if (n <= track_buf.len) track_buf[0..n] else pane.gpa.alloc(i32, n) catch return feedLost(state, bytes, places); + const track = if (n <= track_buf.len) track_buf[0..n] else pane.gpa.alloc(i32, n) catch return feedLost(outside, state, bytes, places); defer if (n > track_buf.len) pane.gpa.free(track); - const rows_after = if (n <= rows_buf.len) rows_buf[0..n] else pane.gpa.alloc(i32, n) catch return feedLost(state, bytes, places); + const rows_after = if (n <= rows_buf.len) rows_buf[0..n] else pane.gpa.alloc(i32, n) catch return feedLost(outside, state, bytes, places); defer if (n > rows_buf.len) pane.gpa.free(rows_after); - const erased_after = if (n <= erased_buf.len) erased_buf[0..n] else pane.gpa.alloc(bool, n) catch return feedLost(state, bytes, places); + const erased_after = if (n <= erased_buf.len) erased_buf[0..n] else pane.gpa.alloc(bool, n) catch return feedLost(outside, state, bytes, places); defer if (n > erased_buf.len) pane.gpa.free(erased_after); var k: usize = 0; for (spans[0..nspans]) |span| for ([_]i32{ span.row, span.row +| (span.rows - 1) }) |row| { @@ -913,7 +913,7 @@ pub const Pane = struct { track[k] = at.grid; k += 1; }; - const fed = Term.feed(state, bytes, track, rows_after, erased_after, places); + const fed = Term.feed(outside, state, bytes, track, rows_after, erased_after, places); const after = tape.value(.positions, keepTold, .{Term.Told{ .rows = fed.rows, .erased = fed.erased, .cleared = fed.cleared, .alive = fed.alive, .failed = failed or fed.failed }}); if (after.rows.len != n or after.erased.len != n) return false; // a replica its authority's states apart (diverged) failed = after.failed; @@ -994,8 +994,8 @@ pub const Pane = struct { return t; } - fn feedLost(state: *Term.State, bytes: []const u8, places: []?usize) bool { - _ = Term.feed(state, bytes, &.{}, &.{}, &.{}, places); + fn feedLost(outside: *Term.Outside, state: *Term.State, bytes: []const u8, places: []?usize) bool { + _ = Term.feed(outside, state, bytes, &.{}, &.{}, &.{}, places); return true; } @@ -1016,21 +1016,19 @@ pub const Pane = struct { } /// Its terminal's grid reflowed to `cols` by `rows`, every open view's - /// place carried through it (`Scrolled`; `live` the live view's index). - pub fn resizeGrid(pane: *Pane, live: u8, cols: u16, rows: u16) void { - // A client's speculation does what its replay does (its - // selections) but the grid: it waits for no round trip. Under bytes - // it owes the grid (`touchTerminal`): its input is replayed when - // confirmed, never taken as speculated (replica.zig `confirm`). + /// place carried through it (`Scrolled`). A client's speculation does + /// what its replay does (its selections) but the grid, which it owes + /// (Term.resize: counted, not made): its input is replayed when + /// confirmed, never taken as speculated (replica.zig `confirm`). + pub fn resizeGrid(pane: *Pane, p: *Pardes, cols: u16, rows: u16) void { const state = pane.terminal orelse return; if (cols != pane.cols) for (0..pane.sel.len) |button| { pane.clearPointerSelection(button); pane.sel[button].state = .none; }; - if (tape.speculating()) return tape.touchTerminal(); - var scrolled: Scrolled = .of(pane, live); - defer scrolled.put(pane, live); - Term.resize(state, cols, rows, scrolled.places()); + var scrolled: Scrolled = .of(pane, p.live); + defer scrolled.put(pane, p.live); + Term.resize(&p.outside, state, cols, rows, scrolled.places()); } /// The rows its terminal's top is passed over by in a view whose rect @@ -1188,7 +1186,7 @@ pub fn reloadTerminals(p: *Pardes) void { // frontend's draw sets its own view's between steps (ansi.zig), a // window's other than a terminal's, and the snapshot holds it. Term.cellPixels(state, p.view().cell_pixels.w, p.view().cell_pixels.h); - const mine: ?u64 = Term.reload(state) catch null; + const mine: ?u64 = Term.reload(&p.outside, state) catch null; p.shell_rows.markStale(pane); if (tape.value(.reload, sameHash, .{mine}) != mine) tape.diverged("a terminal reloaded at a join is not the session's"); }; @@ -1216,10 +1214,10 @@ pub fn createDoc(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { /// A terminal pane: a pane and its emulator. Slot ownership, serial /// assignment and spawn effects remain core lifecycle invariants. -pub fn createTerminal(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { +pub fn createTerminal(outside: *Term.Outside, gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { const pane = try createDoc(gpa, cols, rows); errdefer gpa.destroy(pane); - pane.terminal = try Term.open(emulatorGpa(gpa), cols, rows); + pane.terminal = try Term.open(outside, emulatorGpa(gpa), cols, rows); pane.tty_filter = true; return pane; } @@ -1324,7 +1322,7 @@ pub fn teardownPane(p: *Pardes, pane: *Pane) void { // A pane with none (a file's, a picker's, a preview's) closes in a // speculation as anywhere. if (pane.terminal) |state| if (!p.tape.authorityOnly("close a terminal")) { - Term.close(state, p.gpa); + Term.close(&p.outside, state); pane.terminal = null; }; pane.clearCwd(); @@ -1361,7 +1359,7 @@ pub fn newShell(p: *Pardes, id: usize, cwd: []const u8) !*Pane { if (cwd.len > limits.host_path_cap) return error.PathTooLong; // A speculation opens no emulator: a terminal is the authority's to open. if (p.tape.authorityOnly("open a terminal")) return error.OutOfMemory; - const pane = try panes.createTerminal(p.gpa, p.view().screen_w, p.view().screen_h); + const pane = try panes.createTerminal(&p.outside, p.gpa, p.view().screen_w, p.view().screen_h); // Named by the directory it is started in from the first, so the // shell saying it is there is no rename (`new N /` then `rename`); // out of memory for it, the shell names it when it says. @@ -1394,7 +1392,7 @@ pub fn newCommand(p: *Pardes, id: usize, cwd: []const u8, line: []const u8) !*Pa const owned = try p.gpa.dupe(u8, line); errdefer p.gpa.free(owned); if (p.tape.authorityOnly("open a terminal")) return error.OutOfMemory; - const pane = try panes.createTerminal(p.gpa, p.view().screen_w, p.view().screen_h); + const pane = try panes.createTerminal(&p.outside, p.gpa, p.view().screen_w, p.view().screen_h); pane.command = owned; pane.command_pty = true; pane.body.mode = .tty; diff --git a/core/replica.zig b/core/replica.zig index f4a3284c..0ae302e8 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -413,9 +413,10 @@ pub const Stats = struct { } }; -/// `terminal`: its speculation read a terminal or moved one's view (or a -/// terminal had the keyboard), so what it did depends on the emulator. -const Pending = struct { seq: u32, msg: []u8, spec: ?[]u8 = null, sent_ns: u64 = 0, terminal: bool = false, guess: ?tape.Guess = null }; +/// `outside`: how far its speculation moved its core's count of writes +/// outside the rollback copy (Pardes.outside): not 0, it owes an emulator +/// a write (a grid's size), which only its replay makes. +const Pending = struct { seq: u32, msg: []u8, spec: ?[]u8 = null, sent_ns: u64 = 0, outside: u64 = 0, guess: ?tape.Guess = null }; pub fn parseUnit(msg: []const u8) ?Unit { if (msg.len < unit_head) return null; @@ -690,9 +691,14 @@ pub const Replica = struct { r.stats.units += 1; r.since_check +|= 1; if (u.origin == r.id) if (r.t.core) |c| r.echo.confirmed(c, u.seq); - // The pty's bytes fed its emulators: its predicted echo judged - // against them. - defer if (r.diverged == null and tape.feedsTerminal(u.tape)) if (r.t.core) |c| if (c.echo != null) r.echo.fed(c); + // THE ONE QUESTION of a unit: did applying it write state outside + // the rollback copy (an emulator: Pardes.outside, the count of those + // writes, moved over its apply, read off the core that applied it)? + // Such a unit is applied once, to the confirmed core, never kept to + // replay over a copy; and its emulators' new state is what the + // predicted echo is judged against. + var moved = false; + defer if (r.diverged == null and moved) if (r.t.core) |c| if (c.echo != null) r.echo.fed(c); // A copy taken ahead (`ready`), nothing on top: it stays the point a // rollback goes back to, the unit replayed on it and kept in `since`, // not let go and taken again (a megabyte walked) for each unit of @@ -716,19 +722,20 @@ pub const Replica = struct { // nothing ends on again (`neutral`); none, not known. r.last_digest.clearRetainingCapacity(); if (lastDigest(u.tape)) |d| r.last_digest.appendSlice(r.gpa, d) catch {}; - if (r.pending.items[0].terminal) { - // Right, but what it did wrote an emulator (or owes one a - // write: a grid's size): replayed later (a rollback's - // `since`) it would write it again. So it is taken now, over - // the emulator its step read, and the ones on top applied - // again over it. + // Its speculation's own count (`Pending.outside`: the fast + // path's premise, the same records, makes it this unit's): it + // owes an emulator a write (a grid's size), which a speculation + // never makes: kept, the write would be missing; replayed later + // (a rollback's `since`), made then. So it is taken now, on the + // confirmed core, and the ones on top applied again over it. + moved = r.pending.items[0].outside != 0; + if (moved) { r.toConfirmed(); if (tape.replayUnit(&r.t, u.tape)) |why| return r.fail(why); r.freePending(r.pending.orderedRemove(0)); r.dirty = true; return; } - const read_terminal = r.pending.items[0].terminal; r.freePending(r.pending.orderedRemove(0)); r.applied -= 1; if (r.applied == 0) { @@ -752,11 +759,10 @@ pub const Replica = struct { // input kept to replay over it as a unit of the session's // that comes while idle is: a step writes some bytes of the // megabyte the copy is, walked once in `rebase_after` units, - // not once a key. Not over one that read a terminal (replayed - // later it would read the deltas since), nor once a pane - // opened, closed or was torn down since the copy (what it - // holds outside the copy was made or freed: `ahead`'s rule). - if (!read_terminal and !r.panesMoved()) return r.keepSince(u.tape); + // not once a key. Not once a pane opened, closed or was torn + // down since the copy (what it holds outside the copy was + // made or freed: `ahead`'s rule). + if (!r.panesMoved()) return r.keepSince(u.tape); r.copy.release(); rollback.Epoch.select(null); r.clearSince(); @@ -771,13 +777,11 @@ pub const Replica = struct { r.last_digest.clearRetainingCapacity(); if (ends) |d| r.last_digest.appendSlice(r.gpa, d) catch {}; } - // A terminal's output, or a join's reloads, never taken so (the one - // rule): what it writes outside the copy is applied once, at its - // place, and much of it no digest covers (a colour set, a mode, the - // pages a reload remakes). - if (r.applied > 0 and u.origin != r.id and ends != null and std.mem.eql(u8, ends.?, r.last_digest.items) and - !tape.feedsTerminal(u.tape)) - { + // The one question needs no read here: the session's digest after + // the unit holds its count of writes outside the copy, so a unit that + // wrote an emulator (a terminal's output, a colour set no other + // digested field shows, a join's reloads) never ends where it began. + if (r.applied > 0 and u.origin != r.id and ends != null and std.mem.eql(u8, ends.?, r.last_digest.items)) { // Nothing a digest covers moved: what was applied on top is // what the session will apply on top of it. Replayed when the // copy is next put back. @@ -806,7 +810,7 @@ pub const Replica = struct { // replayed by a rollback were, if at all, as they came). const check = ends != null and r.checkDue(); r.t.checks = check; - const writes = Term.writes; + const outside = if (r.t.core) |c| c.outside.n else 0; const replayed = tape.replayUnit(&r.t, u.tape); r.t.checks = false; if (replayed) |why| { @@ -820,6 +824,7 @@ pub const Replica = struct { // draw nothing. Read after the replay: before it, it is what the // units before asked (and a first unit has no core yet). if (r.core().needs_frame) r.moved = true; + moved = r.core().outside.n != outside; if (check) { r.since_check = 0; r.stats.checks += 1; @@ -837,15 +842,15 @@ pub const Replica = struct { // or freed here, and is not put back with the copy: a rollback // replaying the unit again would close a terminal freed already (the // soak, a `Del` of the shell). Let go with the copy. - // The one rule: a unit that wrote an emulator (a terminal's output, - // a grid reflowed, a view moved, one reloaded at a join) wrote what - // no copy holds: kept, a rollback would replay it into what it - // wrote already (the bytes fed twice). It goes with the copy: the - // state is the confirmed one, nothing being on top. + // The one question: a unit that wrote an emulator (a terminal's + // output, a grid reflowed, one opened, closed or reloaded at a join) + // wrote what no copy holds: kept, a rollback would replay it into + // what it wrote already (the bytes fed twice). It goes with the + // copy: the state is the confirmed one, nothing being on top. const c = r.core(); for (c.retired_panes.current, c.retired_panes.previous) |x, y| retiring = retiring or x != null or y != null; for (c.panes, serials) |slot, n| retiring = retiring or (if (slot) |pane| pane.serial else 0) != n; - if (retiring or Term.writes != writes) { + if (retiring or moved) { r.copy.release(); rollback.Epoch.select(null); return r.clearSince(); @@ -952,6 +957,7 @@ pub const Replica = struct { tape.beginSpeculation(&r.t); // The time it was sent with, every time it is applied. r.t.guess = p.guess; + const outside = c.outside.n; c.toView(.at(r.view)); // Input into a terminal: what reaches its program (a key in tty // mode, a paste, a mouse report) is a pty write, the authority's, @@ -960,9 +966,9 @@ pub const Replica = struct { // the same bytes in the same order as the session's: it is applied. c.update(in.event); c.step(); - // It owes an emulator a write it skipped (a grid's size): replayed - // when confirmed. - p.terminal = r.t.touched; + // What it owes outside the copy (an emulator's grid: Term.resize + // counts the write a speculation skips): replayed when confirmed. + p.outside = c.outside.n -% outside; const clean = tape.endSpeculation(&r.t); const dt = nowNs() - t0; // Where a blob was written, should one be: the input that did. @@ -3973,6 +3979,39 @@ test "bytes: a session's output taken over a copy held ahead is fed once: a roll try sameTerminals(b.a, b.r); } +test "bytes: a session's reflow of a terminal's grid over a copy held ahead is the count's to decide: the copy goes, and a rollback does not reflow the grid again" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const b = try BytesPair.init(); + defer b.deinit(); + try b.output("a line long enough to wrap once the grid is narrower than it is now, and then some more\r\n"); + b.r.ready(); + try std.testing.expect(b.r.copy.held); + // The unit carries no output: its sync reflows the grid, which no record + // names; the core that applied it counted the write. + const before = b.r.core().outside.n; + b.r.confirm(try b.a.own(.{ .resize = .{ .cols = 40, .rows = 20 } })); + b.r.settle(); + try std.testing.expect(b.r.core().outside.n != before); + try std.testing.expect(!b.r.copy.held); + try b.rollback(); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); +} + +test "the count of writes outside the copy is digested: a session's emulator written where its client's is not (a colour set, which no other digested field shows) is a digest that names `outside`" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const b = try BytesPair.init(); + defer b.deinit(); + try std.testing.expectEqualStrings("", try partsApart(b.a, b.r, arena.allocator())); + // A write of one side's emulator that no unit carries, as a stray one + // would be: the count alone says it. + const pane = b.a.core.panes[b.shell.index()].?; + _ = pardes.Term.feed(&b.a.core.outside, pane.terminal.?, "\x1b[31m", &.{}, &.{}, &.{}, &.{}); + try std.testing.expectEqualStrings("outside ", try partsApart(b.a, b.r, arena.allocator())); +} + test "bytes: what a terminal's emulator gains while a copy is held is its own: a rollback frees none of it" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const b = try BytesPair.init(); @@ -4245,12 +4284,12 @@ test "bytes: a client joins from a dump with its terminals whole, and every side var line: [128]u8 = undefined; for (0..400) |i| try b.output(try std.fmt.bufPrint(&line, "\x1b[3{d}m{d}\x1b]8;;https://example.com/{d}\x1b\\ link\x1b]8;;\x1b\\\x1b[0m\r\n", .{ i % 8, i, i })); try b.output("half a colour: \x1b[38;2;10;20"); - const reloads = pardes.Term.writes; + const reloads = b.r.core().outside.n; const joined = (try b.a.join(2, null)).?; defer gpa.free(joined.dump); b.r.confirm(joined.unit); try std.testing.expect(b.r.diverged == null); - try std.testing.expect(pardes.Term.writes != reloads); + try std.testing.expect(b.r.core().outside.n != reloads); const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); defer late.deinit(); late.core().echo = null; diff --git a/core/tape.zig b/core/tape.zig index dc53a7c9..5f98238d 100644 --- a/core/tape.zig +++ b/core/tape.zig @@ -294,9 +294,6 @@ pub const Tape = struct { /// The authority's last yes or no to each question a replayed unit /// asked it (`authority`), a speculation's guess. answers: std.AutoHashMapUnmanaged(u64, bool) = .empty, - /// It read a terminal (its rows) or moved one's view: what it did - /// depends on the emulator, which deltas write (`touchTerminal`). - touched: bool = false, /// The allocator of the core a replay makes (a replica's rollback epoch, /// core/rollback.zig), when it is not the tape's own. core_gpa: ?std.mem.Allocator = null, @@ -890,11 +887,6 @@ pub const Tape = struct { return true; } - /// A speculation read a terminal's rows or moved its view (`Tape.touched`). - pub fn touchTerminal(t: *Tape) void { - if (t.speculating) t.touched = true; - } - /// The core a Restore made is the session's from here. pub fn adopt(t: *Tape, p: *Pardes) void { p.tape = t; @@ -1339,10 +1331,6 @@ pub fn authorityOnly(comptime why: []const u8) bool { return (on orelse &none).authorityOnly(why); } -pub fn touchTerminal() void { - (on orelse &none).touchTerminal(); -} - /// A harmless stand-in for what a host call or a syscall would have /// returned to a speculation that is thrown away once it returns: an /// error where one can be said, else zeroes. @@ -1426,7 +1414,6 @@ pub fn beginSpeculation(t: *Tape) void { t.speculating = true; t.poisoned = false; t.poisoned_by = ""; - t.touched = false; t.no_digest = true; t.yields = pardes.turn.yields; t.buf.clearRetainingCapacity(); @@ -1446,29 +1433,6 @@ pub fn endSpeculation(t: *Tape) bool { /// a message may be (replica.zig `lag_max`'s neighbour, wire's bound). pub const unit_max = 1 << 20; -/// Whether a unit writes a terminal's emulator: feeds one its program's -/// output (a pty's read; an input kept by hash is taken to), or reloads -/// every one at a join (`Site.reload`; a join refused too, which moves -/// nothing a digest covers): never taken as moving nothing (the replica -/// engine's one rule, core/replica.zig `confirm`). -pub fn feedsTerminal(bytes: []const u8) bool { - const Tag = std.meta.Tag(Input); - const EventTag = std.meta.Tag(pardes.Event); - const reload: u16 = @as(u16, host_fns.len) + @backingInt(Site.reload); - var r: walk.Reader = .{ .bytes = bytes }; - while (nextRecord(&r)) |rec| switch (rec.kind) { - .blob => if (rec.payload.len > 0 and rec.payload[0] == @backingInt(Kind.input)) return true, - .host => if (rec.payload.len >= 2 and std.mem.bytesToValue(u16, rec.payload[0..2]) == reload) return true, - .input => { - if (rec.payload.len < @sizeOf(Tag) + @sizeOf(EventTag)) continue; - if (!std.mem.eql(u8, rec.payload[0..@sizeOf(Tag)], std.mem.asBytes(&@as(Tag, .update)))) continue; - if (std.mem.eql(u8, rec.payload[@sizeOf(Tag)..][0..@sizeOf(EventTag)], std.mem.asBytes(&@as(EventTag, .output)))) return true; - }, - else => {}, - }; - return false; -} - /// Whether two tapes record the same inputs, host calls and answers, /// their digests aside. pub fn sameRecords(a: []const u8, b: []const u8) bool { diff --git a/test/kitty.zig b/test/kitty.zig index 22b62fb2..0bd849c2 100644 --- a/test/kitty.zig +++ b/test/kitty.zig @@ -641,7 +641,7 @@ test "kitty: an image follows its text when the shell scrolls, resizes and reflo try std.testing.expectEqual(o.y + 2, (try r.placesOf(10))[0].dst.y); // A narrower pane reflows the text; the image stays on its row. const pane = r.pane(0); - pane.resizeGrid(0, 40, pane.rows); + pane.resizeGrid(r.p, 40, pane.rows); const text = try pardes.Term.scrollback(pane.terminal, r.frame.allocator()); var row: usize = 0; var lines = std.mem.splitScalar(u8, text, '\n'); @@ -1167,7 +1167,7 @@ fn fuzzRun(seed: u64, steps: usize, trace: bool) !bool { r.p.update(.{ .resize = .{ .cols = cols, .rows = rows, .cell_pixels = .{ .w = 1 + rng.uintLessThan(u16, 30), .h = 1 + rng.uintLessThan(u16, 60) } } }); r.drain(); }, - 1 => r.pane(0).resizeGrid(0, 1 + rng.uintLessThan(u16, 120), 1 + rng.uintLessThan(u16, 40)), + 1 => r.pane(0).resizeGrid(r.p, 1 + rng.uintLessThan(u16, 120), 1 + rng.uintLessThan(u16, 40)), 2, 3 => { const drawn = try r.places(); if (trace) std.debug.print(" {d} places, {d} placements, {d} images\n", .{ drawn.len, r.placementCount(0), r.storage(0).images.count() }); diff --git a/test/perf.zig b/test/perf.zig index 30e15dcc..8622e31b 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -316,6 +316,7 @@ fn measureCreation(io: std.Io, reps: usize, json: bool) !void { for ([_]bool{ false, true }) |terminal| { var cold_ns: u64 = 0; var cold_deinit_ns: u64 = 0; + var outside: pardes.Term.Outside = .{}; var calls: usize = 0; var bytes: usize = 0; var live: usize = 0; @@ -325,12 +326,12 @@ fn measureCreation(io: std.Io, reps: usize, json: bool) !void { const allocator = counter.allocator(); const begin = nowNs(); const pane = if (terminal) - try pardes.panes.createTerminal(allocator, screen_cols, screen_rows) + try pardes.panes.createTerminal(&outside, allocator, screen_cols, screen_rows) else try pardes.panes.createDoc(allocator, screen_cols, screen_rows); const constructed = nowNs(); const retained = counter.live; - if (pane.terminal) |state| pardes.Term.close(state, allocator); + if (pane.terminal) |state| pardes.Term.close(&outside, state); allocator.destroy(pane); const destroyed = nowNs(); if (counter.live != 0) return error.LeakedPaneMemory; diff --git a/test/terminal.zig b/test/terminal.zig index bad70081..03bcd294 100644 --- a/test/terminal.zig +++ b/test/terminal.zig @@ -82,9 +82,10 @@ fn lineBreaks(comptime n: usize) [2 * n]u8 { test "replay ownership is terminal-only and construction rolls back on allocation failure" { const Case = struct { fn run(gpa: std.mem.Allocator, terminal: bool) !void { - const pane = if (terminal) try panes.createTerminal(gpa, 40, 12) else try panes.createDoc(gpa, 40, 12); + var outside: Term.Outside = .{}; + const pane = if (terminal) try panes.createTerminal(&outside, gpa, 40, 12) else try panes.createDoc(gpa, 40, 12); defer gpa.destroy(pane); - defer if (pane.terminal) |state| close(state, gpa); + defer if (pane.terminal) |state| close(&outside, state); try std.testing.expectEqual(terminal, pane.terminal != null); } }; @@ -98,7 +99,6 @@ test "document construction allocates only the pane and has inert terminal defau const allocator = failing.allocator(); const pane = try panes.createDoc(allocator, 40, 12); defer allocator.destroy(pane); - defer if (pane.terminal) |state| close(state, allocator); try std.testing.expect(pane.terminal == null); try std.testing.expectEqual(@as(usize, 1), failing.alloc_index); try std.testing.expectEqual(@as(usize, 0), failing.resize_index); @@ -109,7 +109,7 @@ test "document construction allocates only the pane and has inert terminal defau try std.testing.expectEqual(Term.Prompt{}, prompt(pane.terminal)); pane.scrollBy(100); pane.followOutput(); - pane.resizeGrid(0, 80, 24); + pane.resizeGrid(undefined, 80, 24); // no terminal: the core is never read try std.testing.expectEqual(Term.Grid{}, grid(pane.terminal)); try std.testing.expectEqualStrings("", try scrollback(pane.terminal, allocator)); try std.testing.expect(!failing.has_induced_failure); |
