diff options
Diffstat (limited to 'src/rollback.zig')
| -rw-r--r-- | src/rollback.zig | 496 |
1 files changed, 496 insertions, 0 deletions
diff --git a/src/rollback.zig b/src/rollback.zig new file mode 100644 index 00000000..9137b6f6 --- /dev/null +++ b/src/rollback.zig @@ -0,0 +1,496 @@ +//! A replica's rollback copy (docs/next-daemon.md, phase 5): the state a +//! speculation can write, saved before it writes, and put back where it was +//! when the authority's order differs. +//! +//! Two halves: +//! - `Epoch`, the replica core's allocator. It knows every allocation, and +//! while a copy is held it frees nothing that was there before (a free +//! is put off) and grows nothing of then in place. What is allocated +//! meanwhile is the epoch's. So whatever the core held when the copy was +//! taken is still where it was when the copy is put back. +//! - `Copy`, the walker's walk of the core's state (src/walk.zig: what a +//! digest covers, so views, buffers, registers, counters and terminal +//! metadata), saving the bytes of every allocation it reaches, the core +//! struct's own included. A file's text, its line index and its undo +//! snapshots are pinned instead: an edit puts a new buffer in their +//! place (File.setContentSpan) and never writes one, so the copy keeps +//! a reference and the put-off free keeps it alive. +//! +//! Putting the copy back writes each saved allocation's bytes over it, so +//! every pointer in them points where it did, at what was there; then the +//! epoch's allocations are freed and its put-off frees forgotten. Letting +//! the copy go (the speculation was right) makes the put-off frees. +//! +//! ponytail: an allocation reached only through a field the walk leaves +//! out (a derived cache's own heap, say) is not saved; that cache is the +//! epoch's as it was written, which is right for one remade from the text +//! it was made of and wrong for one changed in place. The replica harness +//! (test/replicas.zig) checks a digest at every confirmed step. +const std = @import("std"); +const builtin = @import("builtin"); +const pardes = @import("pardes.zig"); +const walk = @import("walk.zig"); +const Allocator = std.mem.Allocator; +const Alignment = std.mem.Alignment; +const Pardes = pardes.Pardes; + +/// Blobs this long or longer (`pinned`) are pinned, not copied. Checked +/// unchanged in a safe build when the copy goes. +const blob_min = 4096; +const checked = builtin.mode == .debug or builtin.mode == .safe; + +pub const Epoch = struct { + child: Allocator = std.heap.c_allocator, + /// Its own bookkeeping, never the epoch's. + meta: Allocator = std.heap.c_allocator, + live: std.AutoHashMapUnmanaged(usize, Entry) = .empty, + on: bool = false, + id: u32 = 0, + born: std.ArrayListUnmanaged(usize) = .empty, + deferred: std.ArrayListUnmanaged(usize) = .empty, + trees: pardes.syntax.HeldTrees = .{ .meta = std.heap.c_allocator }, + + const Entry = struct { len: usize, alignment: Alignment, epoch: u32, freed: bool = false }; + + pub fn allocator(e: *Epoch) Allocator { + return .{ .ptr = e, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } }; + } + + pub fn deinit(e: *Epoch) void { + var it = e.live.iterator(); + while (it.next()) |kv| e.child.rawFree(@as([*]u8, @ptrFromInt(kv.key_ptr.*))[0..kv.value_ptr.len], kv.value_ptr.alignment, @returnAddress()); + e.live.deinit(e.meta); + e.born.deinit(e.meta); + e.deferred.deinit(e.meta); + e.trees.born.deinit(e.meta); + e.trees.freed.deinit(e.meta); + } + + fn mine(e: *const Epoch, entry: Entry) bool { + return e.on and entry.epoch == e.id; + } + + /// The live allocation that starts at `addr`. + pub fn owns(e: *const Epoch, addr: usize) ?Entry { + const entry = e.live.get(addr) orelse return null; + return if (entry.freed) null else entry; + } + + fn note(e: *Epoch, addr: usize, len: usize, alignment: Alignment) bool { + e.live.put(e.meta, addr, .{ .len = len, .alignment = alignment, .epoch = if (e.on) e.id else 0 }) catch return false; + if (e.on) e.born.append(e.meta, addr) catch {}; + return true; + } + + /// Every new allocation filled with this: a core reading memory it never + /// wrote shows as a replica's divergence (test/replicas.zig, a release + /// build's heap is otherwise whatever it was). + pub var fill: ?u8 = null; + + fn alloc(ctx: *anyopaque, len: usize, alignment: Alignment, ra: usize) ?[*]u8 { + const e: *Epoch = @ptrCast(@alignCast(ctx)); + const ptr = e.child.rawAlloc(len, alignment, ra) orelse return null; + if (fill) |b| @memset(ptr[0..len], b); + if (!e.note(@intFromPtr(ptr), len, alignment)) { + e.child.rawFree(ptr[0..len], alignment, ra); + return null; + } + return ptr; + } + + fn resize(ctx: *anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ra: usize) bool { + const e: *Epoch = @ptrCast(@alignCast(ctx)); + const entry = e.live.getPtr(@intFromPtr(memory.ptr)) orelse return false; + // What the copy saved stays its size: the core moves instead. + if (e.on and !e.mine(entry.*)) return false; + if (!e.child.rawResize(memory, alignment, new_len, ra)) return false; + entry.len = new_len; + return true; + } + + fn remap(ctx: *anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ra: usize) ?[*]u8 { + const e: *Epoch = @ptrCast(@alignCast(ctx)); + const old = @intFromPtr(memory.ptr); + const entry = e.live.get(old) orelse return null; + if (e.on and !e.mine(entry)) return null; + const ptr = e.child.rawRemap(memory, alignment, new_len, ra) orelse return null; + _ = e.live.remove(old); + e.live.put(e.meta, @intFromPtr(ptr), .{ .len = new_len, .alignment = alignment, .epoch = entry.epoch }) catch {}; + if (e.mine(entry) and @intFromPtr(ptr) != old) e.born.append(e.meta, @intFromPtr(ptr)) catch {}; + return ptr; + } + + fn free(ctx: *anyopaque, memory: []u8, alignment: Alignment, ra: usize) void { + const e: *Epoch = @ptrCast(@alignCast(ctx)); + const addr = @intFromPtr(memory.ptr); + const entry = e.live.getPtr(addr) orelse return e.child.rawFree(memory, alignment, ra); + if (e.on and !e.mine(entry.*)) { + // Held by the copy until it is put back or let go. + if (!entry.freed) e.deferred.append(e.meta, addr) catch {}; + entry.freed = true; + return; + } + e.child.rawFree(memory.ptr[0..entry.len], entry.alignment, ra); + _ = e.live.remove(addr); + } + + fn reallyFree(e: *Epoch, addr: usize) void { + const entry = e.live.get(addr) orelse return; + e.child.rawFree(@as([*]u8, @ptrFromInt(addr))[0..entry.len], entry.alignment, @returnAddress()); + _ = e.live.remove(addr); + } + + fn begin(e: *Epoch) void { + std.debug.assert(!e.on); + e.id +%= 1; + if (e.id == 0) e.id = 1; + e.on = true; + e.born.clearRetainingCapacity(); + e.deferred.clearRetainingCapacity(); + e.trees.born.clearRetainingCapacity(); + e.trees.freed.clearRetainingCapacity(); + pardes.syntax.held_trees = &e.trees; + } + + /// The copy put back: what the epoch made goes, what it freed stays. + fn discard(e: *Epoch) void { + for (e.born.items) |addr| if (e.live.get(addr)) |entry| if (e.mine(entry)) e.reallyFree(addr); + for (e.deferred.items) |addr| if (e.live.getPtr(addr)) |entry| { + entry.freed = false; + }; + for (e.trees.born.items) |t| pardes.syntax.destroyTree(t); + e.end(); + } + + /// The copy let go: what the epoch freed goes now. + fn keep(e: *Epoch) void { + for (e.deferred.items) |addr| e.reallyFree(addr); + for (e.trees.freed.items) |t| pardes.syntax.destroyTree(t); + e.end(); + } + + fn end(e: *Epoch) void { + e.on = false; + e.born.clearRetainingCapacity(); + e.deferred.clearRetainingCapacity(); + e.trees.born.clearRetainingCapacity(); + e.trees.freed.clearRetainingCapacity(); + if (pardes.syntax.held_trees == &e.trees) pardes.syntax.held_trees = null; + } + + /// The trees of whichever core is stepped next: one in-process harness + /// steps several (syntax.held_trees is process-wide). + pub fn select(e: ?*Epoch) void { + pardes.syntax.held_trees = if (e) |x| (if (x.on) &x.trees else null) else null; + } +}; + +pub const Copy = struct { + meta: Allocator = std.heap.c_allocator, + regions: std.ArrayListUnmanaged(Region) = .empty, + bytes: std.ArrayListUnmanaged(u8) = .empty, + seen: std.AutoHashMapUnmanaged(Seen, void) = .empty, + pins: std.ArrayListUnmanaged(Pin) = .empty, + held: bool = false, + epoch: ?*Epoch = null, + /// The field being walked, for a pin's report, and whether it is one + /// of the blobs: a file's text or an undo snapshot's. + where: []const u8 = "", + pinnable: bool = false, + + const Region = struct { addr: usize, off: usize, len: usize }; + const Pin = struct { addr: usize, len: usize, hash: u64, where: []const u8 }; + const Seen = struct { addr: usize, ty: usize }; + pub const Error = Allocator.Error; + + pub fn deinit(c: *Copy) void { + c.regions.deinit(c.meta); + c.bytes.deinit(c.meta); + c.seen.deinit(c.meta); + c.pins.deinit(c.meta); + } + + pub fn savedBytes(c: *const Copy) usize { + return c.bytes.items.len; + } + + pub fn pinnedBytes(c: *const Copy) usize { + var n: usize = 0; + for (c.pins.items) |pin| n += pin.len; + return n; + } + + /// The copy of `p`, whose allocator is `e`'s, taken: from now on what + /// it held stays where it is until the copy is put back or let go. + pub fn take(c: *Copy, e: *Epoch, p: *const Pardes) Error!void { + std.debug.assert(!c.held); + c.regions.clearRetainingCapacity(); + c.bytes.clearRetainingCapacity(); + c.seen.clearRetainingCapacity(); + c.pins.clearRetainingCapacity(); + c.epoch = e; + // A step drains these before it ends: between steps they hold + // nothing, and a copy is taken between steps. + std.debug.assert(p.effects_len == 0 and p.in_len == 0); + if (c.epoch.?.owns(@intFromPtr(p)) == null) @panic("rollback: the core is not its epoch's"); + try c.object(Pardes, p); + e.begin(); + c.held = true; + } + + /// The core as it was when the copy was taken. + pub fn restore(c: *Copy) void { + std.debug.assert(c.held); + c.check(); + for (c.regions.items) |r| @memcpy(@as([*]u8, @ptrFromInt(r.addr))[0..r.len], c.bytes.items[r.off..][0..r.len]); + c.epoch.?.discard(); + c.held = false; + } + + /// The speculation was right: the copy is not wanted. + pub fn release(c: *Copy) void { + std.debug.assert(c.held); + c.check(); + c.epoch.?.keep(); + c.held = false; + } + + pub fn check(c: *const Copy) void { + if (comptime !checked) return; + for (c.pins.items) |pin| if (std.hash.Wyhash.hash(0, @as([*]const u8, @ptrFromInt(pin.addr))[0..pin.len]) != pin.hash) { + const now = @as([*]const u8, @ptrFromInt(pin.addr))[0..pin.len]; + const entry = c.epoch.?.live.get(pin.addr); + std.debug.print("rollback: {s}, {d} bytes at {x}, pinned, was written in place: now {any}; entry {any}, epoch {d}\n", .{ pin.where, pin.len, pin.addr, now[0..32], entry, c.epoch.?.id }); + @panic("rollback: a pinned blob was written in place"); + }; + } + + fn save(c: *Copy, addr: usize, len: usize) Error!void { + if (len == 0) return; + const off = c.bytes.items.len; + try c.bytes.appendSlice(c.meta, @as([*]const u8, @ptrFromInt(addr))[0..len]); + try c.regions.append(c.meta, .{ .addr = addr, .off = off, .len = len }); + } + + /// Whether the value at `addr` of type `T` was reached before. + fn reached(c: *Copy, comptime T: type, addr: usize) Error!bool { + const key: Seen = .{ .addr = addr, .ty = @intFromPtr(@typeName(T).ptr) }; + const got = try c.seen.getOrPut(c.meta, key); + return got.found_existing; + } + + /// The allocation at `addr`, saved once, whatever reaches it. + fn allocation(c: *Copy, addr: usize) Error!?usize { + const entry = c.epoch.?.owns(addr) orelse return null; + if (try c.reached(void, addr)) return entry.len; + try c.save(addr, entry.len); + return entry.len; + } + + fn visit(c: *Copy, comptime T: type, v: *const T) Error!void { + if (comptime !heapIn(T, 0)) return; + switch (@typeInfo(T)) { + .optional => |o| if (v.*) |*payload| try c.visit(o.child, payload), + .array => |a| if (comptime heapIn(a.child, 0)) for (v) |*e| try c.visit(a.child, e), + .pointer => |p| switch (p.size) { + .one => try c.object(p.child, v.*), + .slice => try c.slice(p.child, v.*), + // No length to walk by: its keeper's (a C handle's buffer). + else => {}, + }, + .@"struct" => |s| { + if (comptime walk.machinery(T)) return; + // A terminal: the authority's (its emulator is never written + // by a speculation: terminal.zig's guards). + if (comptime @hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *walk.Hasher) void) return; + if (s.layout == .@"packed") return; + if (comptime @hasField(T, "items") and @hasField(T, "capacity") and s.field_names.len == 2) { + if (v.capacity == 0) return; + _ = try c.allocation(@intFromPtr(v.items.ptr)); + const E = @typeInfo(@FieldType(T, "items")).pointer.child; + if (comptime heapIn(E, 0)) for (v.items) |*e| try c.visit(E, e); + return; + } + if (comptime @hasDecl(T, "KV") and @hasDecl(T, "Hash") and @hasField(T, "metadata")) { + const m = v.metadata orelse return; + // std's header sits before the metadata, at the start + // of the one allocation. + const header = std.mem.alignForward(usize, 2 * @sizeOf(usize) + @sizeOf(u32), @alignOf(usize)); + _ = try c.allocation(@intFromPtr(m) - header); + var it = v.iterator(); + while (it.next()) |entry| { + try c.visit(@TypeOf(entry.key_ptr.*), entry.key_ptr); + try c.visit(@TypeOf(entry.value_ptr.*), entry.value_ptr); + } + return; + } + if (comptime @hasField(T, "raw") and s.field_names.len == 1 and @hasDecl(T, "load")) return; + if (comptime @hasField(T, "any_future")) return; + if (comptime @hasField(T, "bit_length") and @hasField(T, "masks") and s.field_names.len == 2) { + if (v.bit_length == 0) return; + _ = try c.allocation(@intFromPtr(v.masks) - @sizeOf(@typeInfo(@FieldType(T, "masks")).pointer.child)); + return; + } + inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| { + // What a digest covers, the caches made from it and this + // process's own (the views not live are among it): a + // safe build's free writes over what it frees, so what + // the speculation freed would come back as that. Not the + // queues a step drains (undefined between steps), nor the + // authority's. + if (attr.@"comptime" or comptime (annotated(T, "authority", name) or (annotated(T, "local", name) and unsaved(name)))) continue; + if (comptime opaqueTo(F)) continue; + c.where = @typeName(T) ++ "." ++ name; + c.pinnable = comptime pinned(T, name); + if (comptime walk.lengthOf(T, name) != null and @typeInfo(F) == .array) { + const len = comptime walk.lengthOf(T, name).?; + if (comptime heapIn(@typeInfo(F).array.child, 0)) for (@field(v, name)[0..walk.lengthIn(v, len)]) |*e| try c.visit(@typeInfo(F).array.child, e); + } else try c.visit(F, &@field(v, name)); + } + }, + .@"union" => switch (v.*) { + inline else => |*payload| try c.visit(@TypeOf(payload.*), payload), + }, + .error_union => |e| if (v.*) |*payload| try c.visit(e.payload, payload) else |_| {}, + else => {}, + } + } + + fn object(c: *Copy, comptime P: type, ptr: *const P) Error!void { + if (comptime walk.machinery(P)) return; + const addr = @intFromPtr(ptr); + if (try c.reached(P, addr)) return; + if (comptime @hasDecl(P, "digest") and @TypeOf(P.digest) == fn (*const P, *walk.Hasher) void) return; + if (c.epoch.?.owns(addr) != null) { + _ = try c.reached(void, addr); + try c.fields(P, ptr); + } + try c.visit(P, ptr); + } + + /// A struct's bytes, field by field where it says what its fields are: + /// all of them (this process's own too, which the epoch's frees would + /// leave pointing at nothing), but the queues a step drains and the + /// frame statistics (numbers, megabytes of them), and an array only as + /// far as its length says. + fn fields(c: *Copy, comptime T: type, v: *const T) Error!void { + if (comptime @typeInfo(T) != .@"struct" or !@hasDecl(T, "replica")) return c.save(@intFromPtr(v), @sizeOf(T)); + const s = @typeInfo(T).@"struct"; + inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| { + if (attr.@"comptime") continue; + if (comptime annotated(T, "local", name) and unsaved(name)) continue; + 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)); + } else if (comptime annotatedStruct(F)) { + try c.fields(F, &@field(v, name)); + } else if (comptime @typeInfo(F) == .array and annotatedStruct(@typeInfo(F).array.child)) { + for (&@field(v, name)) |*e| try c.fields(@typeInfo(F).array.child, e); + } else try c.save(at, @sizeOf(F)); + } + } + + fn slice(c: *Copy, comptime E: type, s: []const E) Error!void { + if (s.len == 0) return; + const addr = @intFromPtr(s.ptr); + if (try c.reached([]const E, addr)) return; + if (comptime !heapIn(E, 0)) if (c.pinnable and s.len * @sizeOf(E) >= blob_min and c.epoch.?.owns(addr) != null) { + 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; + }; + _ = try c.allocation(addr); + if (comptime heapIn(E, 0)) for (s) |*e| try c.visit(E, e); + } +}; + +/// The blobs: what an edit puts in place of its predecessor, never writes +/// (File.setContentSpan), and frees raw (memory.freeUnfilled, freeRaw). +fn pinned(comptime T: type, comptime name: []const u8) bool { + const File = pardes.panes.File; + return (T == File.State and (std.mem.eql(u8, name, "content") or std.mem.eql(u8, name, "line_starts"))) or + (T == File.Snapshot and std.mem.eql(u8, name, "content")); +} + +fn annotatedStruct(comptime T: type) bool { + return @typeInfo(T) == .@"struct" and @hasDecl(T, "replica"); +} + +/// The queues every step drains (empty between steps, asserted when a copy +/// is taken: what is in their slots is nothing), and the frame statistics +/// (numbers, and a static name). +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"); +} + +fn annotated(comptime T: type, comptime kind: []const u8, comptime name: []const u8) bool { + @setEvalBranchQuota(100_000); + if (!@hasDecl(T, "replica") or !@hasField(@TypeOf(T.replica), kind)) return false; + inline for (@field(T.replica, kind)) |n| if (comptime std.mem.eql(u8, n, name)) return true; + return false; +} + +/// A field no walk sees into (a C handle, a function): its own keeper's. +fn opaqueTo(comptime F: type) bool { + return switch (@typeInfo(F)) { + .optional => |o| opaqueTo(o.child), + .pointer => |p| p.size == .many or p.size == .c or switch (@typeInfo(p.child)) { + .@"opaque", .@"fn" => true, + else => false, + }, + else => false, + }; +} + +/// Whether a `T` can hold a pointer to the heap at all (else a walk of it +/// finds nothing to save). Deep types count as yes. +fn heapIn(comptime T: type, comptime depth: u32) bool { + if (depth > 12) return true; + return switch (@typeInfo(T)) { + .void, .null, .undefined, .bool, .int, .float, .@"enum", .error_set, .comptime_int, .comptime_float, .enum_literal, .type => false, + .optional => |o| heapIn(o.child, depth + 1), + .array => |a| a.len > 0 and heapIn(a.child, depth + 1), + .pointer => true, + .error_union => |e| heapIn(e.payload, depth + 1), + .@"struct" => |s| blk: { + if (s.layout == .@"packed") break :blk false; + for (s.field_types, s.field_attrs) |F, attr| if (!attr.@"comptime" and heapIn(F, depth + 1)) break :blk true; + break :blk false; + }, + .@"union" => |u| blk: { + for (u.field_types) |F| if (heapIn(F, depth + 1)) break :blk true; + break :blk false; + }, + else => true, + }; +} + +test "a copy put back is the core as it was; one let go keeps what was done" { + var e: Epoch = .{ .child = std.testing.allocator }; + defer e.deinit(); + const gpa = e.allocator(); + const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .image_allocator = gpa, .pdf_allocator = gpa, .tree_sitter_allocator = gpa, .frame_allocator = gpa }); + p.pump(.{}) catch {}; + const before = walk.digest(Pardes, p); + var c: Copy = .{}; + defer c.deinit(); + const typed = "ox y z"; + try c.take(&e, p); + for (typed) |k| p.update(.{ .key = .{ .cp = k, .text = &.{k} } }); + p.update(.{ .key = .{ .cp = pardes.Key.escape } }); + p.pump(.{}) catch {}; + const edited = walk.digest(Pardes, p); + try std.testing.expect(edited != before); + c.restore(); + try std.testing.expectEqual(before, walk.digest(Pardes, p)); + // The same again, let go this time: what was typed stays. + try c.take(&e, p); + for (typed) |k| p.update(.{ .key = .{ .cp = k, .text = &.{k} } }); + p.update(.{ .key = .{ .cp = pardes.Key.escape } }); + p.pump(.{}) catch {}; + try std.testing.expectEqual(edited, walk.digest(Pardes, p)); + c.release(); + try std.testing.expectEqual(edited, walk.digest(Pardes, p)); + p.deinit(); + try std.testing.expectEqual(@as(usize, 0), e.live.count()); +} |
