From 5af775e9817395af39792cc609b832394d4a4fb8 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 30 Oct 2026 15:15:01 -0300 Subject: replica: what only the authority holds, a step reads off the tape (tape.authority): the store's closed panes and Recent, a script's hold on a pane's events, the 9P socket, the session's config directory and startup file; a replica's own are never read, and never put back by a rollback The Panes picker's closed rows, Recent's rows, a closed pane brought back (a Look at @pN, a Panes row), a jump to a closed file and the +Jumps rows read `p.store` and `p.recent`, `.authority` state a replica keeps on its own: its store has no file, its Recent only what it replayed since it joined. The rows made of them went into digested state, so every client of a session diverged together after a Del (H4), every client that joined after one diverged at its first unit forever (H11: trackJump dropped a closed file's jumps at every step when Recent did not know the file), a client's Del of a file the session's Recent knew made the stat the session skipped (H12: noteClosed looked in Recent first), and a client on another machine read its own store (H13). - tape.authority: poison, then a value read: the authority's answer is taped, a replay takes it, a speculation waits for it. One site, `.authority`. - Readers through it: Query's Recent and closed-pane rows, Store.reopen's record, Pardes.recentByHash (jumps, +Jumps), mouse.reportRange's readers check (a script reading a pane's events takes a look or exec: `pane.fs.readers`, the 9P server's), Tty9p's socket check, Pardes.configDir and startupPath (ThemeFile, DumpThemes, Config, DumpConfig, an init file saved), DumpConfig's dump directory. - trackJump no longer reads Recent at every step: a closed file's jump stays; the jump to it drops that file's entries when Recent has forgotten it, as when the file is gone. - noteClosed asks the host (recentKeeps, a taped stat) before it looks in Recent: the same syscall on every side. - The tty toggle, read on every key, is session state: Pardes.tty_toggle, from the options when the core is made, dumped. - The rollback copy no longer saves `store` and `recent` (rollback.zig `unsaved`): their bytes put back pointed at lists the host's heap (recentGpa) had freed, which the epoch never holds. A speculated Del then a Panes listing read a freed name (H8, the segfault). Tests, each failing before: a rollback leaves the store and Recent as a speculation left them; a replica joined after a pane closed has the session's jump to it, its Panes and Recent rows, asked by either (and the variant hunt's Recent written by another window); a replica's Del of a file its session's Recent knows asks the host what the session asked. Co-Authored-By: Claude Opus 5.5 --- src/Output.zig | 10 ++++-- src/Query.zig | 21 +++++++----- src/Store.zig | 46 ++++++++++++++++++++----- src/builtins.zig | 4 +-- src/colors.zig | 5 +-- src/echo.zig | 2 +- src/exec.zig | 9 +++-- src/look.zig | 2 +- src/mouse.zig | 15 ++++++-- src/pardes.zig | 75 ++++++++++++++++++++++++++++++---------- src/replica.zig | 102 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/rollback.zig | 51 ++++++++++++++++++++++++++-- src/tape.zig | 19 +++++++++++ 13 files changed, 311 insertions(+), 50 deletions(-) (limited to 'src') diff --git a/src/Output.zig b/src/Output.zig index 359db1cf..7c8b7f59 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -1005,6 +1005,12 @@ test "full Help renders builtin rows, a call hierarchy guide, then language keys try std.testing.expect(std.mem.indexOf(u8, group, "Callstack: static caller chains") != null); } +/// Where a dump goes by default, as the session's environment says (the +/// authority's, `tape.authority`): in `buf`. +fn dumpDirectory(buf: []u8) []const u8 { + return pardes.dump.defaultDirectory(buf) orelse ""; +} + pub fn openConfig(p: *Pardes, id: usize) !void { var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); @@ -1015,8 +1021,8 @@ pub fn openConfig(p: *Pardes, id: usize) !void { try p.locations_config.write(&located.writer); try config.Runtime.writeReport(&out.writer, .{ .locations = located.written(), - .default_dump_dir = if (host_fs) (pardes.dump.defaultDirectory(&dir_buf) orelse "") else "", - .startup_config_path = p.opts.startup_config_path, + .default_dump_dir = if (host_fs) pardes.tape.authority(dumpDirectory, .{@as([]u8, &dir_buf)}) else "", + .startup_config_path = p.startupPath(), .platform = builtins.viewPlatform(p), .theme_name = p.theme().name, .theme_file = pardes.colors.loadedThemeFile(p), diff --git a/src/Query.zig b/src/Query.zig index 49f58a0e..2f417a68 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -48,6 +48,7 @@ const memory = @import("memory.zig"); const Names = @import("Names.zig"); const Places = @import("Places.zig"); const Stream = @import("Stream.zig"); +const Store = @import("Store.zig"); const Surface = @import("surface.zig").Surface; const Pardes = pardes.Pardes; const Pane = panes.Pane; @@ -591,12 +592,9 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz if (p.fs.serving) Stream.step(p); }, .recent => { - // Every window's files: what the others wrote since, read. - p.store.refresh(p); var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); - Output.recentText(p, &out.writer, true) catch {}; - var lines = std.mem.splitScalar(u8, out.written(), '\n'); + var lines = std.mem.splitScalar(u8, pardes.tape.authority(recentRows, .{ p, &out }), '\n'); while (lines.next()) |ln| { if (ln.len == 0) continue; const rel = Names.relative(ln, dir); @@ -617,10 +615,9 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz } // Then the panes this session closed, the latest first, each // `(closed)` and dimmer (makeNameRows): Enter brings one back - // where it was. Its name alone is matched, not the word. - var i = p.store.closed.items.len; - while (i > 0) : (i -= 1) { - const c = p.store.closed.items[i - 1]; + // where it was. Its name alone is matched, not the word. The + // store's, which a replica has from the authority. + for (pardes.tape.authority(Store.closedNames, .{p})) |c| { var buf: [4096 + 48]u8 = undefined; const row = std.fmt.bufPrint(&buf, config.pane_addr ++ "{d} {s}" ++ closed_word, .{ c.serial, Names.relative(c.name, dir) }) catch continue; const key_at = std.mem.indexOfScalar(u8, row, ' ').? + 1; @@ -652,6 +649,14 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz /// What a Panes row of a closed pane ends with. const closed_word = " (closed)"; +/// Every window's files, as a Recent query lists them: what the others +/// wrote since, read first. The store's (`tape.authority`): in `out`. +fn recentRows(p: *Pardes, out: *std.Io.Writer.Allocating) []const u8 { + p.store.refresh(p); + Output.recentText(p, &out.writer, true) catch {}; + return out.written(); +} + /// The owner's declarations, from a parse that already exists: its sticky /// headers' (TreeContext) at this revision, or the locations cache's. None /// is made here, on the loop, unless `small` and the text is small: a diff --git a/src/Store.zig b/src/Store.zig index 36215234..9c726705 100644 --- a/src/Store.zig +++ b/src/Store.zig @@ -468,6 +468,21 @@ fn unlist(s: *Store, gpa: std.mem.Allocator, serial: u32) void { }; } +/// A closed pane as Panes lists it: its serial and what its row shows. +pub const Named = struct { serial: u32, name: []const u8 }; + +/// This session's closed panes, the latest first (scratch; the names the +/// store's): what a step lists of them (`tape.authority`). +pub fn closedNames(p: *Pardes) []const Named { + const items = p.store.closed.items; + const out = p.scratch.allocator().alloc(Named, items.len) catch return &.{}; + for (out, 0..) |*o, i| { + const c = items[items.len - 1 - i]; + o.* = .{ .serial = c.serial, .name = c.name }; + } + return out; +} + /// The closed pane with this serial, if this session has it. pub fn closedBySerial(s: *const Store, serial: u32) ?*Closed { for (s.closed.items) |*c| if (c.serial == serial) return c; @@ -785,12 +800,10 @@ fn compact(s: *Store, p: *Pardes, file: File, st: File.Stat, path: []const u8) v /// from `from`. False when it is not this session's, or its record is gone /// or bad; the keyboard on it otherwise. pub fn reopen(s: *Store, p: *Pardes, serial: u32, from: usize) bool { - s.refresh(p); const gpa = p.recentGpa(); - const place = (s.closedBySerial(serial) orelse return false).*; - const body = s.bodyOf(p, place) orelse return false; - // Read from the file: this call's to free (`unlist` frees one held). - defer if (place.body.len == 0) gpa.free(body); + // The store's: a replica has the authority's (`tape.authority`). + const place = pardes.tape.authority(record, .{ s, p, serial }) orelse return false; + const body = place.body; const m = parseMeta(body) orelse return false; const free = p.freeSlot() orelse { p.reportError(from, "Panes", error.NoPaneSlots); @@ -826,6 +839,21 @@ pub fn reopen(s: *Store, p: *Pardes, serial: u32, from: usize) bool { return true; } +/// Where a closed pane goes back, and its record's body (scratch). +pub const Record = struct { gainer: u32, below: bool, owner: u32, rows: u16, body: []const u8 }; + +/// Closed pane `serial`'s record, the store read on first; null when it is +/// not this session's, or its record is gone or bad. +fn record(s: *Store, p: *Pardes, serial: u32) ?Record { + s.refresh(p); + const c = (s.closedBySerial(serial) orelse return null).*; + const body = s.bodyOf(p, c) orelse return null; + // Read from the file: this call's to free (`unlist` frees one held). + defer if (c.body.len == 0) p.recentGpa().free(body); + const copy = p.scratch.allocator().dupe(u8, body) catch return null; + return .{ .gainer = c.gainer, .below = c.below, .owner = c.owner, .rows = c.rows, .body = copy }; +} + /// A closed pane's record body: held here, or read from the file and /// checked against its CRC (gpa; the caller frees it when it is not /// `c.body`). @@ -855,8 +883,9 @@ fn bodyOf(s: *Store, p: *Pardes, c: Closed) ?[]u8 { return body; } -/// `@p` naming a pane this session closed: its serial. -pub fn closedAddress(s: *const Store, word: []const u8) ?u32 { +/// `@p` alone, the pane and no place in it: its serial, for a pane +/// this session closed to come back by (`reopen` says whether it did). +pub fn closedAddress(word: []const u8) ?u32 { const addr = @import("config.zig").pane_addr; if (!std.mem.startsWith(u8, word, addr)) return null; const digits = word[addr.len..]; @@ -865,8 +894,7 @@ pub fn closedAddress(s: *const Store, word: []const u8) ?u32 { } else digits.len; // `@p7` alone, or `@p7:` with nothing after it: the pane, no place in it. if (end == 0 or (end < digits.len and !(digits[end] == ':' and end + 1 == digits.len))) return null; - const serial = std.fmt.parseInt(u32, digits[0..end], 10) catch return null; - return if (s.closedBySerial(serial) != null) serial else null; + return std.fmt.parseInt(u32, digits[0..end], 10) catch null; } // ---- tests ---- diff --git a/src/builtins.zig b/src/builtins.zig index 69ac3113..97cdc5a0 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -941,7 +941,7 @@ pub const DumpThemes = struct { pub const enabled = pardes.hosted; pub fn run(c: Ctx) void { if (comptime enabled) { - if (c.p.opts.config_dir == null) { + if (c.p.configDir() == null) { c.p.reportError(c.id, "dump themes", error.NoConfigDirectory); return; } @@ -1607,7 +1607,7 @@ pub const Help = struct { pub const Config = struct { pub const scope: Scope = .session; pub fn run(c: Ctx) void { - const path = c.p.opts.startup_config_path orelse + const path = c.p.startupPath() orelse return c.p.reportFailure(c.id, "Config: no startup file here: no configuration directory"); var real_buf: [4096]u8 = undefined; const real = if (pardes.filesystem.resolveOs(path, &real_buf)) |r| r.path else null; diff --git a/src/colors.zig b/src/colors.zig index c016434b..cc417ccb 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -677,14 +677,15 @@ pub fn requestThemeFile(p: *Pardes, id: usize, argument: []const u8) void { } const absolute = std.fs.path.isAbsolute(input); - if (!absolute and p.opts.config_dir == null) { + const config_dir = if (absolute) null else p.configDir(); + if (!absolute and config_dir == null) { p.reportError(id, "theme file", error.NoConfigDirectory); return; } var joined: [4095]u8 = undefined; const resolved = if (absolute) input else path: { - const dir = p.opts.config_dir.?; + const dir = config_dir.?; const separator = if (dir.len > 0 and dir[dir.len - 1] != std.Io.Dir.path.sep) std.Io.Dir.path.sep_str else ""; break :path std.fmt.bufPrint(&joined, "{s}{s}{s}", .{ dir, separator, input }) catch { p.reportError(id, "theme file", error.PathTooLong); diff --git a/src/echo.zig b/src/echo.zig index 4acd3d11..4560930c 100644 --- a/src/echo.zig +++ b/src/echo.zig @@ -500,7 +500,7 @@ fn forwarded(c: *const Pardes, ev: pardes.Event) bool { else => return false, }; if (k.cp == Key.escape) return false; - return !(k.ctrl and (k.cp == c.opts.tty_toggle or k.cp == 'v' or k.cp == 'V')); + return !(k.ctrl and (k.cp == c.tty_toggle or k.cp == 'v' or k.cp == 'V')); } fn blank(cp: u21) bool { diff --git a/src/exec.zig b/src/exec.zig index e1c13daa..c5218279 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -411,11 +411,16 @@ pub fn spawnTty(p: *Pardes, from: usize) ?*Pane { pub fn spawnV9fsTty(p: *Pardes, from: usize) void { if (comptime !hosted or @import("builtin").os.tag != .linux) return p.reportError(from, "Tty9p", error.LinuxRequired); - if (p.fs.socket_path.len == 0) + // The 9P server's: a replica has the authority's answer. + if (!pardes.tape.authority(servesSocket, .{p})) return p.reportError(from, "Tty9p", error.SessionSocketRequired); _ = spawnTtyWithMount(p, from, true); } +fn servesSocket(p: *Pardes) bool { + return p.fs.socket_path.len != 0; +} + fn spawnTtyWithMount(p: *Pardes, from: usize, v9fs: bool) ?*Pane { // No pane asking (an empty window's tag): the session's directory, as // New's scratch is. @@ -1009,7 +1014,7 @@ pub fn applyStartupConfig(p: *Pardes) void { /// setting lines: a command in it (`Newcol`) is the session's start, and /// would not be right twice. pub fn reapplyInitFile(p: *Pardes, path: []const u8, text: []const u8) void { - const init_path = p.opts.startup_config_path orelse return; + const init_path = p.startupPath() orelse return; if (!std.mem.eql(u8, init_path, path)) return; applyInitText(p, text, true); } diff --git a/src/look.zig b/src/look.zig index 226c96e3..09a22266 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1816,7 +1816,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { // `@p` names no open pane: one this session closed comes // back where it was (Store.reopen), any other is a miss, said. if (t.id >= MAX_PANES or p.panes[t.id] == null) { - if (p.store.closedAddress(pl.path)) |serial| if (p.store.reopen(p, serial, id)) return; + if (@TypeOf(p.store).closedAddress(pl.path)) |serial| if (p.store.reopen(p, serial, id)) return; return missed(p, id, "no pane {s}", .{pl.path[0..@min(pl.path.len, 32)]}); } const target = p.panes[t.id].?; diff --git a/src/mouse.zig b/src/mouse.zig index 67ebf7cf..3281f48a 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -990,10 +990,17 @@ fn reportGesture( operand: exec.PointerOperand, chord_arg: ?[]const u8, ) bool { - if ((p.panes[id] orelse return false).fs.readers == 0) return false; return reportRange(p, id, cmd, text, on_tag, gestureRange(p, id, text, on_tag, operand), chord_arg); } +/// Whether a script reads pane `id`'s events, and so takes its looks and +/// execs: the 9P server's, the authority's alone (a replica has its +/// answer, `tape.authority`). +fn readsEvents(p: *Pardes, id: usize) bool { + const pane = p.panes[id] orelse return false; + return pane.fs.readers != 0; +} + /// An event reader told of a look or an exec of `text` at `range` of the /// tag or body, by a click or a key alike: false when the pane has none. pub fn reportRange( @@ -1006,7 +1013,7 @@ pub fn reportRange( chord_arg: ?[]const u8, ) bool { const scripted = p.panes[id] orelse return false; - if (scripted.fs.readers == 0) return false; + if (!pardes.tape.authority(readsEvents, .{ p, id })) return false; const is_look = cmd == config.look_cmd; const action: ctlfs.events.Action = if (is_look) (if (on_tag) .tag_look else .body_look) @@ -1020,7 +1027,9 @@ pub fn reportRange( if (is_look) { if (!named and std.mem.indexOfAny(u8, text, "/.:") != null) flag |= ctlfs.events.flag_filename; } else if (chord_arg != null) flag |= ctlfs.events.flag_chorded; - if (!ctlfs.events.noteAction(p, id, action, range.q0, range.q1, flag, text)) return false; + // Taken whether or not this process's server has the reader: the + // session's said it has (a replica's has none). + _ = ctlfs.events.noteAction(p, id, action, range.q0, range.q1, flag, text); // A chorded exec's argument follows as two records, its text and where // it came from (`file:#q0,#q1`, empty when that is not known), as acme // sends them (exec.c:182-188); the pane keeps it for the write-back. diff --git a/src/pardes.zig b/src/pardes.zig index f0d2cd0c..36ce6bdb 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -857,7 +857,7 @@ test "Togglettymode builtin and keyboard chord share mode transitions including try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); try std.testing.expect(p.executeBuiltinLine(0, "Togglettymode")); try std.testing.expectEqual(Text.Mode.normal, pane.body.mode); - p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); + p.update(.{ .key = .{ .cp = p.tty_toggle, .ctrl = true } }); try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); // The tag has its own mode: the body keeps tty while the tag is typed into. tagline.enterTag(p, pane); @@ -867,7 +867,7 @@ test "Togglettymode builtin and keyboard chord share mode transitions including try std.testing.expectEqual(Text.Mode.normal, pane.body.mode); try std.testing.expect(pane.focus == .body); tagline.enterTag(p, pane); - p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); + p.update(.{ .key = .{ .cp = p.tty_toggle, .ctrl = true } }); try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); try std.testing.expect(pane.focus == .body); @@ -4732,6 +4732,10 @@ pub const Pardes = struct { /// The views no frontend here draws: a replica client's, which its own /// process draws (src/replica.zig). A pump skips them. undrawn: u8 = 0, + /// The Ctrl key into a terminal's tty mode and out (`--tty-toggle`): the + /// session's, taken from its options when it is made, so a dump carries + /// it to a replica, whose own options are its process's. + tty_toggle: u21 = config.tty_toggle_default, /// per-update scratch (paneCursorLines, selection text); reset each update scratch: std.heap.ArenaAllocator, /// The arena each frame's Surface text is built in, reset by `pump`. Hosts @@ -4797,6 +4801,7 @@ pub const Pardes = struct { .tree_sitter_gpa = opts.tree_sitter_allocator orelse gpa, .opts = opts, .windowed = opts.windowed, + .tty_toggle = opts.tty_toggle, .col_tags = @splat(.{ .what = .column, .gpa = gpa }), .global_tag = .{ .what = .workspace, .gpa = gpa }, .fs = .{}, @@ -4989,7 +4994,10 @@ pub const Pardes = struct { /// Recent keeps it. fn noteClosed(p: *Pardes, pane: *const Pane) void { const d = recentPlace(pane) orelse return; - if (p.recent.get(d.path) == null and !recentKeeps(d.path)) return; + // The host asked first, always: what Recent holds is the + // authority's, and a step that asked only when it did not know the + // file would ask on one side and not the other. + if (!recentKeeps(d.path) and p.recent.get(d.path) == null) return; p.recent.closedSel(p.recentGpa(), d.path, d.line, d.col, d.aline, d.acol); } @@ -5024,9 +5032,38 @@ pub const Pardes = struct { }; } - /// The recent entry a closed jump names, by its path's hash. - pub fn recentByHash(p: *const Pardes, hash: u64) ?recent_files.Entry { - for (p.recent.entries.items) |e| if (std.hash.Wyhash.hash(0, e.path) == hash) return e; + /// The session's configuration directory and startup file, as a step + /// reads them: its process's options, so the authority's + /// (`tape.authority`); a replica's are its own process's. + pub fn configDir(p: *Pardes) ?[]const u8 { + return tape.authority(optsConfigDir, .{p}); + } + + pub fn startupPath(p: *Pardes) ?[]const u8 { + return tape.authority(optsStartupPath, .{p}); + } + + fn optsConfigDir(p: *Pardes) ?[]const u8 { + return p.opts.config_dir; + } + + fn optsStartupPath(p: *Pardes) ?[]const u8 { + return p.opts.startup_config_path; + } + + /// The recent entry a closed jump names, by its path's hash, its path + /// in scratch. Recent is the authority's (every window of its user + /// writes it): a replica has its answer (`tape.authority`). + pub fn recentByHash(p: *Pardes, hash: u64) ?recent_files.Entry { + return tape.authority(recentFound, .{ p, hash }); + } + + fn recentFound(p: *Pardes, hash: u64) ?recent_files.Entry { + for (p.recent.entries.items) |e| if (std.hash.Wyhash.hash(0, e.path) == hash) { + var found = e; + found.path = p.scratch.allocator().dupe(u8, e.path) catch return null; + return found; + }; return null; } @@ -6607,7 +6644,7 @@ pub const Pardes = struct { if (header == null and pane.isTerminal() and pane.body.mode == .tty and pane.focus == .body and pane.prompt == .none) { p.leader_on = false; p.ctrl_w_pending = false; - if (key.ctrl and !key.alt and key.cp == p.opts.tty_toggle) + if (key.ctrl and !key.alt and key.cp == p.tty_toggle) return p.toggleTty(p.active); // With ProgramEsc on, bare Escape leaves only at a shell prompt // (Shift-Esc, above, always). @@ -6672,7 +6709,7 @@ pub const Pardes = struct { } return; } - const tty_toggle = key.ctrl and key.cp == p.opts.tty_toggle; + const tty_toggle = key.ctrl and key.cp == p.tty_toggle; if (pane.isTerminal() and tty_toggle) { return p.toggleTty(p.active); } @@ -7624,10 +7661,12 @@ pub const Pardes = struct { if (i == p.jcur) cur = w; // survives -> lands at w; dies -> the next one does var kept = j; const live = if (j.serial == 0) false else if (p.panes[j.pane]) |pane| pane.serial == j.serial else false; - // A file's pane closed: its entry stays, closed, while the recent - // list knows the file, and a jump to it opens it again. + // A file's pane closed: its entry stays, closed, and a jump to it + // opens it again from Recent, or drops it when Recent has + // forgotten it (`jumpBy`: Recent is the authority's, read when + // it is wanted, not at every step). if (!live) { - if (j.path_hash == 0 or p.recentByHash(j.path_hash) == null) continue; + if (j.path_hash == 0) continue; kept.serial = 0; // Open again in some pane (a look, Recent): the entry is that // pane's, and closed only while no pane has the file. @@ -7727,12 +7766,13 @@ pub const Pardes = struct { // A closed file's entry: opened again at its dot, placed as a look // places it, and the entry is that pane from here on. if (j.serial == 0) { - const e = p.recentByHash(j.path_hash) orelse return; - // Deleted since: its entries go, it is said, and the step goes - // on to the next place, never stuck on one that cannot open. - if (!recentKeeps(e.path)) { + const found = p.recentByHash(j.path_hash); + // Deleted since, or Recent has forgotten it: its entries go (the + // first said), and the step goes on to the next place, never + // stuck on one that cannot open. + if (found == null or !recentKeeps(found.?.path)) { var said: [recent_path_cap + 32]u8 = undefined; - p.setMessage(p.active, std.fmt.bufPrint(&said, "{s}: deleted, skipped", .{e.path}) catch "deleted, skipped"); + if (found) |e| p.setMessage(p.active, std.fmt.bufPrint(&said, "{s}: deleted, skipped", .{e.path}) catch "deleted, skipped"); const hash = j.path_hash; var w: usize = 0; var cur = p.jcur; @@ -7750,6 +7790,7 @@ pub const Pardes = struct { // round takes one file's entries away, so it ends. return p.jumpBy(delta); } + const e = found.?; const from = p.active; look.reopenAt(p, from, e.path, .{ .line = @max(1, j.line), .col = if (j.pdf) 0 else @max(1, j.col) }); const opened = p.panes[p.active] orelse return; @@ -9284,7 +9325,7 @@ test "raw tty forwards Ctrl letters and former global shortcuts to the child" { _ = drainWrites(p, &buf); edit.setYank(p, "register text"); for ('a'..'z' + 1) |letter| { - if (letter == p.opts.tty_toggle) continue; // editor/TTY mode shortcut + if (letter == p.tty_toggle) continue; // editor/TTY mode shortcut if (letter == 'v') continue; // the window's paste, asserted just below p.update(.{ .key = .{ .cp = @intCast(letter), .ctrl = true } }); const expected = [_]u8{@intCast(letter - 'a' + 1)}; diff --git a/src/replica.zig b/src/replica.zig index d6a2e0ef..8b1d84f4 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -3337,3 +3337,105 @@ test "a far join is sent each blob once: joined again with them on disk or in th try std.testing.expectEqual(@as(u64, 0), j.sent_bytes); endJoin(&j, &have); } + +/// A replica joined from the session's dump as it is now, between units, +/// as `Peers.join` sends it: its state, its blobs put back where they go. +fn joinedNow(a: *Authority, id: u16, view: u8) !*Replica { + const gpa = std.testing.allocator; + const was = Stepping.begin(&a.t, null); + var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; + defer blobs.deinit(a.core.gpa); + const state = try pardes.dump.dumpJoin(a.core, &blobs); + defer a.core.gpa.free(state); + tape.resync(&a.t); + was.end(); + var whole: std.ArrayListUnmanaged(u8) = .empty; + defer whole.deinit(gpa); + var pos: usize = 0; + for (blobs.items) |b| { + try whole.appendSlice(gpa, state[pos..b.at]); + try whole.appendSlice(gpa, b.bytes); + pos = b.at; + } + try whole.appendSlice(gpa, state[pos..]); + return Replica.initDump(gpa, id, view, whole.items, .{ .cols = 80, .rows = 24 }); +} + +fn agrees(a: *Authority, r: *Replica) !void { + if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); + try std.testing.expect(r.diverged == null); + try std.testing.expect(r.quiet()); + try std.testing.expectEqual(digestOf(a), r.digest()); +} + +test "a replica joined after a pane closed: the session's jump to it, its Panes and Recent rows, asked by either" { + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + defer a.deinit(); + // A file looked at and closed: a jump to it, Recent's, a closed pane. + var cwd: [std.fs.max_path_bytes]u8 = undefined; + var line: [std.fs.max_path_bytes + 32]u8 = undefined; + const dir = std.mem.span(@as([*:0]u8, @ptrCast(std.c.getcwd(&cwd, cwd.len) orelse return error.NoCwd))); + _ = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/build.zig.zon", .{dir}) }); + _ = try a.local(.{ .command = "Del" }); + try std.testing.expectEqual(@as(usize, 1), a.core.store.closed.items.len); + try std.testing.expect(a.core.njumps > 1); + // What another window of the user's wrote to the store, which the + // session read (src/variants_test.zig's case, the variant hunt's). + a.core.recent.opened(a.core.recentGpa(), try std.fmt.bufPrint(&line, "{s}/build.zig", .{dir})); + const r = try joinedNow(a, 1, 0); + defer r.deinit(); + try std.testing.expectEqual(digestOf(a), r.digest()); + r.confirm(try a.local(.{ .key = .{ .cp = 'j', .text = "j" } })); + r.confirm(try a.local(.{ .command = "Search Panes" })); + r.confirm(try a.local(.{ .command = "Search Recent" })); + try agrees(a, r); + // The replica's own: it waits for the session's rows. + for ([_][]const u8{ "Search Panes", "Search Recent" }) |asked| { + const msg = try gpa.dupe(u8, try r.input(.{ .command = asked })); + defer gpa.free(msg); + r.confirm(try a.take(msg)); + r.settle(); + } + try agrees(a, r); + // The closed pane brought back by the replica's Look at it: the + // session's record of it, off the tape. + { + const closed = try std.fmt.bufPrint(&line, "Look @p{d}", .{a.core.store.closed.items[0].serial}); + const msg = try gpa.dupe(u8, try r.input(.{ .command = closed })); + defer gpa.free(msg); + r.confirm(try a.take(msg)); + r.settle(); + try std.testing.expectEqual(@as(usize, 0), a.core.store.closed.items.len); + try agrees(a, r); + r.confirm(try a.local(.{ .command = "Del" })); + } + // A jump back onto the closed file: opened again, from Recent. + for (0..3) |_| { + const msg = try gpa.dupe(u8, try r.input(.{ .key = .{ .cp = 'o', .ctrl = true } })); + defer gpa.free(msg); + r.confirm(try a.take(msg)); + r.settle(); + } + try agrees(a, r); +} + +test "a replica's Del of a file its session's Recent knows asks the host what the session asked" { + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + defer a.deinit(); + var cwd: [std.fs.max_path_bytes]u8 = undefined; + var line: [std.fs.max_path_bytes + 32]u8 = undefined; + const dir = std.mem.span(@as([*:0]u8, @ptrCast(std.c.getcwd(&cwd, cwd.len) orelse return error.NoCwd))); + _ = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/build.zig.zon", .{dir}) }); + // Joined while it is open: in the session's Recent, in no replica's. + const r = try joinedNow(a, 1, 0); + defer r.deinit(); + const msg = try gpa.dupe(u8, try r.input(.{ .command = "Del" })); + defer gpa.free(msg); + r.confirm(try a.take(msg)); + r.settle(); + try std.testing.expectEqual(@as(usize, 1), a.core.store.closed.items.len); + try agrees(a, r); +} + diff --git a/src/rollback.zig b/src/rollback.zig index b0394d22..bb3ac2dc 100644 --- a/src/rollback.zig +++ b/src/rollback.zig @@ -399,7 +399,7 @@ pub const Copy = struct { const s = @typeInfo(T).@"struct"; inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| { if (attr.@"comptime") continue; - if (comptime (annotated(T, "local", name) or annotated(T, "derived", name)) and unsaved(name)) continue; + if (comptime (annotated(T, "local", name) or annotated(T, "derived", name) or annotated(T, "authority", name)) and unsaved(name)) continue; const at = @intFromPtr(&@field(v, name)); if (comptime walk.lengthOf(T, name) != null and @typeInfo(F) == .array) { try c.save(at, walk.lengthIn(v, comptime walk.lengthOf(T, name).?) * @sizeOf(@typeInfo(F).array.child)); @@ -436,10 +436,15 @@ fn annotatedStruct(comptime T: type) bool { /// (numbers, and a static name), and the rows a terminal was last read as /// (a grid's worth of text, emptied when a copy is taken and when it is /// put back: src/replica.zig), and a replica's predicted echo (src/echo.zig: -/// the replica's, never its core's). +/// the replica's, never its core's). And the store and Recent, a replica's +/// own: on the host's heap (Pardes.recentGpa), which the epoch never puts a +/// free off for, so their bytes put back would point at what is freed. A +/// step reads what the authority holds of them off the tape +/// (tape.authority), never a replica's. fn unsaved(comptime name: []const u8) bool { return std.mem.eql(u8, name, "effects") or std.mem.eql(u8, name, "in_q") or std.mem.eql(u8, name, "frames") or - std.mem.eql(u8, name, "shell_rows") or std.mem.eql(u8, name, "echo"); + std.mem.eql(u8, name, "shell_rows") or std.mem.eql(u8, name, "echo") or std.mem.eql(u8, name, "store") or + std.mem.eql(u8, name, "recent"); } fn annotated(comptime T: type, comptime kind: []const u8, comptime name: []const u8) bool { @@ -601,3 +606,43 @@ test "a file's location rows are pinned whole, with what they own, and come back p.deinit(); try std.testing.expectEqual(@as(usize, 0), e.live.count()); } + +/// `Look `, the name a file of the repository's, absolute. +fn lookAt(buf: []u8, name: []const u8) ![]const u8 { + var cwd: [std.fs.max_path_bytes]u8 = undefined; + const dir = std.c.getcwd(&cwd, cwd.len) orelse return error.NoCwd; + return std.fmt.bufPrint(buf, "Look {s}/{s}", .{ std.mem.span(@as([*:0]u8, @ptrCast(dir))), name }); +} + +test "a rollback leaves the store and Recent as a speculation left them: they live on the host's heap, which no copy holds" { + var e: Epoch = .{ .child = std.testing.allocator }; + defer e.deinit(); + const gpa = e.allocator(); + const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .image_allocator = gpa, .pdf_allocator = gpa, .tree_sitter_allocator = gpa, .frame_allocator = gpa }); + p.pump(.{}) catch {}; + var line: [std.fs.max_path_bytes + 16]u8 = undefined; + p.update(.{ .command = try lookAt(&line, "build.zig.zon") }); + p.update(.{ .command = "Del" }); + p.pump(.{}) catch {}; + try std.testing.expectEqual(@as(usize, 1), p.store.closed.items.len); + // Both lists full to what they hold: the next of each moves them. + p.store.closed.shrinkAndFree(p.recentGpa(), p.store.closed.items.len); + p.recent.entries.shrinkAndFree(p.recentGpa(), p.recent.entries.items.len); + const recents = p.recent.entries.items.len; + var c: Copy = .{}; + defer c.deinit(); + try c.take(&e, p); + // A speculation opens a file and closes it (a Del a replica applies at + // once), and is undone. + p.update(.{ .command = try lookAt(&line, "build.zig") }); + p.update(.{ .command = "Del" }); + p.pump(.{}) catch {}; + c.restore(); + // What the store and Recent hold is where they say it is. + try std.testing.expectEqual(@as(usize, 2), p.store.closed.items.len); + try std.testing.expect(std.mem.endsWith(u8, p.store.closed.items[1].name, "build.zig")); + try std.testing.expectEqual(recents + 1, p.recent.entries.items.len); + p.deinit(); + try std.testing.expectEqual(@as(usize, 0), e.live.count()); +} + diff --git a/src/tape.zig b/src/tape.zig index 3c8dd765..b16f39f9 100644 --- a/src/tape.zig +++ b/src/tape.zig @@ -107,6 +107,8 @@ pub const Site = enum(u16) { /// command printed (a pty/run's answer): a screen-state replica's /// emulator is the last delta's until the next. prompt, + /// What the authority alone holds and a step reads (`authority`). + authority, }; /// What the sites return. wire.semantics hashes their shape with the @@ -125,6 +127,10 @@ pub const results = .{ anyerror![]u8, anyerror!void, terminal.Told, ?pardes.ctlfs.pty.Printed, @typeInfo(@TypeOf(terminal.greeting)).@"fn".return_type.?, + // What only the authority holds (`authority`): a closed pane's record, + // Recent's entry for a closed jump, the closed panes' names. + ?@import("Store.zig").Record, ?@import("recent.zig").Entry, + []const @import("Store.zig").Named, }; /// What a host reports to the core as failed (`shell_failed`, `save_failed`, @@ -813,6 +819,19 @@ pub fn value(comptime s: Site, comptime f: anytype, args: anytype) @typeInfo(@Ty return call(s, null, f, args, false); } +/// A read of what the authority alone holds (`.authority` state a step +/// makes digested state from: the store's closed panes and Recent, which +/// every window of its user writes; the 9P server's readers and socket), +/// taped as `value` is; a speculation that reaches it waits for the +/// authority's answer, as at a host call. A replica's own is never read. +/// What it returns is the tape's arena's on a replay: `f` returns what +/// lives to the step's end (scratch, or the authority's own), and the +/// caller copies what it keeps. +pub fn authority(comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? { + poison(); + return value(.authority, f, args); +} + fn call(comptime s: Site, a: ?std.mem.Allocator, comptime f: anytype, args: anytype, comptime yields: bool) @typeInfo(@TypeOf(f)).@"fn".return_type.? { const R = @typeInfo(@TypeOf(f)).@"fn".return_type.?; comptime { -- cgit v1.3