diff options
| -rw-r--r-- | src/draw.zig | 2 | ||||
| -rw-r--r-- | src/replica.zig | 59 | ||||
| -rw-r--r-- | src/rollback.zig | 13 | ||||
| -rw-r--r-- | src/screen_state.zig | 98 | ||||
| -rw-r--r-- | src/tape.zig | 2 | ||||
| -rw-r--r-- | src/terminal.zig | 125 | ||||
| -rw-r--r-- | test/replicas.zig | 58 |
7 files changed, 278 insertions, 79 deletions
diff --git a/src/draw.zig b/src/draw.zig index 0cc5c80d..03bc0cf9 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -521,6 +521,8 @@ fn resolved(color: Color, default: ?[3]u8, palette: ?[16][3]u8) ?[3]u8 { pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { const taped = pardes.tape.enter(p, .render); defer pardes.tape.leave(p, taped); + panes.terminal.drawing = true; + defer panes.terminal.drawing = false; panes.File.refreshHighlights(p); const s = &p.surface; const ncells = @as(usize, p.screen_w) * p.screen_h; diff --git a/src/replica.zig b/src/replica.zig index 92ee7b37..cac8ed59 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -272,7 +272,10 @@ pub const Screens = struct { /// `core` is the session's, its terminals still there. pub fn deinit(s: *Screens, core: *Pardes) void { for (&s.tracks, 0..) |*slot, id| if (slot.*) |*tr| tr.track.deinit(s.gpa, if (s.live(core, id, tr)) &tr.state.vt else null); - for (s.peers.items) |p| s.gpa.destroy(p); + for (s.peers.items) |p| { + for (p) |*pp| pp.peer.deinit(s.gpa); + s.gpa.destroy(p); + } s.peers.deinit(s.gpa); s.out.deinit(s.gpa); s.enc.deinit(); @@ -302,7 +305,10 @@ pub const Screens = struct { const state = pane.terminal orelse continue; const tr = try s.track(core, id); const pp = &s.peers.items[peer][id]; - if (pp.serial != pane.serial) pp.* = .{ .serial = pane.serial }; + if (pp.serial != pane.serial) { + pp.peer.reset(); + pp.serial = pane.serial; + } var marks: [terminal.marks_len]u8 = undefined; s.out.clearRetainingCapacity(); try writeScreenHead(&s.out, s.gpa, @intCast(id), pane.serial, kind_delta); @@ -313,6 +319,45 @@ pub const Screens = struct { } } + /// Rows a peer holds as holes of every terminal a step read (its rows, + /// history and all: text mode over a shell), each a rows message onto + /// `out` (owned): sent after the step and before its unit, so the + /// replica's replay reads what the authority's step read. A history row + /// never changes, so each goes once. Then `filled`. + // ponytail: a step that reads a terminal's rows reads all of them (its + // motion surface), so the first after a flood sends its whole history. + pub fn fill(s: *Screens, core: *Pardes, peer: u16, out: *std.ArrayListUnmanaged([]u8)) !void { + for (core.panes, 0..) |slot, id| { + const pane = slot orelse continue; + const state = pane.terminal orelse continue; + if (!state.read) continue; + const pp = &s.peers.items[peer][id]; + if (pp.serial != pane.serial or pp.peer.holes.items.len == 0) continue; + const tr = try s.track(core, id); + for (pp.peer.holes.items) |hole| { + var lo = hole[0]; + while (lo < hole[1]) { + const hi = @min(hole[1], lo + 512); + s.out.clearRetainingCapacity(); + try writeScreenHead(&s.out, s.gpa, @intCast(id), pane.serial, kind_rows); + var w: std.Io.Writer.Allocating = .fromArrayList(s.gpa, &s.out); + defer s.out = w.toArrayList(); + try screen_state.encodeRows(&s.enc, &tr.track, &state.vt, lo, hi, &w.writer); + try out.append(s.gpa, try s.gpa.dupe(u8, w.written())); + lo = hi; + } + } + pp.peer.holes.clearRetainingCapacity(); + } + } + + /// Every peer is filled: the steps' reads are forgotten. + pub fn filled(_: *Screens, core: *Pardes) void { + for (core.panes) |slot| if (slot) |pane| if (pane.terminal) |state| { + state.read = false; + }; + } + fn track(s: *Screens, core: *Pardes, id: usize) !*Tracked { const pane = core.panes[id].?; if (s.tracks[id]) |*tr| { @@ -571,9 +616,11 @@ pub const Replica = struct { if (r.copy.held) { r.copy.restore(); rollback.Epoch.select(null); - // The copy's terminal rows are of a grid the deltas since moved - // on from: a rollback never brings a terminal's past back. - r.core().shell_rows.stale = true; + // The rows a terminal was read as are no copy's: what the + // speculation built was the epoch's, freed with it, and what + // was there before is of a grid the deltas since moved on + // from (a rollback never brings a terminal's past back). + r.core().shell_rows = .{}; } r.applied = 0; for (r.since.items) |u| if (tape.replayUnit(&r.t, u)) |why| return r.fail(why); @@ -614,6 +661,8 @@ pub const Replica = struct { const c = r.core(); if (!r.copy.held) { const t0 = nowNs(); + // A grid's worth of text the copy would save, and put back stale. + c.shell_rows.reset(c.gpa); r.copy.take(&r.epoch, c) catch return false; rollback.Epoch.select(&r.epoch); r.stats.copy_ns.append(r.gpa, nowNs() - t0) catch {}; diff --git a/src/rollback.zig b/src/rollback.zig index b5f4e966..d87671e6 100644 --- a/src/rollback.zig +++ b/src/rollback.zig @@ -350,7 +350,7 @@ pub const Copy = struct { // the speculation freed would come back as that. Not the // queues a step drains (undefined between steps), nor the // authority's. - if (attr.@"comptime" or comptime (annotated(T, "authority", name) or (annotated(T, "local", name) and unsaved(name)))) continue; + if (attr.@"comptime" or comptime (annotated(T, "authority", name) or ((annotated(T, "local", name) or annotated(T, "derived", name)) and unsaved(name)))) continue; if (comptime opaqueTo(F)) continue; c.where = @typeName(T) ++ "." ++ name; c.pinnable = comptime pinned(T, name); @@ -390,7 +390,7 @@ pub const Copy = struct { const s = @typeInfo(T).@"struct"; inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| { if (attr.@"comptime") continue; - if (comptime annotated(T, "local", name) and unsaved(name)) continue; + if (comptime (annotated(T, "local", name) or annotated(T, "derived", name)) and unsaved(name)) continue; const at = @intFromPtr(&@field(v, name)); if (comptime walk.lengthOf(T, name) != null and @typeInfo(F) == .array) { try c.save(at, walk.lengthIn(v, comptime walk.lengthOf(T, name).?) * @sizeOf(@typeInfo(F).array.child)); @@ -429,10 +429,13 @@ fn annotatedStruct(comptime T: type) bool { } /// The queues every step drains (empty between steps, asserted when a copy -/// is taken: what is in their slots is nothing), and the frame statistics -/// (numbers, and a static name). +/// is taken: what is in their slots is nothing), the frame statistics +/// (numbers, and a static name), and the rows a terminal was last read as +/// (a grid's worth of text, emptied when a copy is taken and when it is +/// put back: src/replica.zig). fn unsaved(comptime name: []const u8) bool { - return std.mem.eql(u8, name, "effects") or std.mem.eql(u8, name, "in_q") or std.mem.eql(u8, name, "frames"); + return std.mem.eql(u8, name, "effects") or std.mem.eql(u8, name, "in_q") or std.mem.eql(u8, name, "frames") or + std.mem.eql(u8, name, "shell_rows"); } fn annotated(comptime T: type, comptime kind: []const u8, comptime name: []const u8) bool { diff --git a/src/screen_state.zig b/src/screen_state.zig index e91f1e14..27e20c0f 100644 --- a/src/screen_state.zig +++ b/src/screen_state.zig @@ -191,8 +191,10 @@ const Known = struct { pub const Track = struct { rows: Rows = .{}, version: u32 = 0, - /// The emulator's change count the newest version was made at. + /// The emulator's change count the newest version was made at, and its + /// history's rows. changes: u32 = 0, + history: u64 = 0, /// The newest version: its active rows (pins, good while the emulator /// is unchanged) and their addresses, and its meta. pins: std.ArrayList(Pin) = .empty, @@ -236,6 +238,8 @@ pub const Track = struct { tr.version +%= 1; if (tr.version == 0) tr.version = 1; tr.changes = changes; + const primary = &t.screens.get(.primary).?.pages; + tr.history = primary.total_rows - primary.rows; tr.meta.clearRetainingCapacity(); { var rw: snapshot.record.Writer = .init(gpa, &tr.meta.writer); @@ -271,6 +275,15 @@ pub const Peer = struct { /// The versions in flight, oldest first. flight: [bound]u32 = undefined, n: u8 = 0, + /// The history rows its replica holds as holes, absolute, as the + /// replica keeps them (Replica.apply's rule, from what it was sent): + /// what `fill` sends before a step reads them. + top: u64 = 0, + holes: std.ArrayListUnmanaged([2]u64) = .empty, + + pub fn deinit(peer: *Peer, gpa: std.mem.Allocator) void { + peer.holes.deinit(gpa); + } /// Every version up to `seq` has landed. pub fn ack(peer: *Peer, seq: u32) void { @@ -282,7 +295,36 @@ pub const Peer = struct { /// Start the peer afresh: it lost its state, or never had one. pub fn reset(peer: *Peer) void { - peer.* = .{}; + var holes = peer.holes; + holes.clearRetainingCapacity(); + peer.* = .{ .holes = holes }; + } + + /// Its replica's holes once it applies a delta to `tr`'s newest version + /// against `base`, as Replica.apply makes them. + fn noteSent(peer: *Peer, gpa: std.mem.Allocator, tr: *const Track, base: ?*const Known, rows: u16) !void { + const top = tr.rows.top; + const history = tr.history; + if (base) |b| { + if (top > peer.top) { + const tail = @min(top -| b.top, rows, history); + if (top - peer.top >= @as(u64, rows) + history) { + peer.holes.clearRetainingCapacity(); + if (history > tail) try peer.holes.append(gpa, .{ top - history, top - tail }); + } else if (top - tail > peer.top) try peer.holes.append(gpa, .{ peer.top, top - tail }); + } + } else { + peer.holes.clearRetainingCapacity(); + if (history > 0) try peer.holes.append(gpa, .{ top - history, top }); + } + peer.top = top; + // Those older than its history's oldest row are gone with it. + var i: usize = 0; + while (i < peer.holes.items.len) { + const hole = &peer.holes.items[i]; + hole[0] = @max(hole[0], top -| history); + if (hole[0] >= hole[1]) _ = peer.holes.orderedRemove(i) else i += 1; + } } }; @@ -317,6 +359,7 @@ pub fn encode(e: *Encoder, tr: *Track, peer: *Peer, t: *Terminal, changes: u32, tr.cache_base = base_version; } try out.writeAll(tr.cache.written()); + try peer.noteSent(e.gpa, tr, base, t.rows); peer.sent = tr.version; peer.flight[peer.n] = tr.version; peer.n += 1; @@ -389,30 +432,41 @@ fn needBlob(e: *Encoder, base: ?*const Known, p: Pin, h: Hash) !void { try e.needed.append(e.gpa, .{ .pin = p, .hash = h }); } -/// The primary screen's rows `[lo, hi)` the authority still has, as u32 -/// epoch, u32 count, then each as u64 row, u32 length, blob: a replica's -/// fetch of history it holds as holes. -// ponytail: every row its blob, none by address: phase 6's content cache. +/// The primary screen's rows `[lo, hi)` the authority still has, for a +/// replica that holds them as holes: u32 epoch, u32 blobs, each u64 hash, +/// u32 length, bytes, then u32 rows, each u64 row and u64 hash. A blob goes +/// once a message (a flood's rows are one). +// ponytail: blobs once a message, not once a peer: phase 6's content cache. pub fn encodeRows(e: *Encoder, tr: *Track, t: *Terminal, lo: u64, hi: u64, out: *std.Io.Writer) !void { try tr.rows.update(t); var blobs: std.Io.Writer.Allocating = .init(e.gpa); defer blobs.deinit(); - var count: u32 = 0; + var rows: std.Io.Writer.Allocating = .init(e.gpa); + defer rows.deinit(); + e.listed.clearRetainingCapacity(); + var nblobs: u32 = 0; + var nrows: u32 = 0; var abs = lo; // The active area is the deltas'. while (abs < @min(hi, tr.rows.top)) : (abs += 1) { const p = tr.rows.pinAt(t, abs) orelse continue; - const start = blobs.written().len; - try blobs.writer.writeInt(u64, abs, .little); - try blobs.writer.writeInt(u32, 0, .little); - try e.rowBlob(p.node.page(), p.rowAndCell().row, t.cols, &blobs.writer); - const len: u32 = @intCast(blobs.written().len - start - 12); - std.mem.writeInt(u32, blobs.written()[start + 8 ..][0..4], len, .little); - count += 1; + const h = rowHash(p.node.page(), p.rowAndCell().row, t.cols); + try rows.writer.writeInt(u64, abs, .little); + try rows.writer.writeInt(u64, h, .little); + nrows += 1; + if ((try e.listed.getOrPut(e.gpa, h)).found_existing) continue; + e.blob.clearRetainingCapacity(); + try e.rowBlob(p.node.page(), p.rowAndCell().row, t.cols, &e.blob.writer); + try blobs.writer.writeInt(u64, h, .little); + try blobs.writer.writeInt(u32, @intCast(e.blob.written().len), .little); + try blobs.writer.writeAll(e.blob.written()); + nblobs += 1; } try out.writeInt(u32, tr.rows.epoch, .little); - try out.writeInt(u32, count, .little); + try out.writeInt(u32, nblobs, .little); try out.writeAll(blobs.written()); + try out.writeInt(u32, nrows, .little); + try out.writeAll(rows.written()); } /// A replica's terminal: what it was sent, written into a ghostty Terminal. @@ -631,9 +685,15 @@ pub const Replica = struct { var in: std.Io.Reader = .fixed(bytes); if (try in.takeInt(u32, .little) != r.epoch) return; // numbered before a resize const primary = t.screens.get(.primary).?; + var blobs: std.AutoHashMapUnmanaged(Hash, []const u8) = .empty; + defer blobs.deinit(gpa); + for (0..try in.takeInt(u32, .little)) |_| { + const h = try in.takeInt(u64, .little); + try blobs.put(gpa, h, try in.take(try in.takeInt(u32, .little))); + } for (0..try in.takeInt(u32, .little)) |_| { const abs = try in.takeInt(u64, .little); - const blob = try in.take(try in.takeInt(u32, .little)); + const blob = blobs.get(try in.takeInt(u64, .little)) orelse return error.MissingBlob; // Only a hole is written: a row the replica holds is the // authority's already, and newer than what this fetch saw. if (abs >= r.top or !r.inHole(abs)) continue; @@ -852,6 +912,7 @@ pub const Soak = struct { s.b.deinit(gpa); gpa.destroy(s.b); s.enc.deinit(); + s.peer.deinit(gpa); s.rep.deinit(gpa); for (s.flight.items) |f| { gpa.free(f.delta); @@ -1088,6 +1149,7 @@ fn bench(gpa: std.mem.Allocator, io: std.Io, w: *std.Io.Writer) !void { var tr: Track = .init(gpa); defer tr.deinit(gpa, t); var peer: Peer = .{}; + defer peer.deinit(gpa); out.clearRetainingCapacity(); var t0 = std.Io.Clock.awake.now(io).nanoseconds; _ = try encode(&enc, &tr, &peer, t, changes, "", &out.writer); @@ -1135,9 +1197,10 @@ fn floods(gpa: std.mem.Allocator, ca: std.mem.Allocator, io: std.Io, w: *std.Io. var reps: [3]Replica = @splat(.{}); var bs: [3]Terminal = undefined; for (bs[0..npeers]) |*b| b.* = try Terminal.init(io, ca, .{ .cols = 2, .rows = 2, .max_scrollback_bytes = 32 << 20 }); - defer for (bs[0..npeers], reps[0..npeers]) |*b, *r| { + defer for (bs[0..npeers], reps[0..npeers], peers[0..npeers]) |*b, *r, *peer| { b.deinit(ca); r.deinit(ca); + peer.deinit(ca); }; var applies: std.ArrayList(u64) = .empty; defer applies.deinit(gpa); @@ -1348,6 +1411,7 @@ test "a replica's terminal pane draws as its authority's does" { var enc: Encoder = .init(gpa); defer enc.deinit(); var peer: Peer = .{}; + defer peer.deinit(gpa); var tr: Track = .init(gpa); defer tr.deinit(gpa, ta); var rep: Replica = .{}; diff --git a/src/tape.zig b/src/tape.zig index 0609ce0b..b1080149 100644 --- a/src/tape.zig +++ b/src/tape.zig @@ -88,6 +88,8 @@ pub const Site = enum(u16) { mtime, cwd, pointer, + /// What a terminal's ingest told the positions pardes keeps over it. + positions, }; /// Fields a host writes straight into the core between its calls. diff --git a/src/terminal.zig b/src/terminal.zig index 6c3eeda7..fcb284a0 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -161,6 +161,10 @@ pub const State = struct { /// Counts the emulator's writes (output, a resize, its view scrolled): /// a new count is a new state for its replicas (screen_state.Track). changes: u32 = 0, + /// A step read its rows (its history too): a replica replaying that + /// step must hold them, so its authority sends the ones it does not + /// before the step's unit (replica.Screens.fill). + read: bool = false, /// The emulator as its program has made it, for the replay digest /// (src/walk.zig): the active screen's text, how much history is above @@ -855,6 +859,7 @@ pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { state.stream = .init(.{ .handler = .{ .inner = state.vt.vtHandler() }, .allocator = gpa }); state.reply_len = 0; state.changes = 0; + state.read = false; // Every field its default (create leaves them what the heap had, which // a digest then reads: two replicas must agree, src/replica.zig). state.reply_dropped = 0; @@ -1072,11 +1077,15 @@ pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void { if (comptime !enabled) return; if (pane.terminal == null) return; if (authorityOnly()) return; - // A replica's emulator is what the authority's deltas make it. - if (pardes.tape.screenReplica()) return; const has_positions = pane.ovl != null or pane.body.cur_pinned or pane.body.vsel.active or pane.body.msel.active or pane.body.nsel > 0 or pane.body.last_edit != null or pane.look_at != null or pane.body.ed_undo_len > 0 or pane.body.ed_redo_len > 0 or pointerRowCount(pane) > 0; + // A replica's emulator is what the authority's deltas make it; what + // pardes keeps over it moves as the authority's ingest told it. + if (pardes.tape.screenReplica()) { + if (has_positions) ingestWithPositions(pane, bytes); + return; + } // Sticky bottom, as every other terminal does it: output drags the // viewport down only when the viewport was already on the last row, so // a reader scrolled back into the scrollback stays where they scrolled. @@ -1095,7 +1104,9 @@ const PositionPin = struct { edit_row: ?i32 = null, }; -fn trackRow(pages: *ghostty_vt.PageList, row: i32, failed: *bool) RowPin { +fn trackRow(maybe_pages: ?*ghostty_vt.PageList, row: i32, failed: *bool) RowPin { + // A screen-state replica's: told by the tape, not its emulator. + const pages = maybe_pages orelse return .{ .offset = row }; if (row < 0) return .{ .offset = row }; const bounded: usize = @min(@as(usize, @intCast(row)), pages.total_rows - 1); var left = pages.total_rows - 1 - bounded; @@ -1125,7 +1136,7 @@ fn pinnedRow(pages: ?*ghostty_vt.PageList, row: RowPin) i32 { return 0; } -fn trackPosition(pages: *ghostty_vt.PageList, target: *i32, overlay: ?*EditBuffer, failed: *bool) PositionPin { +fn trackPosition(pages: ?*ghostty_vt.PageList, target: *i32, overlay: ?*EditBuffer, failed: *bool) PositionPin { var grid = target.*; if (overlay) |edit| { const lines: i32 = @intCast(modal.lineCount(edit.text)); @@ -1144,11 +1155,24 @@ fn pointerRowCount(pane: *const Pane) usize { return count; } +/// What an ingest told the positions over it (`ingestWithPositions`): each +/// tracked row where it is after it (the spans' starts and ends, the +/// positions, the pointer rows, in that order) and whether the program +/// erased it, whether the screen was cleared, whether its pages lived and +/// whether a pin could not be made. Taped: a screen-state replica, which +/// ingests nothing, is told the authority's. +const Told = struct { rows: []const i32, erased: []const bool, cleared: bool, alive: bool, failed: bool }; + +fn told(t: Told) Told { + return t; +} + fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { const screens = &pane.terminal.?.vt.screens; const key = screens.active_key; const generation = screens.generation(key); - const pages = &screens.active.pages; + const replica = pardes.tape.screenReplica(); + const pages: ?*ghostty_vt.PageList = if (replica) null else &screens.active.pages; const Group = struct { overlay: ?*EditBuffer, cursor: *i32, selection: *panes.Text.CharSel }; var groups: [history_max * 2 + 1]Group = undefined; groups[0] = .{ @@ -1230,31 +1254,61 @@ fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { } }; } else failed = true; - // Whether the program cleared the screen (ED 2, a switch of screens); - // pardes reads the flag nowhere else. - pane.terminal.?.vt.flags.dirty.clear = false; - ingest(pane, bytes); - const cleared = pane.terminal.?.vt.flags.dirty.clear; - // RIS can destroy the alternate screen and every pin it owned. - const alive = if (screens.generation(key) == generation) pages else null; - var moved = false; - var pointer_rows_lost = alive == null or pointer_positions == null; - if (pointer_positions) |pins| for (pins) |position| { - if (alive != null) if (position.row.pin) |pin| { - if (pin.garbage) pointer_rows_lost = true; + var cleared = false; + var alive: ?*ghostty_vt.PageList = null; + if (!replica) { + // Whether the program cleared the screen (ED 2, a switch of + // screens); pardes reads the flag nowhere else. + pane.terminal.?.vt.flags.dirty.clear = false; + ingest(pane, bytes); + cleared = pane.terminal.?.vt.flags.dirty.clear; + // RIS can destroy the alternate screen and every pin it owned. + alive = if (screens.generation(key) == generation) pages else null; + } + const pointers: []PositionPin = pointer_positions orelse &.{}; + const n = 2 * nspans + npositions + pointers.len; + // On the stack, as the local path never allocated here but for the + // pointer's rows. + var rows_buf: [512]i32 = undefined; + var erased_buf: [512]bool = undefined; + const rows_after = if (n <= rows_buf.len) rows_buf[0..n] else pane.gpa.alloc(i32, n) catch return; + 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; + defer if (n > erased_buf.len) pane.gpa.free(erased_after); + @memset(rows_after, 0); + @memset(erased_after, false); + if (!replica) { + var k: usize = 0; + for (spans[0..nspans]) |span| for ([_]RowPin{ span.start, span.end }) |rp| { + rows_after[k] = pinnedRow(alive, rp); + erased_after[k] = alive != null and rp.pin != null and rp.pin.?.garbage; + k += 1; + }; + for ([_][]PositionPin{ positions[0..npositions], pointers }) |batch| for (batch) |position| { + rows_after[k] = pinnedRow(alive, position.row); + erased_after[k] = alive != null and position.row.pin != null and position.row.pin.?.garbage; + k += 1; }; + } + const after = pardes.tape.value(.positions, told, .{Told{ .rows = rows_after, .erased = erased_after, .cleared = cleared, .alive = alive != null, .failed = failed }}); + if (after.rows.len != n or after.erased.len != n) return; // a replica its authority's states apart (diverged) + failed = after.failed; + const at_position = 2 * nspans; + const at_pointer = at_position + npositions; + var moved = false; + var pointer_rows_lost = !after.alive or pointer_positions == null; + for (0..pointers.len) |i| if (after.erased[at_pointer + i]) { + pointer_rows_lost = true; }; // The program cleared the screen, or the rows the live copy stood on are // gone (pruned, a reset): the copy goes with them, as what the program // drew next. Kept, ghostty would move its rows to the top of what is // left, over the program's new text. - var copy_lost = cleared or alive == null; - for (spans[0..nspans]) |span| { - if (span.overlay == overlay) if (span.start.pin) |pin| if (alive != null and pin.garbage) { - copy_lost = true; - }; - const start = pinnedRow(alive, span.start); - const rows = @max(1, pinnedRow(alive, span.end) -| start +| 1); + var copy_lost = after.cleared or !after.alive; + for (spans[0..nspans], 0..) |span, i| { + if (span.overlay == overlay and after.erased[2 * i]) copy_lost = true; + const start = after.rows[2 * i]; + const rows = @max(1, after.rows[2 * i + 1] -| start +| 1); moved = moved or start != span.overlay.row or rows != span.overlay.rows; span.overlay.row = start; span.overlay.rows = rows; @@ -1266,23 +1320,16 @@ fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { // The rule above for the copy holds for the selections: one whose row // is gone (ED 3 erased its history row, which ghostty flags `garbage`) // goes too, rather than being clamped to the top. - const erased = struct { - fn at(owner: ?*ghostty_vt.PageList, all: []const PositionPin, index: usize) bool { - if (owner == null) return false; - const pin = all[index].row.pin orelse return false; - return pin.garbage; - } - }.at; + const erased = after.erased[at_position..]; const vsel_lost = if (vsel_at) |i| - erased(alive, positions[0..npositions], i) or (copy_lost and positions[i].edit_row != null) + erased[i] or (copy_lost and positions[i].edit_row != null) else false; - const msel_lost = if (msel_at) |i| erased(alive, positions[0..npositions], i) or erased(alive, positions[0..npositions], i + 1) else false; + const msel_lost = if (msel_at) |i| erased[i] or erased[i + 1] else false; var sels_keep: [panes.Text.max_selections]bool = undefined; - for (0..pane.body.nsel) |i| sels_keep[i] = !(erased(alive, positions[0..npositions], sels_at + 2 * i) or - erased(alive, positions[0..npositions], sels_at + 2 * i + 1)); - for ([_][]PositionPin{ positions[0..npositions], pointer_positions orelse &.{} }) |batch| for (batch) |position| { - var row = pinnedRow(alive, position.row); + for (0..pane.body.nsel) |i| sels_keep[i] = !(erased[sels_at + 2 * i] or erased[sels_at + 2 * i + 1]); + for ([_][]PositionPin{ positions[0..npositions], pointers }, [_]usize{ at_position, at_pointer }) |batch, first| for (batch, first..) |position, k| { + var row = after.rows[k]; if (position.overlay) |edit| { if (position.edit_row) |relative| { row = edit.row +| relative; @@ -1887,7 +1934,11 @@ pub fn setEditText(p: *Pardes, pane: *Pane, new: []u8) void { } +/// Set while a frame is drawn: what it reads is no step's. +pub var drawing = false; + fn buildRows(alloc: std.mem.Allocator, p: *Pardes, pane: *Pane) !Rows { + if (!drawing) pane.terminal.?.read = true; const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(p.scratch.allocator(), .{ .screen = .{} }); var pit = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); // split yields one more item than delimiters; the extra final slot is the diff --git a/test/replicas.zig b/test/replicas.zig index 1acd1c11..9b5c3c3b 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -113,6 +113,8 @@ const Totals = struct { flood_delta_bytes: u64 = 0, flood_unit_bytes: u64 = 0, fetched: u64 = 0, + /// Bytes of rows sent before a step's unit, the step having read them. + filled_bytes: u64 = 0, resets: u64 = 0, screens_wrong: u64 = 0, screens_checked: u64 = 0, @@ -141,7 +143,7 @@ const Totals = struct { fn nextEvent(random: std.Random, buf: *[64]u8, wheel_at: ?[2]u16) pardes.Event { const typed = "abcdefghijklmnopqrstuvwxyz0123456789 -_=+,:;()"; const normal = "hjklwbe0$xpuyoOiaAIdcv.nN%sC"; - switch (random.uintLessThan(u8, 42)) { + switch (random.uintLessThan(u8, 43)) { 0...15 => { buf[0] = typed[random.uintLessThan(usize, typed.len)]; return .{ .key = .{ .cp = buf[0], .text = buf[0..1] } }; @@ -173,6 +175,9 @@ fn nextEvent(random: std.Random, buf: *[64]u8, wheel_at: ?[2]u16) pardes.Event { 37 => return .{ .resize = .{ .cols = @intCast(random.intRangeAtMost(u16, 60, 120)), .rows = @intCast(random.intRangeAtMost(u16, 16, 40)) } }, 38 => return .{ .mouse = .{ .button = .left, .kind = .press, .col = random.uintLessThan(u16, 80), .row = random.uintLessThan(u16, 24) } }, 39 => return .{ .mouse = .{ .button = .left, .kind = .release, .col = random.uintLessThan(u16, 80), .row = random.uintLessThan(u16, 24) } }, + // Out of a shell's tty mode and back: its text, a cursor and + // selections over it. + 40 => return .{ .key = .{ .cp = 'b', .ctrl = true } }, else => { const at = wheel_at orelse return .{ .key = .{ .cp = Key.escape } }; return .{ .mouse = .{ .button = if (random.uintLessThan(u8, 3) == 0) .wheel_down else .wheel_up, .kind = .press, .col = at[0], .row = at[1] } }; @@ -252,14 +257,18 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { const sr = a.core.rects[shell]; const wheel_at: ?[2]u16 = if (sr.h > 2) .{ sr.x + sr.w / 2, sr.y + sr.h / 2 } else null; - // What the shell's program prints: a full-screen program, then a flood - // of `yes`, read 4 KB at a time as a pty gives it. + // What the shell's program prints: a full-screen program, a shell's + // session (prompts, titles, directories, a clear now and then), then a + // flood of `yes`, read 4 KB at a time as a pty gives it. const tui = try screen_state.tuiStream(gpa); defer gpa.free(tui); + const session = try screen_state.shellStream(gpa); + defer gpa.free(session); const yes = try screen_state.yesStream(gpa, @intCast(r.flood_mb * (1 << 20) / 3)); defer gpa.free(yes); const tui_at: u64 = 400_000; - const flood_at: u64 = 1_500_000; + const session_at: u64 = 1_000_000; + const flood_at: u64 = 2_500_000; var flood_end: u64 = 0; var program: struct { bytes: []const u8 = &.{}, at: usize = 0 } = .{}; // The authority's version of each terminal, as its screen showed then. @@ -290,6 +299,7 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { // Each client's first input, soon; the programs; the first frame. for (0..r.clients) |c| try push(&queue, &n, .{ .at = random.uintLessThan(u64, 200_000), .n = 0, .kind = .input, .who = @intCast(c + 1), .bytes = &.{} }); try push(&queue, &n, .{ .at = tui_at, .n = 0, .kind = .output, .who = 0, .bytes = &.{} }); + try push(&queue, &n, .{ .at = session_at, .n = 0, .kind = .output, .who = 2, .bytes = &.{} }); try push(&queue, &n, .{ .at = flood_at, .n = 0, .kind = .output, .who = 1, .bytes = &.{} }); try push(&queue, &n, .{ .at = frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} }); var frames_left: u32 = 0; @@ -353,13 +363,17 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { // The program's next read, 4 KB, then the next a // fraction of a millisecond on (ghostty's pace). if (program.at == program.bytes.len) { - program = .{ .bytes = if (m.who == 0) tui else yes }; + program = .{ .bytes = switch (m.who) { + 0 => tui, + 1 => yes, + else => session, + } }; } - const k = @min(program.bytes.len - program.at, if (m.who == 0) @as(usize, 700) else 4096); + const k = @min(program.bytes.len - program.at, if (m.who == 1) @as(usize, 4096) else 700); const chunk = program.bytes[program.at..][0..k]; program.at += k; if (program.at < program.bytes.len) - try push(&queue, &n, .{ .at = m.at + if (m.who == 0) @as(u64, 3_000) else 450, .n = 0, .kind = .output, .who = m.who, .bytes = &.{} }) + try push(&queue, &n, .{ .at = m.at + if (m.who == 1) @as(u64, 450) else 3_000, .n = 0, .kind = .output, .who = m.who, .bytes = &.{} }) else if (m.who == 1) flood_end = m.at; if (m.who == 1) flood_units += 1; a.output(.{ .output = .{ .pane = shell, .bytes = chunk } }); @@ -369,17 +383,17 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { // The authority's own steps since the last unit, and // the terminals as they are: what the input's step // reads, before it is stepped. - if (try a.pending()) |batch| try sendUnit(&queue, &n, batch, m.at, down[0..r.clients], random, one_way, jitter, totals, m.at >= flood_at and flood_end == 0); + if (try a.pending()) |batch| try sendUnit(&queue, &n, batch, m.at, down[0..r.clients], random, one_way, jitter, totals, m.at >= flood_at and flood_end == 0, &screens, a.core, peers[0..r.clients]); try flushAll(&screens, a.core, peers[0..r.clients], &owed, &queue, &n, m.at, &down, random, one_way, jitter, &versions, totals); break :in try a.take(m.bytes); }, }; - if (unit) |u| try sendUnit(&queue, &n, u, m.at, down[0..r.clients], random, one_way, jitter, totals, false); + if (unit) |u| try sendUnit(&queue, &n, u, m.at, down[0..r.clients], random, one_way, jitter, totals, false, &screens, a.core, peers[0..r.clients]); for (host.echo.items) |e| try push(&queue, &n, .{ .at = m.at + 2_000, .n = 0, .kind = .echo, .who = e.pane, .bytes = e.bytes }); host.echo.clearRetainingCapacity(); }, .frame => { - if (try a.pending()) |batch| try sendUnit(&queue, &n, batch, m.at, down[0..r.clients], random, one_way, jitter, totals, m.at >= flood_at and flood_end == 0); + if (try a.pending()) |batch| try sendUnit(&queue, &n, batch, m.at, down[0..r.clients], random, one_way, jitter, totals, m.at >= flood_at and flood_end == 0, &screens, a.core, peers[0..r.clients]); const t0 = screens.encode_ns; const before = totals.delta_bytes; try flushAll(&screens, a.core, peers[0..r.clients], &owed, &queue, &n, m.at, &down, random, one_way, jitter, &versions, totals); @@ -453,8 +467,21 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { } } -/// A unit of the authority's to every replica, down its link. -fn sendUnit(q: *std.PriorityQueue(Msg, void, Msg.order), n: *u64, unit: []const u8, now: u64, down: []Link, random: std.Random, one_way: u64, jitter: u64, totals: *Totals, flooding: bool) !void { +/// A unit of the authority's to every replica, down its link: first the +/// rows of its terminals its step read that a replica holds as holes. +fn sendUnit(q: *std.PriorityQueue(Msg, void, Msg.order), n: *u64, unit: []const u8, now: u64, down: []Link, random: std.Random, one_way: u64, jitter: u64, totals: *Totals, flooding: bool, screens: *replica.Screens, core: *pardes.Pardes, peers: []const u16) !void { + var rows: std.ArrayListUnmanaged([]u8) = .empty; + defer rows.deinit(gpa); + for (down, peers, 1..) |*l, peer, who| { + rows.clearRetainingCapacity(); + try screens.fill(core, peer, &rows); + for (rows.items) |bytes| { + totals.filled_bytes += bytes.len; + try q.push(gpa, .{ .at = l.arrive(random, now, one_way, jitter), .n = n.*, .kind = .screen_down, .who = @intCast(who), .bytes = bytes }); + n.* += 1; + } + } + screens.filled(core); totals.unit_bytes += unit.len * down.len; if (flooding) totals.flood_unit_bytes += unit.len * down.len; for (down, 1..) |*l, who| { @@ -523,7 +550,7 @@ pub fn main(init: std.process.Init) !void { }); const flood_s = @as(f64, @floatFromInt(@max(1, t.flood_us))) / 1e6; - try term_lines.print(gpa, "{d:>4} {d:>7.1} {d:>9.0} {d:>9.0} {d:>5}/{d:<5} {d:>5}/{d:<5} {d:>7} {d:>6} {d:>6}/{d:<6}\n", .{ + try term_lines.print(gpa, "{d:>4} {d:>7.1} {d:>9.0} {d:>9.0} {d:>5}/{d:<5} {d:>5}/{d:<5} {d:>7} {d:>9} {d:>6} {d:>6}/{d:<6}\n", .{ rtt, @as(f64, @floatFromInt(t.flood_deltas)) / flood_s / @as(f64, @floatFromInt(clients)), @as(f64, @floatFromInt(t.flood_delta_bytes)) / flood_s / @as(f64, @floatFromInt(clients)), @@ -533,13 +560,14 @@ pub fn main(init: std.process.Init) !void { pct(t.apply_ns.items, 50) / 1000, pct(t.apply_ns.items, 99) / 1000, t.fetched, + t.filled_bytes / 1024, t.resets, t.screens_checked, t.screens_wrong, }); if (t.divergences > 0 or t.unequal > 0 or t.screens_wrong > 0) failed = true; } - std.debug.print("terminals: deltas a replica applied a second under the flood; a peer's bytes a second under the flood (deltas, units); encode a frame of the flood for every peer, apply a delta (us); rows fetched; resets; deltas checked/wrong\n", .{}); - std.debug.print(" rtt deltas/s delta B/s unit B/s encode p50/p99 apply p50/p99 fetched resets checked/wrong\n{s}", .{term_lines.items}); + std.debug.print("terminals: deltas a replica applied a second under the flood; a peer's bytes a second under the flood (deltas, units); encode a frame of the flood for every peer, apply a delta (us); rows fetched, KB of rows sent before the step that read them; resets; deltas checked/wrong\n", .{}); + std.debug.print(" rtt deltas/s delta B/s unit B/s encode p50/p99 apply p50/p99 fetched filled KB resets checked/wrong\n{s}", .{term_lines.items}); if (failed) std.process.exit(1); } |
