Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix(session): a save reports its own outcome, and the skip needs the file to still be there (#273)

justrachb30905a207d6
diff --git a/src/session.zig b/src/session.zig
index e98dbf9c..be9a75b2 100644
--- a/src/session.zig
+++ b/src/session.zig
@@ -176,14 +176,17 @@ fn fingerprint(root: *Agent, name: []const u8) u64 {
/// 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| {
+ const ticket = queueSave(root, arena, .cwd(), 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;
+ // Only THIS save's outcome: a background autosave that failed two turns ago
+ // is not /save's failure, and reporting it as one made /save print "save
+ // failed" (and skip the rename) for a file it had just written correctly.
+ if (session_writer.errorFor(ticket)) |err| return err;
}
/// #273: the interactive turn path's save. Skips entirely when nothing changed,
@@ -194,7 +197,7 @@ pub fn saveSession(root: *Agent, arena: Allocator, name: []const u8) !void {
/// 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);
+ _ = try queueSave(root, arena, .cwd(), name);
}
/// Wait for any queued save to reach disk. The exit/quit/switch bound on how
@@ -207,13 +210,23 @@ pub fn flushSaves() void {
/// 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 {
+ _ = try queueSave(root, arena, dir, name);
+}
+
+/// `saveSessionTo` plus the writer ticket for the save it queued — 0 when
+/// nothing needed writing. A synchronous caller keeps the ticket so it can ask
+/// `session_writer.errorFor` about ITS OWN write and not about someone else's.
+fn queueSave(root: *Agent, arena: Allocator, dir: Io.Dir, name: []const u8) !u64 {
// #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.
+ if (!hasMeaningfulState(root)) return 0;
+ // #273: nothing has changed since the last successful write of this session
+ // AND that write is still what the file holds (a second graff, an editor or
+ // an rm all invalidate it — the skip is never taken on trust).
const fp = fingerprint(root, name);
- if (session_writer.alreadySaved(fp)) return;
+ const rel = try sessionPath(arena, name);
+ if (session_writer.alreadySaved(root.io, dir, rel, fp)) return 0;
var aw: Io.Writer.Allocating = .init(root.gpa);
defer aw.deinit();
var s: std.json.Stringify = .{ .writer = &aw.writer };
@@ -291,9 +304,9 @@ pub fn saveSessionTo(root: *Agent, arena: Allocator, dir: Io.Dir, name: []const
// #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.
// #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));
+ const path = try root.gpa.dupe(u8, rel);
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);
+ return 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
diff --git a/src/session_run.zig b/src/session_run.zig
index 2b08dbfb..8b00dd95 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -351,11 +351,11 @@ pub fn compactResumedSession(root: *agent_mod.Agent) void {
/// goal); `root` is already stable main()-owned storage.
pub fn finalizeSession(gpa: Allocator, io: Io, arena: Allocator, out: *Io.Writer, root: *agent_mod.Agent, json_mode: bool) !void {
if (!json_mode and root.messages.items.len > 0) {
- session.saveSession(root, arena, root.session_name) catch |err| {
+ if (session.saveSession(root, arena, root.session_name)) |_| {
+ out.print("{s}↩ session saved → {s}{s}{s}\n", .{ ansi.style.dim, root.session_name, ansi.style.reset, session.session_ext }) catch {};
+ } else |err| { // one line, and true: never contradict a failure with "saved" (#273)
out.print("{s}⚠ session save failed: {t}{s}\n", .{ ansi.style.yellow, err, ansi.style.reset }) catch {};
- out.flush() catch {};
- };
- out.print("{s}↩ session saved → {s}{s}{s}\n", .{ ansi.style.dim, root.session_name, ansi.style.reset, session.session_ext }) catch {};
+ }
out.flush() catch {};
} else {
session.saveSession(root, arena, root.session_name) catch {};
diff --git a/src/session_tests.zig b/src/session_tests.zig
index 5d7edfc1..54cc1d21 100644
--- a/src/session_tests.zig
+++ b/src/session_tests.zig
@@ -168,18 +168,46 @@ test "an unchanged conversation skips the save entirely (#273)" {
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" });
+ // Nothing changed and nothing touched the file: the save is skipped whole.
+ // The write counter is the proof — not that the bytes match (they would
+ // even if we had re-serialized and rewritten them), but that no write
+ // happened at all.
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 "the skip never fires over a session file something else rewrote (#273/#289)" {
+ 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 second graff resumed on the same name writes its own snapshot over
+ // ours — the advisory lock is only held during the write, so this lands.
+ // Our next save (the exit save, or a /save with nothing new since the last
+ // turn) must NOT skip on "we already wrote this state": the file no longer
+ // holds our conversation, and a skip would silently drop every turn we have.
+ try tmp.dir.writeFile(io, .{ .sub_path = ".graff/sessions/wf.session.json", .data = "{\"messages\":[\"the other graff\"]}" });
+ try session.saveSessionTo(&f.root, arena, tmp.dir, "wf");
+ session.flushSaves();
+ const repaired = try readSaved(tmp.dir, gpa);
+ defer gpa.free(repaired);
+ try std.testing.expect(std.mem.indexOf(u8, repaired, "first prompt") != null);
+ try std.testing.expect(std.mem.indexOf(u8, repaired, "the other graff") == null);
+ try std.testing.expectEqual(@as(usize, 2), session_writer.stats().writes);
+}
+
test "any change to the conversation produces a save (#273)" {
const io = std.testing.io;
const gpa = std.testing.allocator;
diff --git a/src/session_writer.zig b/src/session_writer.zig
index 2c2ab5d0..4752489a 100644
--- a/src/session_writer.zig
+++ b/src/session_writer.zig
@@ -9,11 +9,13 @@
//!
//! 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.
+//! matches the last SUCCESSFUL write *and the file still holds that write*
+//! (`Mark`), 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. The disk check is what
+//! keeps the skip from becoming a silent data loss when something else
+//! rewrites the session file between our saves.
//! 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
@@ -46,6 +48,12 @@
//! 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.
+//!
+//! Failures are reported per save, not per process: `submit` returns a ticket
+//! and `errorFor(ticket)` answers for that save alone. A background autosave's
+//! failure belongs to the turn that queued it — charging it to whatever save
+//! happened to ask next made `/save` report a failure for a file it had just
+//! written correctly.
const std = @import("std");
const Io = std.Io;
@@ -122,6 +130,9 @@ const Job = struct {
dir: Io.Dir,
path: []u8,
data: []u8,
+ fp: u64,
+ /// The `submit` that queued this job — see `errorFor`.
+ ticket: u64,
fn deinit(job: Job, gpa: Allocator) void {
gpa.free(job.path);
@@ -129,6 +140,22 @@ const Job = struct {
}
};
+/// Evidence that one fingerprint is on disk RIGHT NOW. Not "we wrote it once":
+/// the file we wrote it to, plus that file's identity (inode), length and mtime
+/// as observed the instant after the write. A fingerprint alone only records
+/// what THIS process last serialized, and the session file is shared — a second
+/// graff in the same workspace (#289) writes its own snapshot the moment our
+/// lock is released, and an `rm`/editor/restore can replace it just as easily.
+/// Skipping on the fingerprint alone would then skip forever over a file that
+/// no longer holds this conversation, including on the exit save.
+const Mark = struct {
+ fp: u64,
+ path: []u8,
+ inode: Io.File.INode,
+ size: u64,
+ mtime_ns: i96,
+};
+
/// 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 };
@@ -148,8 +175,11 @@ 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 mark: ?Mark = null; // the newest state PROVEN to be on disk
+var mark_gpa: Allocator = undefined; // owns mark.path while mark != null
+var tickets: u64 = 0; // the last ticket handed out by submit
+var last_error: ?anyerror = null; // the NEWEST write's failure, if it failed
+var error_ticket: u64 = 0; // and whose failure that is
var writes: usize = 0;
var superseded: usize = 0;
/// Test seam: hold the worker before it claims a job, so a test can prove a
@@ -157,32 +187,53 @@ var superseded: usize = 0;
/// `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;
+/// True when `dir`/`path` still holds exactly the bytes we last wrote for `fp`,
+/// so the caller can skip serializing entirely.
+///
+/// The check is against the FILE, not against our memory of it: the mark is
+/// trusted only while the session file is still the same inode, at the same
+/// length, with the same mtime we saw right after writing it. Anything else —
+/// another graff's snapshot, a delete, a hand edit — invalidates the mark, and
+/// the save goes through and repairs the file instead of silently no-opping.
+pub fn alreadySaved(io: Io, dir: Io.Dir, path: []const u8, fp: u64) bool {
+ const wio = writer_io orelse return false; // nothing has ever been saved
+ mutex.lockUncancelable(wio);
+ defer mutex.unlock(wio);
+ const m = mark orelse return false;
+ if (m.fp != fp or !std.mem.eql(u8, m.path, path)) return false;
+ const st = dir.statFile(io, path, .{}) catch {
+ clearMark(); // gone or unreadable: never skip over a file we cannot see
+ return false;
+ };
+ if (st.inode != m.inode or st.size != m.size or st.mtime.nanoseconds != m.mtime_ns) {
+ clearMark(); // someone else's bytes are in the file now
+ return false;
+ }
+ return true;
}
/// 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 {
+/// recorded against the returned ticket instead of returned. Falls back to the
+/// pre-#273 inline write when no thread can be spawned.
+///
+/// The returned ticket identifies THIS save. After `drain()`, `errorFor(ticket)`
+/// answers for it and for nothing else.
+pub fn submit(gpa: Allocator, io: Io, dir: Io.Dir, path: []u8, data: []u8, fp: u64) u64 {
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;
+ tickets += 1;
+ const ticket = tickets;
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;
+ writeNow(gpa, io, dir, path, data, fp, ticket);
+ return ticket;
}
defer mutex.unlock(io);
if (pending) |old| {
@@ -190,26 +241,65 @@ pub fn submit(gpa: Allocator, io: Io, dir: Io.Dir, path: []u8, data: []u8, fp: u
superseded += 1;
}
gpa_of_pending = gpa;
- pending = .{ .io = io, .dir = dir, .path = path, .data = data };
- mark = fp;
+ pending = .{ .io = io, .dir = dir, .path = path, .data = data, .fp = fp, .ticket = ticket };
work.broadcast(io);
+ return ticket;
}
/// 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 {
+fn writeNow(gpa: Allocator, io: Io, dir: Io.Dir, path: []const u8, data: []const u8, fp: u64, ticket: u64) void {
var failed: ?anyerror = null;
session_lock.writeSession(io, dir, path, data) catch |err| {
failed = err;
};
+ const evidence: ?Mark = if (failed == null) observe(gpa, io, dir, path, fp) else null;
mutex.lockUncancelable(io);
defer mutex.unlock(io);
+ finish(gpa, failed, ticket, evidence);
+}
+
+/// What the file looks like immediately after a successful write. Null when
+/// that cannot be observed (the stat fails, or the path cannot be kept): no
+/// evidence means no skip, which costs a redundant write and never a lost one.
+fn observe(gpa: Allocator, io: Io, dir: Io.Dir, path: []const u8, fp: u64) ?Mark {
+ const st = dir.statFile(io, path, .{}) catch return null;
+ const kept = gpa.dupe(u8, path) catch return null;
+ return .{
+ .fp = fp,
+ .path = kept,
+ .inode = st.inode,
+ .size = st.size,
+ .mtime_ns = st.mtime.nanoseconds,
+ };
+}
+
+fn clearMark() void {
+ if (mark) |old| mark_gpa.free(old.path);
+ mark = null;
+}
+
+fn setMark(gpa: Allocator, m: Mark) void {
+ clearMark();
+ mark = m;
+ mark_gpa = gpa;
+}
+
+/// Record one write's outcome; the mutex is held. `last_error` always describes
+/// the NEWEST write, so a success wipes an older failure (the disk is current
+/// again) and no save is ever blamed for a failure that predates it.
+fn finish(gpa: Allocator, failed: ?anyerror, ticket: u64, evidence: ?Mark) void {
+ clearMark();
if (failed) |err| {
last_error = err;
- mark = null;
- } else {
- mark = fp;
- writes += 1;
+ error_ticket = ticket;
+ // Nothing is on disk for this state: the cleared mark makes the next
+ // save write again instead of skipping on a write that never landed.
+ return;
}
+ writes += 1;
+ last_error = null;
+ error_ticket = 0;
+ if (evidence) |m| setMark(gpa, m);
}
fn worker(io: Io) void {
@@ -229,16 +319,12 @@ fn worker(io: Io) void {
session_lock.writeSession(job.io, job.dir, job.path, job.data) catch |err| {
failed = err;
};
+ const evidence: ?Mark = if (failed == null) observe(gpa, job.io, job.dir, job.path, job.fp) else null;
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;
+ finish(gpa, failed, job.ticket, evidence);
idle.broadcast(io);
mutex.unlock(io);
}
@@ -254,15 +340,25 @@ pub fn drain() void {
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 {
+/// The failure of the save that `submit` gave `ticket` to, cleared as it is
+/// read. Call it after `drain()`.
+///
+/// Scoped to the ticket on purpose. A background autosave's failure belongs to
+/// the turn that queued it, not to the next synchronous save: reporting turn 5's
+/// lost flock race as `/save release-notes`'s own failure made the command print
+/// "save failed" and skip the rename, for a file it had just written correctly.
+/// A ticket is answered by its own write, or by a newer one that superseded or
+/// followed it and failed in its place — then this state is not on disk either.
+pub fn errorFor(ticket: u64) ?anyerror {
+ if (ticket == 0) return null; // this caller queued nothing; nothing to report
const io = writer_io orelse return null;
mutex.lockUncancelable(io);
defer mutex.unlock(io);
- defer last_error = null;
- return last_error;
+ const err = last_error orelse return null;
+ if (error_ticket < ticket) return null; // an older save's failure, not ours
+ last_error = null;
+ error_ticket = 0;
+ return err;
}
pub fn stats() Stats {
@@ -311,8 +407,10 @@ pub fn resetForTest() void {
defer mutex.unlock(io);
if (pending) |old| old.deinit(gpa_of_pending);
pending = null;
- mark = null;
+ clearMark();
+ tickets = 0;
last_error = null;
+ error_ticket = 0;
writes = 0;
superseded = 0;
paused = false;
@@ -373,13 +471,43 @@ test "a queued save reaches disk and drain waits for it (#273)" {
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);
+ _ = 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));
+ try std.testing.expect(alreadySaved(io, tmp.dir, "s/a.json", 1));
+ try std.testing.expect(!alreadySaved(io, tmp.dir, "s/a.json", 2)); // other state
+ try std.testing.expect(!alreadySaved(io, tmp.dir, "s/other.json", 1)); // other file
+}
+
+test "the skip needs the bytes to still be on disk, not just to have been written (#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/e.json"), try gpa.dupe(u8, "ten turns"), 3);
+ drain();
+ try std.testing.expect(alreadySaved(io, tmp.dir, "s/e.json", 3));
+
+ // A second graff in the same workspace writes its own snapshot over ours
+ // (#289: the lock is only held during the write). The state we would skip
+ // on is no longer what the file holds, so the skip must not happen — the
+ // exit save has to rewrite and win, as it did before #273.
+ try tmp.dir.writeFile(io, .{ .sub_path = "s/e.json", .data = "another graff" });
+ try std.testing.expect(!alreadySaved(io, tmp.dir, "s/e.json", 3));
+ // Invalidated for good: not a one-shot that re-trusts itself next call.
+ try std.testing.expect(!alreadySaved(io, tmp.dir, "s/e.json", 3));
+
+ // Same for a session file that is deleted out from under us.
+ _ = submit(gpa, io, tmp.dir, try gpa.dupe(u8, "s/e.json"), try gpa.dupe(u8, "ten turns"), 3);
+ drain();
+ try std.testing.expect(alreadySaved(io, tmp.dir, "s/e.json", 3));
+ try tmp.dir.deleteFile(io, "s/e.json");
+ try std.testing.expect(!alreadySaved(io, tmp.dir, "s/e.json", 3));
}
test "a newer save supersedes an older queued one (#273)" {
@@ -391,8 +519,8 @@ test "a newer save supersedes an older queued one (#273)" {
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);
+ _ = 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();
@@ -410,7 +538,7 @@ test "no queued save is lost at shutdown (#273)" {
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);
+ _ = 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
@@ -428,10 +556,35 @@ test "a failed write clears the skip mark so the next save retries (#273)" {
// 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);
+ const ticket = 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
+ try std.testing.expect(!alreadySaved(io, tmp.dir, "blocked/d.json", 5)); // never skip on a write that failed
+ try std.testing.expect(errorFor(ticket) != null);
+ try std.testing.expect(errorFor(ticket) == null); // reported once
+}
+
+test "a background failure is never charged to a later save (#273)" {
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ resetForTest();
+ defer resetForTest();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+
+ // Turn 5's autosave loses the race and fails in the background.
+ try tmp.dir.writeFile(io, .{ .sub_path = "blocked", .data = "" });
+ const autosave = submit(gpa, io, tmp.dir, try gpa.dupe(u8, "blocked/f.json"), try gpa.dupe(u8, "turn 5"), 8);
+ drain();
+
+ // `/save release-notes` writes its own file, successfully. It must report
+ // ITS outcome — reporting the autosave's error made /save print "save
+ // failed" and skip the rename for a file it had just written correctly.
+ const named = submit(gpa, io, tmp.dir, try gpa.dupe(u8, "s/release-notes.json"), try gpa.dupe(u8, "everything"), 9);
+ drain();
+ try std.testing.expect(errorFor(named) == null);
+ try expectFile(tmp.dir, "s/release-notes.json", "everything");
+ // And the older ticket cannot resurrect it either: the newer write means
+ // the failure no longer describes the disk.
+ try std.testing.expect(errorFor(autosave) == null);
}