From 1ce129e7415590a4979e71da683966c056fba532 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 19 Nov 2026 21:32:26 -0300 Subject: replica: a client's stats line (PARDES_REPLICA_STATS) prints its rebases, copies and checks, and `rebases` counts only a rebase that puts the copy back under inputs applied on top (the kept units replayed, the inputs applied again), not the free let-go with nothing applied: the three counters that name a heavy block of the client path were kept and never printed (pardes-perf-plan section 1 repair 3); no behaviour changes Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/replica.zig | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/core/replica.zig b/core/replica.zig index c68848f2..3a36a06b 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -568,6 +568,8 @@ pub const Stats = struct { /// the authority did not share), or another's unit first. mispredicted: u32 = 0, foreign: u32 = 0, + /// The copy put back at `rebase_after` kept units with inputs applied + /// on top: the kept units replayed, the inputs applied again. rebases: u32 = 0, units: u32 = 0, /// Its digest compared with the session's (a unit's, or quiet). @@ -1041,13 +1043,13 @@ pub const Replica = struct { const kept = r.gpa.dupe(u8, unit) catch return r.fail("out of memory"); r.since.append(r.gpa, kept) catch return r.fail("out of memory"); if (r.since.items.len >= rebase_after) { - r.stats.rebases += 1; // Nothing on top: it is the confirmed state already. if (r.applied == 0) { r.copy.release(); rollback.Epoch.select(null); return r.clearSince(); } + r.stats.rebases += 1; r.toConfirmed(); r.dirty = true; } @@ -3241,13 +3243,13 @@ pub const Link = struct { var buf: [1024]u8 = undefined; const e = &c.r.echo.stats; var w: std.Io.Writer = .fixed(&buf); - w.print("inputs {d} at_once {d} stopped {d} units {d} fast {d} neutral {d} mispredicted {d} foreign {d} visible {d} rtt_us {d} spec_us {d}/{d} copy_us {d}/{d} rollback_us {d}/{d} join_ms {d} blobs {d} from_memory {d} from_disk {d} sent_kb {d} echo {d}/{d} confirmed {d} missed {d} draws {d} again {d}", .{ + w.print("inputs {d} at_once {d} stopped {d} units {d} fast {d} neutral {d} mispredicted {d} foreign {d} visible {d} rtt_us {d} spec_us {d}/{d} copy_us {d}/{d} rollback_us {d}/{d} join_ms {d} blobs {d} from_memory {d} from_disk {d} sent_kb {d} echo {d}/{d} confirmed {d} missed {d} draws {d} again {d} rebases {d} copies {d} checks {d}", .{ st.inputs, st.speculated, st.stopped, st.units, st.fast, c.r.neutral, st.mispredicted, st.foreign, c.visible, c.r.rtt_ns / 1000, pctOf(st.spec_ns.items, 50) / 1000, pctOf(st.spec_ns.items, 99) / 1000, pctOf(st.copy_ns.items, 50) / 1000, pctOf(st.copy_ns.items, 99) / 1000, pctOf(st.rollback_ns.items, 50) / 1000, pctOf(st.rollback_ns.items, 99) / 1000, c.join_ms, c.join.blobs, c.join.from_memory, c.join.from_disk, c.join.sent_bytes >> 10, e.predicted, e.predicted + e.unpredicted, e.confirmed, e.mispredicted, - c.draws, c.again, + c.draws, c.again, st.rebases, st.copies, st.checks, }) catch return; // What stopped its inputs, last: a word a pair before it. w.writeAll(" stops ") catch return; -- cgit v1.3 From 12d058283aabb10d02ae86552ed82fcd48ba91af Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 19 Nov 2026 22:05:20 -0300 Subject: Term: a terminal's stream keeps the sequence its program began and has not ended (ghostty's continuation, up to 64 KiB: a CSI, an OSC, a UTF-8 codepoint, a kitty graphics chunk), its snapshot carries it and a load feeds it again, so a snapshot may be taken between any two reads (docs: reports/pardes-term-bytes.md, section 1; the brief's step 1a): ghostty promises it for its standard handler only, and a test pins it over pardes's MarkedHandler, a cut at every byte of a CSI, a link, pardes's own OSC 133 marks, a UTF-8 codepoint, a kitty graphics payload and three device queries (on the tree before: the first cut, inside the CSI, came to another terminal); the parse's cost with tracking on, pardes-perf --terminal-mib 8 and 32, instructions:u, three runs each, off and on alternated in one tree: 3,924.06M -> 3,924.09M and 13,202.27M -> 13,202.58M (+0.001%, +0.002%); term-test 16/16 Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/term/terminal.zig | 146 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 125 insertions(+), 21 deletions(-) diff --git a/core/term/terminal.zig b/core/term/terminal.zig index d99cfb79..f92da3fd 100644 --- a/core/term/terminal.zig +++ b/core/term/terminal.zig @@ -201,13 +201,17 @@ pub const State = struct { /// The stream over the emulator, its answers to the program and its /// size reports routed here, PNG decoded: what `create` and a dump's - /// load both do once the emulator is in place. - fn wire(s: *State) void { - s.stream = .init(.{ .handler = .{ .inner = s.vt.vtHandler() }, .allocator = s.gpa }); + /// load both do once the emulator is in place. False when the stream's + /// keeper of a sequence in flight had no room (ghostty goes on without + /// it, swallowing the error): `open` and `load` refuse the terminal then, + /// as at any allocation that fails. + fn wire(s: *State) bool { + s.stream = .init(.{ .handler = .{ .inner = s.vt.vtHandler() }, .allocator = s.gpa, .continuation_max_bytes = continuation_max }); s.stream.handler.inner.effects.write_pty = ptyReport; s.stream.handler.inner.effects.device_attributes = ptyDeviceAttrs; s.stream.handler.inner.effects.size = ptySize; if (comptime images_enabled) TerminalImages.installPngDecoder(); + return s.stream.continuation.?.bytes.capacity > 0; } }; @@ -268,14 +272,42 @@ pub fn parts(s: *const State) Term.Parts { }; } +/// The most bytes of a sequence its program began and has not ended (a +/// CSI, an OSC, a UTF-8 codepoint, a kitty graphics chunk: 4 KiB of payload) +/// that its stream keeps, so a snapshot taken between any two reads carries +/// it (`snapshot`). Past it the sequence is lost at a cut, as every one was +/// before. +pub const continuation_max = 64 * 1024; + /// Its emulator as the dump keeps it: ghostty's snapshot (both screens, -/// their history, styles, links and kitty images). A sequence its program -/// had begun and not ended is not kept: the snapshot is at the ground -/// state. `slim`, a join's dump (dump.zig `dumpJoin`): its size alone, an +/// their history, styles, links and kitty images), and the sequence its +/// program had begun and not ended, which `load` feeds again. `slim`, a +/// join's dump under screen state (dump.zig `dumpJoin`): its size alone, an /// emulator made afresh there, which its first delta replaces. pub fn snapshot(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer, slim: bool) !void { if (slim) return w.writeAll(std.mem.asBytes(&[2]u16{ s.vt.cols, s.vt.rows })); - try ghostty_vt.snapshot.encode(gpa, w, &s.vt, .{ .continuation = .ground }); + var held: std.Io.Writer.Allocating = .init(gpa); + defer held.deinit(); + s.stream.writeContinuation(&held.writer) catch |err| switch (err) { + // Longer than it keeps: lost, as at the ground state. + error.ContinuationUnavailable, error.ContinuationDisabled => held.clearRetainingCapacity(), + error.WriteFailed => return error.OutOfMemory, + }; + const continuation: ghostty_vt.snapshot.Continuation = if (held.written().len > 0) .{ .bytes = held.written() } else .ground; + try ghostty_vt.snapshot.encode(gpa, w, &s.vt, .{ .continuation = continuation }); +} + +/// `snapshot`'s bytes decoded, the emulator not yet at its address. +fn decode(gpa: std.mem.Allocator, bytes: []const u8) !ghostty_vt.snapshot.Decoded { + if (bytes.len == 4) { + const size = std.mem.bytesToValue([2]u16, bytes[0..4]); + return .{ .terminal = try emulator(gpa, @max(1, size[0]), @max(1, size[1])), .continuation = .ground, .history_rows = .{} }; + } + var reader: std.Io.Reader = .fixed(bytes); + return ghostty_vt.snapshot.decodeExact(gpa, terminalIo(), &reader, .{ + .max_continuation_bytes = continuation_max, + .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, + }); } /// `snapshot`'s bytes and `parts` back into a new terminal, as `open` @@ -283,22 +315,29 @@ pub fn snapshot(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer, slim pub fn load(gpa: std.mem.Allocator, bytes: []const u8, saved: *const Term.Parts) !*State { const out = try gpa.create(State); errdefer gpa.destroy(out); - var reader: std.Io.Reader = .fixed(bytes); - if (reader.buffer.len == 4) { - const size = std.mem.bytesToValue([2]u16, bytes[0..4]); - out.* = .{ .gpa = gpa, .vt = try emulator(gpa, @max(1, size[0]), @max(1, size[1])), .stream = undefined }; - } else { - var decoded = try ghostty_vt.snapshot.decodeExact(gpa, terminalIo(), &reader, .{ - .max_continuation_bytes = 0, - .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, - }); - defer decoded.deinit(gpa); - out.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined }; + var decoded = try decode(gpa, bytes); + defer decoded.deinit(gpa); + out.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined }; + if (!install(out, decoded.continuation, saved)) { + out.stream.deinit(); + out.vt.deinit(gpa); + return error.OutOfMemory; } + return out; +} + +/// A decoded emulator at its address made a terminal: its stream wired, +/// the sequence in flight fed again, what pardes kept beside it put back; +/// whether its stream had all the room it wanted (`wire`). +fn install(out: *State, continuation: ghostty_vt.snapshot.Continuation, saved: *const Term.Parts) bool { if (comptime images_enabled) inline for (.{ .primary, .alternate }) |which| { if (out.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = .allWithTempDir(tempDir()); }; - out.wire(); + const whole = out.wire(); + switch (continuation) { + .ground => {}, + .bytes => |bytes| out.stream.nextSlice(bytes), + } const reply = saved.reply[0..@min(saved.reply.len, out.reply.len)]; @memcpy(out.reply[0..reply.len], reply); out.reply_len = @intCast(reply.len); @@ -321,7 +360,7 @@ pub fn load(gpa: std.mem.Allocator, bytes: []const u8, saved: *const Term.Parts) const screen = out.vt.screens.active; const bottom = screen.pages.scrollbar().offset; screen.scroll(.{ .delta_row = @as(isize, @intCast(saved.view)) - @as(isize, @intCast(bottom)) }); - return out; + return whole; } /// The allocator it was opened with, its own from then on. @@ -755,7 +794,11 @@ pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State { // Every other field its default, never what the heap had: a digest // reads them, and two replicas must agree (core/replica.zig). state.* = .{ .gpa = gpa, .vt = try emulator(gpa, cols, rows), .stream = undefined }; - state.wire(); + if (!state.wire()) { + state.stream.deinit(); + state.vt.deinit(gpa); + return error.OutOfMemory; + } return state; } @@ -1522,3 +1565,64 @@ test "the luminance table answers exactly what ghostty computes" { } } } + +/// Its snapshot as the dump writes it, `gpa`'s (the tests below). +fn snapshotOf(gpa: std.mem.Allocator, s: *const State) ![]u8 { + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + try snapshot(s, gpa, &out.writer, false); + return out.toOwnedSlice(); +} + +/// Two terminals as a replica compares them: their snapshots' bytes, what +/// pardes keeps beside the emulator, and the digest. +fn expectSame(gpa: std.mem.Allocator, a: *const State, b: *const State) !void { + const x = try snapshotOf(gpa, a); + defer gpa.free(x); + const y = try snapshotOf(gpa, b); + defer gpa.free(y); + try std.testing.expectEqualSlices(u8, x, y); + var ma: [marks_len]u8 = undefined; + var mb: [marks_len]u8 = undefined; + try std.testing.expectEqualSlices(u8, marksOf(a, &ma), marksOf(b, &mb)); + try std.testing.expectEqualSlices(u8, a.reply[0..a.reply_len], b.reply[0..b.reply_len]); + var ha: std.hash.Wyhash = .init(0); + var hb: std.hash.Wyhash = .init(0); + digest(a, &ha, true); + digest(b, &hb, true); + try std.testing.expectEqual(ha.final(), hb.final()); +} + +test "a snapshot taken inside a sequence carries it: over pardes's own handler the load continues as the terminal fed whole" { + // ghostty promises the continuation for its standard handler; pardes's + // MarkedHandler wraps it (OSC 133 marks, erases): cut at every byte of + // a CSI, an OSC (a link, pardes's own marks), a UTF-8 codepoint, a + // kitty graphics payload (APC) and a device query. + const gpa = std.testing.allocator; + const streams = [_][]const u8{ + "a\x1b[38;2;10;20;30mcolour\x1b[0m b", + "\x1b]8;;https://example.com/x\x1b\\link\x1b]8;;\x1b\\ c", + "x\u{1F469}\u{200D}\u{1F4BB}y \u{6F22}\u{5B57} \u{E9}", + "\x1b_Ga=T,i=7,f=24,s=1,v=1;AAAA\x1b\\ after", + "\x1b]133;A;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07ls\r\n\x1b]133;C;aid=pardes\x07out\r\n\x1b]133;D;0;aid=pardes\x07", + "q\x1b[6n\x1b[c\x1b[16t z", + }; + for (streams) |stream| for (1..stream.len) |cut| { + const whole = try open(gpa, 24, 5); + defer close(whole); + whole.stream.nextSlice(stream[0..cut]); + whole.stream.nextSlice(stream[cut..]); + const cutting = try open(gpa, 24, 5); + defer close(cutting); + cutting.stream.nextSlice(stream[0..cut]); + const bytes = try snapshotOf(gpa, cutting); + defer gpa.free(bytes); + const loaded = try load(gpa, bytes, &parts(cutting)); + defer close(loaded); + loaded.stream.nextSlice(stream[cut..]); + expectSame(gpa, whole, loaded) catch |err| { + std.debug.print("cut at byte {d} of {f}\n", .{ cut, std.ascii.hexEscape(stream, .lower) }); + return err; + }; + }; +} -- cgit v1.3 From 98b2bc05cd7b6c78952600029939bbc44c5fc56b Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 19 Nov 2026 22:06:32 -0300 Subject: Term.reload: a live terminal made again from its own snapshot where it is (the snapshot made, decoded, the old emulator let go, the new one installed with its stream, its sequence in flight and pardes's parts), returning the snapshot's hash: what makes two emulators with other histories of pages equal again, since ghostty prunes its history a page at a time against a limit in bytes and a snapshot does not say how its rows were cut into pages (reports/pardes-term-bytes.md, sections 1 and 2; the brief's step 1b; an Ops entry, the core's Term.reload); the sizing's join check as a test of the tree: plain text, a build's log and heavy colour and links (a truecolour a cell, a link a word, marks piled on letters) past a 1 MiB scrollback at 120x40, cut at random read boundaries: with every side reloaded (the session, a replica there from the start, a joiner loaded from the session's snapshot after) the same snapshot bytes, digest, marks and replies after more bytes and again after two reflows, 6 of 6 joins; without the reload the heavy joiner is another terminal, 2 of 2 (the pages pruned otherwise); term-test 17/17, core-test 848/991 (143 skipped), shell-test 1027/1030 Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- abi/term.zig | 3 + core/Term.zig | 8 +++ core/term/term.zig | 1 + core/term/terminal.zig | 167 +++++++++++++++++++++++++++++++++++++++++++++++-- 4 files changed, 175 insertions(+), 4 deletions(-) diff --git a/abi/term.zig b/abi/term.zig index c437f62f..68434e8e 100644 --- a/abi/term.zig +++ b/abi/term.zig @@ -343,6 +343,9 @@ pub const Ops = struct { snapshot: *const fn (s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer, slim: bool) anyerror!void, /// `snapshot`'s bytes and `parts` back into a new terminal. load: *const fn (gpa: std.mem.Allocator, snapshot: []const u8, parts: *const Parts) anyerror!*State, + /// Its emulator made again from its own snapshot where it is (a join: + /// every side does it); the snapshot's hash. + reload: *const fn (s: *State) anyerror!u64, // ---- output and view ---- /// One read of its program's output (`Told` says where the tracked diff --git a/core/Term.zig b/core/Term.zig index fde36420..5025ba2b 100644 --- a/core/Term.zig +++ b/core/Term.zig @@ -123,6 +123,14 @@ pub fn close(s: *State, _: std.mem.Allocator) void { own.destroy(s); } +/// Its emulator made again from its own snapshot, where it is: at a join +/// 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 { + return the().reload(s.impl); +} + /// When its next kitty animation frame is due (ms on the core's clock), as /// its last drawn frame left it; null when nothing plays. pub fn due(s: *const State) ?u64 { diff --git a/core/term/term.zig b/core/term/term.zig index 6e36816a..6f62b827 100644 --- a/core/term/term.zig +++ b/core/term/term.zig @@ -31,6 +31,7 @@ pub const ops: iface.Ops = .{ .parts = cast(iface.Ops, "parts", terminal_.parts), .snapshot = cast(iface.Ops, "snapshot", terminal_.snapshot), .load = cast(iface.Ops, "load", terminal_.load), + .reload = cast(iface.Ops, "reload", terminal_.reload), .feed = cast(iface.Ops, "feed", terminal_.feed), .grid = cast(iface.Ops, "grid", terminal_.grid), .viewTo = cast(iface.Ops, "viewTo", terminal_.viewTo), diff --git a/core/term/terminal.zig b/core/term/terminal.zig index f92da3fd..a4120f5a 100644 --- a/core/term/terminal.zig +++ b/core/term/terminal.zig @@ -301,7 +301,7 @@ pub fn snapshot(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer, slim fn decode(gpa: std.mem.Allocator, bytes: []const u8) !ghostty_vt.snapshot.Decoded { if (bytes.len == 4) { const size = std.mem.bytesToValue([2]u16, bytes[0..4]); - return .{ .terminal = try emulator(gpa, @max(1, size[0]), @max(1, size[1])), .continuation = .ground, .history_rows = .{} }; + return .{ .terminal = try emulator(gpa, @max(1, size[0]), @max(1, size[1]), scrollback_max), .continuation = .ground, .history_rows = .{} }; } var reader: std.Io.Reader = .fixed(bytes); return ghostty_vt.snapshot.decodeExact(gpa, terminalIo(), &reader, .{ @@ -326,6 +326,34 @@ pub fn load(gpa: std.mem.Allocator, bytes: []const u8, saved: *const Term.Parts) return out; } +/// Its emulator made again from its own snapshot, where it is, what pardes +/// keeps beside it kept: what a replica and its session do at a join, so +/// that both, and the joiner loaded from the session's, hold the same pages +/// (ghostty cuts rows into pages, and prunes whole ones, by its history, +/// which a snapshot does not carry). The snapshot's hash, which every side +/// compares; on an error it is as it was. +pub fn reload(s: *State) !u64 { + const gpa = s.gpa; + var bytes: std.Io.Writer.Allocating = .init(gpa); + defer bytes.deinit(); + try snapshot(s, gpa, &bytes.writer, false); + var decoded = try decode(gpa, bytes.written()); + defer decoded.deinit(gpa); + var saved = parts(s); + var reply: [@typeInfo(@FieldType(State, "reply")).array.len]u8 = undefined; + @memcpy(reply[0..saved.reply.len], saved.reply); + saved.reply = reply[0..saved.reply.len]; + const kept = .{ s.changes, s.read, s.resize_to }; + if (comptime images_enabled) s.images.deinit(gpa); + s.stream.deinit(); + s.vt.deinit(gpa); + s.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined, .changes = kept[0] +% 1, .read = kept[1], .resize_to = kept[2] }; + // Short of room for its sequence in flight it goes on without it (lost + // at the next cut), as ghostty's stream does: not worth a terminal. + _ = install(s, decoded.continuation, &saved); + return std.hash.Wyhash.hash(0, bytes.written()); +} + /// A decoded emulator at its address made a terminal: its stream wired, /// the sequence in flight fed again, what pardes kept beside it put back; /// whether its stream had all the room it wanted (`wire`). @@ -770,11 +798,14 @@ pub fn close(state: *State) void { } /// A terminal pane's emulator, `cols` by `rows`, as `open` makes one. -fn emulator(gpa: std.mem.Allocator, cols: u16, rows: u16) !ghostty_vt.Terminal { +/// How much history a terminal keeps, in bytes of ghostty's pages. +const scrollback_max = 16 * 1024 * 1024; + +fn emulator(gpa: std.mem.Allocator, cols: u16, rows: u16, history: usize) !ghostty_vt.Terminal { return ghostty_vt.Terminal.init(terminalIo(), gpa, .{ .cols = cols, .rows = rows, - .max_scrollback_bytes = 16 * 1024 * 1024, + .max_scrollback_bytes = history, .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, // Every kitty medium, as ghostty and kitty take them: a file (t=f), // a temporary file it then deletes (t=t, in the temp directory and @@ -789,11 +820,17 @@ fn emulator(gpa: std.mem.Allocator, cols: u16, rows: u16) !ghostty_vt.Terminal { /// A new emulator, `cols` by `rows`, allocated with `gpa`, its own from /// then on (`State.gpa`). pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State { + return openKeeping(gpa, cols, rows, scrollback_max); +} + +/// `open`, keeping `history` bytes of history (the tests below fill a +/// smaller one). +fn openKeeping(gpa: std.mem.Allocator, cols: u16, rows: u16, history: usize) !*State { const state = try gpa.create(State); errdefer gpa.destroy(state); // Every other field its default, never what the heap had: a digest // reads them, and two replicas must agree (core/replica.zig). - state.* = .{ .gpa = gpa, .vt = try emulator(gpa, cols, rows), .stream = undefined }; + state.* = .{ .gpa = gpa, .vt = try emulator(gpa, cols, rows, history), .stream = undefined }; if (!state.wire()) { state.stream.deinit(); state.vt.deinit(gpa); @@ -1626,3 +1663,125 @@ test "a snapshot taken inside a sequence carries it: over pardes's own handler t }; }; } + +/// What the join tests below stream: plain text, a build's log, and heavy +/// colour and links (a truecolour a cell, a link a word, marks piled on +/// letters, wide characters: what runs a page out of room for styles, +/// links and graphemes), `lines` of it, no clear. +const Corpus = enum { text, logs, heavy }; + +fn corpus(gpa: std.mem.Allocator, which: Corpus, lines: usize) ![]u8 { + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + const w = &out.writer; + var prng: std.Random.DefaultPrng = .init(@as(u64, @intFromEnum(which)) + 11); + const random = prng.random(); + const words = [_][]const u8{ "the", "quick", "brown", "fox", "jumps", "over", "a", "lazy", "dog", "./core/replica.zig:1234:", "error:", "expected", "\u{6F22}\u{5B57}", "na\u{EF}ve" }; + for (0..lines) |i| switch (which) { + .text => { + for (0..random.uintLessThan(usize, 18)) |_| try w.print("{s} ", .{words[random.uintLessThan(usize, words.len)]}); + try w.print("{d}\r\n", .{i}); + }, + .logs => try w.print("[{d:>3}%] \x1b[32mBuilding CXX object\x1b[0m src/CMakeFiles/core.dir/module_{d}.cpp.o{s}\r\n", .{ i * 100 / lines, i, if (i % 9 == 0) " \x1b[1;33mwarning:\x1b[0m unused variable" else "" }), + .heavy => switch (i % 3) { + 0 => { + for (0..100) |x| try w.print("\x1b[38;2;{d};{d};{d}m{c}", .{ (i * 7 + x * 3) % 256, (i * 13 + x * 5) % 256, (x * 11 + i) % 256, @as(u8, @intCast(97 + (x + i) % 26)) }); + try w.writeAll("\x1b[0m\r\n"); + }, + 1 => { + for (0..18) |x| try w.print("\x1b]8;;https://example.com/{d}/{d}\x1b\\w{d}\x1b]8;;\x1b\\ ", .{ i, x, x }); + try w.writeAll("\r\n"); + }, + else => { + for (0..40) |x| { + try w.writeByte(@intCast(97 + (x + i) % 26)); + for (0..1 + x % 6) |j| try w.print("{u}", .{@as(u21, @intCast(0x300 + (x * 3 + j + i) % 0x6f))}); + } + try w.writeAll(" \u{6F22}\u{5B57}\u{6F22}\u{5B57} \u{1F469}\u{200D}\u{1F4BB}\r\n"); + }, + }, + }; + return out.toOwnedSlice(); +} + +/// `bytes[from..to]` fed in reads of 4 KiB, and two reflows on the way +/// at `stops` (to a little over half the width and three rows taller, then +/// back), as the join tests' every side takes them. +fn feedReflowing(s: *State, bytes: []const u8, from: usize, to: usize, stops: [2]usize) void { + const cols = s.vt.cols; + const rows = s.vt.rows; + var at = from; + while (at < to) { + if (at == stops[0]) resize(s, cols / 2 + 1, rows + 3, false); + if (at == stops[1]) resize(s, cols * 2 - 2, rows - 3, false); + var end = @min(to, at + 4096); + for (stops) |stop| if (at < stop and stop < end) { + end = stop; + }; + s.stream.nextSlice(bytes[at..end]); + at = end; + } +} + +fn sameSnapshot(gpa: std.mem.Allocator, a: *const State, b: *const State) !bool { + const x = try snapshotOf(gpa, a); + defer gpa.free(x); + const y = try snapshotOf(gpa, b); + defer gpa.free(y); + return std.mem.eql(u8, x, y); +} + +test "a join at a cut: every side reloaded from its own snapshot holds the same terminal as the joiner, after more bytes and after two reflows; a joiner nobody reloaded for with heavy colour does not" { + // The sizing pass's join check (reports/pardes-term-bytes.md, section 2) + // in the tree: a scrollback past its limit (pruned a page at a time, + // by the history of its pages), cut at a random read boundary, often + // inside a sequence. + const gpa = std.testing.allocator; + var prng: std.Random.DefaultPrng = .init(29); + const random = prng.random(); + var heavy_apart: usize = 0; + for ([_]Corpus{ .text, .logs, .heavy }, [_]usize{ 6000, 6000, 3000 }) |which, lines| { + const bytes = try corpus(gpa, which, lines); + defer gpa.free(bytes); + for (0..2) |_| { + const cut = bytes.len / 3 + random.uintLessThan(usize, bytes.len / 3); + const mid = cut + (bytes.len - cut) / 2; + const stops: [2]usize = .{ mid + (bytes.len - mid) / 3, mid + 2 * (bytes.len - mid) / 3 }; + // The session, and a replica that was there from the start. + const session = try openKeeping(gpa, 120, 40, 1 << 20); + defer close(session); + const there = try openKeeping(gpa, 120, 40, 1 << 20); + defer close(there); + feedReflowing(session, bytes, 0, cut, stops); + feedReflowing(there, bytes, 0, cut, stops); + // The same join made without the reload: the session as it + // would go on, and a joiner loaded from its snapshot. + const lineage = try openKeeping(gpa, 120, 40, 1 << 20); + defer close(lineage); + feedReflowing(lineage, bytes, 0, cut, stops); + const before = try snapshotOf(gpa, session); + defer gpa.free(before); + const unreloaded = try load(gpa, before, &parts(session)); + defer close(unreloaded); + // The join as it is made: every side reloads, the joiner loads + // the session's snapshot taken after (the join's dump). + const hash = try reload(session); + try std.testing.expectEqual(hash, try reload(there)); + try std.testing.expectEqual(hash, std.hash.Wyhash.hash(0, before)); + const after = try snapshotOf(gpa, session); + defer gpa.free(after); + const joiner = try load(gpa, after, &parts(session)); + defer close(joiner); + for ([_]*State{ session, there, joiner, unreloaded, lineage }) |s| feedReflowing(s, bytes, cut, mid, stops); + try expectSame(gpa, session, there); + try expectSame(gpa, session, joiner); + if (!try sameSnapshot(gpa, lineage, unreloaded)) heavy_apart += @intFromBool(which == .heavy); + for ([_]*State{ session, there, joiner }) |s| feedReflowing(s, bytes, mid, bytes.len, stops); + try expectSame(gpa, session, there); + try expectSame(gpa, session, joiner); + } + } + // The fault the reload mends is real: a joiner nobody reloaded for is + // another terminal once heavy colour has pruned pages cut otherwise. + try std.testing.expectEqual(2, heavy_apart); +} -- cgit v1.3 From ba10cc4ff30d08d27ad35576df04a03282b6521b Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 19 Nov 2026 22:15:16 -0300 Subject: Term: the two things a speculation writes into a terminal and no rollback puts back move into the pane, which the copy holds and the digest covers: the cell its program last heard the mouse at (Pane.term_mouse, handed to Term.mouse and Term.wheel, which ghostty's encoder reads and writes) and its kitty graphics as glyph art (Pane.term_petscii, which the Petscii builtin flips and the images' draw takes in ImagesAt): the sizing's table (reports/pardes-term-bytes.md, section 1; the brief's step 1c); Parts loses both (a dump of an older build carries them and they are passed over by name: a terminal's Petscii chosen before an Upgrade is off after it), Ops loses petscii and togglePetscii; term-test 17/17, core-test 848/991 (143 skipped), shell-test 1027/1030 Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- abi/term.zig | 11 +++++------ core/Term.zig | 21 ++++++--------------- core/ansi.zig | 1 + core/builtins.zig | 4 ++-- core/mouse.zig | 10 +++++----- core/panes.zig | 6 ++++++ core/tagline.zig | 3 ++- core/term/TerminalImages.zig | 9 ++++----- core/term/term.zig | 2 -- core/term/terminal.zig | 35 ++++++++--------------------------- test/terminal.zig | 7 +++---- 11 files changed, 42 insertions(+), 67 deletions(-) diff --git a/abi/term.zig b/abi/term.zig index 68434e8e..40f9e4f3 100644 --- a/abi/term.zig +++ b/abi/term.zig @@ -231,6 +231,9 @@ pub const ImagesAt = struct { now_ms: u64, cell_w: u32, cell_h: u32, + /// Its images as glyph art even where pixels could be drawn (the + /// pane's Petscii). + petscii: bool = false, }; /// What a predicted echo reads of a cell: its codepoint, whether the shell @@ -286,8 +289,6 @@ pub const Applied = struct { seq: u32, extra: []const u8 }; pub const Parts = struct { reply: []const u8 = "", reply_dropped: u32 = 0, - mouse_cell: ?Coordinate = null, - petscii: bool = false, /// The view's top row, counted from the top of the history. view: usize = 0, phase: Prompt.Phase = .none, @@ -363,8 +364,8 @@ pub const Ops = struct { // ---- input ---- key: *const fn (s: *State, k: plain.Key, out: *std.Io.Writer) error{WriteFailed}!void, - mouse: *const fn (s: *State, buf: *[64]u8, action: MouseAction, button: ?MouseButton, mods: MouseMods, col: i32, row: i32, any_pressed: bool) []const u8, - wheel: *const fn (s: *State, buf: *[64]u8, turn: MouseButton, col: u16, row: u16, mods: MouseMods) ?[]const u8, + mouse: *const fn (s: *State, last: *?Parts.Coordinate, buf: *[64]u8, action: MouseAction, button: ?MouseButton, mods: MouseMods, col: i32, row: i32, any_pressed: bool) []const u8, + wheel: *const fn (s: *State, last: *?Parts.Coordinate, buf: *[64]u8, turn: MouseButton, col: u16, row: u16, mods: MouseMods) ?[]const u8, paste: *const fn (s: ?*const State, text: []u8) [3][]const u8, modes: *const fn (s: ?*const State) Modes, promptMoves: *const fn (s: *State, row: i32, col: i32) ?Moves, @@ -406,8 +407,6 @@ pub const Ops = struct { /// what it keeps to draw them is its own allocator's), and their /// placeholder cells blanked in `frame` (`frame_cols` wide). images: *const fn (s: *State, gpa: std.mem.Allocator, at: ImagesAt, out: *std.ArrayList(plain.Placement), frame: []plain.Cell, frame_cols: u16) void, - petscii: *const fn (s: ?*const State) ?bool, - togglePetscii: *const fn (s: *State) void, hasImages: *const fn (s: ?*const State) bool, // ---- its replicas ---- diff --git a/core/Term.zig b/core/Term.zig index 5025ba2b..82d5dad7 100644 --- a/core/Term.zig +++ b/core/Term.zig @@ -30,6 +30,8 @@ pub const Moves = iface.Moves; pub const MouseMods = iface.MouseMods; pub const MouseButton = iface.MouseButton; pub const MouseAction = iface.MouseAction; +/// A grid cell (the one a program last heard the mouse at: Pane.term_mouse). +pub const Coordinate = iface.Parts.Coordinate; pub const Page = iface.Page; pub const Span = iface.Span; pub const Ink = iface.Ink; @@ -212,13 +214,13 @@ pub fn key(s: *State, k: plain.Key, out: *std.Io.Writer) !void { /// One mouse event for its program, as the mode and format it set ask for /// it; empty when the program does not hear of it. -pub fn mouse(s: *State, buf: *[64]u8, action: MouseAction, button: ?MouseButton, mods: MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 { - return the().mouse(s.impl, buf, action, button, mods, col, row, any_pressed); +pub fn mouse(s: *State, last: *?Coordinate, buf: *[64]u8, action: MouseAction, button: ?MouseButton, mods: MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 { + return the().mouse(s.impl, last, buf, action, button, mods, col, row, any_pressed); } /// A wheel turn for its program; null when the wheel is not the program's. -pub fn wheel(s: *State, buf: *[64]u8, turn: MouseButton, col: u16, row: u16, mods: MouseMods) ?[]const u8 { - return the().wheel(s.impl, buf, turn, col, row, mods); +pub fn wheel(s: *State, last: *?Coordinate, buf: *[64]u8, turn: MouseButton, col: u16, row: u16, mods: MouseMods) ?[]const u8 { + return the().wheel(s.impl, last, buf, turn, col, row, mods); } /// A paste as xterm makes one: three parts, the text between the brackets @@ -362,17 +364,6 @@ pub fn images(s: *State, gpa: std.mem.Allocator, at: ImagesAt, out: *std.ArrayLi the().images(s.impl, gpa, at, out, frame, frame_cols); } -/// The Petscii builtin on it: its kitty graphics as glyph art, or back to -/// pixels; null for none. -pub fn petscii(s: ?*const State) ?bool { - const o = ops orelse return null; - return o.petscii(if (s) |state| state.impl else null); -} - -pub fn togglePetscii(s: *State) void { - the().togglePetscii(s.impl); -} - /// Whether the screen showing holds any kitty graphics image. pub fn hasImages(s: ?*const State) bool { const o = ops orelse return false; diff --git a/core/ansi.zig b/core/ansi.zig index 6c23fee6..5f522536 100644 --- a/core/ansi.zig +++ b/core/ansi.zig @@ -228,6 +228,7 @@ pub fn images(p: *Pardes, s: *Surface, pane: *Pane, id: usize, tx: u16, tw: u16, .cols = @min(tw, pane.cols), .rows_of = rows_of[0..vp_rows], .tty_mode = pane.body.mode == .tty, + .petscii = pane.term_petscii, .now_ms = p.clock.stepped_ns / std.time.ns_per_ms, .cell_w = @max(1, p.view().cell_pixels.w), .cell_h = @max(1, p.view().cell_pixels.h), diff --git a/core/builtins.zig b/core/builtins.zig index 6f37e86d..66b22dcc 100644 --- a/core/builtins.zig +++ b/core/builtins.zig @@ -749,13 +749,13 @@ pub const Petscii = struct { pub const takes_arg = true; pub fn run(c: Ctx) void { // `on|off` sets it, as the tag's `petscii:on` reads; none flips it. - const now = if (c.pane.addon) |k| k.art.glyph else panes.Term.petscii(c.pane.terminal) orelse false; + const now = if (c.pane.addon) |k| k.art.glyph else c.pane.terminal != null and c.pane.term_petscii; if (c.arg != null) { const want = stateArg(c, OnOff, "Petscii", "on or off") orelse return; if ((want == .on) == now) return; } if (c.pane.addon) |k| k.art.glyph = !k.art.glyph; - if (c.pane.terminal) |state| panes.Term.togglePetscii(state); + if (c.pane.terminal != null) c.pane.term_petscii = !c.pane.term_petscii; } }; diff --git a/core/mouse.zig b/core/mouse.zig index 3d7c5af9..5e240930 100644 --- a/core/mouse.zig +++ b/core/mouse.zig @@ -184,7 +184,7 @@ fn programWheel(p: *Pardes, id: usize, m: Mouse, col: u16, row: u16) bool { .wheel_left => .wheel_left, else => .wheel_right, }; - const bytes = panes.Term.wheel(pane.terminal.?, &buf, wheel, gcol, grow, .{ .alt = m.alt, .ctrl = m.ctrl }) orelse return true; + const bytes = panes.Term.wheel(pane.terminal.?, &pane.term_mouse, &buf, wheel, gcol, grow, .{ .alt = m.alt, .ctrl = m.ctrl }) orelse return true; for (0..@intCast(config.wheel_rows)) |_| p.emitWrite(id, bytes); return true; } @@ -298,7 +298,7 @@ fn programMouse(p: *Pardes, m: Mouse) bool { }; if (m.kind == .press) grab.held |= bit; if (m.kind == .release) grab.held &= ~bit; - const bytes = panes.Term.mouse(pane.terminal.?, &buf, action, button, mods, col, row, grab.held != 0); + const bytes = panes.Term.mouse(pane.terminal.?, &pane.term_mouse, &buf, action, button, mods, col, row, grab.held != 0); if (bytes.len > 0) p.emitWrite(grab.id, bytes); if (grab.held == 0) v.mouse_grab = null; return true; @@ -322,7 +322,7 @@ fn programMouse(p: *Pardes, m: Mouse) bool { pane.focus = .body; pane.closePrompt(); v.mouse_grab = .{ .id = id, .serial = pane.serial, .held = bit, .unshift = shifted_to_program }; - const bytes = panes.Term.mouse(pane.terminal.?, &buf, .press, button, mods, cell.col, cell.row, true); + const bytes = panes.Term.mouse(pane.terminal.?, &pane.term_mouse, &buf, .press, button, mods, cell.col, cell.row, true); if (bytes.len > 0) p.emitWrite(id, bytes); return true; }, @@ -330,7 +330,7 @@ fn programMouse(p: *Pardes, m: Mouse) bool { // pardes's. .release, .drag => return false, .motion => { - const bytes = panes.Term.mouse(pane.terminal.?, &buf, .motion, null, mods, cell.col, cell.row, false); + const bytes = panes.Term.mouse(pane.terminal.?, &pane.term_mouse, &buf, .motion, null, mods, cell.col, cell.row, false); if (bytes.len > 0) p.emitWrite(id, bytes); // Under 1003 the move is the program's; below that pardes // hovers as ever. @@ -432,7 +432,7 @@ fn chordCutPaste(p: *Pardes, cut: bool) edit.Error!void { const row = @max(0, pane.sel[sel_slot].r1 - @as(i32, pane.tag_rows)); var mb: [64]u8 = undefined; for ([_]panes.Term.MouseAction{ .press, .release }) |action| { - const bytes = panes.Term.mouse(pane.terminal.?, &mb, action, .left, .{}, col, row, action == .press); + const bytes = panes.Term.mouse(pane.terminal.?, &pane.term_mouse, &mb, action, .left, .{}, col, row, action == .press); if (bytes.len > 0) p.emitWrite(s.id, bytes); } } diff --git a/core/panes.zig b/core/panes.zig index b928917a..56a8e82a 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -125,6 +125,12 @@ pub const Pane = struct { pub const Focus = enum { body, tag }; pub const SessionView = struct { wrap: bool = true, layered: bool = true, body_h: u32 = 0, tagline_h: u32 = 0, rect_h: u16 = 0 }; terminal: ?*Term.State = null, + /// Its terminal's, kept by the pane, which a rollback puts back, not by + /// the emulator, which none does (a speculation writes them): the grid + /// cell its program last heard the mouse at (motion is told once a + /// cell), and its kitty graphics drawn as glyph art (Petscii). + term_mouse: ?Term.Coordinate = null, + term_petscii: bool = false, gpa: std.mem.Allocator, serial: u32 = 0, /// What the control filesystem keeps of this pane -- addr and limit, the diff --git a/core/tagline.zig b/core/tagline.zig index 456a6b6e..660ecbf9 100644 --- a/core/tagline.zig +++ b/core/tagline.zig @@ -157,7 +157,8 @@ pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]co if (pane.file) |f| return if (pane.prompt == .name) pane.input.own orelse f.path else f.path; // A terminal showing kitty graphics says how it draws them, as an image // pane does, and so does one drawing them as glyph art by choice. - if (panes.Term.petscii(pane.terminal)) |chosen| { + if (pane.terminal != null) { + const chosen = pane.term_petscii; const on = chosen or !p.view().frontend.native_images; if (chosen or panes.Term.hasImages(pane.terminal)) return std.fmt.allocPrint(arena, "{s} petscii:{s}", .{ (try shownDir(arena, pane)), if (on) "on" else "off" }); diff --git a/core/term/TerminalImages.zig b/core/term/TerminalImages.zig index feba5ddc..d0d364a1 100644 --- a/core/term/TerminalImages.zig +++ b/core/term/TerminalImages.zig @@ -24,9 +24,6 @@ const image_decode_pixels: usize = 64 * 1024 * 1024; /// oldest past this): a 4K picture in RGBA, with room for a second. pub const storage_limit = 64 * 1024 * 1024; -/// This pane asks for its images as glyph art even where pixels could be -/// drawn (the Petscii builtin). -petscii: bool = false, /// Pixels in RGBA for images ghostty-vt holds in another format (RGB, /// grey): only for images on screen, dropped the frame they are not. /// The emulator's own allocator's, as the emulator is (`draw`'s `own`): @@ -191,7 +188,7 @@ pub fn draw( const bottom = pages.getBottomRight(.viewport) orelse return; const cw: u32 = @max(1, where.cell_w); const ch: u32 = @max(1, where.cell_h); - const ctx: Ctx = .{ .ti = ti, .own = own, .gpa = gpa, .out = out, .pane = where.pane, .serial = where.serial, .tx = where.tx, .body_y = where.body_y, .cols = where.cols, .rows_of = rows_of, .cw = cw, .ch = ch }; + const ctx: Ctx = .{ .ti = ti, .own = own, .gpa = gpa, .out = out, .pane = where.pane, .serial = where.serial, .tx = where.tx, .body_y = where.body_y, .cols = where.cols, .rows_of = rows_of, .cw = cw, .ch = ch, .glyph = where.petscii }; // Handed on lowest z first (the storage's order is a hash map's), the // order a shell draws them in; equal z keeps the order they came in. const first = out.items.len; @@ -283,6 +280,8 @@ const Ctx = struct { rows_of: []const ?u16, cw: u32, ch: u32, + /// Its images as glyph art (the pane's Petscii). + glyph: bool, /// Draw `src` of `img` over `dst`, one cell row of it at a time: a row /// is shown, or not, or shown elsewhere, as the body lays it out. @@ -323,7 +322,7 @@ const Ctx = struct { }, .key = plain.Placement.keyOf(ctx.serial, img.id, @truncate(img.generation)), .z = z, - .art = .{ .glyph = ctx.ti.petscii }, + .art = .{ .glyph = ctx.glyph }, }) catch {}; } } diff --git a/core/term/term.zig b/core/term/term.zig index 6f62b827..4bb60079 100644 --- a/core/term/term.zig +++ b/core/term/term.zig @@ -63,8 +63,6 @@ pub const ops: iface.Ops = .{ .spanColor = terminal_.spanColor, .paint = cast(iface.Ops, "paint", terminal_.paint), .images = cast(iface.Ops, "images", terminal_.images), - .petscii = cast(iface.Ops, "petscii", terminal_.petscii), - .togglePetscii = cast(iface.Ops, "togglePetscii", terminal_.togglePetscii), .hasImages = cast(iface.Ops, "hasImages", terminal_.hasImages), .encoder = cast(iface.Ops, "encoder", terminal_.encoder), .encoderFree = cast(iface.Ops, "encoderFree", terminal_.encoderFree), diff --git a/core/term/terminal.zig b/core/term/terminal.zig index a4120f5a..4de389bd 100644 --- a/core/term/terminal.zig +++ b/core/term/terminal.zig @@ -181,9 +181,6 @@ pub const State = struct { reply: [4096]u8 = undefined, reply_len: u16 = 0, reply_dropped: u32 = 0, - /// The grid cell the program last heard the mouse at, so motion is - /// reported once per cell. - mouse_cell: ?ghostty_vt.Coordinate = null, /// The kitty graphics its program placed, as drawn (TerminalImages.zig). images: TerminalImages = if (images_enabled) .{} else {}, /// Counts the emulator's writes (output, a resize, its view scrolled): @@ -257,8 +254,6 @@ pub fn parts(s: *const State) Term.Parts { return .{ .reply = s.reply[0..s.reply_len], .reply_dropped = s.reply_dropped, - .mouse_cell = if (s.mouse_cell) |c| .{ .x = c.x, .y = c.y } else null, - .petscii = if (comptime images_enabled) s.images.petscii else false, .view = s.vt.screens.active.pages.scrollbar().offset, .phase = h.phase, .started = h.started, @@ -370,8 +365,6 @@ fn install(out: *State, continuation: ghostty_vt.snapshot.Continuation, saved: * @memcpy(out.reply[0..reply.len], reply); out.reply_len = @intCast(reply.len); out.reply_dropped = saved.reply_dropped; - out.mouse_cell = coordinate(saved.mouse_cell); - out.images = if (images_enabled) .{ .petscii = saved.petscii } else {}; const h = &out.stream.handler; h.phase = saved.phase; h.started = saved.started; @@ -674,10 +667,13 @@ pub fn paste(state: ?*const State, text: []u8) [3][]const u8 { /// 1015 urxvt, 1005 UTF-8, else X10) how, modifiers as shift+4, meta+8, /// ctrl+16. `col`,`row` are the 0-based grid cell; a drag that left the /// grid is reported clamped to its edge, motion only when the cell -/// changed. Empty when the program does not hear of it. -pub fn mouse(state: *State, buf: *[64]u8, action: Term.MouseAction, button: ?Term.MouseButton, mods: Term.MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 { +/// changed from `last`, the cell it last heard of (its pane's, which a +/// rollback puts back). Empty when the program does not hear of it. +pub fn mouse(state: *State, last: *?Term.Parts.Coordinate, buf: *[64]u8, action: Term.MouseAction, button: ?Term.MouseButton, mods: Term.MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 { const input = ghostty_vt.input; var writer = std.Io.Writer.fixed(buf); + var cell = coordinate(last.*); + defer last.* = if (cell) |c| .{ .x = c.x, .y = c.y } else null; var opts: input.MouseEncodeOptions = .{ .event = state.vt.flags.mouse_event, .format = state.vt.flags.mouse_format, @@ -687,7 +683,7 @@ pub fn mouse(state: *State, buf: *[64]u8, action: Term.MouseAction, button: ?Ter .padding = .{}, }, .any_button_pressed = any_pressed, - .last_cell = &state.mouse_cell, + .last_cell = &cell, }; // A release is always reported; the rest only over the grid, or held. if (action == .release) opts.any_button_pressed = true; @@ -716,7 +712,7 @@ pub fn mouse(state: *State, buf: *[64]u8, action: Term.MouseAction, button: ?Ter /// program: its mouse report while it tracks the mouse, else, on the /// alternate screen, an arrow key in the cursor keys' mode (none for a /// sideways turn). Null when the wheel is not the program's (`Modes.wheel`). -pub fn wheel(state: *State, buf: *[64]u8, turn: Term.MouseButton, col: u16, row: u16, mods: Term.MouseMods) ?[]const u8 { +pub fn wheel(state: *State, last: *?Term.Parts.Coordinate, buf: *[64]u8, turn: Term.MouseButton, col: u16, row: u16, mods: Term.MouseMods) ?[]const u8 { const now = modes(state); if (!now.wheel) return null; const m = &state.vt.modes; @@ -725,7 +721,7 @@ pub fn wheel(state: *State, buf: *[64]u8, turn: Term.MouseButton, col: u16, row: .wheel_down => if (m.get(.cursor_keys)) "\x1bOB" else "\x1b[B", else => null, }; - return mouse(state, buf, .press, turn, mods, col, row, false); + return mouse(state, last, buf, .press, turn, mods, col, row, false); } /// The whole scrollback as plain text, `gpa`-owned: what a terminal's body @@ -1536,21 +1532,6 @@ pub fn due(state: *const State) ?u64 { return state.images.animation_due_ms; } -/// The Petscii builtin on a terminal: its kitty graphics as glyph art, -/// or back to pixels where the shell draws pixels. -pub fn togglePetscii(state: *State) void { - if (comptime !images_enabled) return; - state.images.petscii = !state.images.petscii; -} - -/// Whether the pane draws its kitty graphics as glyph art by choice; null -/// for a pane with no emulator. -pub fn petscii(maybe: ?*const State) ?bool { - if (comptime !images_enabled) return null; - const state = maybe orelse return null; - return state.images.petscii; -} - /// Whether the screen showing holds any kitty graphics image. pub fn hasImages(maybe: ?*const State) bool { if (comptime !images_enabled) return false; diff --git a/test/terminal.zig b/test/terminal.zig index e6c530d5..b7b9cd33 100644 --- a/test/terminal.zig +++ b/test/terminal.zig @@ -34,7 +34,6 @@ const prompt = Term.prompt; const scroll = Term.scroll; const scrollback = Term.scrollback; const commandOutput = Term.commandOutput; -const petscii = Term.petscii; const filterOf = emu.filterOf; const filterPalette = emu.filterPalette; const keyedRgb = emu.keyedRgb; @@ -892,7 +891,7 @@ test "a terminal's image is a placement whatever the frontend draws, and the Pet try pardes.dump.dumpState(p); const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); defer restored.deinit(); - try std.testing.expectEqual(@as(?bool, true), petscii(restored.panes[0].?.terminal)); + try std.testing.expect(restored.panes[0].?.term_petscii); try std.testing.expect(p.executeBuiltinLine(0, "Petscii")); _ = frame.reset(.retain_capacity); s = try p.render(frame.allocator()); @@ -904,12 +903,12 @@ test "a new terminal draws its program's images as pixels, and one without image const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .shells = 1 }); defer p.deinit(); - try std.testing.expectEqual(false, petscii(p.panes[0].?.terminal).?); + try std.testing.expect(!p.panes[0].?.term_petscii); // A pane without images says nothing of them. try std.testing.expect(std.mem.indexOf(u8, try tagline.tagPrefix(p, p.panes[0].?), "petscii") == null); const id = p.freeSlot().?; const fresh = try p.newShell(id, ""); - try std.testing.expectEqual(false, petscii(fresh.terminal).?); + try std.testing.expect(!fresh.term_petscii); } test "a program asking the cell size in pixels (CSI 16 t) is told the shell's" { -- cgit v1.3 From e8e612685e31989c22f2844cc55d9703d817d1df Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 19 Nov 2026 22:03:17 -0300 Subject: replica: a client's kept list that reaches its bound (rebase_after, 32 units) while a key of its own is applied on top is let go free at the next unit that leaves nothing applied (the key's own unit, next in the stream), not put back with the 32 units replayed and the key applied again; with inputs on top all the while it is put back at twice the bound, so a rollback still replays a bounded list: before the session sends its pump's unit (it moved nothing, kept as neutral) ahead of every client key, so two units are kept a key and whether the 32nd is the pump's (the whole replay, about 50 to 100M instructions on the 3.2 MB file) or the key's own (free) is the parity the client's first units set, which made a near client's `edit` key 14.3 or 16.7 to 18.8M a block of 20 and `key-down` 3.8 or 8.8M by chance of the run, in either order of the send (`klmtkkpz` did not cause it: base against base with the order turned back, 6 runs each, edit medians 17.05 and 17.06M, 4 of 12 blocks over 1.05 in both); the kit (pardes-perf-sendfirst), base against this, 6 runs alternated, 12 blocks each, ReleaseFast, load 16 to 47: client edit 16.88M median (14.28 to 18.78, 5 blocks over 1.05) to 14.28M (14.26 to 14.30, none), key-down 3.83M (3.81 to 8.78, 2 over) to 3.84M (3.81 to 3.99, none), type 11.24M (11.00 to 12.88, 1 over) to 11.15M (11.01 to 11.29, none), rebases 1 to 5 a run to 0, the own path and the session unchanged; a test through the replica's surface (hand-ordered: a pump unit then the key's unit, 31 keys) fails before (one whole replay) and passes; tui core-test 849/992 (143 skipped), shell-test 1028/1031, pane-test 183/184, term-test 15/15, kitty-test 45/45, behaviour-test 275/275 and --replay 275/275 Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/replica.zig | 81 ++++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 67 insertions(+), 14 deletions(-) diff --git a/core/replica.zig b/core/replica.zig index 3a36a06b..040c33ca 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -40,8 +40,10 @@ const checked = builtin.mode == .debug or builtin.mode == .safe; const head_len = 6; // origin or client: u16le, seq: u32le /// A `stamp` frame (wire.zig): its header and the two clocks. const stamp_len = wire.header_len + 16; -/// Confirmed units fast-pathed under one copy before it is taken afresh: -/// a rollback replays them all. +/// Confirmed units kept under one copy before it is let go, at the next +/// unit that leaves nothing applied on top (free: it is the confirmed +/// state); a rollback replays them all, so with inputs applied on top all +/// the while it is put back at twice as many. const rebase_after = 32; /// A client compares its core's digest with the session's at most once in /// this many confirmed units (a unit that carries one, its state the @@ -1037,22 +1039,23 @@ pub const Replica = struct { if (r.diverged == null) r.diverged = r.gpa.dupe(u8, why) catch return; } - /// A unit kept to replay when the copy is next put back; past - /// `rebase_after` of them, that is now (`toConfirmed`). + /// A unit kept to replay when the copy is next put back (`rebase_after`). fn keepSince(r: *Replica, unit: []const u8) void { const kept = r.gpa.dupe(u8, unit) catch return r.fail("out of memory"); r.since.append(r.gpa, kept) catch return r.fail("out of memory"); - if (r.since.items.len >= rebase_after) { - // Nothing on top: it is the confirmed state already. - if (r.applied == 0) { - r.copy.release(); - rollback.Epoch.select(null); - return r.clearSince(); - } - r.stats.rebases += 1; - r.toConfirmed(); - r.dirty = true; + if (r.since.items.len < rebase_after) return; + // Nothing on top: it is the confirmed state already. + if (r.applied == 0) { + r.copy.release(); + rollback.Epoch.select(null); + return r.clearSince(); } + // An input applied on top (the session's pump unit before its own + // unit, the next to come): let go then, not replayed whole now. + if (r.since.items.len < 2 * rebase_after) return; + r.stats.rebases += 1; + r.toConfirmed(); + r.dirty = true; } fn clearSince(r: *Replica) void { @@ -3680,6 +3683,56 @@ test "the copy taken for an input of its own stays once the input is confirmed: try std.testing.expectEqual(@as(u32, 1), r.stats.foreign); } +test "the session's pump units that moved nothing, kept under a key applied on top, reach the kept list's bound: it is let go at the confirm that leaves nothing applied, never replayed whole" { + // The live pair's order (core/replica.zig Peers.boundary): before it + // steps a client's key the session sends its pump's unit, which moved + // nothing; the client takes it with the key applied on top (`neutral`, + // kept), then the key's own unit (fast, kept). Two kept a key: which + // of them is the bound's is the arrivals' parity, and a pump's unit + // while idle turns it. + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + defer a.deinit(); + const r = try Replica.init(gpa, 1, try a.unit(0, 0), false); + defer r.deinit(); + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| gpa.free(m); + sent.deinit(gpa); + } + freshSecond(); + // A first key, confirmed: the copy held, one unit kept (the parity + // that puts the bound on a pump's unit). + try key(r, 'j', &sent); + r.confirm(try a.take(sent.items[0])); + for (1..rebase_after) |i| { + try key(r, if (i % 2 == 0) 'j' else 'k', &sent); + a.pump(); + r.confirm((try a.pending()).?); + r.confirm(try a.take(sent.items[i])); + r.settle(); + try std.testing.expect(r.since.items.len <= rebase_after); + } + try std.testing.expectEqual(@as(u32, rebase_after - 1), r.neutral); + try std.testing.expectEqual(@as(u32, 0), r.stats.rebases); + try agrees(a, r); + // Keys applied on top all the while (one ahead of the session): the + // list is put back and replayed at twice the bound, not let grow. + try key(r, 'j', &sent); + for (0..3 * rebase_after) |i| { + try key(r, 'k', &sent); + a.pump(); + r.confirm((try a.pending()).?); + r.confirm(try a.take(sent.items[rebase_after + i])); + r.settle(); + try std.testing.expect(r.since.items.len <= 2 * rebase_after); + } + try std.testing.expect(r.stats.rebases >= 1); + r.confirm(try a.take(sent.items[sent.items.len - 1])); + r.settle(); + try agrees(a, r); +} + test "a rollback over a Tab it applied measures tabs as its core has them again" { // A tab's width is the core's (settings.tab, handed to every width // function), which the copy holds: once the process's (config.tab_now), -- cgit v1.3 From 55a5f91305df47cd56d7776f4193b6198208e891 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 19 Nov 2026 22:17:29 -0300 Subject: build: the dead and the doubled options go (the start design's step 1, pardes-build-options change 1): `ShellConfig.prebuilt_shaders`, set at build.zig:147 and read nowhere (the `-Dprebuilt-shaders` flag stays: gui.make hands it to sketchbook and the perf identity names it); `tools.add` and `core.assemble` handed the grammar set and -Dtracy beside the `shell_cfg` that holds them (`ShellConfig.tracy` is the checkout's path now, so Parts and the perf identity read it there); `syntax_zig_grammar`, always equal to `syntax_highlighting`; and the four `syntax_*` bools as the one enum they said four ways, `grammars` (`-Dtree-sitter`'s `TreeSitterGrammars`), read by syntax.zig, Output.zig's Build pane and three tests, with abi/wire.zig hashing it as the four words it was hashed as, so `pardes version`'s semantics line did not move on any product (38b5ae573b965550 on tui, gui, the bare build's two, both statics, FreeBSD; d41689a1f97605b8 with -Dtree-sitter=minimal, as on the base); build.zig and build/ 3,005 -> 2,992 lines; every shape configures (12 configurations) and builds as on the base (tui, gui, bare, the macOS library for Linux and aarch64-macos, static on musl and on the window, FreeBSD, -Dtree-sitter=minimal), and the two that fail on the base fail with the same errors (pardes-isolate: core/builtins.zig:510, core/ninep/ctl.zig:1298; -Dtree-sitter=disabled: core/indent.zig:48); tui core-test 848/991 (143 skipped), shell-test 1027/1030, pane-test 183/184, behaviour-test 275/275 (and -- --replay), term-test 15/15, kitty-test 45/45, lib-test, hxlib 538 cases 0 mismatches, process-test 3 of 144 failed (lspcomplete and lspcompletemoved, the base's, and headersweep-restored, on the flaky list: passed alone, 1364 ms), gui unit-test 1625/1629 (the perf check's BaselineHarnessMismatch, the base's); the test names of every suite equal the base's (ledger); load 15-45 on 16 cores Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- abi/wire.zig | 11 +++++++---- build.zig | 7 +------ build/core.zig | 17 ++++++----------- build/tools.zig | 7 ++----- core/Output.zig | 2 +- core/syntax.zig | 11 +++++------ test/behaviour/panes.zig | 2 +- test/behaviour/settings.zig | 2 +- test/output.zig | 2 +- 9 files changed, 25 insertions(+), 36 deletions(-) diff --git a/abi/wire.zig b/abi/wire.zig index b2d32033..26a7131e 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -61,16 +61,19 @@ const family = switch (config.platform) { /// their options and dependencies; -Dstamp-commit stamps one. pub const semantics: u64 = blk: { @setEvalBranchQuota(1_000_000); + // The grammar set as the four words it was hashed as when it was four + // options (highlighting, zig, minimal, full), so the hash stays. + const g = config.grammars; // The two long ones (the dependencies, 2.5 KB, and the tape's shape, // 11 KB) joined on, not formatted: formatting them at comptime was 5 % // of a compile of the core. break :blk std.hash.Wyhash.hash(0, std.fmt.comptimePrint( "wire {d}\npardes {s} {s}\n{s} grammars {} {} {} {} workspace_tag {} sources {}\nusize {d} {t}\n", .{ - version, config.version, config.commit orelse "unstamped", - family, config.syntax_highlighting, config.syntax_zig_grammar, - config.syntax_minimal_grammars, config.syntax_full_grammars, config.workspace_tag, - config.embed_sources, @sizeOf(usize), builtin.cpu.arch.endian(), + version, config.version, config.commit orelse "unstamped", + family, g != .disabled, g != .disabled, + g == .minimal or g == .full, g == .full, config.workspace_tag, + config.embed_sources, @sizeOf(usize), builtin.cpu.arch.endian(), }, ) ++ config.deps ++ "\n" ++ pardes.tape.shape); }; diff --git a/build.zig b/build.zig index b81390c4..cf9a851f 100644 --- a/build.zig +++ b/build.zig @@ -142,9 +142,8 @@ pub fn build(b: *std.Build) void { const shell_cfg: core.ShellConfig = .{ .tree_sitter_grammars = tree_sitter_grammars, - .tracy = tracy != null, + .tracy = tracy, .workspace_tag = workspace_tag, - .prebuilt_shaders = prebuilt_shaders, .embed_sources = embed_sources, .commit = if (stamp_commit) core.gitCommit(b) else null, .change = if (stamp_commit) core.jjChange(b) else null, @@ -156,8 +155,6 @@ pub fn build(b: *std.Build) void { .target = target, .optimize = optimize, .c_optimize = c_optimize, - .tree_sitter_grammars = tree_sitter_grammars, - .tracy = tracy, .shell_cfg = shell_cfg, .platform = platform, .also_gui = also_gui, @@ -320,8 +317,6 @@ pub fn build(b: *std.Build) void { .shell_cfg = shell_cfg, .target = target, .test_filters = test_filters, - .tracy = tracy, - .tree_sitter_grammars = tree_sitter_grammars, .unit_profile = unit_profile, }); tests.add(b, .{ diff --git a/build/core.zig b/build/core.zig index 974d5c7e..b35c066b 100644 --- a/build/core.zig +++ b/build/core.zig @@ -60,11 +60,11 @@ pub fn command(b: *std.Build, argv: []const []const u8) ?[]const u8 { pub const ShellConfig = struct { tree_sitter_grammars: TreeSitterGrammars, - tracy: bool = false, + /// -Dtracy's checkout, whose client a core that asks compiles in. + tracy: ?[]const u8 = null, /// null = "the platform's own default": the macOS shell hands the row to /// its native menu bar, every other shell keeps the acme topbar. workspace_tag: ?bool = null, - prebuilt_shaders: bool = false, embed_sources: bool = false, commit: ?[]const u8 = null, /// The jj change git HEAD is in, and when this configure ran: the @@ -79,11 +79,8 @@ pub const ShellConfig = struct { pub fn shellOptions(b: *std.Build, cfg: ShellConfig, platform: Platform) *std.Build.Step.Options { const o = b.addOptions(); o.addOption(Platform, "platform", platform); - o.addOption(bool, "syntax_highlighting", cfg.tree_sitter_grammars != .disabled); - o.addOption(bool, "syntax_zig_grammar", cfg.tree_sitter_grammars != .disabled); - o.addOption(bool, "syntax_minimal_grammars", cfg.tree_sitter_grammars == .minimal or cfg.tree_sitter_grammars == .full); - o.addOption(bool, "syntax_full_grammars", cfg.tree_sitter_grammars == .full); - o.addOption(bool, "enable_tracy", cfg.tracy); + o.addOption(TreeSitterGrammars, "grammars", cfg.tree_sitter_grammars); + o.addOption(bool, "enable_tracy", cfg.tracy != null); o.addOption(bool, "workspace_tag", cfg.workspace_tag orelse (platform != .macos)); o.addOption(bool, "embed_sources", cfg.embed_sources); o.addOption([]const u8, "version", display_version); @@ -429,8 +426,6 @@ pub fn assemble(b: *std.Build, c: struct { target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, c_optimize: std.lang.Optimize, - tree_sitter_grammars: TreeSitterGrammars, - tracy: ?[]const u8, shell_cfg: ShellConfig, platform: Platform, also_gui: bool, @@ -455,7 +450,7 @@ pub fn assemble(b: *std.Build, c: struct { // nothing else. pardes takes these whatever it builds: the missing ones // are asked for here in one round, the grammars with them, where each // `b.dependency` below would end the configure to fetch its own alone. - const ts = treeSitter(b, io, target, c_optimize, c.tree_sitter_grammars); + const ts = treeSitter(b, io, target, c_optimize, c.shell_cfg.tree_sitter_grammars); inline for (.{ "cloud9", "vaxis", "ghostty", "uucode", "zstbi", "mvzr", "zstd", "xitdb" }) |name| { // A dependency by path (none of these today) has no hash and is always there. const dep = @field(zon.dependencies, name); @@ -623,7 +618,7 @@ pub fn assemble(b: *std.Build, c: struct { .target = target, .optimize = optimize, .cloud9 = cloud9, - .tracy = c.tracy, + .tracy = c.shell_cfg.tracy, .zstd = zstd, .image = image_addon.root_module, .pdf = pdf_built.module, diff --git a/build/tools.zig b/build/tools.zig index 1343fef9..62e9817a 100644 --- a/build/tools.zig +++ b/build/tools.zig @@ -2,7 +2,6 @@ const std = @import("std"); const builtin = @import("builtin"); const Platform = @import("../build.zig").Platform; const PerfBuild = @import("../build.zig").PerfBuild; -const TreeSitterGrammars = @import("../build.zig").TreeSitterGrammars; const core = @import("core.zig"); const testMatch = @import("tests.zig").testMatch; @@ -42,8 +41,6 @@ pub fn add(b: *std.Build, c: struct { shell_cfg: core.ShellConfig, target: std.Build.ResolvedTarget, test_filters: []const []const u8, - tracy: ?[]const u8, - tree_sitter_grammars: TreeSitterGrammars, unit_profile: *std.Build.Step.Compile, }) Tools { const image_harness = program(b, "pardes-image-harness", "test/image_harness.zig", c.target, c.optimize, &.{}); @@ -191,10 +188,10 @@ pub fn add(b: *std.Build, c: struct { .c_optimize = @tagName(c.c_optimize), .terminal_optimize = @tagName(c.ghostty_optimize), .platform = @tagName(c.platform), - .grammars = @tagName(c.tree_sitter_grammars), + .grammars = @tagName(c.shell_cfg.tree_sitter_grammars), .mupdf = c.pdf_addon != null, .jpx = c.enable_jpx, - .tracy = c.tracy != null, + .tracy = c.shell_cfg.tracy != null, .terminal_simd = c.ghostty_simd, .prebuilt_shaders = c.platform == .gui and c.prebuilt_shaders, }); diff --git a/core/Output.zig b/core/Output.zig index 3ac9f521..23409b68 100644 --- a/core/Output.zig +++ b/core/Output.zig @@ -906,7 +906,7 @@ pub fn openBuild(p: *Pardes, id: usize) !void { @tagName(builtin.abi), @tagName(build_options.platform), }); try w.print("grammars {s}\naddons {s}\nsemantics {x:0>16}\n\ndependencies\n{s}", .{ - if (build_options.syntax_full_grammars) "full" else if (build_options.syntax_minimal_grammars) "minimal" else "none", + if (build_options.grammars == .full) "full" else if (build_options.grammars == .minimal) "minimal" else "none", if (@import("builtin_addons").on) "compiled in" else "loaded from /lib/pardes/addons", @import("wire").semantics, build_options.deps, diff --git a/core/syntax.zig b/core/syntax.zig index f95b745a..36aa8c2b 100644 --- a/core/syntax.zig +++ b/core/syntax.zig @@ -7,10 +7,9 @@ const regexp = @import("regexp.zig"); const c_heap = @import("c_heap"); const diff = @import("diff.zig"); -pub const enabled = config.syntax_highlighting; -const zig_grammar = config.syntax_zig_grammar; -const minimal_grammars = config.syntax_minimal_grammars; -const full_grammars = config.syntax_full_grammars; +pub const enabled = config.grammars != .disabled; +const minimal_grammars = config.grammars == .minimal or config.grammars == .full; +const full_grammars = config.grammars == .full; pub const ts = if (enabled) @import("tree-sitter") else struct { pub const Language = opaque {}; @@ -44,7 +43,7 @@ const Spec = struct { fn grammarSelected(comptime g: grammar_manifest.Grammar) bool { return switch (g.tier) { - .zig => zig_grammar, + .zig => enabled, .minimal => minimal_grammars, .full => full_grammars, }; @@ -2169,7 +2168,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 (!zig_grammar) return error.SkipZigTest; + if (!enabled) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); diff --git a/test/behaviour/panes.zig b/test/behaviour/panes.zig index 67155776..8fb85cb7 100644 --- a/test/behaviour/panes.zig +++ b/test/behaviour/panes.zig @@ -888,7 +888,7 @@ test "panes: truncating body empties it, and a stat says the length after" { } test "panes: a rename colours a source its new name's language names, its text unchanged" { - if (!@import("pardes_config").syntax_highlighting) return error.SkipZigTest; + if (@import("pardes_config").grammars == .disabled) return error.SkipZigTest; var s = try Session.initFile(std.testing.allocator, "fn check() void {}\n"); defer s.deinit(); const n = try s.focused(); diff --git a/test/behaviour/settings.zig b/test/behaviour/settings.zig index 66cd97df..bd88b75e 100644 --- a/test/behaviour/settings.zig +++ b/test/behaviour/settings.zig @@ -158,7 +158,7 @@ test "settings: Back and Forward written to exec keep to the focused file" { }); } -const syntax = @import("pardes_config").syntax_highlighting; +const syntax = @import("pardes_config").grammars != .disabled; /// The style /screen draws the cell `into` cells into the first place /// `text` is drawn. diff --git a/test/output.zig b/test/output.zig index 38e8ba0d..17525616 100644 --- a/test/output.zig +++ b/test/output.zig @@ -786,7 +786,7 @@ test "identical result refresh keeps warm content caches without allocation" { const index = try panes.File.lineIndex(p.gpa, file); const styles = try std.testing.allocator.dupe(u8, file.highlights); defer std.testing.allocator.free(styles); - if (@import("pardes_config").syntax_zig_grammar) try std.testing.expect(styles.len > 0); + if (@import("pardes_config").grammars != .disabled) try std.testing.expect(styles.len > 0); const revision = file.revision; const saved_revision = file.saved_revision; const body_ptr = file.content.ptr; -- cgit v1.3 From a481de9feea08de7b5b82c2471de70abd70d7462 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 19 Nov 2026 23:07:14 -0300 Subject: build: one options module a module set, `pardes_options`, and `build_info` beside it (the start design's step 2, pardes-build-options change 2): `core.module` makes the set's options from the build's `ShellConfig` and the set's `Core` (the platform, now a `Core` field in place of a module handed in; the grammar set; the terminal; pardes-isolate's `isolated`; the addons compiled in and the pdf one with them, `builtin_addons` and `builtin_pdf`; tracy; the workspace tag; embedded sources; the library's `lib`), one module shared by the set's five as `pardes_config` was, and `build_info` (version, commit, change, built, deps) made once in `assemble` and given to every set; the three one-value modules made in both values (`term_options`, `pardes_isolation`, `builtin_addons`), `shellOptions`, the six `Parts` fields that held them, `Parts.tracy` and `Parts.embed_sources` (the `ShellConfig` in `Parts` holds both) and the assembly's two options (`opts`, `gui_opts`) go; the library's `pardes-syntax` and the editor (the library's and hxlib's) get `pardes_options` with no terminal, the editor's with `lib` as before; the sources' imports follow, one identifier a line (abi/wire.zig and core/Output.zig import both, the hash's and the Build pane's lines reading the version, commit and dependencies from `build_info`); test programs see it as before, through the core module's import table (pane-test, behaviour-test); `pardes version`'s semantics line did not move on any product (38b5ae573b965550; d41689a1f97605b8 with -Dtree-sitter=minimal); build.zig and build/ 2,992 -> 2,960 lines (3,005 at the base); every shape configures and builds as on the base, pardes-isolate and -Dtree-sitter=disabled failing with the base's same errors (pardes-isolate reaching them through its own options module); tui core-test 848/991 (143 skipped), shell-test 1027/1030, pane-test 183/184, behaviour-test 275/275 (and -- --replay), term-test 15/15, kitty-test 45/45, lib-test (11/11 in the consumer), hxlib 538 cases 0 mismatches, process-test 2 of 144 failed (lspcomplete and lspcompletemoved, the base's), gui unit-test 1625/1629 (the perf check's BaselineHarnessMismatch, the base's); the test names of every suite equal the base's (ledger); the frame and perf gate (gpu/bo-s2 against tree1) PASS: 77/77 frames byte-identical in Debug, the alternated window corpus2x -0.104% (pictures identical in all 10 runs), the 97 per-operation counts within 0.1% (largest image-frame +0.0345%; against the coordinator's pardes-merge22 gate m22-g, 90 within 5 ppm, deep-sel 8-10 ppm, image-frame up to 85 ppm, its known noise); load 5-25 on 16 cores Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- abi/wire.zig | 13 ++--- build.zig | 13 +++-- build/core.zig | 115 ++++++++++++++++---------------------------- build/library.zig | 2 +- build/tests.zig | 4 +- core/Addon.zig | 4 +- core/Editor.zig | 2 +- core/Output.zig | 15 +++--- core/Term.zig | 2 +- core/Text.zig | 2 +- core/config.zig | 2 +- core/lib_editor.zig | 2 +- core/memory.zig | 2 +- core/root.zig | 10 ++-- core/syntax.zig | 2 +- core/tracy.zig | 2 +- dev/root.zig | 6 +-- docs/next-editor.md | 2 +- docs/next-terminal.md | 4 +- runtime/macos.zig | 2 +- runtime/root.zig | 4 +- test/behaviour/panes.zig | 2 +- test/behaviour/settings.zig | 8 +-- test/output.zig | 2 +- 24 files changed, 96 insertions(+), 126 deletions(-) diff --git a/abi/wire.zig b/abi/wire.zig index 26a7131e..1f7d02d2 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -7,7 +7,8 @@ const std = @import("std"); const builtin = @import("builtin"); const pardes = @import("core"); -const config = @import("pardes_config"); +const config = @import("pardes_options"); +const build_info = @import("build_info"); /// 23: a pane of a kind's frame names its rasters by key, their pixels /// crossing before it as strips of 4 MiB at most over the rows it shows @@ -70,12 +71,12 @@ pub const semantics: u64 = blk: { break :blk std.hash.Wyhash.hash(0, std.fmt.comptimePrint( "wire {d}\npardes {s} {s}\n{s} grammars {} {} {} {} workspace_tag {} sources {}\nusize {d} {t}\n", .{ - version, config.version, config.commit orelse "unstamped", - family, g != .disabled, g != .disabled, - g == .minimal or g == .full, g == .full, config.workspace_tag, - config.embed_sources, @sizeOf(usize), builtin.cpu.arch.endian(), + version, build_info.version, build_info.commit orelse "unstamped", + family, g != .disabled, g != .disabled, + g == .minimal or g == .full, g == .full, config.workspace_tag, + config.embed_sources, @sizeOf(usize), builtin.cpu.arch.endian(), }, - ) ++ config.deps ++ "\n" ++ pardes.tape.shape); + ) ++ build_info.deps ++ "\n" ++ pardes.tape.shape); }; /// EndOfStream: the message ends early; WriteFailed: no room for it. diff --git a/build.zig b/build.zig index cf9a851f..fc0c5044 100644 --- a/build.zig +++ b/build.zig @@ -166,7 +166,6 @@ pub fn build(b: *std.Build) void { .pdf_scroll_bench_step = pdf_scroll_bench_step, }); const parts = a.parts; - const opts = a.opts; // Off Linux, whose memfd Addon.zig's loader needs, every core has the // addons compiled in. const compiled_in = target.result.os.tag != .linux; @@ -174,28 +173,28 @@ pub fn build(b: *std.Build) void { // its own flat C ABI instead of runtime/main.zig. Tracy's client and BSD // libutil go to the shell (and Tracy's to the core) alone, as before // core.module. - const root_set = core.module(b, parts, .{ .root = if (platform == .macos) "runtime/macos.zig" else "runtime/main.zig", .config = opts, .builtin_addons = compiled_in, .tracy = true, .util = true }); + const root_set = core.module(b, parts, .{ .root = if (platform == .macos) "runtime/macos.zig" else "runtime/main.zig", .platform = platform, .builtin_addons = compiled_in, .tracy = true, .util = true }); const root_mod = root_set.root; // hxdiff's headless core and pardes-isolate are the primary shell's // configuration compiled two more ways, not two more frontends. - const core_cfg: core.Core = .{ .root = "core/root.zig", .config = opts, .builtin_addons = compiled_in, .tracy = true }; + const core_cfg: core.Core = .{ .root = "core/root.zig", .platform = platform, .builtin_addons = compiled_in, .tracy = true }; const core_set = core.module(b, parts, core_cfg); const core_module = core_set.root; // The core without the terminal module (docs/next-terminal.md, Phase 1): // what core-test is compiled from. No ghostty-vt, wuffs, zstbi or C++; // a shell boot is a scratch pane, a test that needs a terminal skips, // and shell-test runs them all with one. - const lean_cfg: core.Core = .{ .root = "core/root.zig", .config = opts, .builtin_addons = compiled_in, .terminal = false }; + const lean_cfg: core.Core = .{ .root = "core/root.zig", .platform = platform, .builtin_addons = compiled_in, .terminal = false }; const core_lean = core.module(b, parts, lean_cfg); - const isolated_mod: ?*std.Build.Module = if (platform == .tui) core.module(b, parts, .{ .root = "runtime/main.zig", .config = opts, .builtin_addons = compiled_in, .isolated = true }).root else null; + const isolated_mod: ?*std.Build.Module = if (platform == .tui) core.module(b, parts, .{ .root = "runtime/main.zig", .platform = platform, .builtin_addons = compiled_in, .isolated = true }).root else null; // `zig build static`'s: the addons compiled in (Addon.zig). Linked // statically on musl alone, as glibc links only dynamically; the gui's // is dynamic (SDL and the GPU need the display's libraries) with the // addons in it all the same. const static_linkage: ?std.builtin.LinkMode = if (target.result.isMuslLibC()) .static else null; - const static_set: ?core.Modules = if ((platform == .tui and static_linkage != null) or platform == .gui) core.module(b, parts, .{ .root = "runtime/main.zig", .config = opts, .builtin_addons = true }) else null; + const static_set: ?core.Modules = if ((platform == .tui and static_linkage != null) or platform == .gui) core.module(b, parts, .{ .root = "runtime/main.zig", .platform = platform, .builtin_addons = true }) else null; const static_mod: ?*std.Build.Module = if (static_set) |s| s.root else null; - const gui_set: ?core.Modules = if (also_gui) core.module(b, parts, .{ .root = "runtime/main.zig", .config = a.gui_opts.?, .builtin_addons = compiled_in }) else null; + const gui_set: ?core.Modules = if (also_gui) core.module(b, parts, .{ .root = "runtime/main.zig", .platform = .gui, .builtin_addons = compiled_in }) else null; const gui_mod: ?*std.Build.Module = if (gui_set) |s| s.root else null; if (a.pdf.lib) |lib| tools.pdfBenches(b, target, optimize, core_module, lib, pdf_pointer_bench_step, pdf_scroll_bench_step); diff --git a/build/core.zig b/build/core.zig index b35c066b..4e4a748b 100644 --- a/build/core.zig +++ b/build/core.zig @@ -5,7 +5,7 @@ const grammar_manifest = @import("../core/grammar_manifest.zig"); const addons = @import("addons.zig"); const patches = @import("patches.zig"); /// The package manifest, imported UNTYPED on purpose — see the `version` -/// option in `shellOptions` for why that word is load-bearing. +/// option in `buildInfo` for why that word is load-bearing. const zon = @import("../build.zig.zon"); /// Releases are numbered 0.N; the zon holds "0.N.0" because it must be semver, /// and what a user sees drops that ".0". @@ -76,21 +76,34 @@ pub const ShellConfig = struct { lib: bool = false, }; -pub fn shellOptions(b: *std.Build, cfg: ShellConfig, platform: Platform) *std.Build.Step.Options { +/// `pardes_options`: what a module set varies at compile time, one module +/// a configuration, which `module` makes and the set's modules share. +pub fn options(b: *std.Build, cfg: ShellConfig, c: Core, pdf: bool) *std.Build.Step.Options { const o = b.addOptions(); - o.addOption(Platform, "platform", platform); + o.addOption(Platform, "platform", c.platform); o.addOption(TreeSitterGrammars, "grammars", cfg.tree_sitter_grammars); + o.addOption(bool, "terminal", c.terminal); + o.addOption(bool, "isolated", c.isolated); + o.addOption(bool, "builtin_addons", c.builtin_addons); + // ...the pdf one only when it is built (-Dpdf=false leaves it out). + o.addOption(bool, "builtin_pdf", c.builtin_addons and pdf); o.addOption(bool, "enable_tracy", cfg.tracy != null); - o.addOption(bool, "workspace_tag", cfg.workspace_tag orelse (platform != .macos)); + o.addOption(bool, "workspace_tag", cfg.workspace_tag orelse (c.platform != .macos)); o.addOption(bool, "embed_sources", cfg.embed_sources); + o.addOption(bool, "lib", cfg.lib); + return o; +} + +/// `build_info`: the version, and the commit, change and time a stamped +/// build was made from (see `stamp_commit`, read at configure time), and +/// every dependency's hash. +pub fn buildInfo(b: *std.Build, cfg: ShellConfig) *std.Build.Step.Options { + const o = b.addOptions(); o.addOption([]const u8, "version", display_version); - // ...and the commit it was built from, when there is one and the build - // is stamped at all (see `stamp_commit`). Read at configure time. o.addOption(?[]const u8, "commit", cfg.commit); o.addOption(?[]const u8, "change", cfg.change); o.addOption(?[]const u8, "built", cfg.built); o.addOption([]const u8, "deps", deps_text); - o.addOption(bool, "lib", cfg.lib); return o; } @@ -237,16 +250,16 @@ pub fn editorModule(b: *std.Build, name: ?[]const u8, target: std.Build.Resolved /// cell's width for j and k's goal column. vaxis: *std.Build.Module, }) *std.Build.Module { - const options: std.Build.Module.CreateOptions = .{ + const create: std.Build.Module.CreateOptions = .{ .target = target, .optimize = optimize, .root_source_file = b.path("core/lib_editor.zig"), .link_libc = true, }; - const m = if (name) |n| b.addModule(n, options) else b.createModule(options); + const m = if (name) |n| b.addModule(n, create) else b.createModule(create); var lib_cfg = cfg; lib_cfg.lib = true; - m.addOptions("pardes_config", shellOptions(b, lib_cfg, .tui)); + m.addOptions("pardes_options", options(b, lib_cfg, .{ .root = "core/lib_editor.zig", .platform = .tui, .terminal = false }, false)); m.addImport("plain", b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("abi/plain.zig") })); m.addImport("generated_themes", d.themes); d.ts.wire(m); @@ -262,8 +275,10 @@ pub const Parts = struct { target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, cloud9: *std.Build.Module, - /// -Dtracy's checkout, whose client a core that asks compiles in. - tracy: ?[]const u8, + /// The build's options (-Dtracy's checkout, -Dembed-sources...). + cfg: ShellConfig, + /// `build_info`, the same for every set. + info: *std.Build.Step.Options, zstd: *std.Build.Step.Compile, /// The addons, for a core that has them compiled in (Addon.zig); the /// pdf one only when it is built (-Dpdf=false leaves it out). @@ -281,16 +296,6 @@ pub const Parts = struct { uucode: *std.Build.Module, xitdb: *std.Build.Module, doc_typ: *std.Build.Step.Options, - /// -Dembed-sources: the core embeds its sources for /src. - embed_sources: bool, - /// One options module for each value of `terminal`, `isolated` and - /// `on`, shared by every core. - term_on: *std.Build.Step.Options, - term_off: *std.Build.Step.Options, - iso_on: *std.Build.Step.Options, - iso_off: *std.Build.Step.Options, - builtin_on: *std.Build.Step.Options, - builtin_off: *std.Build.Step.Options, }; /// Which core: its root and the few ways the products differ. @@ -299,9 +304,8 @@ pub const Core = struct { /// library), core/root.zig for the core, runtime/root.zig for the /// runtime, or a core file whose tests run on the core's imports. root: []const u8, - /// The shell's options (`pardes_config`): this build's, or the window's - /// in the bare build. - config: *std.Build.Step.Options, + /// This build's, or the window's in the bare build. + platform: Platform, /// The terminal module; without it (core-test) a shell boot is a scratch pane. terminal: bool = true, /// pardes-isolate's: no host but the terminal. @@ -336,7 +340,7 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules { // forkpty: in libc proper on glibc>=2.34 and darwin; the BSDs keep it in libutil if (c.util and (p.target.result.os.tag == .freebsd or p.target.result.os.tag == .netbsd or p.target.result.os.tag == .openbsd)) m.linkSystemLibrary("util", .{}); - if (c.tracy) if (p.tracy) |tracy_path| { + if (c.tracy) if (p.cfg.tracy) |tracy_path| { m.addIncludePath(.{ .cwd_relative = tracy_path }); m.addCSourceFile(.{ .file = .{ .cwd_relative = b.pathJoin(&.{ tracy_path, "public", "TracyClient.cpp" }) }, @@ -356,7 +360,7 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules { for (p.ts.libs.items) |lib| m.linkLibrary(lib); // The /src tree's files that live outside the core's directory // (fs.zig embeds them under the names they had there). - if (p.embed_sources) for ([_][]const u8{ "runtime/9p.zig", "runtime/9p_io.zig", "runtime/main.zig", "dev/host_io.zig" }) |f| + if (p.cfg.embed_sources) for ([_][]const u8{ "runtime/9p.zig", "runtime/9p_io.zig", "runtime/main.zig", "dev/host_io.zig" }) |f| m.addAnonymousImport(f, .{ .root_source_file = b.path(f) }); const runtime = b.createModule(.{ .target = p.target, .optimize = p.optimize, .root_source_file = b.path("runtime/root.zig"), .link_libc = true }); const dev = b.createModule(.{ .target = p.target, .optimize = p.optimize, .root_source_file = b.path("dev/root.zig"), .link_libc = true }); @@ -364,18 +368,15 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules { const root = if (!in_runtime) m else if (std.mem.eql(u8, c.root, "runtime/root.zig")) runtime else b.createModule(.{ .target = p.target, .optimize = p.optimize, .root_source_file = b.path(c.root), .link_libc = true }); // Each options module once, so that the modules share it: a file is in // one module of a compilation. - const term_options = (if (c.terminal) p.term_on else p.term_off).createModule(); const ts_queries = if (p.ts.queries) |q| q.createModule() else null; const doc_typ = p.doc_typ.createModule(); - const pardes_config = c.config.createModule(); - const pardes_isolation = (if (c.isolated) p.iso_on else p.iso_off).createModule(); - const builtin_addons = (if (c.builtin_addons) p.builtin_on else p.builtin_off).createModule(); + const pardes_options = options(b, p.cfg, c, p.pdf != null).createModule(); + const build_info = p.info.createModule(); for ([_]*std.Build.Module{ m, dev, runtime, wire, root }) |x| { x.addImport("cloud9", p.cloud9); if (c.builtin_addons) if (p.pdf) |pdf| x.addImport("pdf_addon", pdf); if (c.builtin_addons) x.addImport("image_addon", p.image); if (c.terminal) x.addImport("term", p.term); - x.addImport("term_options", term_options); x.addImport("plain", p.plain); x.addImport("pardes_addon", p.kind); x.addImport("generated_themes", p.themes); @@ -388,9 +389,8 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules { x.addImport("xitdb", p.xitdb); // config.zig's test checks the words and keys docs/typ names exist. x.addImport("doc_typ", doc_typ); - x.addImport("pardes_config", pardes_config); - x.addImport("pardes_isolation", pardes_isolation); - x.addImport("builtin_addons", builtin_addons); + x.addImport("pardes_options", pardes_options); + x.addImport("build_info", build_info); x.addImport("core", m); x.addImport("dev", dev); x.addImport("runtime", runtime); @@ -399,13 +399,9 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules { return .{ .root = root, .core = m, .dev = dev, .runtime = runtime, .wire = wire }; } -/// What `assemble` makes besides the parts: the shells' options, the -/// addons, and the terminal's pieces the tests and harnesses name. +/// What `assemble` makes besides the parts: the addons, and the terminal's pieces the tests and harnesses name. pub const Assembly = struct { parts: Parts, - /// The shell's options (`pardes_config`), and the window's in the bare build. - opts: *std.Build.Step.Options, - gui_opts: ?*std.Build.Step.Options, /// What an addon in Zig imports (abi/addon.zig). addon_mod: *std.Build.Module, pdf: addons.Pdf, @@ -418,10 +414,10 @@ pub const Assembly = struct { ghostty_simd: bool, }; -/// Every core's parts, the shells' options and the addons, made once and -/// in this order (the configuration numbers what it generates by it): the -/// one-round lazy fetch, tree-sitter and the themes, the patched packages, -/// zstd, the terminal, and the options modules the cores choose between. +/// Every core's parts and the addons, made once and in this order (the +/// configuration numbers what it generates by it): the one-round lazy +/// fetch, tree-sitter and the themes, the patched packages, zstd, the +/// terminal. pub fn assemble(b: *std.Build, c: struct { target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, @@ -463,9 +459,6 @@ pub fn assemble(b: *std.Build, c: struct { const themes_mod = generatedThemes(b, io, target, optimize); - const opts = shellOptions(b, c.shell_cfg, c.platform); - const gui_opts: ?*std.Build.Step.Options = if (c.also_gui) shellOptions(b, c.shell_cfg, .gui) else null; - const zstbi_dep = b.dependency("zstbi", .{ .target = target, .optimize = c_optimize }); const zstbi_mod = zstbi_dep.module("root"); // vaxis, ghostty, mvzr and zstbi are patched as they are fetched @@ -597,28 +590,13 @@ pub fn assemble(b: *std.Build, c: struct { if (ghostty_vt_for_tests) |x| term_mod.addImport("ghostty-vt", x); if (wuffs_mod) |x| term_mod.addImport("wuffs", x); term_mod.addImport("zstbi", zstbi_mod); - - // One options module for each value a core chooses (`module`). - const term_on = b.addOptions(); - term_on.addOption(bool, "terminal", true); - const term_off = b.addOptions(); - term_off.addOption(bool, "terminal", false); - const iso_off = b.addOptions(); - iso_off.addOption(bool, "isolated", false); - const iso_on = b.addOptions(); - iso_on.addOption(bool, "isolated", true); - const builtin_off = b.addOptions(); - builtin_off.addOption(bool, "on", false); - const builtin_on = b.addOptions(); - builtin_on.addOption(bool, "on", true); - // ...the pdf one only when it is built (-Dpdf=false leaves it out). - builtin_on.addOption(bool, "pdf", pdf_built.lib != null); return .{ .parts = .{ .target = target, .optimize = optimize, .cloud9 = cloud9, - .tracy = c.shell_cfg.tracy, + .cfg = c.shell_cfg, + .info = buildInfo(b, c.shell_cfg), .zstd = zstd, .image = image_addon.root_module, .pdf = pdf_built.module, @@ -633,16 +611,7 @@ pub fn assemble(b: *std.Build, c: struct { .uucode = uucode_mod, .xitdb = xitdb_mod, .doc_typ = c.doc_typ, - .embed_sources = c.shell_cfg.embed_sources, - .term_on = term_on, - .term_off = term_off, - .iso_on = iso_on, - .iso_off = iso_off, - .builtin_on = builtin_on, - .builtin_off = builtin_off, }, - .opts = opts, - .gui_opts = gui_opts, .addon_mod = addon_mod, .pdf = pdf_built, .image_addon = image_addon, diff --git a/build/library.zig b/build/library.zig index ebfd8596..8a23debc 100644 --- a/build/library.zig +++ b/build/library.zig @@ -24,7 +24,7 @@ pub fn build(b: *std.Build) void { }); // A library's options: its grammars, nothing stamped, no window. const cfg: core.ShellConfig = .{ .tree_sitter_grammars = tree_sitter_grammars }; - mod.addOptions("pardes_config", core.shellOptions(b, cfg, .tui)); + mod.addOptions("pardes_options", core.options(b, cfg, .{ .root = "core/lib_syntax.zig", .platform = .tui, .terminal = false }, false)); const ts = core.treeSitter(b, io, target, if (optimize == .debug) .fast else optimize, tree_sitter_grammars); const themes = core.generatedThemes(b, io, target, optimize); mod.addImport("generated_themes", themes); diff --git a/build/tests.zig b/build/tests.zig index 50d3dd02..741eb24a 100644 --- a/build/tests.zig +++ b/build/tests.zig @@ -84,7 +84,7 @@ pub fn add(b: *std.Build, c: struct { if (c.ghostty_vt_for_tests) |x| pane_tests.root_module.addImport("ghostty-vt", x); // The core's own options module, not another over the same file: // a file is in one module of a compilation. - pane_tests.root_module.addImport("pardes_config", c.core_module.import_table.get("pardes_config").?); + pane_tests.root_module.addImport("pardes_options", c.core_module.import_table.get("pardes_options").?); const test_addons = b.addOptions(); test_addons.addOptionPath("image", c.image_addon.getEmittedBin()); test_addons.addOption(bool, "has_pdf", c.pdf_addon != null); @@ -129,7 +129,7 @@ pub fn add(b: *std.Build, c: struct { session_module.addOptions("session_options", session_options); // The build's options alone (platform), never the core: a test of a // window's word knows which build it runs in. - const behaviour_tests = units.root(b, "test/behaviour.zig", true, &.{ .{ .name = "session", .module = session_module }, .{ .name = "pardes_config", .module = c.core_module.import_table.get("pardes_config").? } }); + const behaviour_tests = units.root(b, "test/behaviour.zig", true, &.{ .{ .name = "session", .module = session_module }, .{ .name = "pardes_options", .module = c.core_module.import_table.get("pardes_options").? } }); const behaviour_test_step = b.step("behaviour-test", "run the behavioural tests, through the 9P tree alone (test/behaviour/), and the T1 runner (-- [--seed N]... | --monkey | --replay)"); _ = units.add(b, behaviour_tests, behaviour_test_step); // An addon's own test: `--addon-test` over the fake (the template) diff --git a/core/Addon.zig b/core/Addon.zig index ec2f796a..c542e1f1 100644 --- a/core/Addon.zig +++ b/core/Addon.zig @@ -236,9 +236,9 @@ fn fileOf(fd: c_int) ?[5]i64 { /// library exports. A static binary cannot dlopen, and the loader below /// is Linux's (a memfd): this is how either has image and PDF panes. /// A build with -Dpdf=false has the image addon alone. -const compiled_in: []const *const Kind.Ops = if (!@import("builtin_addons").on) +const compiled_in: []const *const Kind.Ops = if (!@import("pardes_options").builtin_addons) &.{} -else if (@import("builtin_addons").pdf) +else if (@import("pardes_options").builtin_pdf) &.{ &@import("image_addon").pardes_addon, &@import("pdf_addon").pardes_addon } else &.{&@import("image_addon").pardes_addon}; diff --git a/core/Editor.zig b/core/Editor.zig index 9781d857..aaf6ab05 100644 --- a/core/Editor.zig +++ b/core/Editor.zig @@ -10,7 +10,7 @@ const Registers = @import("Registers.zig"); /// The library's build (build.zig `library`): a text with no pane and no /// core, its characters its own. Where an edit reaches a pane it branches /// on this at compile time, so the library never compiles the core. -pub const lib = @import("pardes_config").lib; +pub const lib = @import("pardes_options").lib; const Pardes = if (lib) void else @import("Core.zig"); const Syntax = if (lib) @import("lib_editor.zig").Syntax else void; const modal = @import("modal.zig"); diff --git a/core/Output.zig b/core/Output.zig index 23409b68..08abc154 100644 --- a/core/Output.zig +++ b/core/Output.zig @@ -9,7 +9,8 @@ const Pardes = pardes.Pardes; const modal = @import("modal.zig"); const limits = @import("memory.zig").limits; const builtins = @import("builtins.zig"); -const build_options = @import("pardes_config"); +const build_options = @import("pardes_options"); +const build_info = @import("build_info"); const lsp = @import("lsp/lsp.zig"); const look = @import("look.zig"); const locations = @import("locations.zig"); @@ -896,9 +897,9 @@ pub fn openBuild(p: *Pardes, id: usize) !void { const w = &out.writer; try w.print("{s}\n", .{@import("runtime").upgrade.version_line}); try w.print("commit {s}\nchange {s}\nbuilt {s}\n", .{ - build_options.commit orelse "not stamped (a Debug build with -Dplatform or --prefix)", - build_options.change orelse "not stamped", - build_options.built orelse "not stamped", + build_info.commit orelse "not stamped (a Debug build with -Dplatform or --prefix)", + build_info.change orelse "not stamped", + build_info.built orelse "not stamped", }); try w.print("zig {s}\nmode {s}\ntarget {s}-{s}-{s}\nplatform {s}\n", .{ builtin.zig_version_string, @tagName(builtin.mode), @@ -907,9 +908,9 @@ pub fn openBuild(p: *Pardes, id: usize) !void { }); try w.print("grammars {s}\naddons {s}\nsemantics {x:0>16}\n\ndependencies\n{s}", .{ if (build_options.grammars == .full) "full" else if (build_options.grammars == .minimal) "minimal" else "none", - if (@import("builtin_addons").on) "compiled in" else "loaded from /lib/pardes/addons", + if (build_options.builtin_addons) "compiled in" else "loaded from /lib/pardes/addons", @import("wire").semantics, - build_options.deps, + build_info.deps, }); const content = try out.toOwnedSlice(); return openRead(p, id, .{ .cmd = .Build }, "", content); @@ -918,7 +919,7 @@ pub fn openBuild(p: *Pardes, id: usize) !void { pub fn openChangelog(p: *Pardes, id: usize) !void { var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); - try out.writer.print("pardes {s}\n\n", .{build_options.version}); + try out.writer.print("pardes {s}\n\n", .{build_info.version}); try out.writer.writeAll(@embedFile("CHANGELOG.md")); const content = try out.toOwnedSlice(); return openRead(p, id, .{ .cmd = .Changelog }, "", content); diff --git a/core/Term.zig b/core/Term.zig index fde36420..3f975df6 100644 --- a/core/Term.zig +++ b/core/Term.zig @@ -15,7 +15,7 @@ const File = @import("File.zig"); const iface = plain.term; /// The terminal module's entries; null in a core built without it. -pub const ops: ?*const iface.Ops = if (@import("term_options").terminal) &@import("term").ops else null; +pub const ops: ?*const iface.Ops = if (@import("pardes_options").terminal) &@import("term").ops else null; /// What a core without a terminal says, once, where one would have been. pub const none = "no terminal in this build"; diff --git a/core/Text.zig b/core/Text.zig index 51d660cf..1b3e6273 100644 --- a/core/Text.zig +++ b/core/Text.zig @@ -113,7 +113,7 @@ refused: bool = false, pub inline fn pane(t: *Text) ?*Pane { // the library's text has none (lib_editor.zig): known at compile time, // so what an edit does with a pane is not compiled there - if (comptime @import("pardes_config").lib) return null; + if (comptime @import("pardes_options").lib) return null; return switch (t.what) { .body => @alignCast(@fieldParentPtr("body", t)), .tag => @alignCast(@fieldParentPtr("tag", t)), diff --git a/core/config.zig b/core/config.zig index 792a7e62..bb04d24d 100644 --- a/core/config.zig +++ b/core/config.zig @@ -39,7 +39,7 @@ comptime { @setEvalBranchQuota(20_000); // A path here is a leaf: no builtin's path is it or runs past it, and // none of it is a builtin's whole path. The library has no builtins. - if (!@import("pardes_config").lib) for (leader_args) |la| for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |path| { + if (!@import("pardes_options").lib) for (leader_args) |la| for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |path| { if (std.mem.startsWith(u8, path, la.path) or std.mem.startsWith(u8, la.path, path)) @compileError("leader_args path collides with " ++ @tagName(b) ++ ": " ++ la.path); }; diff --git a/core/lib_editor.zig b/core/lib_editor.zig index c459241a..3fe631af 100644 --- a/core/lib_editor.zig +++ b/core/lib_editor.zig @@ -3,7 +3,7 @@ //! true`, docs/next-editor.md). In-memory editing with helix's keys: no //! files, commands, builtins, prompts or views, which come back to the //! caller as an `action`. Nothing is copied here: a key runs the editor's -//! own normal.zig and edit.zig, built with `pardes_config.lib`, where a +//! own normal.zig and edit.zig, built with `pardes_options.lib`, where a //! text has no pane and its characters are its own. //! //! The editor is a value of plain data (`Editor(capacity)`): no pointer, diff --git a/core/memory.zig b/core/memory.zig index c628ae49..0e0dba29 100644 --- a/core/memory.zig +++ b/core/memory.zig @@ -1,6 +1,6 @@ const std = @import("std"); const builtin = @import("builtin"); -const config = @import("pardes_config"); +const config = @import("pardes_options"); const KiB = 1024; const MiB = 1024 * KiB; diff --git a/core/root.zig b/core/root.zig index 69ec3ded..df273738 100644 --- a/core/root.zig +++ b/core/root.zig @@ -98,12 +98,12 @@ pub const Host = host_io.Host; pub const frameMark = tracy.frameMark; /// The shell this build is for (build.zig's `-Dplatform`). -pub const platform = @import("pardes_config").platform; +pub const platform = @import("pardes_options").platform; -pub const version = @import("pardes_config").version; -pub const commit: ?[]const u8 = @import("pardes_config").commit; +pub const version = @import("build_info").version; +pub const commit: ?[]const u8 = @import("build_info").commit; -pub const isolated = @import("pardes_isolation").isolated; +pub const isolated = @import("pardes_options").isolated; pub const font_picker = platform == .gui or platform == .macos; @@ -442,7 +442,7 @@ test { // A window's build links the window's C (font.c over FreeType and // HarfBuzz) into each of its programs, and their allocator (ui_malloc // and the rest) is gui.zig's. - if (comptime @import("term_options").terminal and platform == .gui) _ = @import("dev").gui; + if (comptime @import("pardes_options").terminal and platform == .gui) _ = @import("dev").gui; } /// The container-level `var`s core/ may hold (at the top of a file, in a diff --git a/core/syntax.zig b/core/syntax.zig index 36aa8c2b..ba3851ab 100644 --- a/core/syntax.zig +++ b/core/syntax.zig @@ -1,5 +1,5 @@ const std = @import("std"); -const config = @import("pardes_config"); +const config = @import("pardes_options"); const tracy = @import("tracy.zig"); const grammar_manifest = @import("grammar_manifest.zig"); const locations = @import("locations.zig"); diff --git a/core/tracy.zig b/core/tracy.zig index 3b0b8621..56429b1b 100644 --- a/core/tracy.zig +++ b/core/tracy.zig @@ -5,7 +5,7 @@ const std = @import("std"); const builtin = @import("builtin"); -pub const enable = if (builtin.is_test) false else @import("pardes_config").enable_tracy; +pub const enable = if (builtin.is_test) false else @import("pardes_options").enable_tracy; const SourceLocation = extern struct { name: ?[*:0]const u8, diff --git a/dev/root.zig b/dev/root.zig index 2c70783f..fc3ccfa8 100644 --- a/dev/root.zig +++ b/dev/root.zig @@ -26,9 +26,9 @@ test { _ = glide; // The frontends', which main.zig's test block collected: a shell's // build (shell-test); the core without a terminal never compiled them. - if (comptime @import("term_options").terminal) { - if (comptime @import("pardes_config").platform == .tui) _ = tui; - if (comptime @import("pardes_config").platform == .gui) _ = gui; + if (comptime @import("pardes_options").terminal) { + if (comptime @import("pardes_options").platform == .tui) _ = tui; + if (comptime @import("pardes_options").platform == .gui) _ = gui; _ = vaxis_input; } } diff --git a/docs/next-editor.md b/docs/next-editor.md index 120b4c09..e7168256 100644 --- a/docs/next-editor.md +++ b/docs/next-editor.md @@ -7,7 +7,7 @@ Decided 2026-11-17 on the coordinator's leans (survey: `.scratch/sketch/reports/editor-lib.md`); built the same day. One source of truth: the library runs the functions pardes runs, compiled from the -same files with `pardes_config.lib` set; nothing is copied for it. +same files with `pardes_options.lib` set; nothing is copied for it. ## The calls, as built diff --git a/docs/next-terminal.md b/docs/next-terminal.md index 26996897..c77ccd33 100644 --- a/docs/next-terminal.md +++ b/docs/next-terminal.md @@ -184,9 +184,9 @@ What differs from the plan above, and why: - **The ops are a compile-time constant, not handed over at start.** `Term.ops` (core/Term.zig:18) is `&@import("term").ops` when the build's - `term_options.terminal` says the core has a terminal, null otherwise. + `pardes_options.terminal` says the core has a terminal, null otherwise. Every core module but core-test's is given `term`; core-test's - (`core_lean` in build.zig) is not, and its `term_options` say so. A + (`core_lean` in build.zig) is not, and its `pardes_options` say so. A run-time `Pardes.Options.terminal` would have put the table in every test's options and every host's start for no gain: no build ever has two terminals, and a null known at compile time drops the dead code. diff --git a/runtime/macos.zig b/runtime/macos.zig index 408915da..24285c07 100644 --- a/runtime/macos.zig +++ b/runtime/macos.zig @@ -359,7 +359,7 @@ fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void { core.settings.workspace_tag = if (std.c.getenv("PARDES_WORKSPACE_TAG")) |v| std.mem.eql(u8, std.mem.span(v), "1") else - @import("pardes_config").workspace_tag; + @import("pardes_options").workspace_tag; core.view().frontend.native_images = true; var prompt_rcs = host_io.Shell.prepare(); diff --git a/runtime/root.zig b/runtime/root.zig index ec89e734..930f3389 100644 --- a/runtime/root.zig +++ b/runtime/root.zig @@ -22,9 +22,9 @@ test { _ = ninep; // main.zig's test block collected the crash file's: a shell's build // (shell-test); the core without a terminal (core-test) never compiled it. - if (comptime @import("term_options").terminal) _ = crash; + if (comptime @import("pardes_options").terminal) _ = crash; // A window's build links the window's C (font.c over FreeType and // HarfBuzz) into each of its programs, and their allocator (ui_malloc // and the rest) is gui.zig's. - if (comptime @import("term_options").terminal and @import("pardes_config").platform == .gui) _ = @import("dev").gui; + if (comptime @import("pardes_options").terminal and @import("pardes_options").platform == .gui) _ = @import("dev").gui; } diff --git a/test/behaviour/panes.zig b/test/behaviour/panes.zig index 8fb85cb7..dcde9c4d 100644 --- a/test/behaviour/panes.zig +++ b/test/behaviour/panes.zig @@ -888,7 +888,7 @@ test "panes: truncating body empties it, and a stat says the length after" { } test "panes: a rename colours a source its new name's language names, its text unchanged" { - if (@import("pardes_config").grammars == .disabled) return error.SkipZigTest; + if (@import("pardes_options").grammars == .disabled) return error.SkipZigTest; var s = try Session.initFile(std.testing.allocator, "fn check() void {}\n"); defer s.deinit(); const n = try s.focused(); diff --git a/test/behaviour/settings.zig b/test/behaviour/settings.zig index bd88b75e..cacee701 100644 --- a/test/behaviour/settings.zig +++ b/test/behaviour/settings.zig @@ -37,7 +37,7 @@ test "settings: Pet is the window's: a terminal's view refuses it; a window take defer s.deinit(); // Which build, from its options, not from the answer: a terminal's view // taking Pet must fail here, not pass as a window. - if (comptime @import("pardes_config").platform == .gui) { + if (comptime @import("pardes_options").platform == .gui) { try std.testing.expectEqualStrings("Pet off", try setting(&s, "Pet")); try s.write("/ctl", "Pet cat\n"); try std.testing.expectEqualStrings("Pet cat", try setting(&s, "Pet")); @@ -106,7 +106,7 @@ test "settings: a bad setting value is quoted, so two different bad values log a test "settings: a setting this frontend cannot show says GUI-only, never run as a command, and DumpDir reads back" { var s = try Session.initFile(std.testing.allocator, "x\n"); defer s.deinit(); - if (comptime @import("pardes_config").platform != .gui) { + if (comptime @import("pardes_options").platform != .gui) { _ = try s.refused("/ctl", "GripWidth 120\n"); try std.testing.expectEqualStrings("GripWidth is GUI-only, invalid here \"GripWidth\"", s.said); // A builtin the GUI alone has, written to a ctl or an exec, never @@ -158,7 +158,7 @@ test "settings: Back and Forward written to exec keep to the focused file" { }); } -const syntax = @import("pardes_config").grammars != .disabled; +const syntax = @import("pardes_options").grammars != .disabled; /// The style /screen draws the cell `into` cells into the first place /// `text` is drawn. @@ -314,7 +314,7 @@ test "settings: the user's startup file loads clean, every word of it known and const ctl = try s.read("/ctl"); for ([_][]const u8{ "Theme monokai_pro_classic\n", "CallstackDepth 64\n", "InactiveDim 5\n", "Shell fish\n", "JumpTrail on\n", "LocationsConfig context:4 tscontext:on tslocations:on layout:stacked\n" }) |line| try expectHas(ctl, line); // The window's words, which a terminal's view leaves to the window. - const window = @import("pardes_config").platform == .gui; + const window = @import("pardes_options").platform == .gui; for ([_][2][]const u8{ .{ "GripWidth", "110" }, .{ "CursorBlink", "off" }, .{ "WindowOpacity", "100" }, .{ "TaglineSize", "80" }, .{ "Pet", "frog" } }) |w| try expectHas(ctl, if (window) s.at("\n{s} {s}\n", .{ w[0], w[1] }) else s.at("\n# {s} unsupported\n", .{w[0]})); } diff --git a/test/output.zig b/test/output.zig index 17525616..dc99be8b 100644 --- a/test/output.zig +++ b/test/output.zig @@ -786,7 +786,7 @@ test "identical result refresh keeps warm content caches without allocation" { const index = try panes.File.lineIndex(p.gpa, file); const styles = try std.testing.allocator.dupe(u8, file.highlights); defer std.testing.allocator.free(styles); - if (@import("pardes_config").grammars != .disabled) try std.testing.expect(styles.len > 0); + if (@import("pardes_options").grammars != .disabled) try std.testing.expect(styles.len > 0); const revision = file.revision; const saved_revision = file.saved_revision; const body_ptr = file.content.ptr; -- cgit v1.3 From 2662a45ac245e574987bf6876f4470aed89da09c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 19 Nov 2026 22:06:32 -0300 Subject: replica: the bytes kind of replica made right and joinable (P29, P32; the brief's step 2: 2a, 2b, 2c and 2d in one change): the one rule in place of two, the faults shown first (a session's output kept over a copy held ahead was fed again by a rollback: the digests apart; the pages an emulator gained while a copy was held were the epoch's and freed with it: a crash in PageList.increaseCapacity in the rollback's replay): every replica's emulators on the C heap (panes.emulatorGpa), Term.writes counting the writes into emulators, a unit whose replay wrote one never kept over a copy taken ahead, never taken as moving nothing (tape.feedsTerminal), a client's input that owed a reflow always replayed when confirmed; a speculation moves a terminal's view under bytes as under screen state; tape.unit_max (1 MiB) and Tape.cut, which the session's Peers sets, so a pump's reads are cut into units under it; the join: whole terminals in a joiner's dump, every replica the session included reloading each live terminal in the step that opens or reopens a view (panes.reloadTerminals), the session's hash taped (Site.reload) and compared, kitty records left out of it, the cell pixels set first as a feed does; .positions and .prompt compared with the replica's own emulator on replay; replicas load kitty images by direct data only (Term.direct); Peers.bytes for the soak; six tests (core/replica.zig, bytes:); tui core-test 848/997 (149 skipped), shell-test 1033/1036, pane-test 183/184, term-test 17/17, kitty-test 45/45, behaviour-test 275/275 and --replay 0, process-test 2 of 144 (the base's), image- and kitty-harness pass, unit-test bytes: 22/22; gui unit-test 1633/1637 (the perf check's BaselineHarnessMismatch); the soaks in klrvlrly's Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- abi/term.zig | 2 + core/Core.zig | 2 + core/Term.zig | 32 +++++++ core/dump.zig | 7 +- core/panes.zig | 44 +++++++-- core/replica.zig | 247 +++++++++++++++++++++++++++++++++++++++++++++++-- core/root.zig | 1 + core/tape.zig | 60 +++++++++--- core/term/term.zig | 1 + core/term/terminal.zig | 45 ++++++++- 10 files changed, 408 insertions(+), 33 deletions(-) diff --git a/abi/term.zig b/abi/term.zig index 40f9e4f3..37519309 100644 --- a/abi/term.zig +++ b/abi/term.zig @@ -347,6 +347,8 @@ pub const Ops = struct { /// Its emulator made again from its own snapshot where it is (a join: /// every side does it); the snapshot's hash. reload: *const fn (s: *State) anyerror!u64, + /// Its program's kitty images by direct data alone (a replica's). + direct: *const fn (s: *State) void, // ---- output and view ---- /// One read of its program's output (`Told` says where the tracked diff --git a/core/Core.zig b/core/Core.zig index d5a990e2..9bc40775 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -1175,6 +1175,7 @@ fn openViewInner(p: *Pardes) ?View.Id { // tape does it here: a join dumps the session next, and a core // loaded from a dump has no queue (Replica.initDump). p.settle(); + pardes.panes.reloadTerminals(p); p.needs_frame = true; return .at(Views.open(p) orelse return null); } @@ -1217,6 +1218,7 @@ fn rejoinViewInner(p: *Pardes, k: View.Id) bool { if (!Views.isAway(p, k.index())) return false; p.views_away &= ~(@as(u8, 1) << @intCast(k.index())); p.settle(); + pardes.panes.reloadTerminals(p); p.needs_frame = true; return true; } diff --git a/core/Term.zig b/core/Term.zig index 82d5dad7..9f5d6362 100644 --- a/core/Term.zig +++ b/core/Term.zig @@ -14,6 +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, a +/// view moved, 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 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 } = .{}; + /// The terminal module's entries; null in a core built without it. pub const ops: ?*const iface.Ops = if (@import("term_options").terminal) &@import("term").ops else null; @@ -94,6 +103,9 @@ pub const State = struct { defer arena.deinit(); const parts = try walk.load(iface.Parts, arena.allocator(), bytes[8..][0..n], null); out.* = .{ .impl = try o.load(gpa, bytes[8 + n ..], &parts) }; + writes +%= 1; + // A replica's (a join's, a closed terminal brought back in a step). + if (tape.replaying() or dump.terminal_gpa != null) o.direct(out.impl); } }; @@ -114,6 +126,10 @@ pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State { const s = try gpa.create(State); errdefer gpa.destroy(s); s.* = .{ .impl = try o.open(gpa, cols, rows) }; + writes +%= 1; + // A replica's emulator loads its program's images by direct data alone + // (P32): what is read off the session's machine is the session's. + if (tape.replaying()) o.direct(s.impl); return s; } @@ -121,6 +137,7 @@ pub fn open(gpa: std.mem.Allocator, cols: u16, rows: u16) !*State { /// one it was opened with): the allocator a caller hands is not used. pub fn close(s: *State, _: std.mem.Allocator) void { const own = the().gpa(s.impl); + writes +%= 1; the().close(s.impl); own.destroy(s); } @@ -130,6 +147,14 @@ pub fn close(s: *State, _: std.mem.Allocator) void { /// 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; + const t0 = @import("FrameStats.zig").nowNs(); + defer { + reloads.n += 1; + const dt = @import("FrameStats.zig").nowNs() -| t0; + reloads.ns += dt; + reloads.worst_ns = @max(reloads.worst_ns, dt); + } return the().reload(s.impl); } @@ -142,6 +167,7 @@ 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; the().revive(s.impl); } @@ -160,6 +186,7 @@ pub fn stop() void { /// One read of its program's output (`Told` says where the tracked rows /// went). pub fn feed(s: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool) Told { + writes +%= 1; return the().feed(s.impl, bytes, tracked, rows, erased); } @@ -171,25 +198,30 @@ pub fn grid(s: ?*const State) Grid { /// Its view to a row of its history, or onto its output (null). pub fn viewTo(s: *State, at: ?usize) void { + writes +%= 1; the().viewTo(s.impl, at); } /// Its view moved by a number of rows (negative scrolls back). pub fn scroll(s: *State, delta: i32) void { + writes +%= 1; the().scroll(s.impl, delta); } /// Its view back onto its output. pub fn follow(s: *State) void { + writes +%= 1; the().follow(s.impl); } /// Its grid reflowed, now or when `resizeDeferred` makes it. pub fn resize(s: *State, cols: u16, rows: u16, later: bool) void { + writes +%= 1; the().resize(s.impl, cols, rows, later); } pub fn resizeDeferred(s: *State) bool { + writes +%= 1; return the().resizeDeferred(s.impl); } diff --git a/core/dump.zig b/core/dump.zig index 1616f557..f1d4ed26 100644 --- a/core/dump.zig +++ b/core/dump.zig @@ -261,7 +261,9 @@ pub fn image(p: *Pardes, name: []const u8) ![]u8 { /// first delta brings each afresh). What is left is the session's mutable /// state, made in its step. pub fn dumpJoin(p: *Pardes, deferred: *std.ArrayListUnmanaged(walk.Deferred)) ![]u8 { - slim_terminals = true; + // Under bytes, each terminal whole (as the join's step reloaded it on + // every side: panes.reloadTerminals), its sequence in flight with it. + slim_terminals = p.tape.screen_state; defer slim_terminals = false; // The join's file reads are the session's host's, between its steps: // with its io, which the core's tape holds (a walk's hook takes no more). @@ -270,7 +272,8 @@ pub fn dumpJoin(p: *Pardes, deferred: *std.ArrayListUnmanaged(walk.Deferred)) ![ return dumpWith(p, deferred); } -/// `dumpJoin`'s and `dumpExit`'s: a terminal dumps its size, not its emulator. +/// `dumpJoin`'s under screen state and `dumpExit`'s: a terminal dumps its +/// size, not its emulator. pub var slim_terminals = false; /// `dumpJoin`'s: a plain kind's pane carries its file (SlotRecord.file), /// read with this io. diff --git a/core/panes.zig b/core/panes.zig index 56a8e82a..61c57541 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -966,15 +966,17 @@ pub const Pane = struct { /// replica by its authority (the next delta says), on such an authority /// once the step's unit is out (`resizeDeferred`). pub fn resizeGrid(pane: *Pane, cols: u16, rows: u16) void { - // A screen-state client's speculation does what its replay does - // (its selections, never the grid): it waits for no round trip. - if (!tape.screenState() and tape.authorityOnly("resize a terminal")) return; + // 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`). 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.screenReplica()) return; + if (tape.speculating()) return tape.touchTerminal(); // A client typing at another size than the last typist's read // history rows its replay held as holes, and the rows came // renumbered (2026-10-30): the authority's waits for the unit. @@ -1117,6 +1119,31 @@ pub const Term = @import("Term.zig"); /// not follow the output (no memory for its pin), so it was reset. pub const positions_lost = "terminal edit position reset: out of memory"; +/// At a join (Core's openView, rejoinView): under bytes, every live +/// terminal made again from its own snapshot, on every side alike, the +/// session included (Term.reload): an emulator loaded from a snapshot holds +/// its rows in other pages than one fed from its start, and ghostty prunes +/// its history a page at a time, so the joiner, loaded from the session's +/// dump made next, and the replicas there before it, would part. The +/// session's snapshot's hash is taped, and each replica's own compared +/// with it: a check of the whole emulator at every join. +pub fn reloadTerminals(p: *Pardes) void { + if (tape.screenState()) return; + for (p.panes) |slot| if (slot) |pane| if (pane.terminal) |state| { + // Its cells' size in pixels as a feed sets it (`feedOutput`): a + // 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; + 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"); + }; +} + +fn sameHash(h: ?u64) ?u64 { + return h; +} + /// The sizes steps gave terminals (`Pane.resizeGrid`), made: between /// units, on an authority with screen-state replicas (replica.Peers.unit). pub fn resizeDeferred(p: *Pardes) void { @@ -1147,16 +1174,17 @@ pub fn createTerminal(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { return pane; } -/// A screen-state replica's emulators' allocator (`Term.State.gpa`): the C -/// heap, outside its rollback epoch: written by deltas while a copy is -/// held, no part of it is ever a copy's to save or put back. +/// A replica's emulators' allocator (`Term.State.gpa`): the C heap, +/// outside its rollback epoch: written (by the session's bytes or deltas) +/// while a copy is held, no part of it is ever a copy's to save or put +/// back, or the pages an emulator gains then are freed with the copy. pub const emulator_gpa = std.heap.c_allocator; /// What a terminal's emulator is made with, by `createTerminal` or a pane's /// load (dump.loadPane, a closed terminal brought back): `gpa`, but on a -/// screen-state replica `emulator_gpa`. +/// replica `emulator_gpa`. pub fn emulatorGpa(gpa: std.mem.Allocator) std.mem.Allocator { - return if (tape.screenReplica()) emulator_gpa else gpa; + return if (tape.replaying()) emulator_gpa else gpa; } // ---- the session's pane slots: making, finding, closing and freeing panes, and their prompts ---- diff --git a/core/replica.zig b/core/replica.zig index c68848f2..39af9404 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -905,7 +905,7 @@ 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 and r.applied > 1) { + if (r.pending.items[0].terminal and (r.applied > 1 or !r.t.screen_state)) { // Right, but what it did read a terminal: replayed later (a // rollback's `since`) it would read the deltas that came // after it. So it is taken now, over the emulator its step @@ -959,7 +959,12 @@ pub const Replica = struct { r.last_digest.clearRetainingCapacity(); if (ends) |d| r.last_digest.appendSlice(r.gpa, d) catch {}; } - if (r.applied > 0 and u.origin != r.id and ends != null and std.mem.eql(u8, ends.?, r.last_digest.items)) { + // A terminal's output is 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). + if (r.applied > 0 and u.origin != r.id and ends != null and std.mem.eql(u8, ends.?, r.last_digest.items) and + (r.t.screen_state or !tape.feedsTerminal(u.tape))) + { // 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. @@ -992,6 +997,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 replayed = tape.replayUnit(&r.t, u.tape); r.t.checks = false; if (replayed) |why| { @@ -1015,10 +1021,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. 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) { + if (retiring or (!r.t.screen_state and Term.writes != writes)) { r.copy.release(); rollback.Epoch.select(null); return r.clearSince(); @@ -1139,7 +1150,9 @@ pub const Replica = struct { const keyboard = if (c.panes[c.view().active]) |pane| pane.terminal != null else false; c.update(in.event); c.step(); - p.terminal = r.t.screen_state and (keyboard or r.t.touched); + // Under bytes: it owes an emulator a write it skipped (a grid's + // size), replayed when confirmed. + p.terminal = if (r.t.screen_state) keyboard or r.t.touched else r.t.touched; const clean = tape.endSpeculation(&r.t); const dt = nowNs() - t0; // Where a blob was written, should one be: the input that did. @@ -1215,7 +1228,6 @@ pub const Replica = struct { r.retiring = for (c.retired_panes.current, c.retired_panes.previous) |x, y| { if (x != null or y != null) break true; } else false; - if (!r.t.screen_state) return; for (r.core().panes, &r.views) |slot, *v| v.* = if (slot) |pane| if (pane.terminal) |state| pardes.Term.grid(state).view else null else null; } @@ -1230,7 +1242,6 @@ pub const Replica = struct { } fn putViews(r: *Replica) void { - if (!r.t.screen_state) return; for (r.core().panes, r.views) |slot, at| if (slot) |pane| if (pane.terminal) |state| pardes.Term.viewTo(state, at); } @@ -2055,6 +2066,10 @@ pub const Peers = struct { /// After each flush of a client's terminals, told: the soak's record /// of each terminal as each version left it (test/replicas.zig). flushed: ?struct { ctx: *anyopaque, f: *const fn (*anyopaque, *Pardes, *Screens) void } = null, + /// Its clients' terminals cross as the pty's bytes in its units, each + /// client's emulator its own (P29, P32), not as screen state: the + /// soak's (test/replicas.zig `--bytes`), until the switch. + bytes: bool = false, pub const Note = union(enum) { join: Joining, input: Msg, screen: Msg, gone: *Peer, check: *Peer, joined: *Peer }; /// A connection to join, and the view it joins again for, if it does. @@ -2175,6 +2190,14 @@ pub const Peers = struct { ps.screensOut(core, .flush); } + /// What its steps recorded passed a unit's bound (`tape.unit_max`): a + /// unit of its own now, between two inputs of the pump (Tape.cut). + fn cutUnit(ctx: *anyopaque) void { + const ps: *Peers = @ptrCast(@alignCast(ctx)); + ps.seq += 1; + ps.unit(0, ps.seq); + } + const ScreensOut = enum { flush, fill }; /// What each client is owed of the terminals (`Screens.flush`), or the @@ -2186,6 +2209,7 @@ pub const Peers = struct { } fn screensTo(ps: *Peers, core: *Pardes, peer: *Peer, comptime what: ScreensOut) void { + if (ps.bytes) return; defer { for (ps.msgs.items) |m| ps.gpa.free(m); ps.msgs.clearRetainingCapacity(); @@ -2219,8 +2243,9 @@ pub const Peers = struct { ps.t.unit_digests = true; // Terminals cross as screen state: a unit carries no pty bytes, // and its digest is a word (PARDES_REPLICA_TRACE: one a field). - ps.t.screen_state = true; + ps.t.screen_state = !ps.bytes; ps.t.whole_digest = std.c.getenv("PARDES_REPLICA_TRACE") == null; + ps.t.cut = .{ .ctx = ps, .f = cutUnit }; ps.screens = .init(ps.gpa); tape.on = &ps.t; core.tape = &ps.t; @@ -4139,6 +4164,214 @@ test "a unit that closes or tears down a terminal is never kept over a copy take try std.testing.expectEqual(a.core.store.closed.items.len, r.core().store.closed.items.len); } +/// The emulators of a session's and a replica's terminals as a dump keeps +/// them (what pardes keeps beside each, its whole snapshot): the same +/// bytes, or a test fails. +fn sameTerminals(a: *Authority, r: *Replica) !void { + const gpa = std.testing.allocator; + for (a.core.panes, r.core().panes) |x, y| { + const theirs = (x orelse continue).terminal orelse continue; + const mine = (y orelse return error.NoPane).terminal orelse return error.NoTerminal; + var w1: std.Io.Writer.Allocating = .init(gpa); + defer w1.deinit(); + var w2: std.Io.Writer.Allocating = .init(gpa); + defer w2.deinit(); + try theirs.dumpWrite(gpa, &w1.writer); + try mine.dumpWrite(gpa, &w2.writer); + try std.testing.expectEqualSlices(u8, w1.written(), w2.written()); + } +} + +/// A session and a replica of the bytes kind (its terminals fed the pty's +/// bytes the session's units carry), the session's view on its text pane, +/// and the shell's slot. +const BytesPair = struct { + a: *Authority, + r: *Replica, + shell: pardes.Pane.Id, + + fn init() !BytesPair { + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), false); + errdefer a.deinit(); + const r = try Replica.init(gpa, 1, try a.unit(0, 0), false); + var shell: ?pardes.Pane.Id = null; + for (a.core.panes, 0..) |slot, id| if (slot) |pane| { + if (pane.isTerminal()) shell = .at(id) else if (pane.file != null) a.core.view().active = @intCast(id); + }; + const pair: BytesPair = .{ .a = a, .r = r, .shell = shell orelse return error.NoShell }; + r.confirm(try a.local(.{ .focus = true })); + return pair; + } + + fn deinit(b: BytesPair) void { + b.r.deinit(); + b.a.deinit(); + } + + /// The session's program prints `bytes`, a unit of its own the replica takes. + fn output(b: BytesPair, bytes: []const u8) !void { + b.a.output(.{ .output = .{ .pane = b.shell, .bytes = bytes } }); + b.r.confirm((try b.a.pending()).?); + b.r.settle(); + } + + /// The client types a key over the text, and the session's own key + /// comes first: a rollback, which replays what was kept since the copy. + fn rollback(b: BytesPair) !void { + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| std.testing.allocator.free(m); + sent.deinit(std.testing.allocator); + } + try key(b.r, 'l', &sent); + try std.testing.expectEqual(@as(usize, 1), b.r.applied); + b.r.confirm(try b.a.local(.{ .key = .{ .cp = 'j', .text = "j" } })); + b.r.settle(); + b.r.confirm(try b.a.take(sent.items[0])); + b.r.settle(); + } +}; + +test "bytes: a session's output taken over a copy held ahead is fed once: a rollback does not feed it again" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const b = try BytesPair.init(); + defer b.deinit(); + b.r.ready(); + try std.testing.expect(b.r.copy.held); + try b.output("one line of the program's\r\n"); + try b.rollback(); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); +} + +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(); + defer b.deinit(); + b.r.ready(); + // Pages and their side tables the emulator had not: thousands of rows, + // a colour and a link a word. + var line: [128]u8 = undefined; + for (0..3000) |i| b.a.output(.{ .output = .{ .pane = b.shell, .bytes = 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 }) } }); + b.r.confirm((try b.a.pending()).?); + try b.rollback(); + try b.output("after\r\n"); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); +} + +test "bytes: a session's output that moves nothing the digest covers (a colour set) is never taken as moving nothing: it is fed, at its place" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const b = try BytesPair.init(); + defer b.deinit(); + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| std.testing.allocator.free(m); + sent.deinit(std.testing.allocator); + } + // A key of its own applied on top, the session's colour comes, then the + // key is confirmed, and the session's next output is in that colour. + try key(b.r, 'l', &sent); + try std.testing.expectEqual(@as(usize, 1), b.r.applied); + try b.output("\x1b[31m"); + b.r.confirm(try b.a.take(sent.items[0])); + b.r.settle(); + try b.output("red\r\n"); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); +} + +test "bytes: a mouse motion a speculation told a terminal's program is told again when its input is replayed: the cell last told is the pane's, put back with it" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const b = try BytesPair.init(); + defer b.deinit(); + // The program hears every motion, in SGR form. + try b.output("\x1b[?1003h\x1b[?1006h"); + const at = b.a.core.view().rects[b.shell.index()]; + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| gpa.free(m); + sent.deinit(gpa); + } + // Its speculation encodes the motion (the cell noted) and stops at the + // pty's write; the session's unit for it is replayed. + try sent.append(gpa, try gpa.dupe(u8, try b.r.input(.{ .mouse = .{ .button = .none, .kind = .motion, .col = at.x + 3, .row = at.y + at.h / 2 } }))); + b.r.confirm(try b.a.take(sent.items[0])); + b.r.settle(); + try agrees(b.a, b.r); +} + +test "bytes: a client joins from a dump with its terminals whole, and every side, the session too, reloads each terminal in the step that opens its view: their hashes agree, and all go on as one" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const b = try BytesPair.init(); + defer b.deinit(); + // History with colours and links, a sequence left open at the cut. + 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 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); + const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); + defer late.deinit(); + late.t.screen_state = false; + late.core().echo = null; + try std.testing.expectEqual(joined.digest, late.digest()); + b.a.output(.{ .output = .{ .pane = b.shell, .bytes = ";30mthe rest of it\x1b[0m\r\n" } }); + const rest = (try b.a.pending()).?; + b.r.confirm(rest); + late.confirm(rest); + late.settle(); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); + try agrees(b.a, late); + try sameTerminals(b.a, late); +} + +test "bytes: a session's output past a unit's bound is cut into units under it, between two reads" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const b = try BytesPair.init(); + defer b.deinit(); + const Cuts = struct { + a: *Authority, + units: std.ArrayListUnmanaged([]u8) = .empty, + fn cut(ctx: *anyopaque) void { + const c: *@This() = @ptrCast(@alignCast(ctx)); + c.a.batched = 0; + c.a.seq += 1; + const u = c.a.unit(0, c.a.seq) catch unreachable; + c.units.append(std.testing.allocator, std.testing.allocator.dupe(u8, u) catch unreachable) catch unreachable; + } + }; + var cuts: Cuts = .{ .a = b.a }; + defer { + for (cuts.units.items) |u| gpa.free(u); + cuts.units.deinit(gpa); + } + b.a.t.cut = .{ .ctx = &cuts, .f = Cuts.cut }; + defer b.a.t.cut = null; + // A pump's worth of reads, 64 KiB each, 3 MiB in all. + var read: [64 * 1024]u8 = undefined; + for (&read, 0..) |*c, i| c.* = if (i % 80 == 79) '\n' else @intCast('a' + i % 26); + for (0..48) |_| b.a.output(.{ .output = .{ .pane = b.shell, .bytes = &read } }); + try std.testing.expect(cuts.units.items.len >= 2); + for (cuts.units.items) |u| { + try std.testing.expect(u.len <= tape.unit_max + read.len + 4096); + b.r.confirm(u); + } + if (try b.a.pending()) |u| b.r.confirm(u); + b.r.settle(); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); +} + test "a replica joined from the session's dump replays the units after it" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); diff --git a/core/root.zig b/core/root.zig index 69ec3ded..423eed35 100644 --- a/core/root.zig +++ b/core/root.zig @@ -460,6 +460,7 @@ const allowed_vars = [_]struct { []const u8, []const u8, []const u8 }{ .{ "Kind.zig", "ready", "this process's draws done, each keyed by its core, pane and serial" }, .{ "Names.zig", "dp_rows dp_trace", "the scorer's scratch, written before it is read in one call" }, .{ "Turn.zig", "yield_depth", "this thread's nesting of yields (threadlocal)" }, + .{ "Term.zig", "writes reloads", "this process's emulators' writes, read across one replay on its thread (the replica engine's one rule), and its reloads' count and time" }, .{ "c_heap.zig", "allocators allocators_len allocators_lock last", "the C heap's registry of allocators and its lookup's memo" }, .{ "c_heap.zig", "test_allocator stateless", "its tests'" }, .{ "config.zig", "other_build addon_sources", "the docs check's data, a test's" }, diff --git a/core/tape.zig b/core/tape.zig index 00486666..69b74bc4 100644 --- a/core/tape.zig +++ b/core/tape.zig @@ -131,6 +131,10 @@ pub const Site = enum(u16) { /// What a call into a kind did (Kind.Outcome), and a kind's pane's /// tag prefix: the authority's, whose core alone runs the kind. addon, + /// The hash of a terminal's snapshot as the session reloaded it at a + /// join (panes.reloadTerminals), which every replica's own reload + /// compares. + reload, }; /// What the sites return. wire.semantics hashes their shape with the @@ -297,6 +301,10 @@ pub const Tape = struct { /// not recorded, and no digest covers it. A replica's core never writes /// one but by `apply`. screen_state: bool = false, + /// The session's (replica.Peers): called between two of its inputs once + /// what it recorded since its last unit passes `unit_max`, to send that + /// as a unit: a pump of a flood's reads is cut into units under it. + cut: ?struct { ctx: *anyopaque, f: *const fn (*anyopaque) void } = null, /// A digest as one word (screen-state replicas: every unit of a pty's /// output carries one, at the pty's read rate), not one a field; what /// differs is then not named. @@ -440,6 +448,7 @@ pub const Tape = struct { if ((t.depth == 0 or t.every) and !t.no_digest and !t.unit_digests) recordDigest(t); if (t.depth == 0) t.flush(); t.seeFields(); + if (t.depth == 0 and t.buf.items.len >= unit_max) if (t.cut) |c| c.f(c.ctx); } // ---- replaying ---- @@ -803,6 +812,16 @@ pub const Tape = struct { // Diverged (said in `diverged`): what a speculation gets, harmless, // for the rest of the input. A replica joins again; a replay says so. if (!t.expectHost(id, @tagName(s))) return poisonOf(R); + // What a terminal told (its rows moved, its prompt, a command's + // output) is the session's answer, kept, and a replica whose + // emulators are fed the same bytes asks its own and compares: a + // check a unit, for nothing (P30: a digest, not state). + if (comptime s == .positions or s == .prompt) if (!t.screen_state) { + const mine = @call(.auto, f, full); + t.scratch.clearRetainingCapacity(); + walk.encode(R, &mine, &t.scratch.writer) catch @panic("tape: out of memory"); + if (!std.mem.eql(u8, t.scratch.written(), t.last_ret.bytes[t.last_ret.at..])) t.diverge("what this replica's terminal told ({t}) is not what the session's did", .{s}); + }; var ret = t.last_ret; return walk.decode(R, &ret, a orelse t.arena.allocator()) catch { t.diverge("the tape's answer to {t} is short", .{s}); @@ -882,17 +901,12 @@ pub const Tape = struct { return true; } - /// A speculation that moves a terminal's view: a screen-state replica's - /// may (its rollback puts the view back, replica.zig `views`, and a delta - /// sets it), any other stops (`authorityOnly`). - pub fn viewOnly(t: *Tape, comptime why: []const u8) bool { - if (!t.speculating) return false; - if (t.screen_state) { - t.touched = true; - return false; - } - t.poison(why); - return true; + /// A speculation that moves a terminal's view: it may (its rollback + /// puts the view back, replica.zig `views`); a screen-state replica's + /// says it did (a delta sets the view again). + pub fn viewOnly(t: *Tape, comptime _: []const u8) bool { + if (t.speculating and t.screen_state) t.touched = true; + return false; } /// A speculation read a terminal's rows or moved its view (`Tape.touched`). @@ -1505,6 +1519,30 @@ pub fn endSpeculation(t: *Tape) bool { return !t.poisoned; } +/// About what a unit of the session's holds at most (`Tape.cut`): a pump +/// takes up to 496 reads of 64 KiB, which as one unit could pass the 16 MiB +/// a message may be (replica.zig `lag_max`'s neighbour, wire's bound). +pub const unit_max = 1 << 20; + +/// Whether a unit feeds a terminal its program's output (a pty's read; an +/// input kept by hash is taken to): 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); + 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, + .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/core/term/term.zig b/core/term/term.zig index 4bb60079..b18f5875 100644 --- a/core/term/term.zig +++ b/core/term/term.zig @@ -32,6 +32,7 @@ pub const ops: iface.Ops = .{ .snapshot = cast(iface.Ops, "snapshot", terminal_.snapshot), .load = cast(iface.Ops, "load", terminal_.load), .reload = cast(iface.Ops, "reload", terminal_.reload), + .direct = cast(iface.Ops, "direct", terminal_.direct), .feed = cast(iface.Ops, "feed", terminal_.feed), .grid = cast(iface.Ops, "grid", terminal_.grid), .viewTo = cast(iface.Ops, "viewTo", terminal_.viewTo), diff --git a/core/term/terminal.zig b/core/term/terminal.zig index 4de389bd..055c8981 100644 --- a/core/term/terminal.zig +++ b/core/term/terminal.zig @@ -195,6 +195,11 @@ pub const State = struct { /// the step reads the grid it had, as its replicas' replays do, and the /// rows sent them for it (Screens.fill) are of that grid's numbering. resize_to: ?struct { cols: u16, rows: u16 } = null, + /// Its program's kitty images by direct data alone (`direct`): a + /// replica's emulator, which is not the session's. A file, a temporary + /// file or shared memory is the session's machine's (and a temporary + /// one is deleted by its first reader): its image is absent here. + direct: bool = false, /// The stream over the emulator, its answers to the program and its /// size reports routed here, PNG decoded: what `create` and a dump's @@ -338,15 +343,35 @@ pub fn reload(s: *State) !u64 { var reply: [@typeInfo(@FieldType(State, "reply")).array.len]u8 = undefined; @memcpy(reply[0..saved.reply.len], saved.reply); saved.reply = reply[0..saved.reply.len]; - const kept = .{ s.changes, s.read, s.resize_to }; + const kept = .{ s.changes, s.read, s.resize_to, s.direct }; if (comptime images_enabled) s.images.deinit(gpa); s.stream.deinit(); s.vt.deinit(gpa); - s.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined, .changes = kept[0] +% 1, .read = kept[1], .resize_to = kept[2] }; + s.* = .{ .gpa = gpa, .vt = decoded.toOwned(), .stream = undefined, .changes = kept[0] +% 1, .read = kept[1], .resize_to = kept[2], .direct = kept[3] }; // Short of room for its sequence in flight it goes on without it (lost // at the next cut), as ghostty's stream does: not worth a terminal. _ = install(s, decoded.continuation, &saved); - return std.hash.Wyhash.hash(0, bytes.written()); + return joinHash(bytes.written()); +} + +/// What a join compares of a snapshot (`reload`): every record of it but +/// its kitty images' (tags 8 to 10, which ghostty's framing makes optional: +/// snapshot/record.zig, a u16 tag, a u32 length, a u32 CRC and the payload, +/// after a 10-byte envelope): an image by file or shared memory is the +/// session's alone (P32, `direct`), and no digest reads an image. +fn joinHash(bytes: []const u8) u64 { + const envelope = 10; + const head = 10; + var h: std.hash.Wyhash = .init(0); + h.update(bytes[0..@min(bytes.len, envelope)]); + var at: usize = envelope; + while (at + head <= bytes.len) { + const tag = std.mem.readInt(u16, bytes[at..][0..2], .little); + const end = @min(bytes.len, at + head + std.mem.readInt(u32, bytes[at + 2 ..][0..4], .little)); + if (tag < 8 or tag > 10) h.update(bytes[at..end]); + at = end; + } + return h.final(); } /// A decoded emulator at its address made a terminal: its stream wired, @@ -354,7 +379,7 @@ pub fn reload(s: *State) !u64 { /// whether its stream had all the room it wanted (`wire`). fn install(out: *State, continuation: ghostty_vt.snapshot.Continuation, saved: *const Term.Parts) bool { if (comptime images_enabled) inline for (.{ .primary, .alternate }) |which| { - if (out.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = .allWithTempDir(tempDir()); + if (out.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = if (out.direct) .direct else .allWithTempDir(tempDir()); }; const whole = out.wire(); switch (continuation) { @@ -384,6 +409,16 @@ fn install(out: *State, continuation: ghostty_vt.snapshot.Continuation, saved: * return whole; } +/// Its program's kitty images by direct data alone from now on: the +/// emulator of a replica that is not the session (P32). +pub fn direct(s: *State) void { + if (comptime !images_enabled) return; + s.direct = true; + inline for (.{ .primary, .alternate }) |which| { + if (s.vt.screens.get(which)) |screen| screen.kitty_images.image_limits = .direct; + } +} + /// The allocator it was opened with, its own from then on. pub fn gpaOf(s: *const State) std.mem.Allocator { return s.gpa; @@ -1748,7 +1783,7 @@ test "a join at a cut: every side reloaded from its own snapshot holds the same // the session's snapshot taken after (the join's dump). const hash = try reload(session); try std.testing.expectEqual(hash, try reload(there)); - try std.testing.expectEqual(hash, std.hash.Wyhash.hash(0, before)); + try std.testing.expectEqual(hash, joinHash(before)); const after = try snapshotOf(gpa, session); defer gpa.free(after); const joiner = try load(gpa, after, &parts(session)); -- cgit v1.3 From 30c6341ea868fc22deca16a5fb51fc19828cc2dc Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 19 Nov 2026 22:06:32 -0300 Subject: test/replicas: --bytes, the soak's clients as replicas of the bytes kind (each terminal fed the pty's bytes its units carry): a client dialling 100 ms into the flood, and at the shell session's end DA, DSR, CSI 16 t, a kitty query (answered on the session's pty once whatever the clients), an image by direct data shown and one by a file stored (a=t; shown, it moves the session's cursor and not a client's: a divergence until the file is taped); a join's cost and the reloads printed; --clients 5 --bytes --seeds 8 at 30/80/207 ms: diverged 0, unequal 0, quiet checks 1691/0 1303/0 1797/0, stops off may_wait 0, corpus 22 of 22, no leak, 2,168-2,321 reloads a run at 24-35 ms each (Debug), a join's step median 75 ms, dumps median 904 KB; the screen-state run beside it: diverged 0, unequal 0, deltas 1916/0 2028/0 1812/0, quiet 618/0 835/0 771/0 Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- test/replicas.zig | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/test/replicas.zig b/test/replicas.zig index 910c6e57..70edea75 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -53,6 +53,10 @@ const gpa = std.heap.c_allocator; pub const std_options: std.Options = .{ .log_level = .warn }; extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; var trace = false; +/// `--bytes`: its clients are replicas of the bytes kind, each terminal fed +/// the pty's bytes its units carry into an emulator of its own, joined from +/// a dump with every emulator whole (core/replica.zig `Peers.bytes`). +var bytes_kind = false; /// The PDF the soak opens (`--pdf`), absolute. var pdf_path: ?[]const u8 = null; const frame_us = 16_667; @@ -791,6 +795,9 @@ const Soak = struct { /// encoding cost. framed: bool = false, encode_ns: u64 = 0, + /// The session's pty told the answer to the program's kitty query + /// (`questions`): once, whatever the clients. + kitty_answers: u32 = 0, /// A Peer's queue, swapped out as its writer swaps it (the Peers' /// allocator's). sending: std.ArrayListUnmanaged(u8) = .empty, @@ -809,6 +816,9 @@ const Soak = struct { fn ptyWrite(ctx: ?*anyopaque, id: pardes.Pane.Id, bytes: []const u8) void { const pane = id.index(); const s = of(ctx); + // Only the session's emulator answers its program: a client's + // answers are its tape's, never written (`questions`). + if (std.mem.indexOf(u8, bytes, "\x1b_Gi=31;OK") != null) s.kitty_answers += 1; s.echo.append(gpa, .{ .pane = pane, .bytes = gpa.dupe(u8, bytes) catch return }) catch {}; } @@ -873,6 +883,7 @@ const Soak = struct { pub fn open(s: *Soak, l: *SessionLoop) !pardes.Host { s.l = l; l.peers.threads = false; + l.peers.bytes = bytes_kind; l.peers.flushed = .{ .ctx = s, .f = flushed }; const host: pardes.Host = .{ .ctx = s, .vtable = &vtable }; l.core.host = host; @@ -941,6 +952,9 @@ const Soak = struct { const at: u64 = switch (c) { 0, 1 => s.random.uintLessThan(u64, 100_000), 2 => 1_200_000, + // One joins in the middle of the flood, its emulators loaded + // whole and every other side's reloaded. + 3 => if (bytes_kind) flood_at + 100_000 else 2_300_000, else => 2_000_000 + c * 100_000, }; try net.send(.{ .at = at, .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); @@ -1412,6 +1426,11 @@ const Soak = struct { } const rp = try replica.Replica.initDump(gpa, cl.id, cl.view, m.bytes, .{ .cols = cl.cols, .rows = cl.rows, .distrusted = &cl.distrusted }); cl.r = rp; + // Its terminals its own emulators, fed what the units carry. + if (bytes_kind) { + rp.t.screen_state = false; + rp.core().echo = null; + } rp.stats.samples = true; rp.t.local_files = true; rp.echo.now = m.at * 1000; @@ -1449,6 +1468,11 @@ const Soak = struct { totals.flood_us += s.flood_end -| flood_at; for (s.flood_deltas[0..s.clients.len]) |d| totals.flood_deltas += d; const want = pardes.tape.digestOf(core); + if (bytes_kind) std.debug.print("seed {d} rtt {d} ms: a join's step at worst {d} us (the session's reloads and its dump), the last dump {d} KB ({d} KB of state)\n", .{ s.r.seed, s.r.rtt_ms, s.l.peers.join_ns / 1000, s.l.peers.dump_bytes >> 10, s.l.peers.state_bytes >> 10 }); + if (bytes_kind and s.kitty_answers != 1) { + totals.unequal += 1; + std.debug.print("seed {d} rtt {d} ms: the program's kitty query was answered {d} times on the session's pty\n", .{ s.r.seed, s.r.rtt_ms, s.kitty_answers }); + } for (s.clients, 1..) |*cl, id| { totals.resizes += cl.resizes; totals.wakes += cl.wakes; @@ -1560,7 +1584,11 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { // 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 shell_session = try screen_state.shellStream(gpa); + const session_only = try screen_state.shellStream(gpa); + defer gpa.free(session_only); + const asked = if (bytes_kind) try questions(dir) else ""; + defer if (bytes_kind) gpa.free(asked); + const shell_session = try std.mem.concat(gpa, u8, &.{ session_only, asked }); defer gpa.free(shell_session); const yes = try screen_state.yesStream(gpa, @intCast(r.flood_mb * (1 << 20) / 3)); defer gpa.free(yes); @@ -1584,6 +1612,23 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { if (soak.err) |err| return err; } +/// What the shell's program asks its terminal at the end of its session +/// (`--bytes`): device attributes, the cursor's place, the cell's size in +/// pixels, a kitty query; then a kitty image by direct data, shown, and one +/// by a file of the session's machine, stored (a=t), which no client loads +/// (P32): absent there, as every live terminal's image is under screen +/// state. Shown (a=T) it would move the session's cursor past it and not a +/// client's: a divergence until the file's bytes are taped (a later step). +fn questions(dir: []const u8) ![]u8 { + var path_buf: [300]u8 = undefined; + const path = try std.fmt.bufPrintSentinel(&path_buf, "{s}/pixels.rgb", .{dir}, 0); + try writeText(path, &@as([12]u8, @splat(0x7f))); + var b64: [400]u8 = undefined; + const name = std.base64.standard.Encoder.encode(&b64, path); + return std.fmt.allocPrint(gpa, "\x1b[c\x1b[6n\x1b[16t\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\\r\n" ++ + "\x1b_Ga=T,i=5,f=24,s=2,v=2;AAAAAAAAAAAAAAAA\x1b\\\r\n\x1b_Ga=t,i=6,t=f,f=24,s=2,v=2;{s}\x1b\\\r\n$ ", .{name}); +} + /// A typist: keys 50-200 ms apart, a pause now and then. fn typistGap(random: std.Random) u64 { return if (random.uintLessThan(u8, 12) == 0) random.intRangeAtMost(u64, 300_000, 1_500_000) else random.intRangeAtMost(u64, 50_000, 200_000); @@ -2722,6 +2767,10 @@ pub fn main(init: std.process.Init) !void { echo_mode = true; continue; } + if (std.mem.eql(u8, name, "--bytes")) { + bytes_kind = true; + continue; + } if (i + 1 >= args.len) return error.MissingValue; i += 1; const value = args[i]; @@ -2787,7 +2836,9 @@ pub fn main(init: std.process.Init) !void { defer stop_lines.deinit(gpa); for (rtts) |rtt| { var t: Totals = .{}; + pardes.Term.reloads = .{}; for (first..first + seeds) |seed| try run(init, .{ .seed = seed, .rtt_ms = rtt, .steps = steps, .clients = clients, .flood_mb = flood_mb }, dir, &t); + if (bytes_kind) std.debug.print("rtt {d}: {d} reloads of a terminal at joins, every side (the session's own too), {d} us each, {d} us at worst\n", .{ rtt, pardes.Term.reloads.n, pardes.Term.reloads.ns / @max(1, pardes.Term.reloads.n) / 1000, pardes.Term.reloads.worst_ns / 1000 }); const rollbacks = t.mispredicted + t.foreign; std.debug.print("{d:>4} {d:>6} {d:>7} {d:>7} {d:>6} {d:>6} {d:>6} ({d}+{d}) {d:>5.1}% {d:>6} {d:>5}/{d:<6} {d:>5}/{d:<5} ({d}) {d:>7}/{d:<7} {d:>8} {d:>7}\n", .{ rtt, t.inputs, t.speculated, -- cgit v1.3 From dcf6d58f8aacefd9a66817ef4589f68ce2d42e8a Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 19 Nov 2026 21:56:34 -0300 Subject: build: ghostty's terminal page sized in 4 KiB steps on every target (build/patches.zig `ghostty_page` and `ghostty_mem`, docs/ghostty-page-size.md), so the same pty bytes and resizes give the same emulator on Linux, FreeBSD and an Apple silicon Mac, as a client that replays its session's bytes needs, with Linux and FreeBSD unchanged: ghostty rounds a page to the OS page (src/terminal/page.zig:1770 at the pinned 1.4.0; 4 KiB here and on FreeBSD, 16 KiB on aarch64 macOS) and fills the rounding with rows and grown style room, so the 16 MiB scrollback kept other pages on the Mac: its digest differed from Linux's on every stream that filled the scrollback (source text, build logs, heavy colour, the torture stream: 59 to 1,177 history rows fewer) and its snapshot on the shell stream too (a style capacity hint, 388 against 397); now the layout rounds to 4 KiB and the three assertions that a page's length is a whole number of OS pages (page.zig:247, mem.zig:154 and :346) ask for 4 KiB, which on Linux and FreeBSD is what they were; a Mac maps whole 16 KiB pages under the shorter length (up to 12 KiB a page unused and never touched; 8 KiB for a standard page) and madvise and munmap act on its whole pages; the cross-check driver built from this tree (with the next change) gives on Linux and FreeBSD the lines it gave before the Edit, page counts and bytes included, and on the Mac the same lines, from a ReleaseFast and a ReleaseSafe build through all eight streams with no assertion (.scratch/sketch/reports/pardes-term-xcheck.md, "The reverse Edit"); in place of an earlier form of this change that rounded every target to 16 KiB and cost Linux +0.49% on pardes-perf's at-limit terminal cells and up to 13% of its history; the genizah's ghostty (main e8e7fea1, 2026-06-16) is older than the pin and rounds the same way, so no pin moves it; on both changes: tui term-test 15/15, kitty-test 45/45, core-test 848/991 (143 skipped), shell-test 1027/1030, image-harness and kitty-harness pass; gui unit-test 1625/1629 (4 skipped; the perf check's BaselineHarnessMismatch, the base's), image-harness and kitty-harness pass; the macOS library builds for Linux and aarch64-macos, the FreeBSD tui builds (load 11 to 37); the frame and perf gate (gpu/xcheck-c3, against tree1): 77/77 frames byte-identical, unit-test as the base, perfab corpus2x -0.076% (noise 0.091%), perfops 97 of 97 within 0.1% (terminal on all +0.0069%, the largest +0.0285%) (load 11 to 24) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- build/patches.zig | 32 +++++++++++- docs/ghostty-page-size.md | 128 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 159 insertions(+), 1 deletion(-) create mode 100644 docs/ghostty-page-size.md diff --git a/build/patches.zig b/build/patches.zig index d5ac7372..f58fb926 100644 --- a/build/patches.zig +++ b/build/patches.zig @@ -245,11 +245,41 @@ const ghostty_kitty = [_]Edit{ }, }; +/// ghostty's terminal page (src/terminal/page.zig): a page's size is +/// rounded to 4 KiB on every target, not to the OS page (4 KiB on Linux +/// and FreeBSD, 16 KiB on an Apple aarch64 Mac). The same bytes must give +/// the same emulator on every machine a client runs on, and the rounding +/// decides how many rows a page holds and how much room its style and link +/// tables grow to, so how many history rows the 16 MiB scrollback keeps: +/// a Mac had fewer than Linux once it was full, which the digest saw +/// (docs/ghostty-page-size.md). On Linux and FreeBSD this changes nothing; +/// a Mac maps whole 16 KiB pages under a length that is not one, up to +/// 12 KiB a page left unused, and ghostty's assertions that a page's +/// length is a whole number of OS pages (page.zig, mem.zig) ask for 4 KiB. +const ghostty_page = [_]Edit{ + .{ + .old = " const total_size = alignForward(usize, meta_end, std.heap.page_size_min);\n", + .new = " const total_size = alignForward(usize, meta_end, 4 << 10); // pardes (build/patches.zig)\n", + }, + .{ + .old = " assert(l.total_size % std.heap.page_size_min == 0);\n", + .new = " assert(l.total_size % (4 << 10) == 0); // pardes (build/patches.zig)\n", + }, +}; +const ghostty_mem = [_]Edit{.{ + .old = " assert(memory.len % std.heap.page_size_min == 0);\n", + .new = " assert(memory.len % (4 << 10) == 0); // pardes (build/patches.zig): a page's size\n", + .count = 2, +}}; + pub fn ghosttyKitty(b: *std.Build, patch: *std.Build.Step.Compile, dep: *std.Build.Dependency, vt: *std.Build.Module) void { const files = b.addWriteFiles(); // The rest of src as it is; fonts are the app's, not the library's. - _ = files.addCopyDirectory(dep.path("src"), "", .{ .exclude_extensions = &.{ "graphics_image.zig", ".ttf", ".otf" } }); + // ("terminal/page.zig" leaves terminal/snapshot/page.zig in.) + _ = files.addCopyDirectory(dep.path("src"), "", .{ .exclude_extensions = &.{ "graphics_image.zig", "terminal/page.zig", "terminal/mem.zig", ".ttf", ".otf" } }); _ = files.addCopyFile(apply(b, patch, dep, "src/terminal/kitty/graphics_image.zig", &ghostty_kitty, "ghostty_kitty.zig"), "terminal/kitty/graphics_image.zig"); + _ = files.addCopyFile(apply(b, patch, dep, "src/terminal/page.zig", &ghostty_page, null), "terminal/page.zig"); + _ = files.addCopyFile(apply(b, patch, dep, "src/terminal/mem.zig", &ghostty_mem, null), "terminal/mem.zig"); vt.root_source_file = files.getDirectory().path(b, "lib_vt.zig"); } diff --git a/docs/ghostty-page-size.md b/docs/ghostty-page-size.md new file mode 100644 index 00000000..6e65f36a --- /dev/null +++ b/docs/ghostty-page-size.md @@ -0,0 +1,128 @@ +# ghostty: a terminal's state depends on the OS page size + +A report for upstream (https://github.com/ghostty-org/ghostty), against +the commit pardes pins (83fb95624b04, 1.4.0, `build.zig.zon`). pardes +patches its fetched copy at build time (build/patches.zig, `ghostty_page` +and `ghostty_mem`) until it is fixed there, if upstream wants it fixed. + +## What happens + +A page's memory is rounded up to the OS page (`src/terminal/page.zig`, +`Page.layout`): + +```zig +const total_size = alignForward(usize, meta_end, std.heap.page_size_min); +``` + +`page_size_min` is 4 KiB on x86-64 and aarch64 Linux, FreeBSD and x86-64 +macOS, and 16 KiB on aarch64 macOS (Zig's `std/heap.zig`). The rounding is +not only slack: `Capacity.adjust` fills the rounded size with rows +(`availableBytesForGrid` is `total_size` less the metadata), and a style +table that grows is sized to fill it too. A standard page is 401,408 bytes +on Linux and 409,600 on an Apple silicon Mac. The scrollback limit +(`max_scrollback_bytes`) counts these bytes and prunes a whole page at a +time, so the same bytes fed to two terminals of the same size keep +different history on the two machines, and the snapshot of either +records its own capacity hints. + +pardes meets it because a client of a session runs its own emulator on +the pty's bytes: a Mac client of a Linux session must end with the +session's terminal, row for row. + +## Measured + +A driver fed eight streams through pardes's own wrapper +(`core/term/terminal.zig`), at 120x40, in reads of 4,096 and 65,536 bytes, +resized to 61x43 at a third and back at two thirds; then the hash of +pardes's per-unit digest (the active screen's text, the history's extent, +the view, the cursor) and of ghostty's full snapshot. Linux x86-64 (SIMD +on and off) and FreeBSD 15.1 amd64 gave the same lines; the Mac +(Darwin 25.6, arm64): + +| stream | digest | snapshot | history rows, Linux / Mac | +|---|---|---|---| +| shell, 90 KB | equal | differs (a style capacity hint, 388 / 397, and its record's CRC) | 0 / 0 | +| TUI, 31 KB | equal | equal | 0 / 0 | +| source text, 3.1 MB | differs | differs | 25,323 / 25,264 | +| build logs, 1.6 MB | differs | differs | 15,531 / 15,495 | +| heavy colour and links, 10 MB | differs | differs | 14,201 / 13,024 | +| a colour a cell, a link a word, stacked marks, 9 MB | differs | differs | 4,296 / 3,716 | +| kitty images, raw RGBA, 8.4 MB | equal | equal | 0 / 0 | + +The active screen's text, the cursor and the modes are the same on both; +what differs is how much history is kept and, on the last stream, which +links were dropped for lack of room in a page (19,002 `start_hyperlink +OutOfSpace` on Linux, 19,750 on the Mac). The smallest streams that show +it: the first 601,027 bytes of the source text (the first prune) for the +history, the first 11,690 bytes of the shell stream (its page's style +table grows) for the snapshot alone. + +The same driver built for Linux with `std.options.page_size_min = 16 KiB` +gives the Mac's lines exactly, digest and snapshot, on every stream: the +page size is the whole cause. + +## The fix + +Round a page's size to 4 KiB on every target, whatever the OS page is: + +```diff +--- a/src/terminal/page.zig ++++ b/src/terminal/page.zig +@@ Page.layout +- const total_size = alignForward(usize, meta_end, std.heap.page_size_min); ++ const total_size = alignForward(usize, meta_end, 4 << 10); +@@ Page.init +- assert(l.total_size % std.heap.page_size_min == 0); ++ assert(l.total_size % (4 << 10) == 0); +--- a/src/terminal/mem.zig ++++ b/src/terminal/mem.zig +@@ decommit, recommit +- assert(memory.len % std.heap.page_size_min == 0); ++ assert(memory.len % (4 << 10) == 0); +``` + +Why the Mac is the one that changes: on Linux and FreeBSD, where +`page_size_min` is 4 KiB, the three lines are what they were, so their +terminals are byte for byte what they were (the same history, the same +cost); only an Apple silicon Mac's pages shrink to Linux's sizes. + +Why a Mac can: the length of a page's memory need not be a whole number of +OS pages. A page's memory is `mmap`ed (`Page.init`, `AllocPosix`) or a +pool item allocated alone by the page allocator (`UntouchedPool`, ghostty's +tagged allocator on Darwin, which rounds the mapping up to whole pages and +unmaps it the same way); the pointer stays 16 KiB aligned, as its type +says; only the length is shorter than the mapping. `madvise` (`decommit`, +`recommit`: `FREE_REUSABLE`, `FREE_REUSE`) acts on whole pages, and the +last page of a mapping is that page's alone, the slack included. What +asked for whole OS pages were three assertions, which now ask for 4 KiB: +in a safe build they failed at once on a Mac; in a fast one they were +promises to the optimiser. Nothing else in ghostty's terminal, its page +pool, its compression or its snapshot loader reads the rounding. + +With it, the Mac gives Linux's lines on every stream (and with the PNG fix +of docs/zstbi-fp-contract.md, the PNG stream too). + +## What it costs + +Nothing on Linux and FreeBSD. On an Apple silicon Mac a page's mapping +keeps up to 12 KiB it does not use (8 KiB for a standard page: 401,408 +bytes in 409,600), never touched, so never resident; the scrollback's +16 MiB budget counts the 4 KiB-rounded size, so a Mac now keeps Linux's +history (above: 25,323 rows of source text, 14,201 of heavy colour, where +it kept 25,264 and 13,024). + +Measured with the Edit: on Linux and FreeBSD the cross-check driver's +eighteen lines are the lines it gave before, page counts and page bytes +included; pardes-perf's per-operation counts are within 0.03% of the +base's (its terminal cells +0.007%); on the Mac a ReleaseSafe build of +the driver runs all eight streams, the full scrollbacks' pruning and +page reuse included, with no assertion, and gives Linux's lines. + +## Upstream today + +Not read beyond what is on this machine (no network). The pin, 83fb956 +(1.4.0), has the rounding at `page.zig:1770`. The newest other copy here, +`~/05-genizah/ghostty` at its `main` (e8e7fea1, 2026-06-16, 1.3.2-dev), is +OLDER than the pin and has the same line (`page.zig:1753`). So moving the +pin is no fix as far as can be seen from here; whether upstream changed +it after 1.4.0 is not known. -- cgit v1.3 From 406f34120e3013c1900abfadb7a812dfd54ba89e Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 19 Nov 2026 22:31:10 -0300 Subject: build: no fused multiply-add in zstbi's resize (build/patches.zig `zstbi_cut`: `#pragma STDC FP_CONTRACT OFF`, docs/zstbi-fp-contract.md), so a kitty PNG over 1280 pixels downscales to the same pixels on an Apple silicon Mac as on Linux and FreeBSD, as a client that replays its session's bytes needs: clang contracts `a * b + c` where the CPU has a fused multiply-add, aarch64 always does (the Mac binary had 98 fmadd/fmla in stbir__resize_arbitrary and stbir__resample_horizontal_downsample; the x86-64 ones have none), a fused one rounds once, and the two downscaled pictures of the cross-check's PNG stream came out other pixels on the Mac (the snapshot differed; images are not in the digest) while the one under the bound and raw RGBA did not; with the pragma the Mac's are Linux's; the proof, the cross-check driver built from this tree (and the change before) with no patch of its own (only its step added to a scratch copy): its 18 lines (eight streams by two read sizes, two at 7 bytes: digest and full snapshot after two resizes) the same on Linux x86-64, FreeBSD 15.1 amd64 and the Mac (Darwin 25.6 arm64) (.scratch/sketch/reports/pardes-term-xcheck.md, "Landed"); no zstbi or stb upstream is on this machine to compare; tui term-test 15/15, kitty-test 45/45, core-test 848/991 (143 skipped), shell-test 1027/1030, image-harness and kitty-harness pass; gui unit-test 1625/1629 (4 skipped; the perf check's BaselineHarnessMismatch, the base's), image-harness and kitty-harness pass; the macOS library builds for Linux and aarch64-macos, the FreeBSD tui builds (load 19 to 47); the frame and perf gate (gpu/xcheck-c3, against tree1, with the change before): 77/77 frames byte-identical, perfab corpus2x -0.076%, perfops 97 of 97 within 0.1% Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- build/patches.zig | 8 +++++- docs/zstbi-fp-contract.md | 66 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 docs/zstbi-fp-contract.md diff --git a/build/patches.zig b/build/patches.zig index f58fb926..3d956d26 100644 --- a/build/patches.zig +++ b/build/patches.zig @@ -175,8 +175,14 @@ pub fn vaxis(b: *std.Build, patch: *std.Build.Step.Compile, vaxis_dep: *std.Buil /// zstbi with stb_image and its writer cut out: of it only its resize is /// left, for a terminal PNG's downscale (build/core.zig, "One PNG /// decoder"). zstbi.deinit still resets the reader's and the writer's flip -/// flags, and Image.deinit frees the resize's output. +/// flags, and Image.deinit frees the resize's output. And no fused +/// multiply-add in the resize: clang contracts `a * b + c` where the CPU +/// has one (aarch64 always does), which rounds once, so a PNG downscaled +/// on an Apple silicon Mac came out pixels apart from Linux's, and the same +/// bytes must give the same terminal on every machine a client runs on +/// (docs/zstbi-fp-contract.md). const zstbi_cut = [_]Edit{ + .{ .old = "#include \n", .new = "#include \n#pragma STDC FP_CONTRACT OFF\n" }, .{ .old = "#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n", .new = "void stbi_set_flip_vertically_on_load(int flag) { (void)flag; }\nvoid stbi_image_free(void *p) { zstbiFreePtr(p); }\n" }, .{ .old = "#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n", .new = "void stbi_flip_vertically_on_write(int flag) { (void)flag; }\n" }, }; diff --git a/docs/zstbi-fp-contract.md b/docs/zstbi-fp-contract.md new file mode 100644 index 00000000..95c067fd --- /dev/null +++ b/docs/zstbi-fp-contract.md @@ -0,0 +1,66 @@ +# stb_image_resize: a downscale's pixels depend on the CPU's fused multiply-add + +A report for upstream (https://github.com/zig-gamedev/zstbi, which vendors +nothings/stb's `stb_image_resize.h` v0.97), against the commit pardes pins +(6b9bea1f, `build.zig.zon`). pardes patches its fetched copy at build time +(build/patches.zig, `zstbi_cut`) until it is fixed there, if upstream wants +it fixed. + +## What happens + +pardes downscales a kitty graphics PNG over 1280 pixels with zstbi's +`stbir_resize_uint8` (core/term/TerminalImages.zig, `decodePng`). The +resize is plain C on floats, with no SIMD of its own, and clang compiles C +with `-ffp-contract=on`: where the target has a fused multiply-add, +`a * b + c` becomes one instruction that rounds once instead of twice. +aarch64 always has one; the x86-64 targets pardes builds for here do not +use one. The aarch64 macOS binary has 66 `fmadd`/`fmla` in +`stbir__resize_arbitrary` and 32 in `stbir__resample_horizontal_downsample`; +the x86-64 Linux and FreeBSD binaries have no `vfmadd` anywhere. So the same +PNG downscales to pixels a step apart on an Apple silicon Mac. + +pardes meets it because a client of a session runs its own emulator on the +pty's bytes: a Mac client of a Linux session must end with the session's +terminal, and a join compares the snapshot (which holds each image's +pixels) of the two. + +## Measured + +Three PNGs sent by direct data (`f=100`): 1601x1203 (downscaled to +1280x961), 700x2001 (to 447x1280) and 333x257 (not downscaled). On Linux +x86-64 (SIMD on and off) and FreeBSD 15.1 amd64 the three images' pixels +were the same; on the Mac (Darwin 25.6, arm64) the two downscaled ones +differed and the third was the same, as were two 1024x768 images sent as +raw RGBA (`f=32`). pardes's per-unit digest does not cover images, so only +the snapshot differed. + +## The fix + +Contraction off for the whole translation unit, at the top of zstbi's C file: + +```diff +--- a/src/zstbi.c ++++ b/src/zstbi.c +@@ -1,3 +1,4 @@ + #include ++#pragma STDC FP_CONTRACT OFF +``` + +(`-ffp-contract=off` in zstbi's build flags is the same.) With it the Mac +binary has no fused multiply-add in `stbir_*`, and the Mac's pixels are +Linux's: the three images, and the snapshot (with the page fix of +docs/ghostty-page-size.md, every stream's). + +## What it costs + +A multiply and an add where there was one instruction, in a resize made +once per image sent (a 1601x1203 picture's), on aarch64 only: not +measured, as nothing else of pardes runs it. + +## Upstream today + +Not read beyond what is on this machine (no network): no copy of zstbi or +stb is in `~/05-genizah`. The three zstbi copies in `zig-pkg/` (the pin and +two others) all vendor `stb_image_resize.h` v0.97 with no pragma. stb's own +successor, `stb_image_resize2.h`, has SIMD paths of its own; moving to it +would be another question of the same kind, not a fix of this one. -- cgit v1.3