From 18e674964e5db67d35e1cf5ded128757ced22a98 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 22 Nov 2026 21:55:10 -0300 Subject: replicas: one decision a unit, by one count in the core (pardes-term-join-11, item 2; P54, the coordinator's lean, held against the code first): `Replica.confirm` asked one question four ways from three sources ("did applying this unit write state outside the rollback copy, an emulator?"): the speculation's own observation (`Pending.terminal` from `Tape.touched`, set by `touchTerminal` at a grid it owed and at every READ of a terminal's rows), the unit's records (`tape.feedsTerminal`), a process-wide counter (`Term.writes`, seven increments, shared by every side of the soak's one process) and a dead read (`read_terminal`, always false); round 10's predicate over the records failed because no record names the unit whose `sync` reflows a grid, a load or a teardown; now the core counts its emulators' writes itself (`Pardes.outside`, a `Term.Outside`): a field, so copied with a speculation, digested and dumped, a function of the tape, the same on every side; every write of the `calls` table's WRITE rows takes it first and counts (core/Term.zig `open`, `close`, `revive`, `reload`, `feed`, `resize`, `endOutputHere`, and `replies` when it drained any), a comptime block fails the build if a WRITE row's entry does not take it (the compiler holds the call sites; S1's `calls` test holds that a new write is listed); `resize` owes under a speculation (counted, not made: the grid's guard moved there from panes.zig `resizeGrid`); a load sets it (the walk loads the field; `dumpRead` counts nothing); the one read in `confirm`: on the fast path the count's movement over the input's speculation (`Pending.outside`, a number, equal to the unit's by the path's premise: moved, the unit is replayed once on the confirmed core), on the replay paths its movement over `replayUnit` on the core that applied it (moved over a copy held ahead, the copy goes), and on the neutral path no read at all: the session's digest after the unit holds the count, so a unit that wrote an emulator never ends where it began (`feedsTerminal` deleted with its one use); the predicted echo is judged at every unit that moved it; DELETED: `Tape.touched`, both `touchTerminal`s and the read-touch in edit.zig `shellRows` (a read writes nothing outside the copy; on the one road a speculation reads the confirmed emulator), `Term.writes` and its seven increments, `feedsTerminal`, `read_terminal`; where the lean does not stretch, said and not built: a picture's pixels, a kind's state and the Store's closed list are written BY a speculation, so the fast path must let the copy go, not replay: `panesMoved`, the serials and `retiring` stay for them; the dump changes (a core field): the wire stays at 31 (its history line says so); tests: the existing path tests green (fast, neutral, ahead, owed grid, "a view that sized a terminal closing leaves nothing queued ..." among them); new: a session's reflow of a terminal's grid over a copy held ahead is the count's to decide (a unit with no output record: the copy goes, a rollback does not reflow again), and the count digested (one side's emulator written outside any unit, a colour set no other digested field shows: `partsApart` names `outside` alone); core-test 917/1079 (162 skipped), shell-test 1121/1124 (3 skipped), the gate below Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/replica.zig | 113 +++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 76 insertions(+), 37 deletions(-) (limited to 'core/replica.zig') diff --git a/core/replica.zig b/core/replica.zig index f4a3284c..0ae302e8 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -413,9 +413,10 @@ pub const Stats = struct { } }; -/// `terminal`: its speculation read a terminal or moved one's view (or a -/// terminal had the keyboard), so what it did depends on the emulator. -const Pending = struct { seq: u32, msg: []u8, spec: ?[]u8 = null, sent_ns: u64 = 0, terminal: bool = false, guess: ?tape.Guess = null }; +/// `outside`: how far its speculation moved its core's count of writes +/// outside the rollback copy (Pardes.outside): not 0, it owes an emulator +/// a write (a grid's size), which only its replay makes. +const Pending = struct { seq: u32, msg: []u8, spec: ?[]u8 = null, sent_ns: u64 = 0, outside: u64 = 0, guess: ?tape.Guess = null }; pub fn parseUnit(msg: []const u8) ?Unit { if (msg.len < unit_head) return null; @@ -690,9 +691,14 @@ pub const Replica = struct { r.stats.units += 1; r.since_check +|= 1; if (u.origin == r.id) if (r.t.core) |c| r.echo.confirmed(c, u.seq); - // The pty's bytes fed its emulators: its predicted echo judged - // against them. - defer if (r.diverged == null and tape.feedsTerminal(u.tape)) if (r.t.core) |c| if (c.echo != null) r.echo.fed(c); + // THE ONE QUESTION of a unit: did applying it write state outside + // the rollback copy (an emulator: Pardes.outside, the count of those + // writes, moved over its apply, read off the core that applied it)? + // Such a unit is applied once, to the confirmed core, never kept to + // replay over a copy; and its emulators' new state is what the + // predicted echo is judged against. + var moved = false; + defer if (r.diverged == null and moved) if (r.t.core) |c| if (c.echo != null) r.echo.fed(c); // A copy taken ahead (`ready`), nothing on top: it stays the point a // rollback goes back to, the unit replayed on it and kept in `since`, // not let go and taken again (a megabyte walked) for each unit of @@ -716,19 +722,20 @@ pub const Replica = struct { // nothing ends on again (`neutral`); none, not known. r.last_digest.clearRetainingCapacity(); if (lastDigest(u.tape)) |d| r.last_digest.appendSlice(r.gpa, d) catch {}; - if (r.pending.items[0].terminal) { - // Right, but what it did wrote an emulator (or owes one a - // write: a grid's size): replayed later (a rollback's - // `since`) it would write it again. So it is taken now, over - // the emulator its step read, and the ones on top applied - // again over it. + // Its speculation's own count (`Pending.outside`: the fast + // path's premise, the same records, makes it this unit's): it + // owes an emulator a write (a grid's size), which a speculation + // never makes: kept, the write would be missing; replayed later + // (a rollback's `since`), made then. So it is taken now, on the + // confirmed core, and the ones on top applied again over it. + moved = r.pending.items[0].outside != 0; + if (moved) { r.toConfirmed(); if (tape.replayUnit(&r.t, u.tape)) |why| return r.fail(why); r.freePending(r.pending.orderedRemove(0)); r.dirty = true; return; } - const read_terminal = r.pending.items[0].terminal; r.freePending(r.pending.orderedRemove(0)); r.applied -= 1; if (r.applied == 0) { @@ -752,11 +759,10 @@ pub const Replica = struct { // input kept to replay over it as a unit of the session's // that comes while idle is: a step writes some bytes of the // megabyte the copy is, walked once in `rebase_after` units, - // not once a key. Not over one that read a terminal (replayed - // later it would read the deltas since), nor once a pane - // opened, closed or was torn down since the copy (what it - // holds outside the copy was made or freed: `ahead`'s rule). - if (!read_terminal and !r.panesMoved()) return r.keepSince(u.tape); + // not once a key. Not once a pane opened, closed or was torn + // down since the copy (what it holds outside the copy was + // made or freed: `ahead`'s rule). + if (!r.panesMoved()) return r.keepSince(u.tape); r.copy.release(); rollback.Epoch.select(null); r.clearSince(); @@ -771,13 +777,11 @@ pub const Replica = struct { r.last_digest.clearRetainingCapacity(); if (ends) |d| r.last_digest.appendSlice(r.gpa, d) catch {}; } - // A terminal's output, or a join's reloads, never taken so (the one - // rule): what it writes outside the copy is applied once, at its - // place, and much of it no digest covers (a colour set, a mode, the - // pages a reload remakes). - if (r.applied > 0 and u.origin != r.id and ends != null and std.mem.eql(u8, ends.?, r.last_digest.items) and - !tape.feedsTerminal(u.tape)) - { + // The one question needs no read here: the session's digest after + // the unit holds its count of writes outside the copy, so a unit that + // wrote an emulator (a terminal's output, a colour set no other + // digested field shows, a join's reloads) never ends where it began. + if (r.applied > 0 and u.origin != r.id and ends != null and std.mem.eql(u8, ends.?, r.last_digest.items)) { // Nothing a digest covers moved: what was applied on top is // what the session will apply on top of it. Replayed when the // copy is next put back. @@ -806,7 +810,7 @@ pub const Replica = struct { // replayed by a rollback were, if at all, as they came). const check = ends != null and r.checkDue(); r.t.checks = check; - const writes = Term.writes; + const outside = if (r.t.core) |c| c.outside.n else 0; const replayed = tape.replayUnit(&r.t, u.tape); r.t.checks = false; if (replayed) |why| { @@ -820,6 +824,7 @@ pub const Replica = struct { // draw nothing. Read after the replay: before it, it is what the // units before asked (and a first unit has no core yet). if (r.core().needs_frame) r.moved = true; + moved = r.core().outside.n != outside; if (check) { r.since_check = 0; r.stats.checks += 1; @@ -837,15 +842,15 @@ pub const Replica = struct { // or freed here, and is not put back with the copy: a rollback // replaying the unit again would close a terminal freed already (the // soak, a `Del` of the shell). Let go with the copy. - // The one rule: a unit that wrote an emulator (a terminal's output, - // a grid reflowed, a view moved, one reloaded at a join) wrote what - // no copy holds: kept, a rollback would replay it into what it - // wrote already (the bytes fed twice). It goes with the copy: the - // state is the confirmed one, nothing being on top. + // The one question: a unit that wrote an emulator (a terminal's + // output, a grid reflowed, one opened, closed or reloaded at a join) + // wrote what no copy holds: kept, a rollback would replay it into + // what it wrote already (the bytes fed twice). It goes with the + // copy: the state is the confirmed one, nothing being on top. const c = r.core(); for (c.retired_panes.current, c.retired_panes.previous) |x, y| retiring = retiring or x != null or y != null; for (c.panes, serials) |slot, n| retiring = retiring or (if (slot) |pane| pane.serial else 0) != n; - if (retiring or Term.writes != writes) { + if (retiring or moved) { r.copy.release(); rollback.Epoch.select(null); return r.clearSince(); @@ -952,6 +957,7 @@ pub const Replica = struct { tape.beginSpeculation(&r.t); // The time it was sent with, every time it is applied. r.t.guess = p.guess; + const outside = c.outside.n; c.toView(.at(r.view)); // Input into a terminal: what reaches its program (a key in tty // mode, a paste, a mouse report) is a pty write, the authority's, @@ -960,9 +966,9 @@ pub const Replica = struct { // the same bytes in the same order as the session's: it is applied. c.update(in.event); c.step(); - // It owes an emulator a write it skipped (a grid's size): replayed - // when confirmed. - p.terminal = r.t.touched; + // What it owes outside the copy (an emulator's grid: Term.resize + // counts the write a speculation skips): replayed when confirmed. + p.outside = c.outside.n -% outside; const clean = tape.endSpeculation(&r.t); const dt = nowNs() - t0; // Where a blob was written, should one be: the input that did. @@ -3973,6 +3979,39 @@ test "bytes: a session's output taken over a copy held ahead is fed once: a roll try sameTerminals(b.a, b.r); } +test "bytes: a session's reflow of a terminal's grid over a copy held ahead is the count's to decide: the copy goes, and a rollback does not reflow the grid again" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const b = try BytesPair.init(); + defer b.deinit(); + try b.output("a line long enough to wrap once the grid is narrower than it is now, and then some more\r\n"); + b.r.ready(); + try std.testing.expect(b.r.copy.held); + // The unit carries no output: its sync reflows the grid, which no record + // names; the core that applied it counted the write. + const before = b.r.core().outside.n; + b.r.confirm(try b.a.own(.{ .resize = .{ .cols = 40, .rows = 20 } })); + b.r.settle(); + try std.testing.expect(b.r.core().outside.n != before); + try std.testing.expect(!b.r.copy.held); + try b.rollback(); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); +} + +test "the count of writes outside the copy is digested: a session's emulator written where its client's is not (a colour set, which no other digested field shows) is a digest that names `outside`" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const b = try BytesPair.init(); + defer b.deinit(); + try std.testing.expectEqualStrings("", try partsApart(b.a, b.r, arena.allocator())); + // A write of one side's emulator that no unit carries, as a stray one + // would be: the count alone says it. + const pane = b.a.core.panes[b.shell.index()].?; + _ = pardes.Term.feed(&b.a.core.outside, pane.terminal.?, "\x1b[31m", &.{}, &.{}, &.{}, &.{}); + try std.testing.expectEqualStrings("outside ", try partsApart(b.a, b.r, arena.allocator())); +} + test "bytes: what a terminal's emulator gains while a copy is held is its own: a rollback frees none of it" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const b = try BytesPair.init(); @@ -4245,12 +4284,12 @@ test "bytes: a client joins from a dump with its terminals whole, and every side var line: [128]u8 = undefined; for (0..400) |i| try b.output(try std.fmt.bufPrint(&line, "\x1b[3{d}m{d}\x1b]8;;https://example.com/{d}\x1b\\ link\x1b]8;;\x1b\\\x1b[0m\r\n", .{ i % 8, i, i })); try b.output("half a colour: \x1b[38;2;10;20"); - const reloads = pardes.Term.writes; + const reloads = b.r.core().outside.n; const joined = (try b.a.join(2, null)).?; defer gpa.free(joined.dump); b.r.confirm(joined.unit); try std.testing.expect(b.r.diverged == null); - try std.testing.expect(pardes.Term.writes != reloads); + try std.testing.expect(b.r.core().outside.n != reloads); const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); defer late.deinit(); late.core().echo = null; -- cgit v1.3 From 1ae5ae5e9201a6a942628ca57a6339bc90372317 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 22 Nov 2026 23:13:39 -0300 Subject: tests: what a rollback puts back of the memory the core points to, and a read of a terminal kept on the fast path (pardes-term-join-12, items 1 and 2): round 11's gate aborted in its second soak ("double free or corruption (!prev)", seed 0 at 80 ms, not reproduced alone, 1 of 3 soaks), and its core, kept by systemd-coredump, says where: a client's core at its end (`Replica.deinit` <- `Soak.close`) freeing a jj `Ask` from `jj.Session.deinit`, freed before: not the rows cache round 11 suspected; the class: `jj.Session` (`Pardes.changes`) hashes itself and has no `replica` annotation, so the rollback copy never walked it (rollback.zig `unwalked`): it saved the session's bytes in the core and nothing they point to, and a write in place into that heap (jj.zig `edited` splices every pinned `Changes.lines` and `Heat.lines` at every edit of the file) stays through a put-back that frees what the speculation made; core/jj.zig "a client's own line opened over pinned changes, rolled back by the session's key first ...": a client's `o` in a file with `Changes ::@` pinned, the session's own key first, the `o` applied again: on `trmpwtso` it aborts (a use of the freed lanes, paintLanes index 926155716 of 6), and with a DebugAllocator as the epoch's child (a local diagnostic, never committed) both frees are named: allocated at jj.spliceValues under the client's speculation, freed at rollback.Epoch.discard when the copy is put back, freed again at jj.spliceValues as the `o` is applied again over the answers buffer that still holds what the put-back freed; core/replica.zig "bytes: a terminal's rows read before an idle client's copy are the copy's ...": rows read between steps (a draw's), the copy taken idle (`ready`), a key of the client's on top and the session's first: on `trmpwtso` the rows are dropped (`toConfirmed`'s `shell_rows = .{}`) and left in the epoch until the client ends, a grid's worth of text at every such rollback; core/replica.zig "bytes: a client's key that reads a terminal's rows, the session's output before it in the session's order ...": a `G` over a shell's rows, the program's output first: the output rolls it back (its count moved: never a neutral unit), the `G` is read again over the fed rows and kept on the fast path with the session's cursor: passes on `trmpwtso` (item 2's question: on the one road a kept speculation's read of an emulator is never stale, so "this input read an emulator" needs no fact of its own); shell-test filtered: 11/12 (the jj test's abort), 11/12 (the rows test: expected the cache's address, found it dropped), 12/12 Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/jj.zig | 30 +++++++++++++++++++++++++++ core/replica.zig | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+) (limited to 'core/replica.zig') diff --git a/core/jj.zig b/core/jj.zig index a0dfec10..3d4ca17d 100644 --- a/core/jj.zig +++ b/core/jj.zig @@ -2552,6 +2552,36 @@ test "the lanes ride with the text: a line typed in a nested block is nobody's, try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); } +test "a client's own line opened over pinned changes, rolled back by the session's key first: the lanes it spliced under its copy are the copy's again, freed once; the client ends equal" { + var repo = try Stack.repo(null) orelse return error.SkipZigTest; + defer repo.deinit(testing.allocator); + const R = pardes.replica; + const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{}); + defer a.deinit(); + const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0)); + defer r.deinit(); + var line: [4200]u8 = undefined; + r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) })); + r.confirm(try a.local(.{ .command = "Changes ::@" })); + r.confirm(try a.local(.{ .command = "Look a.zig:4" })); + r.settle(); + const serial = a.core.panes[a.core.view().active].?.serial; + // The client opens a line below: an edit of the file, whose step splices + // the pinned lines' values (jj.edited) under the copy it takes. + const typed = try testing.allocator.dupe(u8, try r.input(.{ .key = .{ .cp = 'o', .text = "o" } })); + defer testing.allocator.free(typed); + try testing.expectEqual(@as(usize, 1), r.applied); + // The session's own key comes first: the copy put back, the `o` applied + // again over it, then confirmed. + r.confirm(try a.local(.{ .key = .{ .cp = 'k', .text = "k" } })); + r.settle(); + r.confirm(try a.take(typed)); + r.settle(); + try testing.expect(r.diverged == null); + try testing.expectEqualSlices(Line, answered(a.core, serial).?.lines, answered(r.core(), serial).?.lines); + try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); +} + /// Two functions four changes wrote: `fn` both, `f2` and `f3` rewrote /// f's line, `g2` g's: f three changes, g two. const Churned = struct { diff --git a/core/replica.zig b/core/replica.zig index 0ae302e8..936eb3e4 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -4012,6 +4012,68 @@ test "the count of writes outside the copy is digested: a session's emulator wri try std.testing.expectEqualStrings("outside ", try partsApart(b.a, b.r, arena.allocator())); } +test "bytes: a terminal's rows read before an idle client's copy are the copy's: a rollback puts them back, neither dropped nor freed twice" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const b = try BytesPair.init(); + defer b.deinit(); + try b.output("a line of the program's\r\nand another\r\n"); + // Its rows read between steps (a draw's), then the copy taken while it + // idles (`ready`): the rows are what the core holds at the copy. + const pane = b.r.core().panes[b.shell.index()].?; + _ = try pardes.edit.shellRows(b.r.core(), pane); + const cached = b.r.core().shell_rows.text_alloc.ptr; + b.r.ready(); + try std.testing.expect(b.r.copy.held); + // A key of the client's on top, the session's own key first: the copy + // put back, the rows with it (not left orphaned in the epoch). + try b.rollback(); + try std.testing.expectEqual(cached, b.r.core().shell_rows.text_alloc.ptr); + try agrees(b.a, b.r); + try b.output("after\r\n"); + _ = try pardes.edit.shellRows(b.r.core(), pane); + try agrees(b.a, b.r); +} + +test "bytes: a client's key that reads a terminal's rows, the session's output before it in the session's order: the output rolls it back, its read is made again over the fed rows, and the input is kept on the fast path with the session's reading" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const b = try BytesPair.init(); + defer b.deinit(); + try b.output("l1\r\nl2\r\nl3\r\n"); + // The shell's pane focused and out of its tty mode (^B): a cursor over + // its rows. + const id = b.shell.index(); + const rect = b.a.core.view().rects[id]; + for ([_]pardes.Event{ + .{ .mouse = .{ .button = .left, .kind = .press, .col = rect.x + 2, .row = rect.y + 1 } }, + .{ .mouse = .{ .button = .left, .kind = .release, .col = rect.x + 2, .row = rect.y + 1 } }, + .{ .key = .{ .cp = 'b', .ctrl = true } }, + }) |ev| { + b.r.confirm(try b.a.own(ev)); + b.r.settle(); + } + try agrees(b.a, b.r); + // G: to the last of its rows, which it reads (edit.shellRows). + const last = try gpa.dupe(u8, try b.r.input(.{ .key = .{ .cp = 'G', .text = "G" } })); + defer gpa.free(last); + try std.testing.expectEqual(@as(usize, 1), b.r.applied); + const read_before = b.r.core().panes[id].?.body.cur_row; + // The program prints two lines before the session takes the G: the + // emulator fed (its count moved, so never a neutral unit), the G + // undone and read again over the rows as fed. + b.a.output(.{ .output = .{ .pane = b.shell, .bytes = "l4\r\nl5\r\n" } }); + b.r.confirm((try b.a.pending()).?); + b.r.settle(); + try std.testing.expectEqual(@as(usize, 1), b.r.applied); + try std.testing.expect(b.r.core().panes[id].?.body.cur_row > read_before); + const fast = b.r.stats.fast; + b.r.confirm(try b.a.take(last)); + b.r.settle(); + try std.testing.expectEqual(fast + 1, b.r.stats.fast); + try agrees(b.a, b.r); + try std.testing.expectEqual(b.a.core.panes[id].?.body.cur_row, b.r.core().panes[id].?.body.cur_row); +} + 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(); -- cgit v1.3 From de0e85daa8ad0bf9618734e16568823aa2b61a54 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 22 Nov 2026 22:48:28 -0300 Subject: replicas: what a core field points to is the rollback copy's, or lives outside the core by its own declaration (pardes-term-join-12, item 1: the double free of round 11's gate): the copy skipped memory two ways, by inference and by a list, and each let a write survive a put-back: (1) `unwalked` took any type with a digest of its own and no `replica` annotation as outside the copy, so `jj.Session` (`Pardes.changes`, added with the layers) was saved as bytes and its heap never: a splice of the pinned lines at a client's edit (jj.edited) wrote a new `lines` into the answers buffer in place, the put-back freed it and left the pointer, and the next splice or the core's end freed it again (the test before this: allocated at jj.spliceValues under the speculation, freed at Epoch.discard, freed again at jj.spliceValues; the soak's abort at jj.Session.deinit); now a type is outside the copy only by declaring it (`outside_copy`: Term.State, the emulator written by confirmed units alone and counted; locations.Row, made again and never written, in a pinned blob), and every other type is walked, whatever digest it has; (2) `unsaved` skipped the rows cache (`Pardes.shell_rows`, `.derived`) and the replica kept it apart by hand (`speculate` emptied it before its take, `toConfirmed` set it `.{}` after a put-back), which an idle client's copy (`ready`) never emptied: the rows read before it were orphaned in the epoch at every rollback; now the cache is the copy's like any state: its text and rows are made whole and freed whole, so they are blobs the copy pins (no copy of a grid's text; freed raw), the put-back restores the cache with the core (valid: no emulator is written while a copy is held: a unit that writes one lets the copy go, or is applied after it is put back), and both hand resets are deleted; THE RULE the compiler holds: a type is skipped by the copy only by its own `outside_copy`, and a cache (`.derived`) on the copy's skip list (`unsaved`) is a compile error ("a cache the core holds is the copy's, or lives beside what it caches, outside the core"); the copy pins a blob once whoever reaches it (a text and the allocation it starts: never pinned twice nor also saved); not changed: the arenas (the copy saves their bytes, not their nodes: scratch content), the queues (asserted empty at a take), the host's and the process's own (store, Recent, the echo, the tape), a picture's pixels under a speculation (replica.zig's ponytail at `initDump`); the three tests of the change before: pass (the jj test and the rows test under a DebugAllocator as the epoch's child too, no double free reported); the gate (g12, a frozen copy; loads 1.5-12): core-test 918/1082 (164 skipped), shell-test 1124/1127 (3 skipped), term-test 17/17, kitty-test 45/45, pane-test 182/183 (1 skipped), behaviour-test and --replay 275/275, process-test 0 of 146 own and as pairs, the soak 3 of 3 whole and 10 of 10 at seed 0 and 80 ms (diverged 0, unequal 0, unlisted 0, quiet checks all agreed, the corpus 22 of 22, no leak, no abort), daemon.py every mode on Debug and ReleaseSafe (plain 3 of 3 each, --far 7 of 7 on ReleaseSafe, --games on ReleaseSafe with the Debug prefix's game libraries), --upgrade from the installed build 3 of 3, R2D 1 of 1, D2R 4 of 7 (two known test races: Exit's clunk answered after the window ended, far_exec's environment read at the exec; one quiet check of a Debug window client's key not in 30 s, load 6.1), --upgrade --gui 3 of 3, the cross-builds, the frame and perf gate against tree4: 77/77 frames, perfab corpus2x +0.014% (noise 0.049%), 121 counts within 0.1% (largest terminal on all +0.0794%), the gui unit-test 1719/1723 in the workspace (4 skipped, none failing; the copy's longer build root fails six tests whose messages name a temporary path: a 9P error's room is Plan 9's 128 bytes, ninep/tree.zig:549-556) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/Term.zig | 5 +++++ core/edit.zig | 11 ++++++++--- core/locations.zig | 4 ++++ core/replica.zig | 12 +----------- core/rollback.zig | 36 +++++++++++++++++++++--------------- 5 files changed, 39 insertions(+), 29 deletions(-) (limited to 'core/replica.zig') diff --git a/core/Term.zig b/core/Term.zig index d1065b49..f0329852 100644 --- a/core/Term.zig +++ b/core/Term.zig @@ -71,6 +71,11 @@ pub const State = struct { /// same snapshot again from the dump. written: bool = true, + /// Not walked by a replica's rollback copy (core/rollback.zig): its + /// emulator is written by confirmed units alone, each write counted + /// (Pardes.outside), never by a speculation, so no copy holds any of it. + pub const outside_copy = {}; + /// The emulator as its program has made it, for the replay digest. pub fn digest(s: *const State, h: *walk.Hasher) void { the().digest(s.impl, h); diff --git a/core/edit.zig b/core/edit.zig index 129b004c..70b765cc 100644 --- a/core/edit.zig +++ b/core/edit.zig @@ -427,8 +427,13 @@ pub var drawing = false; /// A terminal's rows as text (`Term.rows`), kept for one pane until its /// grid moves. Returned slices remain valid until the next cache rebuild -/// or reset. +/// or reset. A replica's rollback copy holds it as any state: its text and +/// rows are made whole and freed whole, never written, so the copy pins +/// them (blobs, freed raw) and puts the cache back with the core: no +/// emulator is written while a copy is held (replica.zig `confirm`: a unit +/// that writes one lets the copy go or is applied after it is put back). pub const RowsCache = struct { + pub const replica = .{ .blob = .{ "text", "rows", "text_alloc" } }; /// whose grid this describes; null = the slot is free pane: ?*const Pane = null, /// the rows joined by '\n' — `flatSurface` hands this back verbatim @@ -442,8 +447,8 @@ pub const RowsCache = struct { stale: bool = false, pub fn reset(c: *RowsCache, gpa: std.mem.Allocator) void { - if (c.text_alloc.len > 0) gpa.free(c.text_alloc); - if (c.rows.len > 0) gpa.free(c.rows); + pardes.memory.freeRaw(gpa, c.text_alloc); + pardes.memory.freeRaw(gpa, c.rows); c.* = .{}; } diff --git a/core/locations.zig b/core/locations.zig index 6972647e..10704912 100644 --- a/core/locations.zig +++ b/core/locations.zig @@ -25,6 +25,10 @@ pub const Row = struct { code_start: usize, colors: []u8 = &.{}, + /// Not walked by a replica's rollback copy (core/rollback.zig): made + /// again, never written, in a blob the copy pins whole. + pub const outside_copy = {}; + /// The replay digest's (core/walk.zig): all of it but its colours. They /// are painted from what this process has painted (the owner's /// highlights a frame made, the locations cache: both derived), so a diff --git a/core/replica.zig b/core/replica.zig index 936eb3e4..b37dcdb2 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -608,10 +608,7 @@ pub const Replica = struct { if (r.t.core) |c| { const was = Stepping.begin(&r.t, &r.epoch); // The state it ends on is whole as it is: the copy let go, its - // put-off frees done. Put back, it would bring back what was - // freed between steps meanwhile (the shell's rows a draw read - // again after a delta), which `toConfirmed` drops and this - // freed again (a held copy across an input of its own, a + // put-off frees done (a held copy across an input of its own, a // rejoin's old replica). if (r.copy.held) r.copy.release(); c.deinit(); @@ -901,11 +898,6 @@ pub const Replica = struct { if (!whole) return r.fail("out of memory for a rollback"); // The frame its host drew is of the memory put back: drawn again. r.moved = true; - // The rows a terminal was read as are no copy's: what the - // speculation built was the epoch's, freed with it, and what - // was there before is of a grid the deltas since moved on - // from (a rollback never brings a terminal's past back). - r.core().shell_rows = .{}; } r.applied = 0; for (r.since.items) |u| if (tape.replayUnit(&r.t, u)) |why| { @@ -942,8 +934,6 @@ pub const Replica = struct { const c = r.core(); if (!r.copy.held) { const t0 = nowNs(); - // A grid's worth of text the copy would save, and put back stale. - c.shell_rows.reset(c.gpa); r.copy.take(&r.epoch, c) catch return false; r.keepSerials(); rollback.Epoch.select(&r.epoch); diff --git a/core/rollback.zig b/core/rollback.zig index a55d3c87..61fb7b89 100644 --- a/core/rollback.zig +++ b/core/rollback.zig @@ -441,7 +441,8 @@ pub const Copy = struct { // the speculation freed would come back as that. Not the // queues a step drains (undefined between steps), nor the // authority's. - if (attr.@"comptime" or comptime (annotated(T, "authority", name) or ((annotated(T, "local", name) or annotated(T, "derived", name)) and unsaved(name)))) continue; + if (comptime annotated(T, "derived", name) and unsaved(name)) @compileError("rollback: " ++ @typeName(T) ++ "." ++ name ++ " is a cache the copy would skip: a cache the core holds is the copy's, or lives beside what it caches, outside the core"); + if (attr.@"comptime" or comptime (annotated(T, "authority", name) or (annotated(T, "local", name) and unsaved(name)))) continue; // A text and its index: written in place, the epoch // notes what each write takes out (`Epoch.wrote`). if (comptime opaqueTo(F) or annotated(T, "journal", name)) continue; @@ -483,7 +484,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) or annotated(T, "authority", name)) and unsaved(name)) continue; + if (comptime (annotated(T, "local", 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)); @@ -501,7 +502,10 @@ pub const Copy = struct { if (try c.reached([]const E, addr)) return; if (c.pinnable and s.len * @sizeOf(E) >= blob_min and c.epoch.?.owns(addr) != null) { // A blob of rows with allocations of their own is pinned whole: - // they are as immutable as it, and kept alive with it. + // they are as immutable as it, and kept alive with it. Once, + // whatever reaches it (a text and the allocation it is the + // start of), and never saved as well. + if (try c.reached(void, addr)) return; const bytes = std.mem.sliceAsBytes(s); try c.pins.append(c.meta, .{ .addr = addr, .len = bytes.len, .hash = if (checked) std.hash.Wyhash.hash(0, bytes) else 0, .where = c.where }); return; @@ -511,14 +515,16 @@ pub const Copy = struct { } }; -/// A type that hashes itself and says nothing of its fields (`replica`): -/// a terminal, the authority's (its emulator is never written by a -/// speculation: terminal.zig's guards), or a location row, made again and -/// never written. One that says its fields' kinds is walked by them, -/// whatever digest it has (the 9P state, fs.Namespace and a pane's: a -/// replayed request writes its buffers in place). +/// A type the copy does not walk: one that says so (`outside_copy`, with +/// why: a terminal's handle, its emulator written by confirmed units alone, +/// counted in Pardes.outside; a location row, made again and never +/// written). Every other type is walked, whatever digest it has: what a +/// core field points to is the copy's, saved or pinned, so that a write +/// into it in place is put back with the rest (jj.Session's answers, whose +/// lines an edit splices: walked by no one while its digest said "skip +/// me", a rollback over a client's edit freed them twice). fn unwalked(comptime T: type) bool { - return @hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *walk.Hasher) void and !@hasDecl(T, "replica"); + return @hasDecl(T, "outside_copy"); } fn annotatedStruct(comptime T: type) bool { @@ -527,10 +533,10 @@ fn annotatedStruct(comptime T: type) bool { /// The queues every step drains (empty between steps, asserted when a copy /// is taken: what is in their slots is nothing), the frame statistics -/// (numbers), 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: core/replica.zig), and a replica's predicted echo (core/term/echo.zig: -/// the replica's, never its core's). And the store and Recent, a replica's +/// (numbers), and a replica's predicted echo (core/term/echo.zig: the +/// replica's, never its core's). Never a cache (`.derived`): what a core +/// field caches is the copy's, or lives beside what it caches, outside the +/// core (a compile error says so). 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 @@ -538,7 +544,7 @@ fn annotatedStruct(comptime T: type) bool { /// `Options.tape`): the process's, which a rollback leaves where it is. 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, "own_frames") or - 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, "echo") or std.mem.eql(u8, name, "store") or std.mem.eql(u8, name, "recent") or std.mem.eql(u8, name, "tape"); } -- cgit v1.3