summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/abi.zig4
-rw-r--r--src/host/Console.zig7
-rw-r--r--src/host/Host.zig6
-rw-r--r--src/host/Sessions.zig349
-rw-r--r--src/layout.zig7
-rw-r--r--src/sketch/root.zig2
6 files changed, 344 insertions, 31 deletions
diff --git a/src/abi.zig b/src/abi.zig
index 4d101d0..286fb09 100644
--- a/src/abi.zig
+++ b/src/abi.zig
@@ -812,8 +812,8 @@ pub const Info = struct {
/// <change>", "git:<sha>[+dirty]", or nothing), then `build`. Each
/// stretch of a recorded session keeps it.
source: []const u8 = "",
- /// Whether the host records sessions to a file (`App.Options.record`;
- /// Debug builds do unless told otherwise).
+ /// Whether the save keeps history, or only the present and the marks
+ /// (`App.Options.record`; Debug builds keep it unless told otherwise).
record: bool = false,
};
diff --git a/src/host/Console.zig b/src/host/Console.zig
index ffa6876..0d4cda0 100644
--- a/src/host/Console.zig
+++ b/src/host/Console.zig
@@ -457,10 +457,13 @@ fn listNamed(self: *Console, host: *Host, marks: bool) !void {
var i = n -| 5;
while (i < n) : (i += 1) {
const e = if (marks) try s.markAt(i) else try s.clipAt(i);
- const key = try s.load(e.session, e.key);
- defer key.free(host.gpa);
const label = e.name();
if (marks) {
+ // An older mark of a name may have gone with history.
+ const key = s.keyAt(e.session, e.key) catch {
+ self.print("#{d} {s}: session {d}, dropped", .{ i, label, e.session });
+ continue;
+ };
self.print("#{d} {s}: session {d} frame {d}", .{ i, label, e.session, key.frame });
} else self.print("#{d} {s}: session {d} frames {d}..{d}", .{ i, label, e.session, e.start, e.end });
}
diff --git a/src/host/Host.zig b/src/host/Host.zig
index 3485d79..4f45ace 100644
--- a/src/host/Host.zig
+++ b/src/host/Host.zig
@@ -704,6 +704,10 @@ pub fn runLine(self: *Host, line: []const u8, now: u64) !void {
// The sketch has printed its own error already.
if (err == error.NotRecording) {
self.console.log("Not recording (an export): no marks or clips.");
+ } else if (err == error.HistoryDropped) {
+ self.console.log("That part of the history is gone: a save keeps 64 MiB, the newest.");
+ } else if (err == error.SaveFull) {
+ self.console.log("No room for a new mark: marks and the present fill the save. Save over a mark's name (its older one goes with history), or start another save (--state).");
} else if (err != error.CommandFailed) self.console.print("{t}. Type help for usage.", .{err});
if (self.timeline.restored) self.jumped = true;
try self.restoredInput(now);
@@ -947,6 +951,8 @@ fn openSessions(self: *Host, record: bool) void {
self.print("not saved: {s}: {t}", .{ path, err });
break :blk .{ .gpa = self.gpa, .io = self.io };
};
+ // Without `.record`, history is trimmed to the present and the marks.
+ self.sessions.history = record;
if (o.headless or self.sessions.mode() != .file) return;
self.print("{s} to {s}", .{ if (record) "recording" else "saving", path });
}
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]);
+ }
+}
diff --git a/src/layout.zig b/src/layout.zig
index d61ebf3..b3c6520 100644
--- a/src/layout.zig
+++ b/src/layout.zig
@@ -22,8 +22,9 @@
const std = @import("std");
const abi = @import("abi.zig");
-/// The most a State may be, in bytes: a save holds at most 64 MiB.
-pub const max_state = 64 << 20;
+/// The most a State may be, in bytes: half of the 64 MiB a save holds, so
+/// history has room (Sessions.max_save).
+pub const max_state = 32 << 20;
pub fn of(comptime T: type, comptime memory: abi.Memory) abi.Layout {
return comptime blk: {
@@ -31,7 +32,7 @@ pub fn of(comptime T: type, comptime memory: abi.Memory) abi.Layout {
switch (memory) {
.state => {
check(T, @typeName(T));
- if (@sizeOf(T) > max_state) @compileError(std.fmt.comptimePrint("State is {d} bytes, and a save holds at most {d} MiB: lower a capacity (an array, an sk.List), or keep what need not be saved in Session.", .{ @sizeOf(T), max_state >> 20 }));
+ if (@sizeOf(T) > max_state) @compileError(std.fmt.comptimePrint("State is {d} bytes, and may be {d} MiB, half of a save, so history has room: lower a capacity (an array, an sk.List), or keep what need not be saved in Session.", .{ @sizeOf(T), max_state >> 20 }));
},
.session => {},
}
diff --git a/src/sketch/root.zig b/src/sketch/root.zig
index 6d496bb..9f4782f 100644
--- a/src/sketch/root.zig
+++ b/src/sketch/root.zig
@@ -306,7 +306,7 @@ pub const Console = struct {
pub const Build = struct {
/// The repository revision the sketch was built from, "" when unknown.
source: []const u8 = "",
- /// Record sessions to a file (`abi.Info.record`).
+ /// Keep history in the save (`abi.Info.record`).
record: bool = false,
};