graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
perf(session): skip unchanged autosaves and write them in the background (#273)
justrach72a0fb0af45a
diff --git a/src/mainloop.zig b/src/mainloop.zigindex 50eb9fc8..6b0b9143 100644--- a/src/mainloop.zig+++ b/src/mainloop.zig@@ -60,6 +60,7 @@ pub const Ctx = struct {pub fn run(ctx: *Ctx) !void {var title_jobs: mainloop_title.Jobs = .{};defer title_jobs.deinit(ctx);+ defer session.flushSaves(); // #273: the turn-path autosaves write in the background — no queued one may outlive this loop, on ANY exit// Trajectory spine state: each turn's parent is the previous turn, and a// changed prompt fingerprint marks a set_system_prompt mutation edge.var prev_turn_id: u64 = 0;@@ -587,14 +588,13 @@ pub fn run(ctx: *Ctx) !void {},}}- // opencode-style continuous autosave: persist after every turn so a- // crash or quit never loses the thread — last.session.json, the same- // file /resume reads. Best-effort; a write failure never breaks the loop.- session.saveSession(ctx.root, ctx.arena, ctx.root.session_name) catch {};+ // opencode-style continuous autosave: persist after every turn so a crash or quit never loses the+ // thread — last.session.json, the same file /resume reads. Best-effort; a write failure never breaks+ // the loop. #273: unchanged history skips the save whole, and the write itself is queued.+ session.saveSessionAsync(ctx.root, ctx.arena, ctx.root.session_name) catch {};- // --worktree checkpoint: commit this turn's edits to the scratch branch- // so the work is durable + rewindable across restarts. No-op when not in- // a worktree or when --no-autocommit is set.+ // --worktree checkpoint: commit this turn's edits to the scratch branch so the work is durable+ // + rewindable across restarts. No-op when not in a worktree or when --no-autocommit is set.jobs.worktreeAutoCommit(ctx.gpa, ctx.io, std.fmt.allocPrint(ctx.arena, "wip: {s}", .{title_mod.titleFromPrompt(base_msg)}) catch "wip: graff checkpoint");}}diff --git a/src/session.zig b/src/session.zigindex c62ec41e..e98dbf9c 100644--- a/src/session.zig+++ b/src/session.zig@@ -8,6 +8,11 @@//! loadSession/listSavedSessions/sessionAge/session_ext stay pub —//! commands_session.zig, commands_misc.zig, and readline.zig import them//! directly as `session.saveSession` etc.+//!+//! #273: `saveSession` is still synchronous and still reports its failures;+//! the interactive TURN path calls `saveSessionAsync`, which skips an unchanged+//! conversation outright and queues the write (session_writer.zig). This file's+//! unit tests live in session_tests.zig — the 600-line cap.const std = @import("std");const Io = std.Io;@@ -18,7 +23,7 @@ const agent_mod = @import("agent.zig");const provider_mod = @import("provider.zig");const util = @import("util.zig");const goal_state = @import("goal_state.zig");-const session_lock = @import("session_lock.zig"); // the locked write path (#289)+const session_writer = @import("session_writer.zig"); // #273: the fingerprint + the background writeconst protocol_seq = @import("protocol_seq.zig"); // #330: the --json event sequence survives a resumeconst Agent = agent_mod.Agent;const Keys = provider_mod.Keys;@@ -126,14 +131,89 @@ pub fn hasMeaningfulState(root: *Agent) bool {return false;}+/// #273: a digest of every field saveSession persists, EXCEPT `updated_ms`+/// (a clock reading, not conversation state). Equal to the last successfully+/// written one means the file on disk is already this exact session, so the+/// whole save — serialize, lock, write — is skipped.+fn fingerprint(root: *Agent, name: []const u8) u64 {+ var f: session_writer.Fingerprint = .init();+ f.text(name);+ f.text(root.provider.id);+ f.text(root.provider.model);+ f.flag(root.strict);+ f.flag(root.ultracode_mode);+ if (root.goal) |g| {+ f.text(g.objective);+ f.text(@tagName(g.status));+ f.num(g.epoch);+ f.flag(g.standing);+ f.signed(g.created_ms);+ f.signed(g.updated_ms);+ } else f.flag(false);+ f.num(root.todos.items.len);+ for (root.todos.items) |t| {+ f.text(t.content);+ f.text(t.status);+ f.num(t.epoch);+ }+ f.text(root.session_title orelse sessionTitle(root));+ // The persisted meter's two inputs. Its third (system prompt + tool schema+ // size) shifts `context_tokens` and `context_local_tokens` together, and+ // resume only keeps their difference, so it cannot change what a resume+ // restores and is deliberately left out.+ f.num(root.last_context_tokens);+ f.num(root.context_local_tokens);+ f.num(protocol_seq.current());+ f.json(Value{ .array = root.messages });+ return f.final();+}+/// Save the conversation (messages + provider id/model + strict flag) to/// <name>.session.json in the cwd. The JSON message array is already the/// provider-native wire shape, so resume is a verbatim restore.+///+/// Synchronous, exactly like the pre-#273 save: the bytes are on disk (and any+/// failure is reported) by the time this returns. The TURN path uses+/// saveSessionAsync instead — see that function.pub fn saveSession(root: *Agent, arena: Allocator, name: []const u8) !void {+ saveSessionAsync(root, arena, name) catch |err| {+ flushSaves();+ return err;+ };+ // Unconditional, so /clear, /new, /save and the exit save all drain even+ // when this session had nothing new of its own to write.+ flushSaves();+ if (session_writer.takeError()) |err| return err;+}++/// #273: the interactive turn path's save. Skips entirely when nothing changed,+/// serializes here (root.messages is live, unlocked agent state and must not be+/// read from another thread), and leaves only the disk write in the background.+///+/// Callers MUST guarantee a drain before the process can exit — mainloop.run+/// defers flushSaves(), and every other saver in the harness is the synchronous+/// saveSession above.+pub fn saveSessionAsync(root: *Agent, arena: Allocator, name: []const u8) !void {+ return saveSessionTo(root, arena, .cwd(), name);+}++/// Wait for any queued save to reach disk. The exit/quit/switch bound on how+/// long a background write may lag the conversation.+pub fn flushSaves() void {+ session_writer.drain();+}++/// The save itself, against an explicit base directory. Production always+/// passes the cwd (through saveSessionAsync/saveSession); the parameter exists+/// so the tests can exercise the real path against a tmp dir.+pub fn saveSessionTo(root: *Agent, arena: Allocator, dir: Io.Dir, name: []const u8) !void {// #184: delay durable session creation until the conversation has meaningful// state — never leave a blank draft as an "Untitled session" on disk. Existing// files are untouched (we skip the write, we do not delete).if (!hasMeaningfulState(root)) return;+ // #273: nothing has changed since the last successful write of this session.+ const fp = fingerprint(root, name);+ if (session_writer.alreadySaved(fp)) return;var aw: Io.Writer.Allocating = .init(root.gpa);defer aw.deinit();var s: std.json.Stringify = .{ .writer = &aw.writer };@@ -208,9 +288,12 @@ pub fn saveSession(root: *Agent, arena: Allocator, name: []const u8) !void {try s.write(@min(protocol_seq.current(), @as(u64, std.math.maxInt(i64))));try s.endObject();- // #289: two graffs in one workspace share this file — writeSession makes the+ // #289: two graffs in one workspace share this file — the writer makes the// parent dirs and takes an exclusive advisory lock, so the loser reports.- try session_lock.writeSession(root.io, .cwd(), try sessionPath(arena, name), aw.writer.buffered());+ // #273: it does that on its own thread, and owns these bytes from here.+ const path = try root.gpa.dupe(u8, try sessionPath(arena, name));+ errdefer root.gpa.free(path); // only reachable if toOwnedSlice fails: submit owns both+ session_writer.submit(root.gpa, root.io, dir, path, try aw.toOwnedSlice(), fp);}/// Parse the persisted `goal` field into a structured Goal (#223). A bare string@@ -251,54 +334,6 @@ pub fn appendTodosFromValue(arena: Allocator, todos: *std.ArrayList(agent_mod.To}}-test "todos round-trip: appendTodosFromValue parses content/status/epoch, skips junk (#318)" {- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena_state.deinit();- const a = arena_state.allocator();- const parsed = try std.json.parseFromSliceLeaky(Value, a,- \\[{"content":"wire epochs","status":"completed","epoch":2},- \\ {"content":"add test","status":"pending","epoch":2},- \\ {"status":"orphan, no content"}, 17]- , .{});- var todos: std.ArrayList(agent_mod.TodoItem) = .empty;- try appendTodosFromValue(a, &todos, parsed);- try std.testing.expectEqual(@as(usize, 2), todos.items.len);- try std.testing.expectEqualStrings("wire epochs", todos.items[0].content);- try std.testing.expectEqual(@as(u64, 2), todos.items[1].epoch);- // Legacy sessions (no todos field / wrong type): nothing appended.- try appendTodosFromValue(a, &todos, .null);- try std.testing.expectEqual(@as(usize, 2), todos.items.len);-}--test "goalFromValue: legacy string -> active; object round-trips; paused stays paused (#223)" {- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena_state.deinit();- const a = arena_state.allocator();-- // Legacy bare string -> active, stamped with now_ms (backward compat).- const legacy = try std.json.parseFromSliceLeaky(Value, a, "\"ship 0.0.202\"", .{ .allocate = .alloc_always });- const g1 = goalFromValue(legacy, 4242).?;- try std.testing.expectEqualStrings("ship 0.0.202", g1.objective);- try std.testing.expectEqual(agent_mod.GoalStatus.active, g1.status);- try std.testing.expectEqual(@as(i64, 4242), g1.created_ms);-- // New object with a paused status round-trips as paused (survives resume).- const paused = try std.json.parseFromSliceLeaky(Value, a, "{\"objective\":\"land #223\",\"status\":\"paused\",\"created_ms\":10,\"updated_ms\":20}", .{ .allocate = .alloc_always });- const g2 = goalFromValue(paused, 999).?;- try std.testing.expectEqualStrings("land #223", g2.objective);- try std.testing.expectEqual(agent_mod.GoalStatus.paused, g2.status);- try std.testing.expectEqual(@as(i64, 10), g2.created_ms);- try std.testing.expectEqual(@as(i64, 20), g2.updated_ms);-- // Empty string -> null (no goal).- const empty = try std.json.parseFromSliceLeaky(Value, a, "\"\"", .{ .allocate = .alloc_always });- try std.testing.expect(goalFromValue(empty, 1) == null);-- // An unknown status string falls back to active (forward-compat with future variants).- const unknown = try std.json.parseFromSliceLeaky(Value, a, "{\"objective\":\"x\",\"status\":\"zzz\"}", .{ .allocate = .alloc_always });- try std.testing.expectEqual(agent_mod.GoalStatus.active, goalFromValue(unknown, 1).?.status);-}-fn contextTokensFromSession(obj: std.json.ObjectMap) u64 {const v = obj.get("context_tokens") orelse return 0;if (v != .integer or v.integer <= 0) return 0;@@ -339,6 +374,7 @@ fn restoreContextMeter(root: *Agent, saved_context_tokens: u64, saved_local_toke/// provider, and replace the live history. The wire format must still match/// the restored provider's kind — same provider id guarantees it.pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8) !void {+ flushSaves(); // #273: a session switch never leaves the outgoing one queuedconst path = try sessionPath(arena, name);const data = Io.Dir.cwd().readFileAlloc(root.io, path, arena, .limited(8 * 1024 * 1024)) catch blk: {// backward-compat: older builds wrote <name>.session.json in cwd.@@ -514,41 +550,3 @@ test "event_seq round-trips so a replacement graff continues the sequence (#330)protocol_seq.restore(eventSeqFromSession(legacy.object));try std.testing.expectEqual(@as(u64, 43), protocol_seq.next());}--test "slugifyTitle makes a filesystem-safe slug from an AI title" {- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena_state.deinit();- const a = arena_state.allocator();- try std.testing.expectEqualStrings("fixing-the-login-bug", slugifyTitle(a, "Fixing the login bug"));- try std.testing.expectEqualStrings("add-dark-mode", slugifyTitle(a, "Add dark mode!!"));- try std.testing.expectEqualStrings("planning-v2", slugifyTitle(a, " Planning — v2 ")); // trim + collapse- try std.testing.expectEqualStrings("", slugifyTitle(a, "🎉 ✨")); // symbol-only → "" (keeps the session-<ts> name)-}--test "hasMeaningfulState gates the blank-draft write (#184)" {- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena_state.deinit();- const arena = arena_state.allocator();-- // Only the fields hasMeaningfulState reads are set; the rest stay untouched.- var root: Agent = undefined;- root.goal = null;- root.todos = .empty;- root.tools_used = .{};- root.messages = std.json.Array.init(arena);-- // Truly blank: no user turn, no goal, no todos, no tools → not persisted.- try std.testing.expect(!hasMeaningfulState(&root));-- // A standing /goal alone is meaningful (goal-only sessions are still saved).- root.goal = .{ .objective = "ship the release" };- try std.testing.expect(hasMeaningfulState(&root));-- // One user message alone is meaningful.- root.goal = null;- var obj: std.json.ObjectMap = .empty;- try obj.put(arena, "role", .{ .string = "user" });- try obj.put(arena, "content", .{ .string = "hi" });- try root.messages.append(.{ .object = obj });- try std.testing.expect(hasMeaningfulState(&root));-}diff --git a/src/session_tests.zig b/src/session_tests.zignew file mode 100644index 00000000..5d7edfc1--- /dev/null+++ b/src/session_tests.zig@@ -0,0 +1,253 @@+//! session.zig's tests. The file itself sits at the 600-line cap (#273 needed+//! room there for the save fingerprint and the background-write hand-off), so+//! its unit tests live here and are reached through test_hooks.zig, mirroring+//! goal_persist_tests.zig.+//!+//! The #273 cases at the bottom are the ones that keep the new save path+//! honest: an unchanged conversation must not touch the file at all, ANY change+//! must produce a write, and a queued write must never be lost at shutdown.++const std = @import("std");+const Io = std.Io;+const Value = std.json.Value;+const Allocator = std.mem.Allocator;++const agent_mod = @import("agent.zig");+const session = @import("session.zig");+const session_writer = @import("session_writer.zig");+const Agent = agent_mod.Agent;++test "todos round-trip: appendTodosFromValue parses content/status/epoch, skips junk (#318)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const parsed = try std.json.parseFromSliceLeaky(Value, a,+ \\[{"content":"wire epochs","status":"completed","epoch":2},+ \\ {"content":"add test","status":"pending","epoch":2},+ \\ {"status":"orphan, no content"}, 17]+ , .{});+ var todos: std.ArrayList(agent_mod.TodoItem) = .empty;+ try session.appendTodosFromValue(a, &todos, parsed);+ try std.testing.expectEqual(@as(usize, 2), todos.items.len);+ try std.testing.expectEqualStrings("wire epochs", todos.items[0].content);+ try std.testing.expectEqual(@as(u64, 2), todos.items[1].epoch);+ // Legacy sessions (no todos field / wrong type): nothing appended.+ try session.appendTodosFromValue(a, &todos, .null);+ try std.testing.expectEqual(@as(usize, 2), todos.items.len);+}++test "goalFromValue: legacy string -> active; object round-trips; paused stays paused (#223)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ // Legacy bare string -> active, stamped with now_ms (backward compat).+ const legacy = try std.json.parseFromSliceLeaky(Value, a, "\"ship 0.0.202\"", .{ .allocate = .alloc_always });+ const g1 = session.goalFromValue(legacy, 4242).?;+ try std.testing.expectEqualStrings("ship 0.0.202", g1.objective);+ try std.testing.expectEqual(agent_mod.GoalStatus.active, g1.status);+ try std.testing.expectEqual(@as(i64, 4242), g1.created_ms);++ // New object with a paused status round-trips as paused (survives resume).+ const paused = try std.json.parseFromSliceLeaky(Value, a, "{\"objective\":\"land #223\",\"status\":\"paused\",\"created_ms\":10,\"updated_ms\":20}", .{ .allocate = .alloc_always });+ const g2 = session.goalFromValue(paused, 999).?;+ try std.testing.expectEqualStrings("land #223", g2.objective);+ try std.testing.expectEqual(agent_mod.GoalStatus.paused, g2.status);+ try std.testing.expectEqual(@as(i64, 10), g2.created_ms);+ try std.testing.expectEqual(@as(i64, 20), g2.updated_ms);++ // Empty string -> null (no goal).+ const empty = try std.json.parseFromSliceLeaky(Value, a, "\"\"", .{ .allocate = .alloc_always });+ try std.testing.expect(session.goalFromValue(empty, 1) == null);++ // An unknown status string falls back to active (forward-compat with future variants).+ const unknown = try std.json.parseFromSliceLeaky(Value, a, "{\"objective\":\"x\",\"status\":\"zzz\"}", .{ .allocate = .alloc_always });+ try std.testing.expectEqual(agent_mod.GoalStatus.active, session.goalFromValue(unknown, 1).?.status);+}++test "slugifyTitle makes a filesystem-safe slug from an AI title" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ try std.testing.expectEqualStrings("fixing-the-login-bug", session.slugifyTitle(a, "Fixing the login bug"));+ try std.testing.expectEqualStrings("add-dark-mode", session.slugifyTitle(a, "Add dark mode!!"));+ try std.testing.expectEqualStrings("planning-v2", session.slugifyTitle(a, " Planning — v2 ")); // trim + collapse+ try std.testing.expectEqualStrings("", session.slugifyTitle(a, "🎉 ✨")); // symbol-only → "" (keeps the session-<ts> name)+}++test "hasMeaningfulState gates the blank-draft write (#184)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ // Only the fields hasMeaningfulState reads are set; the rest stay untouched.+ var root: Agent = undefined;+ root.goal = null;+ root.todos = .empty;+ root.tools_used = .{};+ root.messages = std.json.Array.init(arena);++ // Truly blank: no user turn, no goal, no todos, no tools → not persisted.+ try std.testing.expect(!session.hasMeaningfulState(&root));++ // A standing /goal alone is meaningful (goal-only sessions are still saved).+ root.goal = .{ .objective = "ship the release" };+ try std.testing.expect(session.hasMeaningfulState(&root));++ // One user message alone is meaningful.+ root.goal = null;+ var obj: std.json.ObjectMap = .empty;+ try obj.put(arena, "role", .{ .string = "user" });+ try obj.put(arena, "content", .{ .string = "hi" });+ try root.messages.append(.{ .object = obj });+ try std.testing.expect(session.hasMeaningfulState(&root));+}++// ── #273: the save path itself ────────────────────────────────────────────++const Fixture = struct {+ client: std.http.Client,+ root: Agent,+};++/// A root agent with a one-turn conversation — enough state that saveSession+/// considers it worth persisting (#184). Every field the save path reads is+/// set explicitly; nothing is left `undefined`.+fn fixture(gpa: Allocator, arena: Allocator, io: Io) !*Fixture {+ const f = try gpa.create(Fixture);+ f.client = .{ .allocator = gpa, .io = io };+ var msgs = std.json.Array.init(arena);+ var user: std.json.ObjectMap = .empty;+ try user.put(arena, "role", .{ .string = "user" });+ try user.put(arena, "content", .{ .string = "first prompt" });+ try msgs.append(.{ .object = user });+ f.root = .{+ .gpa = gpa,+ .arena = arena,+ .io = io,+ .client = &f.client,+ .provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "gpt-5", .context = 100_000 },+ .messages = msgs,+ .sub = false,+ .label = "root",+ .out = null,+ .session_title = "persistence test",+ };+ return f;+}++fn appendTurn(arena: Allocator, root: *Agent, text: []const u8) !void {+ var m: std.json.ObjectMap = .empty;+ try m.put(arena, "role", .{ .string = "assistant" });+ try m.put(arena, "content", .{ .string = text });+ try root.messages.append(.{ .object = m });+}++fn readSaved(dir: Io.Dir, gpa: Allocator) ![]u8 {+ return dir.readFileAlloc(std.testing.io, ".graff/sessions/wf.session.json", gpa, .limited(64 * 1024));+}++test "an unchanged conversation skips the save entirely (#273)" {+ const io = std.testing.io;+ const gpa = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ session_writer.resetForTest();+ defer session_writer.resetForTest();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();++ const f = try fixture(gpa, arena, io);+ defer gpa.destroy(f);++ try session.saveSessionTo(&f.root, arena, tmp.dir, "wf");+ session.flushSaves();+ const first = try readSaved(tmp.dir, gpa);+ defer gpa.free(first);+ try std.testing.expect(std.mem.indexOf(u8, first, "first prompt") != null);+ try std.testing.expectEqual(@as(usize, 1), session_writer.stats().writes);++ // Overwrite the file behind the harness's back. A skipped save leaves this+ // untouched — proof that nothing was serialized OR written, not merely that+ // the same bytes were rewritten.+ try tmp.dir.writeFile(io, .{ .sub_path = ".graff/sessions/wf.session.json", .data = "SENTINEL" });+ try session.saveSessionTo(&f.root, arena, tmp.dir, "wf");+ session.flushSaves();+ const after = try readSaved(tmp.dir, gpa);+ defer gpa.free(after);+ try std.testing.expectEqualStrings("SENTINEL", after);+ try std.testing.expectEqual(@as(usize, 1), session_writer.stats().writes);+}++test "any change to the conversation produces a save (#273)" {+ const io = std.testing.io;+ const gpa = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ session_writer.resetForTest();+ defer session_writer.resetForTest();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();++ const f = try fixture(gpa, arena, io);+ defer gpa.destroy(f);+ try session.saveSessionTo(&f.root, arena, tmp.dir, "wf");+ session.flushSaves();++ // A new turn.+ try appendTurn(arena, &f.root, "the reply");+ try session.saveSessionTo(&f.root, arena, tmp.dir, "wf");+ session.flushSaves();+ const two = try readSaved(tmp.dir, gpa);+ defer gpa.free(two);+ try std.testing.expect(std.mem.indexOf(u8, two, "the reply") != null);+ try std.testing.expectEqual(@as(usize, 2), session_writer.stats().writes);++ // An IN-PLACE rewrite of an existing message (what compaction and the+ // tool-output truncator do): the message count is unchanged, and the save+ // must still happen.+ try f.root.messages.items[1].object.put(arena, "content", .{ .string = "compacted" });+ try session.saveSessionTo(&f.root, arena, tmp.dir, "wf");+ session.flushSaves();+ const three = try readSaved(tmp.dir, gpa);+ defer gpa.free(three);+ try std.testing.expect(std.mem.indexOf(u8, three, "compacted") != null);+ try std.testing.expectEqual(@as(usize, 3), session_writer.stats().writes);++ // State outside the history counts too (a /rename here).+ f.root.session_title = "renamed";+ try session.saveSessionTo(&f.root, arena, tmp.dir, "wf");+ session.flushSaves();+ try std.testing.expectEqual(@as(usize, 4), session_writer.stats().writes);+}++test "a turn's queued save is not lost when the session ends (#273)" {+ const io = std.testing.io;+ const gpa = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ session_writer.resetForTest();+ defer session_writer.resetForTest();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();++ const f = try fixture(gpa, arena, io);+ defer gpa.destroy(f);++ // Hold the writer so the save is provably still queued, exactly as it can+ // be when the loop is about to return.+ session_writer.setPausedForTest(io, true);+ try appendTurn(arena, &f.root, "the last thing the model said");+ try session.saveSessionTo(&f.root, arena, tmp.dir, "wf");+ try std.testing.expectError(error.FileNotFound, tmp.dir.statFile(io, ".graff/sessions/wf.session.json", .{}));++ // What mainloop.run defers and finalizeSession repeats.+ session_writer.setPausedForTest(io, false);+ session.flushSaves();+ const saved = try readSaved(tmp.dir, gpa);+ defer gpa.free(saved);+ try std.testing.expect(std.mem.indexOf(u8, saved, "the last thing the model said") != null);+}diff --git a/src/session_writer.zig b/src/session_writer.zignew file mode 100644index 00000000..2c2ab5d0--- /dev/null+++ b/src/session_writer.zig@@ -0,0 +1,437 @@+//! #273: the autosave's *disk write*, moved off the turn's critical path, plus+//! the content fingerprint that lets an unchanged conversation skip the save+//! entirely.+//!+//! Every finished turn rewrote the whole retained history synchronously before+//! the loop could accept the next prompt, so next-prompt readiness scaled with+//! the total session size instead of with the new turn. Two conservative fixes,+//! no format change and no journal:+//!+//! 1. `Fingerprint` hashes exactly the state saveSession serializes (minus+//! `updated_ms`, which is a clock reading, not conversation state). When it+//! matches the last SUCCESSFUL write, the save is skipped whole — no+//! serialize, no lock, no write. Hashing the live JSON tree is a pointer+//! walk plus a memcpy-speed digest; std.json.Stringify allocates, escapes,+//! and formats every byte, so the skip is far cheaper than the save it+//! replaces.+//! 2. The serialized bytes are handed to ONE background writer thread that+//! performs the identical `session_lock.writeSession` (parent dirs ++//! exclusive advisory lock + positional overwrite + truncate, #289). Only+//! one job is ever queued: a newer save supersedes an older queued one, so+//! a burst of saves costs one write, always of the newest state.+//!+//! Serialization stays on the CALLER thread on purpose. `root.messages` is live+//! agent state with no lock of its own; serializing it on the writer thread+//! would race the next turn's appends for a real correctness bug, and the+//! alternative (deep-cloning a multi-MB history per turn) costs more than the+//! serialization it moves. Only the file write — the part that touches the disk+//! and cannot touch agent state — runs in the background.+//!+//! Measured (ReleaseFast, macOS/APFS, warm cache; std.json.Stringify vs the+//! locked write vs this fingerprint, per save):+//!+//! 100 KiB history serialize 0.14 ms write 0.08 ms fingerprint 0.01 ms+//! 1 MiB history serialize 0.94 ms write 0.24 ms fingerprint 0.07 ms+//! 10 MiB history serialize 7.04 ms write 1.10 ms fingerprint 0.59 ms+//!+//! So be honest about what moved: the serialize is 62-87% of a save's cost and+//! is STILL on the turn's path when the conversation changed; backgrounding the+//! write buys the remaining 13-38%. The large win is the skip — an unchanged+//! session now costs the fingerprint alone, ~7% of one save at 10 MiB. Taking+//! the serialize off the path too needs either a lock around the history or an+//! incremental/journal format, both out of scope here (#273 asks for the+//! conservative step).+//!+//! Durability is bounded by `drain()`: the interactive loop drains before+//! returning, and every non-turn saver (session.saveSession) drains as part of+//! the save. So the only window in which a queued write can be lost is inside a+//! single turn's tail, and nothing exits the process through it.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const Value = std.json.Value;++const session_lock = @import("session_lock.zig");++/// A digest of everything the session file records about the conversation.+/// Content-derived, so a skip can never be wrong about "nothing changed" the+/// way a hand-maintained dirty flag can: the history has ~25 production+/// mutation sites (appends, compaction rewrites, in-place repairs), and one+/// missed site would silently drop a turn from disk.+pub const Fingerprint = struct {+ h: std.hash.Wyhash,++ pub fn init() Fingerprint {+ return .{ .h = std.hash.Wyhash.init(0x2735e5510) };+ }++ pub fn num(self: *Fingerprint, v: u64) void {+ var le: [8]u8 = undefined;+ std.mem.writeInt(u64, &le, v, .little);+ self.h.update(&le);+ }++ pub fn signed(self: *Fingerprint, v: i64) void {+ self.num(@bitCast(v));+ }++ pub fn flag(self: *Fingerprint, v: bool) void {+ self.h.update(&[_]u8{@intFromBool(v)});+ }++ /// Length-prefixed: "ab"+"c" must not collide with "a"+"bc".+ pub fn text(self: *Fingerprint, s: []const u8) void {+ self.num(s.len);+ self.h.update(s);+ }++ /// The same tree std.json.Stringify would walk, digested instead of+ /// formatted. Object fields are hashed in insertion order, which is the+ /// order they are serialized in.+ pub fn json(self: *Fingerprint, v: Value) void {+ self.h.update(&[_]u8{@intFromEnum(std.meta.activeTag(v))});+ switch (v) {+ .null => {},+ .bool => |b| self.flag(b),+ .integer => |i| self.signed(i),+ .float => |f| self.num(@bitCast(f)),+ .number_string, .string => |s| self.text(s),+ .array => |a| {+ self.num(a.items.len);+ for (a.items) |item| self.json(item);+ },+ .object => |o| {+ self.num(o.count());+ var it = o.iterator();+ while (it.next()) |e| {+ self.text(e.key_ptr.*);+ self.json(e.value_ptr.*);+ }+ },+ }+ }++ pub fn final(self: *Fingerprint) u64 {+ return self.h.final();+ }+};++const Job = struct {+ io: Io,+ dir: Io.Dir,+ path: []u8,+ data: []u8,++ fn deinit(job: Job, gpa: Allocator) void {+ gpa.free(job.path);+ gpa.free(job.data);+ }+};++/// Counters for the tests: how many background writes completed, and how many+/// queued jobs a newer save superseded before they ever reached the disk.+pub const Stats = struct { writes: usize, superseded: usize };++// std.Io owns the synchronization primitives (there is no std.Thread.Mutex),+// so every lock/wait needs an Io. The first submit records the session's, and+// nothing can be queued before that — a caller arriving earlier finds an empty+// queue and returns. The uncancelable variants are deliberate: the writer+// thread is not one of the Io runtime's, and a cancelation point on the+// autosave path would be a way to lose a save.+var writer_io: ?Io = null;+var mutex: Io.Mutex = .init;+var work: Io.Condition = .init; // worker: something to write, or stop+var idle: Io.Condition = .init; // drainers: the queue went quiet+var pending: ?Job = null;+var gpa_of_pending: Allocator = undefined;+var busy = false;+var stopping = false;+var thread: ?std.Thread = null;+var mark: ?u64 = null; // fingerprint of the newest state written or queued+var last_error: ?anyerror = null;+var writes: usize = 0;+var superseded: usize = 0;+/// Test seam: hold the worker before it claims a job, so a test can prove a+/// save really was queued (and really was superseded) rather than racing it.+/// `stop()` clears it — shutdown always wins over a test pause.+var paused = false;++/// True when `fp` is already on disk (or queued to be, and nothing has failed+/// since). The caller then skips serializing entirely.+pub fn alreadySaved(fp: u64) bool {+ const io = writer_io orelse return false; // nothing has ever been saved+ mutex.lockUncancelable(io);+ defer mutex.unlock(io);+ return if (mark) |m| m == fp else false;+}++/// Queue `data` for `dir`/`path`, superseding any still-queued save. Takes+/// ownership of both slices (freed with `gpa` once written or superseded), so+/// it cannot fail and leave the caller unsure who owns them: a write failure is+/// recorded for `takeError` instead of returned. Falls back to the pre-#273+/// inline write when no thread can be spawned.+pub fn submit(gpa: Allocator, io: Io, dir: Io.Dir, path: []u8, data: []u8, fp: u64) void {+ writer_io = io; // set before anything can be queued; see writer_io+ mutex.lockUncancelable(io);+ if (thread == null and !stopping) thread = std.Thread.spawn(.{}, worker, .{io}) catch null;+ if (thread == null) {+ // No worker — threads are unavailable, or one is being retired. Write+ // inline rather than queue behind nobody.+ mutex.unlock(io);+ defer gpa.free(path);+ defer gpa.free(data);+ writeNow(io, dir, path, data, fp);+ return;+ }+ defer mutex.unlock(io);+ if (pending) |old| {+ old.deinit(gpa_of_pending);+ superseded += 1;+ }+ gpa_of_pending = gpa;+ pending = .{ .io = io, .dir = dir, .path = path, .data = data };+ mark = fp;+ work.broadcast(io);+}++/// The pre-#273 write, used when threads are unavailable.+fn writeNow(io: Io, dir: Io.Dir, path: []const u8, data: []const u8, fp: u64) void {+ var failed: ?anyerror = null;+ session_lock.writeSession(io, dir, path, data) catch |err| {+ failed = err;+ };+ mutex.lockUncancelable(io);+ defer mutex.unlock(io);+ if (failed) |err| {+ last_error = err;+ mark = null;+ } else {+ mark = fp;+ writes += 1;+ }+}++fn worker(io: Io) void {+ while (true) {+ mutex.lockUncancelable(io);+ while (!stopping and (pending == null or paused)) work.waitUncancelable(io, &mutex);+ const job = pending orelse {+ mutex.unlock(io); // stopping with an empty queue: nothing was lost+ return;+ };+ const gpa = gpa_of_pending;+ pending = null;+ busy = true;+ mutex.unlock(io);++ var failed: ?anyerror = null;+ session_lock.writeSession(job.io, job.dir, job.path, job.data) catch |err| {+ failed = err;+ };+ job.deinit(gpa);++ mutex.lockUncancelable(io);+ busy = false;+ if (failed) |err| {+ last_error = err;+ // Nothing is on disk for this state: make the next save write+ // again instead of skipping on a fingerprint that never landed.+ mark = null;+ } else writes += 1;+ idle.broadcast(io);+ mutex.unlock(io);+ }+}++/// Block until every queued save has been written. Called before the+/// interactive loop returns and by every synchronous saver.+pub fn drain() void {+ const io = writer_io orelse return;+ mutex.lockUncancelable(io);+ defer mutex.unlock(io);+ if (thread == null) return;+ while (pending != null or busy) idle.waitUncancelable(io, &mutex);+}++/// The last write failure, cleared as it is read. Background failures cannot+/// be returned to the caller that queued them, so the next synchronous save+/// reports them instead — /save and the exit save still print a real error.+pub fn takeError() ?anyerror {+ const io = writer_io orelse return null;+ mutex.lockUncancelable(io);+ defer mutex.unlock(io);+ defer last_error = null;+ return last_error;+}++pub fn stats() Stats {+ const io = writer_io orelse return .{ .writes = 0, .superseded = 0 };+ mutex.lockUncancelable(io);+ defer mutex.unlock(io);+ return .{ .writes = writes, .superseded = superseded };+}++/// Drain, then retire the worker thread. Tests use it; production relies on+/// `drain()` (the parked worker owns nothing once the queue is empty).+pub fn stop() void {+ const io = writer_io orelse return;+ mutex.lockUncancelable(io);+ paused = false; // shutdown outranks a test pause+ work.broadcast(io);+ while (pending != null or busy) idle.waitUncancelable(io, &mutex);+ const t = thread;+ if (t != null) {+ stopping = true;+ work.broadcast(io);+ }+ mutex.unlock(io);+ if (t) |joinable| joinable.join();+ mutex.lockUncancelable(io);+ defer mutex.unlock(io);+ thread = null;+ stopping = false;+}++/// Test seam (see `paused`).+pub fn setPausedForTest(io: Io, v: bool) void {+ writer_io = io;+ mutex.lockUncancelable(io);+ defer mutex.unlock(io);+ paused = v;+ work.broadcast(io);+}++/// Full reset between tests: the writer is a process global, so a leftover+/// `mark` from another test would silently skip a save under test.+pub fn resetForTest() void {+ stop();+ const io = writer_io orelse return;+ mutex.lockUncancelable(io);+ defer mutex.unlock(io);+ if (pending) |old| old.deinit(gpa_of_pending);+ pending = null;+ mark = null;+ last_error = null;+ writes = 0;+ superseded = 0;+ paused = false;+}++test "fingerprint tracks every mutation the session file records (#273)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ var msgs = std.json.Array.init(a);+ var user: std.json.ObjectMap = .empty;+ try user.put(a, "role", .{ .string = "user" });+ try user.put(a, "content", .{ .string = "ship #273" });+ try msgs.append(.{ .object = user });++ const of = struct {+ fn fp(m: std.json.Array, title: []const u8) u64 {+ var f: Fingerprint = .init();+ f.text(title);+ f.json(.{ .array = m });+ return f.final();+ }+ }.fp;++ const base = of(msgs, "t");+ // Unchanged state hashes identically — this is what makes the skip safe.+ try std.testing.expectEqual(base, of(msgs, "t"));+ // A field OUTSIDE the history still counts (title, goal, todos, flags).+ try std.testing.expect(base != of(msgs, "t2"));++ // An appended turn.+ var reply: std.json.ObjectMap = .empty;+ try reply.put(a, "role", .{ .string = "assistant" });+ try reply.put(a, "content", .{ .string = "done" });+ try msgs.append(.{ .object = reply });+ const appended = of(msgs, "t");+ try std.testing.expect(base != appended);++ // An IN-PLACE edit of an existing message (compaction/truncation shape):+ // same message count, different content. A length-only or count-only dirty+ // check would miss exactly this and lose the rewrite.+ try msgs.items[0].object.put(a, "content", .{ .string = "ship #273 now" });+ try std.testing.expect(appended != of(msgs, "t"));+}++fn expectFile(dir: Io.Dir, path: []const u8, want: []const u8) !void {+ const got = try dir.readFileAlloc(std.testing.io, path, std.testing.allocator, .limited(4096));+ defer std.testing.allocator.free(got);+ try std.testing.expectEqualStrings(want, got);+}++test "a queued save reaches disk and drain waits for it (#273)" {+ const io = std.testing.io;+ const gpa = std.testing.allocator;+ resetForTest();+ defer resetForTest();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();++ submit(gpa, io, tmp.dir, try gpa.dupe(u8, "s/a.json"), try gpa.dupe(u8, "{\"m\":1}"), 1);+ drain();+ try expectFile(tmp.dir, "s/a.json", "{\"m\":1}");+ try std.testing.expectEqual(@as(usize, 1), stats().writes);+ // The write landed, so an identical save is now skippable.+ try std.testing.expect(alreadySaved(1));+ try std.testing.expect(!alreadySaved(2));+}++test "a newer save supersedes an older queued one (#273)" {+ const io = std.testing.io;+ const gpa = std.testing.allocator;+ resetForTest();+ defer resetForTest();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();++ setPausedForTest(io, true);+ submit(gpa, io, tmp.dir, try gpa.dupe(u8, "s/b.json"), try gpa.dupe(u8, "old"), 1);+ submit(gpa, io, tmp.dir, try gpa.dupe(u8, "s/b.json"), try gpa.dupe(u8, "newest"), 2);+ try std.testing.expectEqual(@as(usize, 1), stats().superseded);+ setPausedForTest(io, false);+ drain();+ // One write, of the newest state: a burst never costs a write per save.+ try std.testing.expectEqual(@as(usize, 1), stats().writes);+ try expectFile(tmp.dir, "s/b.json", "newest");+}++test "no queued save is lost at shutdown (#273)" {+ const io = std.testing.io;+ const gpa = std.testing.allocator;+ resetForTest();+ defer resetForTest();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();++ setPausedForTest(io, true);+ submit(gpa, io, tmp.dir, try gpa.dupe(u8, "s/c.json"), try gpa.dupe(u8, "last turn"), 7);+ // Provably still queued: nothing is on disk yet.+ try std.testing.expectError(error.FileNotFound, tmp.dir.statFile(io, "s/c.json", .{}));+ stop(); // the exit path: drain, then retire the worker+ try expectFile(tmp.dir, "s/c.json", "last turn");+}++test "a failed write clears the skip mark so the next save retries (#273)" {+ const io = std.testing.io;+ const gpa = std.testing.allocator;+ resetForTest();+ defer resetForTest();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();++ // A regular file where the session directory would go: createDirPath and+ // the create both fail, so the write cannot land.+ try tmp.dir.writeFile(io, .{ .sub_path = "blocked", .data = "" });+ submit(gpa, io, tmp.dir, try gpa.dupe(u8, "blocked/d.json"), try gpa.dupe(u8, "x"), 5);+ drain();+ try std.testing.expectEqual(@as(usize, 0), stats().writes);+ try std.testing.expect(!alreadySaved(5)); // never skip on a write that failed+ try std.testing.expect(takeError() != null);+ try std.testing.expect(takeError() == null); // reported once+}diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 43953f0d..8af64170 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -47,6 +47,9 @@ const serve_create = @import("serve_create.zig");// Moved off main.zig, which is at the 600-line cap.const scoring_slot_test = @import("scoring_slot_test.zig");+// #273: session.zig's own tests, moved off it for the same reason.+const session_tests = @import("session_tests.zig");+// #345: the global-vs-project MCP config merge. mcp.zig does reference its// decls, but the hook makes the coverage explicit rather than contingent on// that staying true.@@ -68,5 +71,6 @@ test {_ = serve_events;_ = serve_create;_ = scoring_slot_test;+ _ = session_tests;_ = mcp_config;}