From f0f2a5125fd4b034ebcd424afd4a55c3185191ab Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 02:44:13 -0300 Subject: layout: a view's geometry (`rects`, `col_x`, `col_w`) is the layout pass's, never dumped: every load lays each open view out again (dump.zig `afterLoad`: `layout.compute` per open view, as a resize lays it out), and `cols` is held to `ncol` (`View.replica.len`): RUN FIRST on pardes-merge67 (core/fuzz.zig's dump fuzz, the restore road's seed 589): an image's pane 0 rect read back as 534 rows on a 24-row screen (`View.rects`, dumped as it was), drawn: draw.zig:448 `clearRect`, then surface.zig:322's `at` asserted; walk.zig `pastHeld` passes over a pair whose buffer is derived; TEST FIRST: dump.zig "a view's geometry is laid out again at a load, never read: a pane's rect past its screen in a dump is the layout's after it" (merge67: expected 22, found 534); not whole alone: the dump's layout moved, and the fuzz's seeds then reach the indexes the next change holds (`live` past the views, a file's top past its text) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/walk.zig | 2 ++ 1 file changed, 2 insertions(+) (limited to 'core/walk.zig') diff --git a/core/walk.zig b/core/walk.zig index 5e91490c..f6a9c088 100644 --- a/core/walk.zig +++ b/core/walk.zig @@ -249,6 +249,8 @@ const Past = struct { name: []const u8, says: usize, holds: usize }; /// its own. fn pastHeld(comptime T: type, v: *const T, held: ?*const [pairs(T)]usize) ?Past { inline for (0..comptime pairs(T)) |i| { + // A buffer no dump carries (derived) is made again, not read. + if (comptime excluded(T, T.replica.len[i][0])) continue; const buffer = @field(v, T.replica.len[i][0]); const holds = if (comptime @typeInfo(@TypeOf(buffer)) == .array) (if (held) |h| @min(h[i], buffer.len) else buffer.len) else buffer.len; const says = lengthIn(v, T.replica.len[i][1]); -- cgit v1.3 From 2645734806155dac927967289b0f11683eb3a1d0 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 02:56:05 -0300 Subject: walk: a loaded index is held to what it names, and a place to its thing, by a declaration beside the field, read by the comptime walk and checked where `pastHeld` is (the end of a struct's fields in all three decoders: a tape's `decode`, a byte dump's `Loader.fields`, an image's `Get.fields`, through `holdTo`): `replica.index` says what a field names (a field's slots, a predicate's things, or, with a third word, the things of the struct holding it, held where ITS fields end over every value of the type it holds (`heldIn`, `visit`); a fourth word: a span counted from it), and one that names none is REFUSED, the field named, in the words `fromDump` and a Restore say (`Core.live says 9, which names none of Core.openViews: refused`); `replica.place` gives a field's last place (or its first and last) and one past it is that place (the session is there, its view a line off); `replica.left_out` is what a load that left a thing out (another build's pane) does to what named it before the indexes are held (`Pardes.dropMissing`, now every view's); a field that names a slot by its type (`Pane.Id`, `View.Id`) with no declaration is a compile error (`checkSlots`). RUN FIRST, each the dump fuzz with every loaded core drawn at its size, 40x12 and 200x60 and given keys and a wheel notch (core/fuzz.zig `use`), each a panic or an allocation past the fuzz's cap on the tree before: join seed 1761, `Pardes.multi_count` read as 2^30 sized a yank's register array at 17 GB (`d`, Registers.put): a step's own, now not dumped, with `multi_*`, `exec_depth`, `exec_column` (root.zig `kept_out`); join 3682, `File.State.scroll` past its text: `@intCast` into `wrap_line` (File.zig fillBody): clamped to its last line (`lastLine`; a slim dump's file, read again at its revival, to its saved bytes' lines), `scroll_row` to the top line's bytes; join 77, `Messages.head` past its ring (logMessage): clamped (`head`, `len`); restore 1211, `View.screen_h` 0, drawn (draw.zig paintHeaders: surface.zig `at`), and join 24086/28218 a screen sizing a 111 GB frame: a view's screen side is a grid a frontend sizes or the dump is refused: a cell at least (a zero refused, not clamped, as abi/wire.zig `getCols` refuses one), at most 4096 (`View.max_grid`: past any display's; the wire's 512x128 is a client's, and a session's own frontend is wider: a replica test's view is 500 rows); join 14189, `Pane.tag_lead` past i32 (Core.sync): held to the room its prefix is made in (`Pane.prefix_room`); join 18926, an undo's `Journal.done` past its steps (Text.zig `mark`): clamped, `Step.first..n` a span of the journal's entries (refused past them), and join 35489 `Journal.bytes` overflowing (`record`): held to what its entries hold. And a bitset a load made is freed with the rest when the load fails or what held it is let go (`Bits`, on `customs`): the 40,000-seed run's leak (16 KB, `Loader.value` `.bitset`), reached once a refusal came after one was read. Declared beside them, by the brief and by reading: `Pardes.live` (an open view), `theme_file_pane`; `View.active` (a pane there, or any slot in a window with none), `window_pick`, `kind_grab`, `kind_hover`; `Column.panes` (panes there, held as far as `n` now says: a `len` pair, so a digest and a dump take that far); `Pane.sized_by`, `prompt_view`, `search_pane`; `Jump.cur` (place), `Jump.Loc.pane`; the language server's awaited `pane`. TESTS (each site was a failing run first, above): walk.zig "an index read back that names none of its things is refused, its field named, in a tape, a dump and an image; a place past its thing's last is that last", "a thing another build's dump left out takes what named it with it (`left_out`), before the indexes are held"; dump.zig "a dump whose index names no view or pane there is refused, the field named; a top past its text is its last line; a key's replay is not dumped" Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/Core.zig | 56 ++++++- core/File.zig | 20 +++ core/Jump.zig | 9 +- core/Messages.zig | 12 ++ core/Text.zig | 16 ++ core/dump.zig | 91 +++++++++-- core/lsp/Ask.zig | 2 + core/panes.zig | 10 ++ core/root.zig | 2 + core/walk.zig | 445 +++++++++++++++++++++++++++++++++++++++++++++++++++--- 10 files changed, 625 insertions(+), 38 deletions(-) (limited to 'core/walk.zig') diff --git a/core/Core.zig b/core/Core.zig index ff0a84ac..b2f96886 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -93,6 +93,10 @@ pub const View = struct { pub const replica = .{ .len = .{ .{ "leader_keys", "leader_n" }, .{ "cols", "ncol" }, .{ "col_x", "ncol" }, .{ "col_w", "ncol" } }, .derived = .{ "rects", "col_x", "col_w" }, + // What its keyboard is on: a pane there; window mode's outline and + // a kind's press and hover, slots; its screen, a grid a frontend + // sizes (walk.zig `.index`). + .index = .{ .{ "active", Pardes, "focusPanes" }, .{ "window_pick", Pardes, "panes" }, .{ "kind_grab", Pardes, "panes" }, .{ "kind_hover", Pardes, "panes" }, .{ "screen_w", "grids" }, .{ "screen_h", "grids" } }, }; /// A view's slot in `Pardes.views`, as it crosses the core's edge: an /// entry's argument or answer, the wire's welcome. A type of its own, @@ -208,6 +212,15 @@ pub const View = struct { pastes: u32 = 0, links: u32 = 0, link: pardes.Effect.Buf(256) = .{}, + + /// A side of a grid a frontend sizes: a cell at least (a zero is + /// refused, not clamped, as the wire refuses one: abi/wire.zig + /// `getCols`), past no display's (a frame is as many cells as it + /// holds, Surface.cells: a damaged image's asked 111 GB). + pub fn grids(_: *const View, n: usize) bool { + return n >= 1 and n <= max_grid; + } + pub const max_grid = 4096; }; gpa: std.mem.Allocator, @@ -481,6 +494,11 @@ pub const replica = .{ "in_head", "in_len", // The views no frontend here draws (views.zig). "undrawn", + // A step's own, set and put back within it (a key's replay across + // the ranges, normal.replaySels; a word's run, exec.zig): as + // `init` makes them between any two steps. + "multi_first", "multi_stop", "multi_index", + "multi_count", "exec_depth", "exec_column", // How this process was started, and the last dump it made for // its host to write: a session loaded elsewhere has its own. "opts", "dump_out", "dump_export", @@ -493,8 +511,38 @@ pub const replica = .{ // server's own part of `fs` says so in fs.Namespace.) .authority = .{ "host", "store", "recent", "db", "fallback" }, .len = .{ .{ "look_src", "n_look_src" }, .{ "session_dir", "session_dir_len" }, .{ "session_home", "session_home_len" }, .{ "session_shell", "session_shell_len" } }, + // The live view is an open one; a ThemeFile's pane a slot (walk.zig + // `.index`). + .index = .{ .{ "live", "openViews" }, .{ "theme_file_pane", "panes" } }, + // A pane another build's dump could not give: out of every layout. + .left_out = "dropMissing", }; +/// What an index into the session names (walk.zig `.index`): an open view. +pub fn openViews(p: *const Pardes, k: usize) bool { + return k < Views.max and p.views[k] != null; +} + +/// A pane there. +pub fn openPanes(p: *const Pardes, id: usize) bool { + return id < MAX_PANES and p.panes[id] != null; +} + +/// What a view's keyboard may be on: a pane there, or any slot in a window +/// with none (the last column's Delcol leaves one, layout.zig `delColumn`). +pub fn focusPanes(p: *const Pardes, id: usize) bool { + if (id >= MAX_PANES) return false; + if (p.panes[id] != null) return true; + return for (p.panes) |slot| { + if (slot != null) break false; + } else true; +} + +/// The panes a view's columns list that are not there (another build's +/// dump left them out: walk.zig `left_out`) taken out of them, and its +/// keyboard on one that is. +pub const dropMissing = pardes.dump.dropMissing; + /// The message row's entry points, called from everywhere as /// `p.setMessage(...)`; they live with the rest of it in Messages.zig. pub const setStatus = Messages.setStatus; @@ -1929,7 +1977,7 @@ pub fn sync(p: *Pardes) void { // had any; a folded pane shows its first line only. Its prefix // is made once, on the stack: this runs on every event, and not // every event may take from the scratch arena. - var wrap_room: [32 * 1024]u8 = undefined; + var wrap_room: [Pane.prefix_room]u8 = undefined; var wrap_fba = std.heap.FixedBufferAllocator.init(&wrap_room); const wa = wrap_fba.allocator(); const prefix: ?[]const u8 = tagline.prefixIn(p, wa, pane) catch null; @@ -2223,9 +2271,9 @@ pub const PendingWrite = struct { bytes: []u8, off: usize = 0 }; /// place on screen (`col_x`, `col_w`) is worked out each sync, as a pane's /// rect is. pub const Column = struct { - // Zeroed, not undefined: a digest takes the whole of it, a release - // build's heap leaves its unused slots whatever was there before, and - // two replicas must agree on them (core/replica.zig). + /// Its panes, as far as `n` says (what a digest, a dump and a copy take), + /// each a pane there (walk.zig `.index`). + pub const replica = .{ .len = .{.{ "panes", "n" }}, .index = .{.{ "panes", Pardes, "openPanes" }} }; panes: [MAX_PANES]usize = @splat(0), n: usize = 0, weight: u64 = column_weight_unit, diff --git a/core/File.zig b/core/File.zig index 8b7adae3..8e464d61 100644 --- a/core/File.zig +++ b/core/File.zig @@ -108,8 +108,28 @@ pub const State = struct { // none of their bytes, and takes back what a speculation wrote // (core/rollback.zig `Epoch.wrote`). .journal = .{ "content", "line_starts" }, + // Where the view's top is, held to its text (walk.zig `.place`). + .place = .{ .{ "scroll", "lastLine" }, .{ "scroll_row", "lastRow" } }, }; + /// The last line a view's top may be at: its text's. A clean file a + /// slim dump left the text of (dump.zig `Slim`, read from its file + /// again when it is revived) has a line a byte of what it saved at most, + /// in the rows a view counts (`Pane.wrap_line`). + pub fn lastLine(f: *const State) usize { + if (f.content.len == 0) if (f.saved_len) |n| return @min(n, std.math.maxInt(i32)); + return modal.lineCount(f.content) -| 1; + } + + /// The last row of the top's line its top may be at: a row holds a byte + /// of it at least (its rows as wrapped are the view's, made after). + pub fn lastRow(f: *const State) usize { + if (f.content.len == 0) return 0; + const at = modal.lineStartOffset(f.content, f.scroll); + const end = std.mem.indexOfScalarPos(u8, f.content, at, '\n') orelse f.content.len; + return end - at; + } + path: []u8, content: []u8, /// The bytes `content`'s buffer has room for (0: as many as it holds): diff --git a/core/Jump.zig b/core/Jump.zig index ccdb8fdc..a83b6ab4 100644 --- a/core/Jump.zig +++ b/core/Jump.zig @@ -27,12 +27,19 @@ cur: usize = 0, /// (a query answered: Ctrl-o goes back to where it was asked). force: bool = false, -pub const replica = .{ .len = .{.{ "list", "n" }} }; +/// `cur` held to the places there are (walk.zig `.place`). +pub const replica = .{ .len = .{.{ "list", "n" }}, .place = .{.{ "cur", "lastCur" }} }; + +pub fn lastCur(j: *const Jump) usize { + return j.n -| 1; +} const Mouse = pardes.Mouse; const recent_path_cap = limits.host_path_cap; pub const Loc = struct { + /// Its pane's slot (walk.zig `.index`), that pane while `serial` says. + pub const replica = .{ .index = .{.{ "pane", Pardes, "panes" }} }; pane: u16, /// 0 once its pane has closed: a file's entry stays, reopened by a /// jump to it from `path_hash`'s recent entry. diff --git a/core/Messages.zig b/core/Messages.zig index 18b10ff8..040b8d2c 100644 --- a/core/Messages.zig +++ b/core/Messages.zig @@ -19,6 +19,10 @@ const Pardes = pardes.Pardes; const Messages = @This(); +/// Where its ring's next line goes and how many it holds, held to the ring +/// where a dump is read back (walk.zig `.place`). +pub const replica = .{ .place = .{ .{ "head", "lastSlot" }, .{ "len", "size" } } }; + /// The message-row log: a fixed ring, never allocated, never grown. See /// `logMessage` and the `Messages` builtin. log: [limits.message_log]LoggedMessage = @splat(.{}), @@ -26,6 +30,14 @@ log: [limits.message_log]LoggedMessage = @splat(.{}), head: usize = 0, len: usize = 0, +pub fn lastSlot(m: *const Messages) usize { + return m.log.len - 1; +} + +pub fn size(m: *const Messages) usize { + return m.log.len; +} + pub const LoggedMessage = struct { pub const cap = 256; pub const replica = .{ .len = .{.{ "text", "len" }} }; diff --git a/core/Text.zig b/core/Text.zig index ba544bff..37feb081 100644 --- a/core/Text.zig +++ b/core/Text.zig @@ -426,6 +426,8 @@ pub const Place = struct { /// (`entries[first..][0..n]`), and the places at its edges: an undo goes /// back to `before`, a redo to `after`, where it was undone from. pub const Step = struct { + /// Its entries are the journal's (walk.zig `.index`, a span). + pub const replica = .{ .index = .{.{ "first", Journal, "entries", "n" }} }; first: usize, n: usize = 0, before: Place, @@ -438,12 +440,26 @@ pub const Step = struct { /// limits.undo_max steps and limits.undo_bytes of what they hold, the /// oldest step dropped first and the newest kept whatever its size. pub const Journal = struct { + /// `done` held to its steps, `bytes` to what its entries hold (walk.zig + /// `.place`). + pub const replica = .{ .place = .{ .{ "done", "stepCount" }, .{ "bytes", "entryBytes" } } }; steps: std.ArrayList(Step) = .empty, done: usize = 0, entries: std.ArrayList(Entry) = .empty, /// What the entries hold: the bytes they took out, and their own size. bytes: usize = 0, + pub fn stepCount(j: *const Journal) usize { + return j.steps.items.len; + } + + /// What `bytes` says, its one place: what the entries hold. + pub fn entryBytes(j: *const Journal) [2]usize { + var n: usize = 0; + for (j.entries.items) |e| n +|= held(e); + return .{ n, n }; + } + pub fn deinit(j: *Journal, gpa: std.mem.Allocator) void { for (j.entries.items) |e| free(gpa, e); j.entries.deinit(gpa); diff --git a/core/dump.zig b/core/dump.zig index 10d36350..9dcc076e 100644 --- a/core/dump.zig +++ b/core/dump.zig @@ -563,21 +563,25 @@ fn ensureKind(p: *Pardes, pane: *pardes.panes.Pane) !void { pane.terminal = try pardes.Term.open(&p.outside, pardes.panes.emulatorGpa(p.gpa), @max(1, pane.cols), @max(1, pane.rows)); } -/// The panes a column lists that are not there (another build's dump left -/// them out) taken out of it, and the keyboard on one that is. -fn dropMissing(p: *Pardes) void { - const v = p.view(); - for (0..p.view().ncol) |c| { - var n: usize = 0; - for (v.cols[c].panes[0..p.view().cols[c].n]) |id| if (id < MAX_PANES and p.panes[id] != null) { - v.cols[c].panes[n] = id; - n += 1; - }; - v.cols[c].n = n; - } - if (v.active >= MAX_PANES or p.panes[v.active] == null) v.active = for (p.panes, 0..) |slot, i| { - if (slot != null) break i; - } else 0; +/// The panes each view's columns list that are not there (another build's +/// dump left them out) taken out of them, and its keyboard on one that is: +/// at the load's end, and where the core's fields end (walk.zig +/// `left_out`), before what names a pane is held to one there. Every view: +/// the live one may not be one yet then. (Their lengths are held already.) +pub fn dropMissing(p: *Pardes) void { + for (&p.views) |*slot| if (slot.*) |*v| { + for (v.cols[0..v.ncol]) |*col| { + var n: usize = 0; + for (col.panes[0..col.n]) |id| if (id < MAX_PANES and p.panes[id] != null) { + col.panes[n] = id; + n += 1; + }; + col.n = n; + } + if (v.active >= MAX_PANES or p.panes[v.active] == null) v.active = for (p.panes, 0..) |s, i| { + if (s != null) break i; + } else 0; + }; } /// The replacement core for a Restore of the dump at `from`, whose log says @@ -1052,6 +1056,63 @@ test "a view's geometry is laid out again at a load, never read: a pane's rect p _ = try q.render(q.frame_arena.allocator()); } +test "a dump whose index names no view or pane there is refused, the field named; a top past its text is its last line; a key's replay is not dumped" { + // The fuzz's join road (core/fuzz.zig): `live` read past the views + // (views.zig `bit`), a file's top past its text (File.zig fillBody's + // `wrap_line`), and `multi_count` sizing a yank's register at 17 GB. + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("one\ntwo\n"); + const id = p.view().active; + const Refused = struct { + fn by(q: *Pardes, why: []const u8) !void { + inline for (.{ byteDump, dumpBytes }) |dumpOf| { + const bytes = try dumpOf(q); + defer q.gpa.free(bytes); + var notes: std.ArrayList(u8) = .empty; + defer notes.deinit(q.gpa); + try std.testing.expectError(error.BadDump, load(q.gpa, q.opts, bytes, ¬es)); + std.testing.expect(std.mem.indexOf(u8, notes.items, why) != null) catch |err| { + std.debug.print("refused, but not by {s}: {s}\n", .{ why, notes.items }); + return err; + }; + } + } + }; + // No view open to write the shares of (the live one's are its panes'). + p.live = 9; + p.views_open = 0; + try Refused.by(p, "live says 9"); + p.live = 0; + p.views_open = 1; + p.view().active = 9; + try Refused.by(p, ".active says 9"); + p.view().active = id; + const col = &p.view().cols[0].panes[0]; + col.* = 9; + try Refused.by(p, "Column.panes says 9"); + col.* = id; + pane.sized_by = 7; + try Refused.by(p, "Pane.sized_by says 7"); + pane.sized_by = 0; + // Where a thing is, past its end: its last place, the session there. + pane.file.?.scroll = 1 << 40; + p.multi_count = 1 << 30; + inline for (.{ byteDump, dumpBytes }) |dumpOf| { + const bytes = try dumpOf(p); + defer gpa.free(bytes); + const q = try load(gpa, p.opts, bytes, null); + defer q.deinit(); + try std.testing.expectEqual(@as(usize, 2), q.panes[id].?.file.?.scroll); + try std.testing.expectEqual(@as(usize, 1), q.multi_count); + _ = q.frame_arena.reset(.retain_capacity); + _ = try q.render(q.frame_arena.allocator()); + } + pane.file.?.scroll = 0; + p.multi_count = 1; +} + test "a session with every column it may hold dumps and restores them all" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 1200, .rows = 24 }); diff --git a/core/lsp/Ask.zig b/core/lsp/Ask.zig index 4d57f21e..29d36f0a 100644 --- a/core/lsp/Ask.zig +++ b/core/lsp/Ask.zig @@ -27,6 +27,8 @@ seq: u32 = 0, last: ?struct { kind: lsp.Kind, arg: Effect.Buf(128), serial: u32, offset: u32 } = null, /// The query whose answer is awaited. wait: ?struct { + /// Its pane's slot (walk.zig `.index`), that pane while `serial` says. + pub const replica = .{ .index = .{.{ "pane", pardes.Pardes, "panes" }} }; id: u32, kind: lsp.Kind, pane: Pane.Id, diff --git a/core/panes.zig b/core/panes.zig index 08d91df5..62814227 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -36,7 +36,17 @@ pub const Pane = struct { // A picture's memory is its own allocator's (a dump loaded makes // it there). .alloc = .{ .{ "addon", "image" }, .{ "pdf", "image" }, .{ "terminal", "terminal" } }, + // Slots of the session's (walk.zig `.index`): a view's, a pane's, + // each looked at before it is used (one gone since is no error). + .index = .{ .{ "sized_by", Pardes, "views" }, .{ "prompt_view", Pardes, "views" }, .{ "search_pane", Pardes, "panes" } }, + // The tag's prefix as it was placed: one its room holds. + .place = .{.{ "tag_lead", "leadRoom" }}, }; + /// The room a tag's computed prefix is made in, each step (Pardes.sync). + pub const prefix_room = 32 * 1024; + pub fn leadRoom(_: *const Pane) usize { + return prefix_room; + } /// A pane's slot in `Pardes.panes`, as it crosses the core's edge: an /// entry's argument or answer, an event's, an effect's, a host call's. /// A type of its own, so a view's slot (`View.Id`) is not taken for diff --git a/core/root.zig b/core/root.zig index 7056935d..3128f37b 100644 --- a/core/root.zig +++ b/core/root.zig @@ -748,6 +748,8 @@ const kept_out = [_]struct { []const u8, []const u8, []const u8 }{ .{ "Core.zig", "shell_rows", "a terminal's rows as read here, swept at every update; the terminal's own digest covers its active area, not its history (Term.zig `calls`)" }, .{ "Core.zig", "diff_output locations_cache tty_filter_palette body_chrome", "caches of pure functions of their key (a text, a theme): a step finds what it would make; a query row's colours from them are out of its digest (locations.Row.digest), and what a step asks a worker to paint is never decided by them (Stream.paintRows)" }, .{ "Core.zig", "retired_panes", "panes torn down this step, freed at its end" }, + .{ "Core.zig", "multi_first multi_stop multi_index multi_count exec_depth exec_column", "a step's own: set by a key's replay across the ranges (normal.replaySels) and a word's run (exec.zig), each put back before the step ends; between steps what `init` makes, so a load takes them as it makes them (a dump's said 2^30 ranges once: a yank sized its register by it)" }, + .{ "Core.zig", "rects col_x col_w", "a view's geometry: the layout pass's (layout.compute) over its columns and screen, at every sync and resize, and at a load (dump.afterLoad); never read before it" }, .{ "Core.zig", "distrusted frames tape", "Options: the client's own list, its runner's statistics, its tape" }, .{ "Event.zig", "native_image_patches", "what this process's shell can take" }, .{ "panes.zig", "pv pv_known", "the views' shares as this process parks them (views.zig)" }, diff --git a/core/walk.zig b/core/walk.zig index f6a9c088..25e4bdc3 100644 --- a/core/walk.zig +++ b/core/walk.zig @@ -259,14 +259,255 @@ fn pastHeld(comptime T: type, v: *const T, held: ?*const [pairs(T)]usize) ?Past return null; } -/// Every name an annotation gives is a field: a rename cannot quietly put -/// a field back in the digest. +// ---- an index read back is held to what it names ---- +// +// A field that NAMES one of the things a session holds (a view by its slot, +// a pane by its) says what, beside it, as a length says its buffer; a field +// that says WHERE in a thing it is (a scroll, a row), the thing's last place: +// +// pub const replica = .{ +// // One of the slots field `views` has (as many as it holds), or one +// // a predicate of the struct says is there (`fn (*const T, usize) +// // bool`); a third word, one of the things of the struct named +// // second that holds this one (held where ITS fields end, every +// // value of this type it holds); a fourth, the field counting a +// // span of them from it (all within the field named third). +// .index = .{ .{ "sized_by", Pardes, "views" }, .{ "live", "openViews" }, .{ "first", Journal, "entries", "n" } }, +// // Its last place, a function of the struct (`fn (*const T) usize`), +// // or its first and last (`[2]usize`). +// .place = .{ .{ "scroll", "lastLine" } }, +// // What a load that left one of its things out (another build's +// // pane) does to what names it (`fn (*T) void`), before its indexes +// // are held. +// .left_out = "dropMissing", +// }; +// +// A value read back (a tape, a dump, an image: bytes from another process or +// the disk) is held to them where its fields end, beside its lengths +// (`pastHeld`), every declaration of every type at once: an index that names +// none is REFUSED, its field named (the dump is not the session: the view, +// the pane it names is not there); a place past its thing's last is that +// LAST (the session is there, its view a line off). A field that names a +// slot by its type (`Pane.Id`, `View.Id`) and says nothing is a compile +// error (`checkSlots`); a bare integer that does is found by reading, as +// the lengths' were, until it is typed as its slot. + +fn declared(comptime T: type, comptime kind: []const u8) usize { + return if (@hasDecl(T, "replica") and @hasField(@TypeOf(T.replica), kind)) @field(T.replica, kind).len else 0; +} + +/// An index read back that names none of what it says it indexes. +const Unnamed = struct { holder: []const u8, name: []const u8, says: usize, of: []const u8 }; + +/// What an index field says, as a number: an integer, an optional one's (null +/// names nothing), a slot's enum's (`Pane.Id`). +fn number(comptime F: type, v: F) ?usize { + return switch (@typeInfo(F)) { + .int => std.math.cast(usize, v) orelse std.math.maxInt(usize), + .optional => |o| if (v) |x| number(o.child, x) else null, + .@"enum" => |e| number(e.tag_type, @backingInt(v)), + else => @compileError("walk: an `index` names a thing by a number, not " ++ @typeName(F)), + }; +} + +/// How many of field `name`'s elements `v` holds: as far as its length says. +fn heldOf(comptime T: type, v: *const T, comptime name: []const u8) usize { + const all = &@field(v, name); + if (comptime isList(@TypeOf(all.*))) return all.items.len; + return if (comptime lengthOf(T, name)) |len| @min(lengthIn(v, len), all.len) else all.len; +} + +/// Whether `h` has the thing `i` names by `what`: a field of it (one of its +/// slots), or a predicate of it. +fn hasThing(comptime H: type, h: *const H, comptime what: []const u8, i: usize) bool { + if (comptime @hasField(H, what)) { + return i < heldOf(H, h, what); + } else return @field(H, what)(h, i); +} + +/// The first number field `name` of `u` says (each of an array as far as its +/// length says) that names no thing of `h`'s by `what`. +fn firstUnnamed(comptime U: type, u: *const U, comptime name: []const u8, comptime H: type, h: *const H, comptime what: []const u8) ?usize { + const F = @FieldType(U, name); + if (comptime @typeInfo(F) == .array) { + for (@field(u, name)[0..heldOf(U, u, name)]) |e| if (number(@typeInfo(F).array.child, e)) |i| if (!hasThing(H, h, what, i)) return i; + return null; + } + const i = number(F, @field(u, name)) orelse return null; + return if (hasThing(H, h, what, i)) null else i; +} + +/// `at` held to `[first, last]`: a place past its thing's last is that last. +fn clampTo(comptime F: type, at: *F, first: usize, last: usize) void { + switch (@typeInfo(F)) { + .int => if (at.* > last) { + at.* = @intCast(last); + } else if (at.* < first) { + at.* = @intCast(first); + }, + .optional => |o| if (at.*) |*x| clampTo(o.child, x, first, last), + else => @compileError("walk: a `place` is a number, not " ++ @typeName(F)), + } +} + +/// The types `T`'s value holds whose indexes name `T`'s things (a third word +/// `T`): held where `T`'s fields end. +fn heldIn(comptime T: type) []const type { + comptime { + if (!@hasDecl(T, "replica")) return &.{}; + var out: []const type = &.{}; + for (graph(&.{T})) |U| if (@typeInfo(U) == .@"struct") for (0..declared(U, "index")) |k| { + const d = U.replica.index[k]; + if (d.len >= 3) if (d[1] == T) { + out = out ++ .{U}; + break; + }; + }; + return out; + } +} + +/// Whether a value of `X` can hold a `U`, as a dump walks it. +fn reaches(comptime X: type, comptime U: type) bool { + comptime { + @setEvalBranchQuota(100_000_000); + return switch (kindOf(Canon(X))) { + .@"struct", .optional, .one, .slice, .array, .@"union" => for (graph(&.{Canon(X)})) |Y| { + if (Y == U) break true; + } else false, + else => false, + }; + } +} + +/// `v`'s places held to their things' last, then the first of its indexes, +/// and of every value it holds whose indexes name its things, that names +/// none (see above). +fn heldIndexes(comptime T: type, v: *T) ?Unnamed { + inline for (0..comptime declared(T, "place")) |k| { + const d = T.replica.place[k]; + const held = @field(T, d[1])(v); + const span: [2]usize = if (@TypeOf(held) == usize) .{ 0, held } else held; + clampTo(@FieldType(T, d[0]), &@field(v, d[0]), span[0], span[1]); + } + inline for (0..comptime declared(T, "index")) |k| { + const d = T.replica.index[k]; + if (comptime d.len == 2) if (firstUnnamed(T, v, d[0], T, v, d[1])) |i| + return .{ .holder = @typeName(T), .name = d[0], .says = i, .of = @typeName(T) ++ "." ++ d[1] }; + } + inline for (comptime heldIn(T)) |U| if (visit(T, v, U, T, v, 0)) |bad| return bad; + return null; +} + +/// Every `U` that `x` holds (its fields as a dump walks them, as far as each +/// length says; optionals, arrays, slices, lists, unions and pointers +/// followed), its indexes into `h`'s things held; the first that names none. +/// A value nested past `max_depth` (a pointer that is its own holder: a +/// damaged dump's) is refused too. +fn visit(comptime X: type, x: *const X, comptime U: type, comptime H: type, h: *const H, depth: u16) ?Unnamed { + if (comptime !reaches(X, U)) return null; + if (depth == max_depth) return .{ .holder = @typeName(X), .name = "", .says = depth, .of = "a depth a session's values nest to" }; + if (X == U) inline for (0..comptime declared(U, "index")) |k| { + const d = U.replica.index[k]; + if (comptime d.len >= 3) if (comptime d[1] == H) { + const of = @typeName(H) ++ "." ++ d[2]; + if (comptime d.len == 3) { + if (firstUnnamed(U, x, d[0], H, h, d[2])) |i| return .{ .holder = @typeName(U), .name = d[0], .says = i, .of = of }; + } else { + // A span: as many as its count says from it, all there (an + // empty one may stand at their end). + const end = @as(usize, @field(x, d[0])) +| @field(x, d[3]); + if (end > heldOf(H, h, d[2])) return .{ .holder = @typeName(U), .name = d[0], .says = @field(x, d[0]), .of = of }; + } + }; + }; + switch (@typeInfo(X)) { + .optional => |o| if (x.*) |*c| return visit(o.child, c, U, H, h, depth + 1), + .array => |a| for (x) |*e| if (visit(a.child, e, U, H, h, depth + 1)) |bad| return bad, + .pointer => |p| switch (p.size) { + .one => return visit(p.child, x.*, U, H, h, depth + 1), + .slice => for (x.*) |*e| if (visit(p.child, e, U, H, h, depth + 1)) |bad| return bad, + else => {}, + }, + .@"struct" => { + if (comptime isAtomic(X)) return visit(@FieldType(X, "raw"), &x.raw, U, H, h, depth + 1); + if (comptime isList(X)) return visit(@FieldType(X, "items"), &x.items, U, H, h, depth + 1); + inline for (comptime dumpFields(X)) |name| { + const F = @FieldType(X, name); + if (comptime reaches(F, U)) { + if (comptime lengthOf(X, name) != null) { + for (@field(x, name)[0..heldOf(X, x, name)]) |*e| if (visit(Element(F), e, U, H, h, depth + 1)) |bad| return bad; + } else if (visit(F, &@field(x, name), U, H, h, depth + 1)) |bad| return bad; + } + } + }, + .@"union" => switch (x.*) { + inline else => |*payload| return visit(@TypeOf(payload.*), payload, U, H, h, depth + 1), + }, + else => {}, + } + return null; +} + +/// `out`'s lengths held to what their buffers hold as read (`pastHeld`), and +/// its indexes to what they name (`heldIndexes`), where a reader (`Loader`, +/// `Get`) has read its fields: the dump refused, the field named. One that +/// left a thing out since `dropped` (another build's pane) first has `T`'s +/// `left_out` take out what names it. +fn holdTo(l: anytype, comptime T: type, out: *T, held: *const [pairs(T)]usize, dropped: usize) error{BadDump}!void { + if (pastHeld(T, out, held)) |past| { + l.note("{s}.{s} says {d}, past the {d} its buffer holds: refused", .{ @typeName(T), past.name, past.says, past.holds }); + return error.BadDump; + } + if (comptime @hasDecl(T, "replica")) if (comptime @hasField(@TypeOf(T.replica), "left_out")) if (l.dropped != dropped) @field(T, T.replica.left_out)(out); + if (heldIndexes(T, out)) |bad| { + l.note("{s}.{s} says {d}, which names none of {s}: refused", .{ bad.holder, bad.name, bad.says, bad.of }); + return error.BadDump; + } +} + +/// A slot's type (`Pane.Id`, `View.Id`: an enum that is `at` a slot and +/// gives its `index`), bare, optional or in an array. +fn isSlot(comptime F: type) bool { + return switch (@typeInfo(F)) { + .optional => |o| isSlot(o.child), + .array => |a| isSlot(a.child), + .@"enum" => @hasDecl(F, "at") and @hasDecl(F, "index"), + else => false, + }; +} + +/// A field a dump carries that names a slot by its type says what it +/// indexes (`.index`): a compile error otherwise, so that one added later +/// is held where it is read back. +fn checkSlots(comptime T: type) void { + for (dumpFields(T)) |name| if (isSlot(@FieldType(T, name))) { + for (0..declared(T, "index")) |k| { + if (std.mem.eql(u8, T.replica.index[k][0], name)) break; + } else @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " names a slot: say what it indexes (`replica.index`)"); + }; +} + +/// Every name an annotation gives is a field (and what an index or a place +/// says it is held to, a field or a function): a rename cannot quietly put a +/// field back in the digest, nor take one out of its rule. fn checkAnnotations(comptime T: type) void { if (!@hasDecl(T, "replica")) return; inline for (@typeInfo(@TypeOf(T.replica)).@"struct".field_names) |kind| { + if (comptime std.mem.eql(u8, kind, "left_out")) { + if (!@hasDecl(T, T.replica.left_out)) @compileError("walk: " ++ @typeName(T) ++ " has no " ++ T.replica.left_out ++ " for what a load left out"); + continue; + } inline for (@field(T.replica, kind)) |entry| { - const name = if (comptime std.mem.eql(u8, kind, "len") or std.mem.eql(u8, kind, "alloc")) entry[0] else entry; + const pair = comptime std.mem.eql(u8, kind, "len") or std.mem.eql(u8, kind, "alloc") or std.mem.eql(u8, kind, "index") or std.mem.eql(u8, kind, "place"); + const name = if (pair) entry[0] else entry; if (!@hasField(T, name)) @compileError("walk: " ++ @typeName(T) ++ " annotates no field " ++ name); + if (comptime std.mem.eql(u8, kind, "index") or std.mem.eql(u8, kind, "place")) { + const H = if (entry.len >= 3) entry[1] else T; + const what = if (entry.len >= 3) entry[2] else entry[1]; + if (entry.len == 4) if (!@hasField(T, entry[3])) @compileError("walk: " ++ @typeName(T) ++ " counts its span by no field " ++ entry[3]); + if (!@hasField(H, what) and !@hasDecl(H, what)) @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " is held to " ++ what ++ ", which " ++ @typeName(H) ++ " has not"); + } } } } @@ -634,7 +875,7 @@ pub fn decode(comptime T: type, r: *Reader, a: std.mem.Allocator) TapeError!T { try decodeError(F, r, &@field(out, name)); } else @field(out, name) = try decode(F, r, a); } - if (pastHeld(T, &out, null) != null) return error.BadTape; + if (pastHeld(T, &out, null) != null or heldIndexes(T, &out) != null) return error.BadTape; return out; }, .@"union" => |u| { @@ -818,7 +1059,10 @@ fn collect(comptime T: type, comptime list: []const type) []const type { comptime { for (list) |U| if (U == T) return list; var out: []const type = list ++ .{T}; - if (kindOf(T) == .@"struct") checkAnnotations(T); + if (kindOf(T) == .@"struct") { + checkAnnotations(T); + checkSlots(T); + } for (children(T)) |C| out = collect(C, out); return out; } @@ -1205,6 +1449,8 @@ pub const Loader = struct { filled: usize = 0, /// How deep `skip` is in the dump's own types. depth: u16 = 0, + /// How many things (a session's panes) it left out (`holdTo`). + dropped: usize = 0, pub fn init(gpa: std.mem.Allocator, bytes: []const u8, table: []const u8) DecodeError!Self { var l: Self = .{ .gpa = gpa, .own = gpa, .bytes = bytes, .arena = .init(gpa) }; @@ -1550,6 +1796,10 @@ pub const Loader = struct { .bitset => { const bits = try l.bitCount(); out.* = try .initEmpty(l.gpa, bits); + l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&Bits(T).free) }) catch |err| { + out.deinit(l.gpa); + return err; + }; const words = (bits + @bitSizeOf(usize) - 1) / @bitSizeOf(usize); if (words > 0) @memcpy(std.mem.sliceAsBytes(out.masks[0..words]), try l.take(words * @sizeOf(usize))); }, @@ -1618,6 +1868,7 @@ pub const Loader = struct { if (droppable) { l.letGo(before); out[i] = null; + l.dropped += 1; l.note("{s}[{d}] left out", .{ l.field, i }); } else failed = true; }; @@ -1630,6 +1881,7 @@ pub const Loader = struct { const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed"; const outer = l.field; defer l.field = outer; + const dropped = l.dropped; // How far each array a length cuts was read: none yet (one read in // place holds what it held). var held: [pairs(T)]usize = @splat(if (existing) std.math.maxInt(usize) else 0); @@ -1640,7 +1892,7 @@ pub const Loader = struct { try l.oneField(T, field, s.fields[k].ty, out, packed_struct, existing); if (comptime pairAt(T, field)) |i| held[i] = l.filled; } - return l.heldTo(T, out, &held); + return holdTo(l, T, out, &held, dropped); } var found: std.StaticBitSet(@max(1, names.len)) = .empty; var failed = false; @@ -1684,15 +1936,7 @@ pub const Loader = struct { } }; if (failed) return error.Incompatible; - return l.heldTo(T, out, &held); - } - - /// `out`'s lengths held to what their buffers hold as read (`pastHeld`): - /// the dump refused, the length named. - fn heldTo(l: *Self, comptime T: type, out: *const T, held: *const [pairs(T)]usize) DecodeError!void { - const past = pastHeld(T, out, held) orelse return; - l.note("{s}.{s} says {d}, past the {d} its buffer holds: refused", .{ @typeName(T), past.name, past.says, past.holds }); - return error.BadDump; + return holdTo(l, T, out, &held, dropped); } fn oneField(l: *Self, comptime T: type, comptime field: []const u8, ty: u32, out: *T, comptime packed_struct: bool, existing: bool) DecodeError!void { @@ -1779,6 +2023,16 @@ pub const Loader = struct { } }; +/// A bitset a load made, freed as a `dumpRead`'s value is (`customs`) when +/// the load fails or what held it is let go: its words are no `made` slice. +fn Bits(comptime T: type) type { + return struct { + fn free(b: *T, gpa: std.mem.Allocator) void { + b.deinit(gpa); + } + }; +} + /// `out` as a new `T` is before a load reads its fields: each field's /// default, an allocator `gpa`. fn freshOf(comptime T: type, out: *T, gpa: std.mem.Allocator) void { @@ -2069,6 +2323,8 @@ pub const Get = struct { allocs: Allocators = .{}, /// How many elements the last array read holds (`pastHeld`). filled: usize = 0, + /// How many things (a session's panes) it left out (`holdTo`). + dropped: usize = 0, const Cursor = Mem.Cursor(.read_only); pub const Error = error{ BadDump, Incompatible, OutOfMemory }; @@ -2330,6 +2586,10 @@ pub const Get = struct { const words = (bits + @bitSizeOf(usize) - 1) / @bitSizeOf(usize); if (got.value.len != 8 + words * @sizeOf(usize)) return error.BadDump; out.* = try .initEmpty(l.gpa, bits); + l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&Bits(T).free) }) catch |err| { + out.deinit(l.gpa); + return err; + }; if (words > 0) @memcpy(std.mem.sliceAsBytes(out.masks[0..words]), got.value[8..]); }, } @@ -2510,6 +2770,7 @@ pub const Get = struct { if (droppable) { l.letGo(before); out[i] = null; + l.dropped += 1; l.note("{s}[{d}] left out", .{ l.field, i }); } else failed = true; }; @@ -2521,6 +2782,7 @@ pub const Get = struct { const names = comptime dumpFields(T); const outer = l.field; defer l.field = outer; + const dropped = l.dropped; const map = Mem.HashMap(.read_only).init(c) catch return error.Incompatible; var found: std.StaticBitSet(@max(1, names.len)) = .empty; var failed = false; @@ -2572,9 +2834,7 @@ pub const Get = struct { }; }; if (failed) return error.Incompatible; - const past = pastHeld(T, out, &held) orelse return; - l.note("{s}.{s} says {d}, past the {d} its buffer holds: refused", .{ @typeName(T), past.name, past.says, past.holds }); - return error.BadDump; + return holdTo(l, T, out, &held, dropped); } fn oneField(l: *Get, comptime T: type, comptime field: []const u8, c: Cursor, out: *T, existing: bool) Error!void { @@ -2886,6 +3146,155 @@ test "a length past what its buffer holds is refused where it is read back (a ta try std.testing.expectError(error.BadDump, get.get(Room, (try Get.member(root, "room")).?)); } +test "an index read back that names none of its things is refused, its field named, in a tape, a dump and an image; a place past its thing's last is that last" { + const S = struct { + const Self = @This(); + const Inner = struct { + at: u8 = 0, + list: [3]u8 = @splat(0), + n: u8 = 0, + // Indexes into the struct holding it, held where its fields end. + pub const replica = .{ .len = .{.{ "list", "n" }}, .index = .{ .{ "at", Self, "there" }, .{ "list", Self, "there" } } }; + }; + things: [4]?u8 = @splat(null), + live: u8 = 0, + slot: ?u16 = null, + scroll: u32 = 0, + inner: [2]?*Inner = @splat(null), + pub const replica = .{ .index = .{ .{ "live", "there" }, .{ "slot", "things" } }, .place = .{.{ "scroll", "last" }} }; + pub fn there(s: *const Self, i: usize) bool { + return i < s.things.len and s.things[i] != null; + } + pub fn last(_: *const Self) usize { + return 9; + } + }; + const gpa = std.testing.allocator; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + var inner: S.Inner = .{ .at = 2, .list = .{ 0, 2, 1 }, .n = 2 }; + const good: S = .{ .things = .{ 1, null, 3, null }, .live = 2, .slot = 3, .scroll = 50, .inner = .{ &inner, null } }; + // Each a value no session has: the field it names. + const Bad = struct { []const u8, S }; + var bad_at: S.Inner = .{ .at = 1 }; + var bad_list: S.Inner = .{ .list = .{ 0, 3, 0 }, .n = 2 }; + const bad = [_]Bad{ + .{ "S.live says 1", blk: { + var v = good; + v.live = 1; + break :blk v; + } }, + .{ "S.slot says 4", blk: { + var v = good; + v.slot = 4; + break :blk v; + } }, + .{ "Inner.at says 1", blk: { + var v = good; + v.inner[1] = &bad_at; + break :blk v; + } }, + .{ "Inner.list says 3", blk: { + var v = good; + v.inner[1] = &bad_list; + break :blk v; + } }, + }; + var notes: std.ArrayList(u8) = .empty; + + // A dump. + const bytes = try save(S, gpa, &good); + defer gpa.free(bytes); + const back = try load(S, a, bytes, null); + try std.testing.expectEqual(@as(u32, 9), back.scroll); + try std.testing.expectEqual(@as(?u16, 3), back.slot); + for (bad) |b| { + const dumped = try save(S, gpa, &b[1]); + defer gpa.free(dumped); + notes.clearRetainingCapacity(); + try std.testing.expectError(error.BadDump, load(S, a, dumped, ¬es)); + try std.testing.expect(std.mem.indexOf(u8, notes.items, b[0]) != null); + } + + // A tape. + var buf: [256]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + try encode(S, &good, &w); + for (bad) |b| try encode(S, &b[1], &w); + var r: Reader = .{ .bytes = w.buffered() }; + try std.testing.expectEqual(@as(u32, 9), (try decode(S, &r, a)).scroll); + for (bad) |_| try std.testing.expectError(error.BadTape, decode(S, &r, a)); + + // An image. + var image: std.Io.Writer.Allocating = .init(gpa); + defer image.deinit(); + var db = try Mem.init(std.Io.failing, .{ .buffer = &image, .file_id = 0 }); + var put: Put = .{ .gpa = gpa }; + defer put.deinit(); + try db.runContext(struct { + put: *Put, + good: *const S, + bad: []const Bad, + pub fn run(ctx: @This(), cursor: *Mem.Cursor(.read_write)) !void { + const map = try Mem.HashMap(.read_write).init(cursor.*); + try ctx.put.member(map, "good", S, ctx.good); + inline for (0..4) |i| try ctx.put.member(map, std.fmt.comptimePrint("bad{d}", .{i}), S, &ctx.bad[i][1]); + } + }{ .put = &put, .good = &good, .bad = &bad }); + var get: Get = .init(a); + defer get.deinit(); + const root = db.rootCursor().readOnly(); + try std.testing.expectEqual(@as(u32, 9), (try get.get(S, (try Get.member(root, "good")).?)).scroll); + inline for (0..4) |i| { + get.notes.clearRetainingCapacity(); + try std.testing.expectError(error.BadDump, get.get(S, (try Get.member(root, std.fmt.comptimePrint("bad{d}", .{i}))).?)); + try std.testing.expect(std.mem.indexOf(u8, get.notes.items, bad[i][0]) != null); + } +} + +test "a thing another build's dump left out takes what named it with it (`left_out`), before the indexes are held" { + const Old = struct { + const Thing = struct { n: u32 = 0 }; + things: [2]?*Thing = @splat(null), + at: ?u8 = null, + }; + // A thing whose `n` changed kind, no default: it is left out. + const New = struct { + const Self = @This(); + const Thing = struct { n: struct { a: u8 } }; + things: [2]?*Thing = @splat(null), + at: ?u8 = null, + pub const replica = .{ .index = .{.{ "at", "there" }}, .left_out = "forget" }; + pub fn there(s: *const Self, i: usize) bool { + return i < s.things.len and s.things[i] != null; + } + pub fn forget(s: *Self) void { + if (s.at) |i| if (!s.there(i)) { + s.at = null; + }; + } + }; + const Unforgiving = struct { + const Self = @This(); + things: [2]?*New.Thing = @splat(null), + at: ?u8 = null, + pub const replica = .{ .index = .{.{ "at", "there" }} }; + pub fn there(s: *const Self, i: usize) bool { + return i < s.things.len and s.things[i] != null; + } + }; + const gpa = std.testing.allocator; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var one: Old.Thing = .{ .n = 1 }; + const bytes = try save(Old, gpa, &.{ .things = .{ &one, null }, .at = 0 }); + defer gpa.free(bytes); + const new = try load(New, arena.allocator(), bytes, null); + try std.testing.expect(new.things[0] == null and new.at == null); + try std.testing.expectError(error.BadDump, load(Unforgiving, arena.allocator(), bytes, null)); +} + test "a bitset's count read back is held to the bytes left, read or passed over, in a dump and an image: never a size that overflows" { const gpa = std.testing.allocator; const B = struct { bits: std.DynamicBitSetUnmanaged = .{}, after: []const u8 = "" }; -- cgit v1.3 From 4e28df7f8e02ceec66a9d62ca75f8ec006e26d7c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 05:28:45 -0300 Subject: layout: a view's geometry is read back as its session holds it, never laid out again at a load, and held to its screen (walk.zig `.within`): a dump whose rect or column is off its screen is REFUSED, the field named: RUN FIRST (the soak, `replicas -- --clients 5`, Debug): `rpplxwst` ALONE diverged 124 at rtt 30 (225 clients parted at their first unit after a join, `addon pdf: its state after view is not the session's (it breaks PA_PLAIN)` and `the tape's answer to addon is short`; then 532 keys into the pdf's pane stopped at `a key into a kind's pane`, the kind distrusted; the witness's replay past a divergence panicked, `integer overflow` in Core.advanceInner), `pardes-merge67` 0 at 30, 80 and 207 ms; THE CAUSE: a join opens its client a view (views.zig `open`: the live one's screen and columns, NO rects: laid out at that view's first input), and rpplxwst's load (dump.zig `afterLoad`) laid every view out again, so the client had rects for its own view the session had not, told its plain kinds a view the session never told them (Kind.zig `step`, `viewOf`), and parted at the session's next step; a join's dump is the session: THE FIX: `rects`, `col_x`, `col_w` back in the digest, the dump and the copy as merge67 had them, `afterLoad`'s relayout gone (and walk.zig `pastHeld`'s pass over a derived buffer with it), and where a value read back may be is declared beside the field: `replica.within` (a predicate of the struct by the entry's place in the field, as far as its length says), checked with the indexes (`heldIndexes`) in all three decoders (a tape's `decode`, a byte dump's and an image's `holdTo`): `View.rects` on its screen (`onScreen`: x + w <= screen_w, y + h <= screen_h, as the layout pass puts every one, and a view not laid out yet has empty ones), a column's edge with its width (`columnOnScreen`, declared on `col_w`), refused in words (`Core.View.rects[0] is not within Core.View.onScreen: refused`), never clamped (a clamped rect is a state no session had); `cols` stays held to `ncol` (a column past `ncol` is a dropped one's, which the index rule would read); TESTS FIRST: replica.zig "a client joins with its session's geometry as the session holds it ..." (a plain kind keeping the rows its view was told; on pardes-load-index: `expected 0, found 5`, the joined view's rect, and without that line `the tape's answer to addon is short (tape byte 241, in tick)`), dump.zig "a view's geometry is read back as the session holds it, never laid out again; a rect or a column off its screen is refused, the field named" (the fuzz's restore seed 589: a pane 534 rows tall on a 24-row screen; a column 900 wide; a column's edge at 900), walk.zig's index test gains an entry not where it may be (`S.edges[1] is not within`, a tape, a dump and an image) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/Core.zig | 23 ++++++++++++++++++---- core/dump.zig | 59 ++++++++++++++++++++++++++++++++++---------------------- core/replica.zig | 39 +++++++++++++++++++++++++++++++++++++ core/walk.zig | 55 +++++++++++++++++++++++++++++++++++++--------------- 4 files changed, 133 insertions(+), 43 deletions(-) (limited to 'core/walk.zig') diff --git a/core/Core.zig b/core/Core.zig index b2f96886..6c981adf 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -87,16 +87,18 @@ const Pardes = @This(); /// One client's view of the session (views.zig): its screen and layout, /// its focus, its pointer and gestures, its jumps, its key prefixes. pub const View = struct { - /// Its geometry (`rects`, `col_x`, `col_w`) is the layout pass's over - /// its columns and screen: never dumped, laid out again at a load - /// (dump.afterLoad), as a resize lays it out. pub const replica = .{ .len = .{ .{ "leader_keys", "leader_n" }, .{ "cols", "ncol" }, .{ "col_x", "ncol" }, .{ "col_w", "ncol" } }, - .derived = .{ "rects", "col_x", "col_w" }, // What its keyboard is on: a pane there; window mode's outline and // a kind's press and hover, slots; its screen, a grid a frontend // sizes (walk.zig `.index`). .index = .{ .{ "active", Pardes, "focusPanes" }, .{ "window_pick", Pardes, "panes" }, .{ "kind_grab", Pardes, "panes" }, .{ "kind_hover", Pardes, "panes" }, .{ "screen_w", "grids" }, .{ "screen_h", "grids" } }, + // Its geometry, read back as the session holds it (a view opened + // and not laid out yet has none, on a join's client too, whose + // kinds are told its views as the session's are): on its screen, + // a pane's rect and a column's `col_x` with its width (walk.zig + // `.within`). + .within = .{ .{ "rects", "onScreen" }, .{ "col_w", "columnOnScreen" } }, }; /// A view's slot in `Pardes.views`, as it crosses the core's edge: an /// entry's argument or answer, the wire's welcome. A type of its own, @@ -221,6 +223,19 @@ pub const View = struct { return n >= 1 and n <= max_grid; } pub const max_grid = 4096; + + /// Pane slot `id`'s rect on the screen, where the layout pass puts + /// every one (a frame is the screen's cells: one past it, drawn, is a + /// cell outside the frame). + pub fn onScreen(v: *const View, id: usize) bool { + const r = v.rects[id]; + return @as(u32, r.x) + r.w <= v.screen_w and @as(u32, r.y) + r.h <= v.screen_h; + } + + /// Column `c` on the screen: its left edge and its width. + pub fn columnOnScreen(v: *const View, c: usize) bool { + return @as(u32, v.col_x[c]) + v.col_w[c] <= v.screen_w; + } }; gpa: std.mem.Allocator, diff --git a/core/dump.zig b/core/dump.zig index 9dcc076e..b4561ae2 100644 --- a/core/dump.zig +++ b/core/dump.zig @@ -143,14 +143,6 @@ pub fn dumpExit(p: *Pardes) !void { /// view showed in a dump made before the layer's lines were the buffer's /// (wire 31 and older: a view's bit, no lines), its lines in it (jj.loaded). fn afterLoad(p: *Pardes) void { - // Each view laid out again over its columns and its screen, as a resize - // lays it out: its geometry is derived, never read (View.replica). - const live = p.live; - for (p.views, 0..) |slot, k| if (slot != null) { - p.live = @intCast(k); - layout.compute(p); - }; - p.live = live; for (p.panes) |slot| if (slot) |pane| if (pane.file) |*f| { const text = pardes.panes.File.fileText(f, p.scratch.allocator()) catch continue; f.context.reload(p.tree_sitter_gpa, f.path, text, f.revision); @@ -1036,24 +1028,45 @@ test "a dump keeps the session's settings, and a restore applies them" { try std.testing.expect(!restored.settings.wrap); } -test "a view's geometry is laid out again at a load, never read: a pane's rect past its screen in a dump is the layout's after it" { - // The fuzz's restore road, seed 589: an image whose pane 0 said 534 - // rows on a 24-row screen, drawn: surface.zig's `at` asserted. +test "a view's geometry is read back as the session holds it, never laid out again; a rect or a column off its screen is refused, the field named" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); - const want = p.view().rects[0]; - p.view().rects[0].h = 534; - p.view().col_w[0] = 900; - const dumped = try dumpBytes(p); - defer gpa.free(dumped); - p.view().rects[0] = want; - const q = try load(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }, dumped, null); - defer q.deinit(); - try std.testing.expectEqual(want, q.view().rects[0]); - try std.testing.expectEqual(@as(u16, 80), q.view().col_w[0]); - _ = q.frame_arena.reset(.retain_capacity); - _ = try q.render(q.frame_arena.allocator()); + // Not what the layout pass would make of its columns (a view opened + // and not laid out yet has no rects at all): as the session has it. + p.view().rects[0].h -= 1; + const held = p.view().rects[0]; + inline for (.{ byteDump, dumpBytes }) |dumpOf| { + const bytes = try dumpOf(p); + defer gpa.free(bytes); + const q = try load(gpa, p.opts, bytes, null); + defer q.deinit(); + try std.testing.expectEqual(held, q.view().rects[0]); + } + // The fuzz's restore road, seed 589: an image whose pane 0 said 534 + // rows on a 24-row screen, drawn: surface.zig's `at` asserted. + const Off = struct { at: *u16, to: u16, why: []const u8 }; + for ([_]Off{ + .{ .at = &p.view().rects[0].h, .to = 534, .why = "View.rects[0] is not within" }, + .{ .at = &p.view().col_w[0], .to = 900, .why = "View.col_w[0] is not within" }, + // A column's edge is held with its width. + .{ .at = &p.view().col_x[0], .to = 900, .why = "View.col_w[0] is not within" }, + }) |off| { + const was = off.at.*; + off.at.* = off.to; + defer off.at.* = was; + inline for (.{ byteDump, dumpBytes }) |dumpOf| { + const bytes = try dumpOf(p); + defer gpa.free(bytes); + var notes: std.ArrayList(u8) = .empty; + defer notes.deinit(gpa); + try std.testing.expectError(error.BadDump, load(gpa, p.opts, bytes, ¬es)); + std.testing.expect(std.mem.indexOf(u8, notes.items, off.why) != null) catch |err| { + std.debug.print("refused, but not by {s}: {s}\n", .{ off.why, notes.items }); + return err; + }; + } + } } test "a dump whose index names no view or pane there is refused, the field named; a top past its text is its last line; a key's replay is not dumped" { diff --git a/core/replica.zig b/core/replica.zig index 46320fea..4126972a 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -6615,6 +6615,45 @@ test "a kind's place moved in a step of another view's: a replica's key that rea try agrees(a, r); } +/// Placed, plain (PA_PLAIN): a client runs it, and its state is the rows +/// its last view was told. +const Viewed = struct { + const pa = pardes.Kind.c; + const words = [_]pa.pa_word{std.mem.zeroInit(pa.pa_word, .{ .name = "Viewed", .opens = 1, .doc = "the rows its view was told" })}; + const ops = std.mem.zeroInit(pardes.Kind.Ops, .{ + .head = std.mem.zeroInit(pa.pa_head, .{ .size = @sizeOf(pa.pa_head), .abi = pardes.Kind.abi, .name = "viewed".* ++ @as([10]u8, @splat(0)), .version = 1, .exts = "", .flags = pa.PA_PLAIN, .words = &words, .nwords = 1 }), + .open = Placed.open, + .paint = Placed.paint, + .view = Placed.view, + }); +}; + +test "a client joins with its session's geometry as the session holds it: the view opened for it, not laid out yet, is not laid out in the client either, and a plain kind is told the same views on both" { + // The soak's (test/replicas.zig): a client parted at its first unit + // after its join, `addon pdf: its state after view is not the + // session's`: it had laid every view out at its load, its own new one + // too, which the session lays out at that view's first input. + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); + defer a.deinit(); + var words: [64]pardes.Kind.LoadedWord = undefined; + const viewed = pardes.Kind.loadedOf(&Viewed.ops, "/x/viewed.so", @splat(7), &words); + _ = try a.local(.{ .addon = .{ .op = .load, .pane = .at(0), .kind = &viewed } }); + _ = try a.local(.{ .command = "Viewed" }); + const kid = a.core.view().active; + const joined = (try a.join(1, null)).?; + defer gpa.free(joined.dump); + const r = try Replica.initDump(gpa, 1, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); + defer r.deinit(); + try std.testing.expect(r.loaded(joined.digest)); + try runsHere(r, kid, &Viewed.ops); + try std.testing.expectEqual(a.core.views[joined.view].?.rects[kid], r.core().views[joined.view].?.rects[kid]); + // The session's own step tells the kind each view whose facts changed. + r.confirm(try a.local(.tick)); + r.settle(); + try agrees(a, r); +} + /// A kind whose every key asks a job, for the job tokens' test. const Jobber = struct { const pa = pardes.Kind.c; diff --git a/core/walk.zig b/core/walk.zig index 25e4bdc3..51b0a384 100644 --- a/core/walk.zig +++ b/core/walk.zig @@ -249,8 +249,6 @@ const Past = struct { name: []const u8, says: usize, holds: usize }; /// its own. fn pastHeld(comptime T: type, v: *const T, held: ?*const [pairs(T)]usize) ?Past { inline for (0..comptime pairs(T)) |i| { - // A buffer no dump carries (derived) is made again, not read. - if (comptime excluded(T, T.replica.len[i][0])) continue; const buffer = @field(v, T.replica.len[i][0]); const holds = if (comptime @typeInfo(@TypeOf(buffer)) == .array) (if (held) |h| @min(h[i], buffer.len) else buffer.len) else buffer.len; const says = lengthIn(v, T.replica.len[i][1]); @@ -276,6 +274,10 @@ fn pastHeld(comptime T: type, v: *const T, held: ?*const [pairs(T)]usize) ?Past // // Its last place, a function of the struct (`fn (*const T) usize`), // // or its first and last (`[2]usize`). // .place = .{ .{ "scroll", "lastLine" } }, +// // Where each of its entries (as far as its length says) may be, +// // a predicate of the struct by the entry's place in the field +// // (`fn (*const T, usize) bool`): a view's rects on its screen. +// .within = .{ .{ "rects", "onScreen" } }, // // What a load that left one of its things out (another build's // // pane) does to what names it (`fn (*T) void`), before its indexes // // are held. @@ -286,18 +288,20 @@ fn pastHeld(comptime T: type, v: *const T, held: ?*const [pairs(T)]usize) ?Past // the disk) is held to them where its fields end, beside its lengths // (`pastHeld`), every declaration of every type at once: an index that names // none is REFUSED, its field named (the dump is not the session: the view, -// the pane it names is not there); a place past its thing's last is that -// LAST (the session is there, its view a line off). A field that names a -// slot by its type (`Pane.Id`, `View.Id`) and says nothing is a compile -// error (`checkSlots`); a bare integer that does is found by reading, as -// the lengths' were, until it is typed as its slot. +// the pane it names is not there), and so is an entry that is not where it +// may be (no session's: a rect past its screen); a place past its thing's +// last is that LAST (the session is there, its view a line off). A field +// that names a slot by its type (`Pane.Id`, `View.Id`) and says nothing is +// a compile error (`checkSlots`); a bare integer that does is found by +// reading, as the lengths' were, until it is typed as its slot. fn declared(comptime T: type, comptime kind: []const u8) usize { return if (@hasDecl(T, "replica") and @hasField(@TypeOf(T.replica), kind)) @field(T.replica, kind).len else 0; } -/// An index read back that names none of what it says it indexes. -const Unnamed = struct { holder: []const u8, name: []const u8, says: usize, of: []const u8 }; +/// An index read back that names none of what it says it indexes, or +/// (`within`) the entry `says` of a field that is not where it may be. +const Unnamed = struct { holder: []const u8, name: []const u8, says: usize, of: []const u8, within: bool = false }; /// What an index field says, as a number: an integer, an optional one's (null /// names nothing), a slot's enum's (`Pane.Id`). @@ -395,6 +399,11 @@ fn heldIndexes(comptime T: type, v: *T) ?Unnamed { if (comptime d.len == 2) if (firstUnnamed(T, v, d[0], T, v, d[1])) |i| return .{ .holder = @typeName(T), .name = d[0], .says = i, .of = @typeName(T) ++ "." ++ d[1] }; } + inline for (0..comptime declared(T, "within")) |k| { + const d = T.replica.within[k]; + for (0..heldOf(T, v, d[0])) |i| if (!@field(T, d[1])(v, i)) + return .{ .holder = @typeName(T), .name = d[0], .says = i, .of = @typeName(T) ++ "." ++ d[1], .within = true }; + } inline for (comptime heldIn(T)) |U| if (visit(T, v, U, T, v, 0)) |bad| return bad; return null; } @@ -461,7 +470,10 @@ fn holdTo(l: anytype, comptime T: type, out: *T, held: *const [pairs(T)]usize, d } if (comptime @hasDecl(T, "replica")) if (comptime @hasField(@TypeOf(T.replica), "left_out")) if (l.dropped != dropped) @field(T, T.replica.left_out)(out); if (heldIndexes(T, out)) |bad| { - l.note("{s}.{s} says {d}, which names none of {s}: refused", .{ bad.holder, bad.name, bad.says, bad.of }); + if (bad.within) + l.note("{s}.{s}[{d}] is not within {s}: refused", .{ bad.holder, bad.name, bad.says, bad.of }) + else + l.note("{s}.{s} says {d}, which names none of {s}: refused", .{ bad.holder, bad.name, bad.says, bad.of }); return error.BadDump; } } @@ -499,10 +511,11 @@ fn checkAnnotations(comptime T: type) void { continue; } inline for (@field(T.replica, kind)) |entry| { - const pair = comptime std.mem.eql(u8, kind, "len") or std.mem.eql(u8, kind, "alloc") or std.mem.eql(u8, kind, "index") or std.mem.eql(u8, kind, "place"); + const held = comptime std.mem.eql(u8, kind, "index") or std.mem.eql(u8, kind, "place") or std.mem.eql(u8, kind, "within"); + const pair = comptime held or std.mem.eql(u8, kind, "len") or std.mem.eql(u8, kind, "alloc"); const name = if (pair) entry[0] else entry; if (!@hasField(T, name)) @compileError("walk: " ++ @typeName(T) ++ " annotates no field " ++ name); - if (comptime std.mem.eql(u8, kind, "index") or std.mem.eql(u8, kind, "place")) { + if (held) { const H = if (entry.len >= 3) entry[1] else T; const what = if (entry.len >= 3) entry[2] else entry[1]; if (entry.len == 4) if (!@hasField(T, entry[3])) @compileError("walk: " ++ @typeName(T) ++ " counts its span by no field " ++ entry[3]); @@ -3146,7 +3159,7 @@ test "a length past what its buffer holds is refused where it is read back (a ta try std.testing.expectError(error.BadDump, get.get(Room, (try Get.member(root, "room")).?)); } -test "an index read back that names none of its things is refused, its field named, in a tape, a dump and an image; a place past its thing's last is that last" { +test "an index read back that names none of its things is refused, its field named, in a tape, a dump and an image, and so is an entry not where it may be; a place past its thing's last is that last" { const S = struct { const Self = @This(); const Inner = struct { @@ -3161,10 +3174,14 @@ test "an index read back that names none of its things is refused, its field nam slot: ?u16 = null, scroll: u32 = 0, inner: [2]?*Inner = @splat(null), - pub const replica = .{ .index = .{ .{ "live", "there" }, .{ "slot", "things" } }, .place = .{.{ "scroll", "last" }} }; + edges: [2]u8 = @splat(0), + pub const replica = .{ .index = .{ .{ "live", "there" }, .{ "slot", "things" } }, .place = .{.{ "scroll", "last" }}, .within = .{.{ "edges", "inside" }} }; pub fn there(s: *const Self, i: usize) bool { return i < s.things.len and s.things[i] != null; } + pub fn inside(s: *const Self, i: usize) bool { + return s.edges[i] < 8; + } pub fn last(_: *const Self) usize { return 9; } @@ -3200,7 +3217,13 @@ test "an index read back that names none of its things is refused, its field nam v.inner[1] = &bad_list; break :blk v; } }, + .{ "S.edges[1] is not within", blk: { + var v = good; + v.edges = .{ 7, 8 }; + break :blk v; + } }, }; + const n_bad = bad.len; var notes: std.ArrayList(u8) = .empty; // A dump. @@ -3239,14 +3262,14 @@ test "an index read back that names none of its things is refused, its field nam pub fn run(ctx: @This(), cursor: *Mem.Cursor(.read_write)) !void { const map = try Mem.HashMap(.read_write).init(cursor.*); try ctx.put.member(map, "good", S, ctx.good); - inline for (0..4) |i| try ctx.put.member(map, std.fmt.comptimePrint("bad{d}", .{i}), S, &ctx.bad[i][1]); + inline for (0..n_bad) |i| try ctx.put.member(map, std.fmt.comptimePrint("bad{d}", .{i}), S, &ctx.bad[i][1]); } }{ .put = &put, .good = &good, .bad = &bad }); var get: Get = .init(a); defer get.deinit(); const root = db.rootCursor().readOnly(); try std.testing.expectEqual(@as(u32, 9), (try get.get(S, (try Get.member(root, "good")).?)).scroll); - inline for (0..4) |i| { + inline for (0..n_bad) |i| { get.notes.clearRetainingCapacity(); try std.testing.expectError(error.BadDump, get.get(S, (try Get.member(root, std.fmt.comptimePrint("bad{d}", .{i}))).?)); try std.testing.expect(std.mem.indexOf(u8, get.notes.items, bad[i][0]) != null); -- cgit v1.3 From c90db8c04787d923bbef500eb78c68fd65715cf0 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 05:55:02 -0300 Subject: walk, views, Core: what the 40,000-seed dump fuzz reached once a view's geometry is in the dump again (its seeds land elsewhere; and the dump holds its tree's path, so each tree's seeds damage bytes of their own), each a run first: (1) THE WORKSPACE'S RUN (my gate's fuzz40k, the join road): `views.undumped` took `bit(d.k)` of a view's shares whose `k` was past any view (`integer does not fit in destination type` at views.zig `bit`), and `Shares.k` declared an index (`slots`) did NOT hold it: the `[]Shares` was a REFERENCE (walk.zig `Loader.ref`) to bytes made for another type, read as shares without being decoded (no-panic-1's open item, "references read back as another type", reached): every allocation a load makes records what it holds (`Made.of`, `typeWord` of its element), and a reference read back is to a value of its own type or the dump is refused (`Loader.ref`, `Get.again`, at a pointer's and a slice's, in both readers: a damaged one had one type's bytes read as another's, pointers and alignment and all; the writers share a reference between values of one type only, so no session's dump is refused); the skips' placeholders hold no type, so a reference to one is refused; `Shares.k` stays declared (a slot read back is held); (3) THE WORKSPACE'S RUN with (1) (my gate h2's fuzz40k): leaked 1 allocation, 7 bytes, a byte dump's theme (dump.zig `loadKnowing`: `l.get([]const u8)` failed after its slice was made, and the load's `defer` cut its books back to before the mounts, dropping the half-made slice unfreed: a leak at every such damaged join dump or Restore): a root read that fails lets go of what it had made (`Loader.get`, `Get.get`: `mark`/`letGo`, merge65's mechanism), so no caller's books hold half of a value; (2) MY SECOND TREE'S RUN (the join road): `Pardes.resize_count` read back as the most a usize holds, `+= 1` at the next resize (`integer overflow`, Core.zig `updateInner`, the fuzz's `use` resizing to 40x12): a count that only grows saturates (`+|=`); the fuzz with them: 40000 join and 1779 image seeds green in my second tree three times (212 seeds refused by `.within` each: 211 a pane's rect off its screen, 1 a column; 210 on the join road, 2 on the image's); in the workspace 40000 join seeds green with no leak (206 refused by `.within`), the image road green to seed 1366: seed 1367 there reaches xitdb's own reader (`switch on corrupt value`, xitdb lib.zig `readBytesObjectAlloc`, from Db.zig `Read.open` in dump.check: the last agent's seed 1780 in another tree, a dependency's, not here) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/Core.zig | 2 +- core/views.zig | 6 ++++++ core/walk.zig | 55 ++++++++++++++++++++++++++++++++++--------------------- 3 files changed, 41 insertions(+), 22 deletions(-) (limited to 'core/walk.zig') diff --git a/core/Core.zig b/core/Core.zig index 6c981adf..835eb86c 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -1753,7 +1753,7 @@ fn updateInner(p: *Pardes, ev: Event) void { v.cell_pixels.w = @max(1, sz.cell_pixels.w); v.cell_pixels.h = @max(1, sz.cell_pixels.h); layout.compute(p); - p.resize_count += 1; + p.resize_count +|= 1; }, .output => |o| { const pane = p.panes[o.pane.index()] orelse return; diff --git a/core/views.zig b/core/views.zig index 4f2d5744..4c020981 100644 --- a/core/views.zig +++ b/core/views.zig @@ -82,6 +82,12 @@ pub const Shares = struct { k: u8, panes: []const Share = &.{}, + /// Its view, a slot (walk.zig `.index`). + pub const replica = .{ .index = .{.{ "k", "slots" }} }; + pub fn slots(_: *const Shares, k: usize) bool { + return k < max; + } + pub const Share = struct { id: u16, pv: PaneView }; }; diff --git a/core/walk.zig b/core/walk.zig index 51b0a384..7a77fdb6 100644 --- a/core/walk.zig +++ b/core/walk.zig @@ -1398,8 +1398,11 @@ fn countOf(n: u64) DecodeError!usize { } /// An allocation a load made: what a reference to it finds, and what a -/// failed load frees. -const Made = struct { bytes: []u8, alignment: std.mem.Alignment, gpa: std.mem.Allocator, dead: bool = false }; +/// failed load frees. `of`: what it holds (`typeWord` of its element); a +/// reference read back is to a value of its own type, or the dump is +/// refused (a damaged one would have one type's bytes read as another's, +/// pointers and all). +const Made = struct { bytes: []u8, alignment: std.mem.Alignment, gpa: std.mem.Allocator, dead: bool = false, of: u64 = 0 }; /// How far a reader had made things before a value: what that value made /// is everything after it (`letGo`). @@ -1509,8 +1512,8 @@ pub const Loader = struct { } } - fn made(l: *Self, bytes: []u8, alignment: std.mem.Alignment) DecodeError!usize { - try l.shared.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa }); + fn made(l: *Self, bytes: []u8, alignment: std.mem.Alignment, of: u64) DecodeError!usize { + try l.shared.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa, .of = of }); return l.shared.items.len - 1; } @@ -1609,6 +1612,11 @@ pub const Loader = struct { /// The next root, made: what it points at is `gpa`'s. pub fn get(l: *Self, comptime T: type) DecodeError!T { + // A root that fails lets go of what it had made: its caller's books + // (a load's, cut back past what it frees itself) never hold half + // of a value. + const at = l.mark(); + errdefer l.letGo(at); var out: T = undefined; try l.fresh(T, &out); try l.value(T, try l.root(), &out); @@ -1750,12 +1758,12 @@ pub const Loader = struct { }, .one => { const C = @typeInfo(T).pointer.child; - if (try l.ref()) |again| { + if (try l.ref(C)) |again| { out.* = @ptrCast(@alignCast(again.ptr)); return; } const one = try l.gpa.create(C); - const at = l.made(std.mem.asBytes(one), .of(C)) catch |err| { + const at = l.made(std.mem.asBytes(one), .of(C), typeWord(C)) catch |err| { l.gpa.destroy(one); return err; }; @@ -1821,22 +1829,23 @@ pub const Loader = struct { /// A reference to a pointer or slice made before, or null for a /// new one (its length then read). - fn ref(l: *Self) DecodeError!?[]u8 { + fn ref(l: *Self, comptime E: type) DecodeError!?[]u8 { const n = try l.scalar(u32); if (n == 0) return null; if (n > l.shared.items.len) return error.BadDump; const got = l.shared.items[n - 1]; if (got.dead) return error.Incompatible; + if (got.of != typeWord(E)) return error.BadDump; return got.bytes; } fn slice(l: *Self, comptime E: type, s: SrcType) DecodeError![]E { - if (try l.ref()) |again| return @as([*]E, @ptrCast(@alignCast(again.ptr)))[0 .. again.len / @max(1, @sizeOf(E))]; + if (try l.ref(E)) |again| return @as([*]E, @ptrCast(@alignCast(again.ptr)))[0 .. again.len / @max(1, @sizeOf(E))]; const n = try l.count(); if (n == 0) return &.{}; if (n > l.bytes.len - l.at) return error.EndOfDump; const many = try l.gpa.alloc(E, n); - const at = l.made(std.mem.sliceAsBytes(many), .of(E)) catch |err| { + const at = l.made(std.mem.sliceAsBytes(many), .of(E), typeWord(E)) catch |err| { l.gpa.free(many); return err; }; @@ -1994,14 +2003,14 @@ pub const Loader = struct { .float => _ = try l.take(s.bits / 8), .optional => if ((try l.take(1))[0] != 0) try l.skip(s.child), .one => if (try l.scalar(u32) == 0) { - _ = try l.made(&.{}, .@"1"); + _ = try l.made(&.{}, .@"1", 0); l.shared.items[l.shared.items.len - 1].dead = true; try l.skip(s.child); }, .slice => if (try l.scalar(u32) == 0) { const n = try l.scalar(u64); if (n > 0) { - _ = try l.made(&.{}, .@"1"); + _ = try l.made(&.{}, .@"1", 0); l.shared.items[l.shared.items.len - 1].dead = true; } try l.skipMany(s.child, n); @@ -2390,6 +2399,9 @@ pub const Get = struct { /// The value at `c`, made: what it points at is `gpa`'s. pub fn get(l: *Get, comptime T: type, c: Cursor) Error!T { + // As `Loader.get`: a value that fails leaves nothing made. + const at = l.mark(); + errdefer l.letGo(at); var out: T = undefined; try l.fresh(T, &out); try l.value(T, c, &out); @@ -2441,8 +2453,8 @@ pub const Get = struct { /// An allocation made for the value at `slot`, kept: what a value met /// again is, and what `rollback` frees. - fn keep(l: *Get, bytes: []u8, alignment: std.mem.Alignment, slot: xitdb.Slot) Error!usize { - try l.made.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa }); + fn keep(l: *Get, bytes: []u8, alignment: std.mem.Alignment, slot: xitdb.Slot, of: u64) Error!usize { + try l.made.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa, .of = of }); const at = l.made.items.len - 1; // Not kept after all: the caller frees it. if (placed(slot)) l.memo.put(l.own, slotWord(slot), at) catch |err| { @@ -2453,13 +2465,14 @@ pub const Get = struct { } /// The value made before for the same place, when there was one. - fn again(l: *Get, slot: xitdb.Slot) Error!?[]u8 { + fn again(l: *Get, slot: xitdb.Slot, comptime E: type) Error!?[]u8 { if (!placed(slot)) return null; const at = l.memo.get(slotWord(slot)) orelse return null; // Made, then let go of by the reader's caller (a dump's mounts). if (at >= l.made.items.len) return null; const m = l.made.items[at]; if (m.dead) return error.Incompatible; + if (m.of != typeWord(E)) return error.BadDump; return m.bytes; } @@ -2539,12 +2552,12 @@ pub const Get = struct { }, .one => { const C = @typeInfo(T).pointer.child; - if (try l.again(slot)) |bytes| { + if (try l.again(slot, C)) |bytes| { out.* = @ptrCast(@alignCast(bytes.ptr)); return; } const one = try l.gpa.create(C); - const at = l.keep(std.mem.asBytes(one), .of(C), slot) catch |err| { + const at = l.keep(std.mem.asBytes(one), .of(C), slot, typeWord(C)) catch |err| { l.gpa.destroy(one); return err; }; @@ -2674,7 +2687,7 @@ pub const Get = struct { /// A slice of `E` at `c`: numbers' bytes, a blob's text by its hash, or /// a list; one met again is the same. fn slice(l: *Get, comptime E: type, c: Cursor, slot: xitdb.Slot) Error![]E { - if (try l.again(slot)) |bytes| return @as([*]E, @ptrCast(@alignCast(bytes.ptr)))[0 .. bytes.len / @max(1, @sizeOf(E))]; + if (try l.again(slot, E)) |bytes| return @as([*]E, @ptrCast(@alignCast(bytes.ptr)))[0 .. bytes.len / @max(1, @sizeOf(E))]; if (comptime numbers(E)) { switch (slot.tag) { .bytes, .short_bytes => {}, @@ -2692,7 +2705,7 @@ pub const Get = struct { l.gpa.free(got.bytes); return &.{}; } - _ = l.keep(got.bytes, .@"1", slot) catch |err| { + _ = l.keep(got.bytes, .@"1", slot, typeWord(u8)) catch |err| { l.gpa.free(got.bytes); return err; }; @@ -2704,7 +2717,7 @@ pub const Get = struct { const n = got.bytes.len / width; if (n == 0) return &.{}; const many = try l.gpa.alloc(E, n); - const at = l.keep(std.mem.sliceAsBytes(many), .of(E), slot) catch |err| { + const at = l.keep(std.mem.sliceAsBytes(many), .of(E), slot, typeWord(E)) catch |err| { l.gpa.free(many); return err; }; @@ -2721,7 +2734,7 @@ pub const Get = struct { // sizes nothing. if (n > (c.db.core.length() catch return error.BadDump) / (@bitSizeOf(xitdb.Slot) / 8)) return error.BadDump; const many = try l.gpa.alloc(E, n); - const at = l.keep(std.mem.sliceAsBytes(many), .of(E), slot) catch |err| { + const at = l.keep(std.mem.sliceAsBytes(many), .of(E), slot, typeWord(E)) catch |err| { l.gpa.free(many); return err; }; @@ -2742,7 +2755,7 @@ pub const Get = struct { const at = (texts.getCursor(std.mem.readInt(u256, got.value[0..32], .big)) catch return error.BadDump) orelse return error.BadDump; const text = at.readBytesAlloc(l.gpa, most(at)) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.BadDump; const bytes: []u8 = @constCast(text); - _ = l.keep(bytes, .@"1", slot) catch |err| { + _ = l.keep(bytes, .@"1", slot, typeWord(u8)) catch |err| { l.gpa.free(bytes); return err; }; -- cgit v1.3