diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-16 23:35:54 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-17 12:15:01 -0300 |
| commit | c3b9938e9cb381bc7378fdca9073520ff1711ad6 (patch) | |
| tree | 33f707ef2075bc26083a3c21d34a41b4a0e9c7ac | |
| parent | b2f7c605c279b2dea0c25180730c3d2e7b4b7d45 (diff) | |
| download | sketchbook-c3b9938e9cb381bc7378fdca9073520ff1711ad6.tar.gz sketchbook-c3b9938e9cb381bc7378fdca9073520ff1711ad6.zip | |
Play past sessions back, re-synced at their keyframes
play session S [at SECONDS] restores the session's keyframe before that
time (a binary search over its keyframes' times), replays its frames up to
it and leaves it paused there; without a time it plays from the start. At
each later keyframe the replay reaches, the State is compared with it over
the leaves migration kept: a keyframe taken of what update made (periodic,
mark, before a reload, exit) that differs is reported once, "diverged
before frame F: N values, first <field>", and every keyframe is restored,
so a replay across a jump the log does not hold (set, load, a sketch
command) goes on from the State that followed it. A session built from
another source or build says so. The console's status line names the
session, frame and time, the mark, the clip and where it records.
test-past records a session, replays it by the same build (the mark's
State exactly, frame 120's two seconds in, no divergence), then by a build
with an edited fixture (one divergence, before the mark).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
| -rw-r--r-- | build.zig | 31 | ||||
| -rw-r--r-- | src/host/Console.zig | 55 | ||||
| -rw-r--r-- | src/host/Host.zig | 32 | ||||
| -rw-r--r-- | src/host/Sessions.zig | 16 | ||||
| -rw-r--r-- | src/host/timeline.zig | 23 | ||||
| -rw-r--r-- | test/past.script | 8 | ||||
| -rw-r--r-- | test/past_diverged.script | 6 | ||||
| -rw-r--r-- | test/past_replay.script | 12 |
8 files changed, 179 insertions, 4 deletions
@@ -355,6 +355,37 @@ pub fn build(b: *Build) void { test_step.dependOn(&killed.step); b.step("test-kill", "A session survives kill -9 up to its last commit").dependOn(&killed.step); + // A past session plays again: from its start to a mark, the same + // State leaf by leaf; two seconds in, from the keyframe before; and, + // built from edited code, it diverges before the mark, says so once, + // and goes on from the mark's State. + const edited = sb.app(.{ .name = "replay", .root_source_file = b.path("test/replay.zig"), .record = true }).addReloadCheck(.{ + .script = b.path("test/past_diverged.script"), + .edits = &.{.{ .file = "test/replay.zig", .old = "@splat(0.01)", .new = "@splat(0.02)" }}, + }); + const past = b.addSystemCommand(&.{ "sh", "-c", + \\set -e + \\db="${4%.state}.xitdb" + \\rm -f "$4" "$4.store" "$db" + \\"$0" --headless --script "$1" --state "$4" "$5" + \\"$0" --headless --script "$2" --state "$4" "$5" + \\"$0" --headless --script "$3" --state "$4" "$6" + \\test "$(stat -c %s "$db")" -lt 1048576 + \\rm -f "$4" "$4.store" "$db" + }); + past.setName("past sessions replay"); + past.addArtifactArg(host_exe); + past.addFileArg(b.path("test/past.script")); + past.addFileArg(b.path("test/past_replay.script")); + past.addFileArg(b.path("test/past_diverged.script")); + _ = past.addOutputFileArg("past.state"); + past.addArtifactArg(recorded); + past.addArtifactArg(edited.edited); + past.has_side_effects = true; + past.expectExitCode(0); + test_step.dependOn(&past.step); + b.step("test-past", "Replay past sessions, to a time and across a code change").dependOn(&past.step); + // Recorded input replays to the same state: played, seeked, stepped, // and after a live pointer move (core host behaviour, not an API). const replay = b.addRunArtifact(host_exe); diff --git a/src/host/Console.zig b/src/host/Console.zig index 88e4864..9f14830 100644 --- a/src/host/Console.zig +++ b/src/host/Console.zig @@ -14,7 +14,7 @@ pub const Key = enum { left, right, home, end, backspace, delete, clear, tab, su const Line = struct { bytes: [118]u8 = @splat(0), len: usize = 0 }; const host_commands = [_][]const u8{ - "help", "overlay memory", "overlay sound", "get", "set", "reset", "save", "load", "snapshot", "recording", "marks", "clips", + "help", "overlay memory", "overlay sound", "get", "set", "reset", "save", "load", "snapshot", "recording", "marks", "clips", "play session", "record", "stop", "play", "pause", "step", "seek start", "seek end", "diff", "quit", "exit", "overlay timing", "sessions", "timing on", "timing off", "timing frame", "timing work", "timing reset", "timing stats", }; @@ -238,6 +238,17 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const h.startRecording(); self.recording = .of(n); self.print("Started recording {s} from snapshot {s}.", .{ n, from }); + } else if (eq(command, "play") and arg != null and eq(arg.?, "session")) { + var more = std.mem.tokenizeAny(u8, rest, " \t"); + const index = std.fmt.parseInt(u64, more.next() orelse return error.ExpectedSession, 10) catch return error.InvalidSession; + var at: ?u64 = null; + if (more.next()) |word| { + if (!eq(word, "at")) return error.UnexpectedArgument; + const seconds = std.fmt.parseFloat(f64, more.next() orelse return error.ExpectedPosition) catch return error.InvalidPosition; + at = @intFromFloat(@max(0, seconds) * std.time.ns_per_s); + } + try stop(host); + return self.playSession(host, index, at, now); } else if (eq(command, "play")) { const n = try nameOr(arg, &self.recording); try stop(host); @@ -301,8 +312,12 @@ pub fn draw(self: *const Console, host: *Host, out: *std.ArrayList(abi.Command), const width: f32 = @floatFromInt(host.canvas[0]); const h = &host.timeline; try out.append(arena, .{ .rect = .{ .dst = .{ .x = 0, .y = top, .w = width, .h = panel_height }, .color = .{ .r = 24, .g = 28, .b = 28 } } }); - const status = try std.fmt.allocPrint(arena, "{s} | {t} | snapshot {s} | recording {s} | event {d} | {d}ms | rec {t}", .{ - host.name, h.mode, self.snapshot.get(), self.recording.get(), h.cursor, h.position / std.time.ns_per_ms, host.sessions.mode(), + const s = &host.sessions; + const playing = h.mode == .playing or h.mode == .paused; + const frame = if (playing) (if (h.key) |k| k.frame else 0) + h.fed else s.frames; + const at = (if (playing) h.position else s.last_time -| s.first_time) / std.time.ns_per_s; + const status = try std.fmt.allocPrint(arena, "{s} | {t} | session {d} frame {d} ({d}:{d:0>2}) | mark {s} | clip {s} | rec {t}", .{ + host.name, h.mode, if (playing) h.session orelse s.session else s.session, frame, at / 60, at % 60, self.snapshot.get(), self.recording.get(), s.mode(), }); try out.append(arena, .{ .text = .{ .x = 12, .y = top + 8, .scale = 1, .color = hint, .bytes = status } }); for (&self.lines, 0..) |*line, i| { @@ -378,6 +393,40 @@ fn loadClip(host: *Host, n: []const u8) !void { host.timeline.load(key, events); } +/// Plays session `index` from its start, or paused `at` nanoseconds into +/// it: from the newest keyframe before then, replayed up to it. +fn playSession(self: *Console, host: *Host, index: u64, at: ?u64, now: u64) ![]const abi.Event { + const s = &host.sessions; + const h = &host.timeline; + if (index == s.session) try s.commit(.none); + const sum = try s.summary(index); + if (sum.keys == 0) return error.EmptyRecording; + const t0 = (try s.keyAt(index, 0)).time; + const k = if (at) |t| try s.keyBefore(index, .time, t0 + t) orelse 0 else 0; + const key = try s.load(index, k); + errdefer key.free(host.gpa); + var events: std.ArrayList(abi.Event) = .empty; + errdefer events.deinit(host.gpa); + try s.events(index, key.batch, key.frame, sum.frames, &events); + var checks: @TypeOf(h.checks) = .empty; + errdefer checks.deinit(host.gpa); + for (k + 1..sum.keys) |j| { + const later = try s.keyAt(index, j); + try checks.append(host.gpa, .{ .frame = later.frame, .key = j, .observed = switch (later.why) { + .periodic, .mark, .before_reload, .exit => true, + else => false, + } }); + } + h.load(key, events); + h.session = index; + h.checks = checks; + try h.play(now); + self.print("Playing session {d} from frame {d}.", .{ index, key.frame }); + if (key.build != host.build or !eq(key.source, host.source)) self.print("session {d} frame {d} was built from {s}; replaying with {s}", .{ index, key.frame, key.source, host.source }); + if (at) |t| return h.seekTime((t0 + t) -| h.base); + return &.{}; +} + /// A replay of a clip made by other code may diverge: say so. fn warnBuild(self: *Console, host: *const Host) void { const key = host.timeline.key orelse return; diff --git a/src/host/Host.zig b/src/host/Host.zig index 1fe1db2..1c9d65a 100644 --- a/src/host/Host.zig +++ b/src/host/Host.zig @@ -373,10 +373,42 @@ pub fn update(self: *Host, events: []const abi.Event) void { self.started = false; const ctx = self.context(); self.sketch.update(&ctx, self.live().ptr); + if (self.timeline.mode == .playing or self.timeline.mode == .paused) self.resync(); } self.input.events = &.{}; } +/// After a replayed frame of a past session: at each keyframe it reaches, +/// live state is compared with the keyframe (over the leaves migration +/// kept), any difference said, and the keyframe restored. +fn resync(self: *Host) void { + const h = &self.timeline; + h.fed += 1; + const session = h.session orelse return; + const reached = h.key.?.frame + h.fed; + while (h.next_check < h.checks.items.len and h.checks.items[h.next_check].frame <= reached) { + const check = h.checks.items[h.next_check]; + h.next_check += 1; + if (check.frame < reached) continue; + const key = self.sessions.load(session, check.key) catch |err| return self.print("session {d} keyframe {d}: {t}", .{ session, check.key, err }); + defer key.free(self.gpa); + var arena: std.heap.ArenaAllocator = .init(self.gpa); + defer arena.deinit(); + const saved = arena.allocator().alignedAlloc(u8, .fromByteUnits(memory.page), self.state.layout.size) catch return; + const from = memory.restore(arena.allocator(), key.layout, key.state, self.state.layout, saved, self.sketch.defaults) catch |err| return self.print("session {d} keyframe {d}: {t}", .{ session, check.key, err }); + if (check.observed) { + const diff = memory.compareKept(from, self.state.layout, self.live(), saved); + if (diff.first) |first| { + var buf: [96]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + first.leaf.name(first.offset, &w) catch {}; + self.print("diverged before frame {d}: {d} values, first {s}", .{ reached, diff.count, w.buffered() }); + } + } + @memcpy(self.live(), saved); + } +} + /// After live state was restored from a snapshot: the pointer, buttons and /// keys tracked so far belong to other bytes, so they start over. A new /// recording then begins with events that bring back what is held now, so diff --git a/src/host/Sessions.zig b/src/host/Sessions.zig index 6f10bba..4399c63 100644 --- a/src/host/Sessions.zig +++ b/src/host/Sessions.zig @@ -81,7 +81,8 @@ keys: u64 = 0, batch: std.ArrayList(u8) = .empty, /// The first pending frame's tick. batch_time: u64 = 0, -/// The latest event time logged: times never go back. +/// The first and latest event time logged: times never go back. +first_time: u64 = 0, last_time: u64 = 0, /// The last keyframe's time, stretch and bytes' hash. key_time: u64 = 0, @@ -191,6 +192,7 @@ pub fn frame(s: *Sessions, one: []abi.Event, state: []const u8, why: ?Why) !void if (why) |w| { _ = try s.keyframe(w, state); } else if (tick -| s.key_time >= periodic_ns) _ = try s.keyframe(.periodic, state); + if (s.frames == 0) s.first_time = tick; if (s.batch.items.len == 0) { try s.batch.appendSlice(s.gpa, std.mem.asBytes(&std.mem.nativeToLittle(u64, s.frames))); s.batch_time = tick; @@ -487,6 +489,18 @@ pub fn load(s: *Sessions, session: u64, k: u64) !Loaded { } } +/// Keyframe `k`'s frame, time and why, without its bytes. +pub fn keyAt(s: *Sessions, session: u64, k: u64) !struct { frame: u64, time: u64, why: Why } { + switch (s.db) { + .off => return error.NotRecording, + inline .memory, .file => |*db| { + const R = Read(@TypeOf(db.*)); + const e = try R.at(try R.list(try R.session(db, session), .keys) orelse return error.NoSuchKeyframe, k); + return .{ .frame = try R.uint(e, .frame), .time = try R.uint(e, .time), .why = std.enums.fromInt(Why, try R.uint(e, .why)) orelse return error.CorruptSession }; + }, + } +} + /// The newest keyframe of `session` whose `by` (`.frame` or `.time`) is at /// most `value`: a binary search. pub fn keyBefore(s: *Sessions, session: u64, by: K, value: u64) !?u64 { diff --git a/src/host/timeline.zig b/src/host/timeline.zig index 697a9df..c2eeff3 100644 --- a/src/host/timeline.zig +++ b/src/host/timeline.zig @@ -61,10 +61,29 @@ pub const Timeline = struct { /// Set whenever live state is restored from a keyframe, for the host /// to reset the input state that went with the old bytes. restored: bool = false, + /// Frames fed since the keyframe was restored. + fed: u64 = 0, + /// A past session played (`play session`), not a clip: its index, and + /// its keyframes after the one played from, checked against the replay + /// as their frames are reached (Host.resync). + session: ?u64 = null, + checks: std.ArrayList(Check) = .empty, + next_check: usize = 0, + + pub const Check = struct { + frame: u64, + key: u64, + /// Taken of what `update` made (periodic, a mark, before a reload, + /// at exit): a replay must match it. Other keyframes follow a jump + /// the log does not hold, and are restored without a word. + observed: bool, + }; pub fn deinit(self: *Timeline) void { if (self.key) |k| k.free(self.gpa); + self.key = null; self.events.deinit(self.gpa); + self.checks.deinit(self.gpa); } /// Puts a keyframe, in whatever layout it was taken, into live state. @@ -73,6 +92,8 @@ pub const Timeline = struct { defer arena.deinit(); _ = try memory.restore(arena.allocator(), key.layout, key.state, self.state.layout, self.state.slot(0), self.defaults); self.restored = true; + self.fed = 0; + self.next_check = 0; } /// Makes a clip, its start keyframe and its frames, the one played; both @@ -81,6 +102,8 @@ pub const Timeline = struct { self.deinit(); self.key = key; self.events = events; + self.session = null; + self.checks = .empty; var it = frames(events.items); const first = it.next(); self.base = if (first) |f| f[f.len - 1].time else 0; diff --git a/test/past.script b/test/past.script new file mode 100644 index 0000000..8ac9c25 --- /dev/null +++ b/test/past.script @@ -0,0 +1,8 @@ +# Session 0 of test-past (see build.zig): pointer driven, a mark at frame +# 30, a jump (`set`) at frame 60, 300 frames in all. +move 300 200 +frames 29 +console save probe +frames 29 +console set velocity[0] 5 +frames 240 diff --git a/test/past_diverged.script b/test/past_diverged.script new file mode 100644 index 0000000..6d275a2 --- /dev/null +++ b/test/past_diverged.script @@ -0,0 +1,6 @@ +# Session 0, replayed by a build whose pointer chase differs: it diverges +# before the mark and is put back on it. +console play session 0 +expect-log was built from +frames 40 +expect-log diverged before frame 30 diff --git a/test/past_replay.script b/test/past_replay.script new file mode 100644 index 0000000..0f11c64 --- /dev/null +++ b/test/past_replay.script @@ -0,0 +1,12 @@ +# Session 0 again, by the same build: from its start, half a second in is +# the mark's State exactly; two seconds in, from the jump's keyframe, is +# frame 120's. +console play session 0 +console seek 499 +expect-snapshot probe +expect-no-log diverged +console play session 0 at 2 +expect updates 121 +console pause +frames 30 +expect-no-log diverged |
