summaryrefslogtreecommitdiff
path: root/src/host/Sessions.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-17 01:27:03 -0300
committerGabriel Schneider <[email protected]>2026-11-17 12:15:01 -0300
commit8bf10e316178755b8710e27c807dbf9b6a1d37a8 (patch)
tree99edaa7916fe0c2e5f7f90bd600c32f414fbc47d /src/host/Sessions.zig
parent1ce323f2f21b94f9c4fc4e7a6986612cf30cf183 (diff)
downloadsketchbook-8bf10e316178755b8710e27c807dbf9b6a1d37a8.tar.gz
sketchbook-8bf10e316178755b8710e27c807dbf9b6a1d37a8.zip
The cap: a save is at most 64 MiB, State half of it, history dropped oldest first
A save grew without bound. Now Sessions.max_save is 64 MiB and layout.max_state 32 MiB, so history always has room (the compile error says so: "State is N bytes, and may be 32 MiB, half of a save, so history has room: ..."). A commit that leaves the file past the cap trims it (Sessions.trim): one transaction drops history oldest first, a keyframe by removing its pages (its frame, batch and time stay, so keyframe numbers, keyBefore and marks by index still resolve) and a batch of frames by emptying its slot, until the keyframes' written pages and the batches left count three quarters of the cap; then the file is compacted into `<path>.new` and renamed over it, and the run goes on in the new file (compact now reopens). A dropped keyframe's pages may still be shared by a later one, so a round can free less than it counted: the next round lowers the count by the overshoot, four rounds at most. Never dropped: the present (the newest keyframe and the batches from its own on), the keyframe of the newest mark of each name, the keyframe of the newest clip of each name and every batch holding one of its frames. A session left with nothing loses its keyframes, batches and stretches; its summary stays. Asked for, what was dropped is error.HistoryDropped, which the console says in words ("That part of the history is gone: a save keeps 64 MiB, the newest."). Marks are pinned under the cap: a mark of a new name needs room for a whole State, history trimmed to make it; without, it is refused, error.SaveFull, the console saying how to make room: save over a mark's name (the older one then goes with history) or start another save. A mark over an existing name is always taken. (The spec's "room" rule, refusing only after a trim failed, let one mark take the file past the cap; room for a whole State keeps the cap hard, at the price of refusing early for a big State.) Builds that do not record (`history` false, from Info.record) use the same mechanism with the history limit zero: every commit holding a keyframe drops all it may (no compaction unless past the cap), and the exit compacts, so the disk holds at most the last minute of input while it runs and the present and the marks after. The exit compaction a recording build made past twice its contents plus 64 MiB is gone: the cap's compaction does that work. Measured (Debug, unit test): a trim of a 64 MiB file to 48 MiB takes 165-187 ms (two rounds of drop and compaction, the first ending 0.5% over); a no-history trim at a keyframe, 0-5 ms. ReleaseFast not measured. The console's `marks` reads each mark's keyframe fields, not its State: an older mark of a name may have gone with history (listed "dropped" when its session went whole). Docs: record means "keep history" in App.Options, sketch.Build and abi.Info. Tests: zig build test, 168/168 steps, 137/137 tests. New, in Sessions.zig: 100 keyframes of 1 MiB each with marks at the 5th and 20th: the file never past the cap, the oldest keyframes and frames HistoryDropped, both marks and the newest keyframe whole, the present's frames readable; without history, 20 keyframes and a mark: only the mark and the present stay, the file compacted at exit under three times the State and the present reopening whole; 2 MiB marks until one is refused (SaveFull, the file under the cap), then one over an old name taken and the file under the cap, every mark whole. micscope 67/67, 10/10; spheres 75/75, 3/3; noc e2e 292/292; the drat-meout copy 87/87, 30/30. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'src/host/Sessions.zig')
-rw-r--r--src/host/Sessions.zig349
1 files changed, 326 insertions, 23 deletions
diff --git a/src/host/Sessions.zig b/src/host/Sessions.zig
index ae649bf..cf0ab24 100644
--- a/src/host/Sessions.zig
+++ b/src/host/Sessions.zig
@@ -34,8 +34,14 @@
//! One transaction (`commit`) a second of session time, and at once for a
//! reload, a mark, a clip's start or end, and exit: a crash loses less than
//! a second of play; fsync only at exit and for a mark. A file a crash or
-//! power loss tore opens at its last whole commit (`mend`); a clean exit
-//! compacts one that commits left past twice its contents (`close`).
+//! power loss tore opens at its last whole commit (`mend`).
+//!
+//! A save is at most `max_save`: a commit that leaves the file past it
+//! drops history oldest first and compacts the file to three quarters of
+//! it (`trim`); the present, the newest mark of each name and the newest
+//! clip of each name are never dropped. A build that does not record
+//! (`history` false) drops all it may at every keyframe, and compacts at
+//! exit: what it keeps is the present and the marks.
const Sessions = @This();
const std = @import("std");
const xitdb = @import("xitdb");
@@ -59,6 +65,9 @@ pub const max_name = 32;
/// A memory database (a scripted run's) stops recording at this size: ten
/// hours or more of play at 60 Hz. What it holds stays readable.
pub const memory_max: u64 = 256 << 20;
+/// The most a save's file holds (State is at most half of it,
+/// `abi.layout.max_state`, so history has room).
+pub const max_save: u64 = 64 << 20;
pub const K = enum(u64) { version = 1, sessions, marks, clips, started, ended, from, stretches, batches, keys, frames, frame, build, source, layout, batch, stretch, why, time, state, line, name, session, key, start, end, pages, size, written };
fn key(k: K) u64 {
@@ -123,6 +132,8 @@ full: bool = false,
/// The console line that last changed State, for the next keyframe.
line: [256]u8 = undefined,
line_len: usize = 0,
+/// Keep history, up to `max_save`; else only the present and the marks.
+history: bool = true,
/// Opens the database at `path` (file mode: created with its directory when
/// missing; one a crash or power loss tore is opened at its last whole
@@ -195,40 +206,208 @@ pub fn deinit(s: *Sessions) void {
}
/// The last frames, an exit keyframe of `state`, and the session's end, in
-/// one transaction synced to disk; then closed.
+/// one transaction synced to disk; then closed. Without history the file is
+/// compacted, so the frames it dropped are gone from the disk too.
pub fn close(s: *Sessions, state: []const u8, ended: u64) void {
defer s.deinit();
if (s.db == .off) return;
s.stopClip() catch {};
_ = s.keyframe(.exit, state) catch {};
s.commitSynced(.{ .end = ended }) catch |err| std.log.warn("sessions: last commit failed: {t}", .{err});
- if (s.db != .file) return;
- const size = s.file.?.length(s.io) catch return;
- if (size < compact_floor) return;
- const live = liveSize(&s.db.file) catch return;
- if (size > 2 * live + compact_floor) s.compact() catch |err| std.log.warn("sessions: not compacted: {t}", .{err});
+ if (s.db == .file and !s.history) s.compact() catch |err| std.log.warn("sessions: not compacted: {t}", .{err});
}
-/// The database's file compacted at a clean exit, once it is past twice what
-/// its batches and keyframes hold plus this: every commit leaves the
-/// nodes it copied behind.
-const compact_floor: u64 = 64 << 20;
-
/// Writes what the database holds now, without the nodes commits left
-/// behind, to `<path>.new`, synced, and renames it over the file.
+/// behind, to `<path>.new`, synced, renames it over the file, and goes on
+/// in it.
fn compact(s: *Sessions) !void {
const cwd = std.Io.Dir.cwd();
var buf: [std.fs.max_path_bytes + 8]u8 = undefined;
const new = try std.fmt.bufPrint(&buf, "{s}.new", .{s.path});
const file = try cwd.createFile(s.io, new, .{ .read = true, .truncate = true });
- errdefer cwd.deleteFile(s.io, new) catch {};
- defer file.close(s.io);
- var buffer: std.Io.Writer.Allocating = .init(s.gpa);
- defer buffer.deinit();
+ errdefer {
+ file.close(s.io);
+ cwd.deleteFile(s.io, new) catch {};
+ }
+ const buffer = try s.gpa.create(std.Io.Writer.Allocating);
+ buffer.* = .init(s.gpa);
+ errdefer {
+ buffer.deinit();
+ s.gpa.destroy(buffer);
+ }
var offsets: std.AutoHashMap(u64, u64) = .init(s.gpa);
defer offsets.deinit();
- _ = try s.db.file.compact(.buffered_file, .{ .file = file, .buffer = &buffer, .fsync = true }, &offsets);
+ var db = try s.db.file.compact(.buffered_file, .{ .file = file, .buffer = buffer, .fsync = true }, &offsets);
+ db.core.file.fsync = false;
try cwd.rename(new, cwd, s.path, s.io);
+ s.file.?.close(s.io);
+ s.buffer.?.deinit();
+ s.gpa.destroy(s.buffer.?);
+ s.file = file;
+ s.buffer = buffer;
+ s.db = .{ .file = db };
+}
+
+/// Drops history oldest first, then compacts the file: until its keyframes'
+/// pages and frames are under three quarters of `max_save`, or, without
+/// history, all it may (compacted only past `max_save`; `close` does it
+/// at exit). A few rounds at most: what a dropped keyframe wrote may still
+/// be shared by one kept, so a round can free less than it counted.
+fn trim(s: *Sessions) !void {
+ const goal = max_save / 4 * 3;
+ var keep: u64 = if (s.history) goal else 0;
+ for (0..4) |_| {
+ var dropped: u64 = 0;
+ var left: u64 = 0;
+ try s.db.file.runContext(Trim(Disk){ .s = s, .keep = keep, .dropped = &dropped, .left = &left });
+ var size = try s.file.?.length(s.io);
+ if (!s.history and size <= max_save) return;
+ try s.compact();
+ size = try s.file.?.length(s.io);
+ if (size <= goal or dropped == 0) return;
+ // What the count leaves out (lists, maps, stretches) is the rest.
+ keep = left -| (size - goal);
+ }
+}
+
+/// A keyframe's pages or a batch of frames, for `trim`.
+const Item = struct { session: u64, index: u64, frame: u64, bytes: u64, batch: bool, keep: bool };
+
+/// The transaction of `trim`: drops a keyframe by removing its pages (its
+/// fields stay, so keyframe numbers and searches by frame still work) and
+/// a batch by emptying its slot, oldest first, until what is left counts at
+/// most `keep` bytes; a session left with nothing loses its keyframes,
+/// batches and stretches. Never the present (the newest keyframe and the
+/// batches from its own on), the keyframe of the newest mark or clip of a
+/// name, or a batch holding a frame of such a clip.
+fn Trim(comptime DB: type) type {
+ return struct {
+ s: *Sessions,
+ keep: u64,
+ /// Bytes dropped, and counted after.
+ dropped: *u64,
+ left: *u64,
+
+ const R = Read(DB);
+ const Map = DB.HashMap(.read_write);
+ const List = DB.ArrayList(.read_write);
+
+ pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void {
+ var arena: std.heap.ArenaAllocator = .init(ctx.s.gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const root = try Map.init(cursor.*);
+ const all = try R.list(root.readOnly(), .sessions) orelse return;
+ const n = try all.count();
+ var pinned: std.AutoHashMapUnmanaged(At, void) = .empty;
+ const Clip = struct { session: u64, start: u64, end: u64 };
+ var clips: std.ArrayList(Clip) = .empty;
+ for ([_]K{ .marks, .clips }) |which| {
+ const list = try R.list(root.readOnly(), which) orelse continue;
+ var names: std.StringHashMapUnmanaged(void) = .empty;
+ var i = try list.count();
+ while (i > 0) {
+ i -= 1;
+ const e = try R.at(list, i);
+ var buf: [max_name]u8 = undefined;
+ const name = (try R.field(e, .name)).readBytes(&buf) catch return error.CorruptSession;
+ if ((try names.getOrPut(a, try a.dupe(u8, name))).found_existing) continue;
+ const at: At = .{ .session = try R.uint(e, .session), .key = try R.uint(e, .key) };
+ try pinned.put(a, at, {});
+ const end = if (which == .clips) try R.uint(e, .end) else continue;
+ try clips.append(a, .{ .session = at.session, .start = try R.uint(e, .start), .end = if (end == 0) std.math.maxInt(u64) else end });
+ }
+ }
+ // The present: the newest keyframe, and the batches from its own on.
+ var now: At = undefined;
+ var now_batch: u64 = 0;
+ var i = n;
+ while (true) {
+ if (i == 0) return;
+ i -= 1;
+ const keys = try R.list(try R.at(all, i), .keys) orelse continue;
+ const n_keys = try keys.count();
+ if (n_keys == 0) continue;
+ now = .{ .session = i, .key = n_keys - 1 };
+ now_batch = try R.uint(try R.at(keys, n_keys - 1), .batch);
+ break;
+ }
+ try pinned.put(a, now, {});
+ // What is not dropped yet, each session's in frame order.
+ var items: std.ArrayList(Item) = .empty;
+ var total: u64 = 0;
+ for (0..n) |si| {
+ const ses = try R.at(all, si);
+ const start = items.items.len;
+ if (try R.list(ses, .keys)) |keys| for (0..try keys.count()) |k| {
+ const e = try R.at(keys, k);
+ if (try e.getCursor(key(.pages)) == null) continue;
+ const written = if (try e.getCursor(key(.written))) |w| try w.readUint() else 0;
+ try items.append(a, .{ .session = si, .index = k, .frame = try R.uint(e, .frame), .bytes = written, .batch = false, .keep = pinned.contains(.{ .session = si, .key = k }) });
+ };
+ if (try R.list(ses, .batches)) |batches| for (0..try batches.count()) |b| {
+ var c = try batches.getCursor(@intCast(b)) orelse continue;
+ if ((try c.slot()).tag == .none) continue;
+ var buf: [8]u8 = undefined;
+ var reader = try c.reader(&buf);
+ var head: [8]u8 = undefined;
+ try reader.interface.readSliceAll(&head);
+ try items.append(a, .{ .session = si, .index = b, .frame = std.mem.readInt(u64, &head, .little), .bytes = reader.size, .batch = true, .keep = si == now.session and b >= now_batch });
+ };
+ const mine = items.items[start..];
+ std.mem.sort(Item, mine, {}, struct {
+ fn lessThan(_: void, x: Item, y: Item) bool {
+ return x.frame < y.frame or (x.frame == y.frame and !x.batch and y.batch);
+ }
+ }.lessThan);
+ // A batch holds frames up to the next batch's first.
+ const frames = try R.uint(ses, .frames);
+ var end: u64 = std.math.maxInt(u64);
+ var j = mine.len;
+ while (j > 0) {
+ j -= 1;
+ const it = &mine[j];
+ if (!it.batch) continue;
+ const last = @min(end, frames);
+ for (clips.items) |clip| if (clip.session == si and clip.start < last and it.frame < clip.end) {
+ it.keep = true;
+ };
+ end = it.frame;
+ }
+ for (mine) |it| total += it.bytes;
+ }
+ // Dropped oldest first.
+ const sessions = try List.init(try root.putCursor(key(.sessions)));
+ var left: std.ArrayList(u64) = .empty;
+ try left.appendNTimes(a, 0, n);
+ for (items.items) |it| {
+ if (it.keep or total <= ctx.keep) {
+ left.items[it.session] += 1;
+ continue;
+ }
+ const ses = try Map.init(try sessions.putCursor(@intCast(it.session)));
+ if (it.batch) {
+ try (try List.init(try ses.putCursor(key(.batches)))).put(@intCast(it.index), .{ .slot = null });
+ } else {
+ const k = try Map.init(try (try List.init(try ses.putCursor(key(.keys)))).putCursor(@intCast(it.index)));
+ _ = try k.remove(key(.pages));
+ try k.put(key(.written), .{ .uint = 0 });
+ }
+ total -= it.bytes;
+ ctx.dropped.* += it.bytes;
+ }
+ ctx.left.* = total;
+ for (left.items, 0..) |kept, si| {
+ if (kept > 0 or si >= now.session) continue;
+ var any = false;
+ var it = pinned.keyIterator();
+ while (it.next()) |at| any = any or at.session == si;
+ if (any) continue;
+ const ses = try Map.init(try sessions.putCursor(@intCast(si)));
+ for ([_]K{ .keys, .batches, .stretches }) |k| _ = try ses.remove(key(k));
+ }
+ }
+ };
}
/// The bytes of every session's batches and keyframes' pages (each written
@@ -243,7 +422,7 @@ fn liveSize(db: *Disk) !u64 {
const session = try R.Map.init(c);
if (try R.list(session, .batches)) |batches| {
var b = try batches.iterator();
- while (try b.next()) |blob| live += try blob.count();
+ while (try b.next()) |blob| live += if ((try blob.slot()).tag == .none) 0 else try blob.count();
}
if (try R.list(session, .keys)) |keys| {
var k = try keys.iterator();
@@ -391,8 +570,15 @@ pub fn stretch(s: *Sessions, st: Stretch) !void {
}
/// Mark `name`: a keyframe of `state` (`why`: `.mark`, or `.import`),
-/// synced to disk. Returns the keyframe's index.
+/// synced to disk. Returns the keyframe's index. A mark of a new name needs
+/// room for a whole State under `max_save`, history dropped to make it
+/// (`trim`): without, it is refused (`error.SaveFull`). A mark over an
+/// existing name lets the older one go with history.
pub fn mark(s: *Sessions, name: []const u8, why: Why, state: []const u8) !u64 {
+ if (s.db == .file and try s.file.?.length(s.io) + state.len > max_save and try s.findMark(name) == null) {
+ try s.trim();
+ if (try s.file.?.length(s.io) + state.len > max_save) return error.SaveFull;
+ }
const k = try s.keyframe(why, state);
try s.commitSynced(.{ .mark = .{ .name = name, .key = k } });
return k;
@@ -460,7 +646,10 @@ pub fn commit(s: *Sessions, extra: Extra) !void {
s.committed = s.frames;
s.batch.clearRetainingCapacity();
}
+ const keyed = s.queued.items.len > 0;
s.dropQueued();
+ if (s.db != .file) return;
+ if ((try s.file.?.length(s.io)) > max_save or (!s.history and keyed)) s.trim() catch |err| std.log.warn("sessions: history not trimmed: {t}", .{err});
}
fn Commit(comptime DB: type) type {
@@ -668,7 +857,7 @@ pub fn load(s: *Sessions, session: u64, k: u64) !Loaded {
const stretch_entry = try R.at(try R.list(ses, .stretches) orelse return error.CorruptSession, st);
const why = std.enums.fromInt(Why, try R.uint(e, .why)) orelse return error.CorruptSession;
const pages = try R.list(e, .pages);
- const state = if (pages) |list| try R.pages(list, try R.uint(e, .size), s.gpa) else try R.bytes(e, .state, s.gpa);
+ const state = if (pages) |list| try R.pages(list, try R.uint(e, .size), s.gpa) else if (try e.getCursor(key(.state))) |whole| try whole.readBytesAlloc(s.gpa, null) else return error.HistoryDropped;
errdefer s.gpa.free(state);
const line = try R.bytes(e, .line, s.gpa);
errdefer s.gpa.free(line);
@@ -759,7 +948,9 @@ pub fn events(s: *Sessions, session: u64, from: u64, start: u64, end: u64, out:
const n = try batches.count();
var i = from;
while (i < n) : (i += 1) {
- const blob = try (try batches.getCursor(@intCast(i)) orelse return error.CorruptSession).readBytesAlloc(s.gpa, null);
+ const cursor = try batches.getCursor(@intCast(i)) orelse return error.CorruptSession;
+ if ((try cursor.slot()).tag == .none) return error.HistoryDropped;
+ const blob = try cursor.readBytesAlloc(s.gpa, null);
defer s.gpa.free(blob);
if (blob.len < 8 or (blob.len - 8) % @sizeOf(abi.Event) != 0) return error.CorruptSession;
var f = std.mem.readInt(u64, blob[0..8], .little);
@@ -1281,3 +1472,115 @@ test "an exported session keeps its keyframes' shared pages shared" {
defer loaded.free(gpa);
try std.testing.expectEqualSlices(u8, state, loaded.state);
}
+
+test "a session database past max_save drops its oldest history: the present and the marks stay, the file under it" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path});
+ // 2 MiB of State, its first half rewritten each second: a keyframe
+ // writes 1 MiB, so the cap is reached at about the 60th.
+ const state = try gpa.alloc(u8, 2 << 20);
+ defer gpa.free(state);
+ @memset(state, 1);
+ var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000);
+ defer s.deinit();
+ for (0..100) |k| {
+ @memset(state[0 .. 1 << 20], @truncate(k + 2));
+ var one = [_]abi.Event{abi.Event.tick(k * std.time.ns_per_s, std.time.ns_per_s)};
+ try s.frame(&one, state, if (k == 0) .start else .jump);
+ if (k == 5) _ = try s.mark("a", .mark, state);
+ if (k == 20) _ = try s.mark("b", .mark, state);
+ try std.testing.expect(try s.file.?.length(io) <= max_save);
+ }
+ try s.commit(.none);
+ // The oldest keyframes and frames are gone; the marks and the newest
+ // keyframe read back whole.
+ try std.testing.expectError(error.HistoryDropped, s.load(0, 1));
+ var log: std.ArrayList(abi.Event) = .empty;
+ defer log.deinit(gpa);
+ try std.testing.expectError(error.HistoryDropped, s.events(0, 0, 0, 2, &log));
+ for ([_]struct { []const u8, u8 }{ .{ "a", 7 }, .{ "b", 22 } }) |want| {
+ const m = (try s.findMark(want[0])).?;
+ const loaded = try s.load(m.session, m.key);
+ defer loaded.free(gpa);
+ try std.testing.expectEqual(want[1], loaded.state[0]);
+ try std.testing.expectEqual(@as(u8, 1), loaded.state[1 << 20]);
+ }
+ const newest = try s.load(0, s.keys - 1);
+ defer newest.free(gpa);
+ try std.testing.expectEqualSlices(u8, state, newest.state);
+ try s.events(0, newest.batch, newest.frame, s.frames, &log);
+}
+
+test "a session database without history keeps the present and the marks, and leaves nothing else at exit" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path});
+ var state: [64 << 10]u8 = @splat(1);
+ var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000);
+ s.history = false;
+ for (0..20) |k| {
+ @memset(state[0 .. 32 << 10], @truncate(k + 2));
+ var one = [_]abi.Event{abi.Event.tick(k * std.time.ns_per_s, std.time.ns_per_s)};
+ try s.frame(&one, &state, if (k == 0) .start else .jump);
+ if (k == 3) _ = try s.mark("a", .mark, &state);
+ }
+ try s.commit(.none);
+ try std.testing.expectError(error.HistoryDropped, s.load(0, 1));
+ const m = (try s.findMark("a")).?;
+ const loaded = try s.load(m.session, m.key);
+ loaded.free(gpa);
+ s.close(&state, 2000);
+ // At exit: compacted to the present, the mark and the session's fields.
+ try std.testing.expect((try tmp.dir.statFile(io, "t.xitdb", .{})).size < 3 * state.len);
+ var again = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 3000);
+ defer again.deinit();
+ var log: std.ArrayList(abi.Event) = .empty;
+ defer log.deinit(gpa);
+ const now = (try again.present(&log)).?;
+ defer now.free(gpa);
+ try std.testing.expectEqualSlices(u8, &state, now.state);
+}
+
+test "a session database full of marks refuses a mark of a new name, and takes one over an old name" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path});
+ // 2 MiB of State, all of it changed for each mark.
+ const state = try gpa.alloc(u8, 2 << 20);
+ defer gpa.free(state);
+ var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000);
+ defer s.deinit();
+ var name: [8]u8 = undefined;
+ var k: u8 = 0;
+ while (true) : (k += 1) {
+ @memset(state, k + 1);
+ _ = s.mark(try std.fmt.bufPrint(&name, "m{d}", .{k}), .mark, state) catch |err| {
+ try std.testing.expectEqual(error.SaveFull, err);
+ break;
+ };
+ try std.testing.expect(k < 40 and try s.file.?.length(io) <= max_save);
+ }
+ try std.testing.expect(k > 20);
+ @memset(state, 99);
+ try std.testing.expectError(error.SaveFull, s.mark("new", .mark, state));
+ _ = try s.mark("m3", .mark, state);
+ try s.commit(.none);
+ try std.testing.expect(try s.file.?.length(io) <= max_save);
+ // Every mark's newest keyframe is whole.
+ for (0..k) |i| {
+ const m = (try s.findMark(try std.fmt.bufPrint(&name, "m{d}", .{i}))).?;
+ const loaded = try s.load(m.session, m.key);
+ defer loaded.free(gpa);
+ try std.testing.expectEqual(@as(u8, if (i == 3) 99 else @intCast(i + 1)), loaded.state[state.len - 1]);
+ }
+}