Skip to content

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

Python

Validate batched edits before replacing files

Rach Pradhanf310de011dab
diff --git a/docs/adr/0178-batched-edits-preflight-before-commit.md b/docs/adr/0178-batched-edits-preflight-before-commit.md
new file mode 100644
index 00000000..0c482453
--- /dev/null
+++ b/docs/adr/0178-batched-edits-preflight-before-commit.md
@@ -0,0 +1,41 @@
+# 0178. Batched edits preflight before one replacement
+
+Status: accepted 2026-09-23
+
+## Context
+
+`edit_file` already accepts an `edits` array, but its loop called the single-span
+writer for every element. If a later span was missing or ambiguous, earlier
+spans had already changed the file. A nine-span case with an ambiguous third
+span left the first two edits behind, so retrying the corrected batch no longer
+matched the original text. The loop also reread, wrote, and verified once per
+successful span and discarded owned result strings without freeing them.
+
+## Decision
+
+Resolve and confine the selected worktree path as for a single edit, then hold
+the same per-path lock from source read through final verification. Apply spans
+in order to an in-memory draft, honoring `replace_all`, unique-match errors,
+and the source-size ceiling after each span. Any invalid span returns its
+one-based index before a snapshot or write. On a valid batch, record one root
+snapshot, stage the complete draft in the destination directory, replace the
+file once, and verify the resulting bytes exactly. Preserve existing mode and
+reject symlink paths under the common file-tool confinement policy.
+
+## Consequences and validation
+
+This gives an all-span preflight guarantee and one committed replacement, not
+a transaction across external writers. The lock serializes in-process edits;
+the existing size/mtime drift check retries once and is not compare-and-swap.
+The staged replacement prevents readers holding the old inode from seeing a
+truncated batch. A failure after rename or during verification can report an
+error after bytes have changed. Batched edits use the repository's native
+replacement helper rather than invoking the optional splice companion for
+each span. This retains staged replacement while avoiding per-span writes.
+
+Unit coverage exercises dependent spans, invalid later spans,
+selected worktrees, executable mode, open readers, symlink refusal, and
+same-path lock contention. The offline `atomic-edit-batch-rejects-later-span`
+tier-2 case proves the failed-then-corrected tool loop and fails against the
+previous implementation. Independent review checked locking and replacement
+semantics. No model-backed latency or token reduction is claimed by this fix.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 6cdfb536..55f87792 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -201,6 +201,7 @@ record only when you need the evidence or the edge cases.
| [0175](0175-rlm-preserves-dependent-tool-order.md) | RLM speculates only leading read-only calls, then preserves statement order and stopped tool results. |
| [0176](0176-completed-streams-do-not-replay-on-trailer-timeout.md) | A trailer deadline after valid completion returns buffered output; missing usage stays explicitly unknown. |
| [0177](0177-owned-async-tool-execution.md) | Direct read-only async jobs own their lifetime, preserve order, and join before the next request. |
+| [0178](0178-batched-edits-preflight-before-commit.md) | Preflight every edit span in memory, then perform one verified replacement; an invalid later span leaves the file unchanged. |
## When to write one
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonl
index 66f3a4b9..dd5e47fe 100644
--- a/evals/harness_behavior.jsonl
+++ b/evals/harness_behavior.jsonl
@@ -134,3 +134,4 @@
{"id": "rlm-indexed-print-refuses-and-recovers", "why": "Unsupported Python-style result indexing must report an error without pretending to execute the nested host or executing later side effects; the supported text binding form recovers.", "args": ["--lean"], "prompt": "Run the scripted checks and report only observed results.", "script": [{"tool": "rlm", "arguments": {"code": "print(bash(\"printf ran > nested-marker\")[\"stdout\"])\nx = write_file(path=\"tail-marker\", content=\"ran\")"}}, {"tool": "rlm", "arguments": {"code": "r = bash(\"printf VERIFIED\")\nprint(r)"}}, {"text": "Verified using the supported text result."}], "verify_command": ["python3", "-c", "from pathlib import Path; assert not Path(\"nested-marker\").exists(); assert not Path(\"tail-marker\").exists()"], "assert": [{"event": {"type": "tool_call_finished", "name": "rlm", "is_error": true}}, {"events_at_most": {"match": {"type": "tool_call_finished", "is_error": true}, "count": 1}}, {"request_contains": {"index": 1, "text": "host results are text"}}, {"event": {"type": "tool_result", "name": "rlm", "is_error": false, "text": "VERIFIED"}}, {"final_text_contains": "Verified using the supported text result."}]}
{"id": "gateway-failure-usage-unknown", "why": "A typed gateway failure with no usage must preserve the provider diagnostic and label totals as incomplete instead of implying a free zero-token call.", "args": ["-p", "summarize the fixture"], "prompt": "summarize the fixture", "script": [{"text": "partial", "stream_error": {"type": "gateway_error", "code": "request_failed", "message": "fixture request failed"}}], "expected_exit": 1, "assert": [{"stderr_contains": "gateway_error request_failed"}, {"stderr_contains": "known subtotal: 0 api call(s)"}, {"stderr_contains": "1 failed request attempt(s) without usage (tokens and cost unknown)"}]}
{"id": "gateway-retry-usage-remains-incomplete", "why": "A recovered retry retains known successful usage while the failed attempt remains explicitly unknown.", "prompt": "summarize the fixture", "script": [{"text": "partial", "stream_error": {"type": "api_error", "message": "Internal error during token parsing"}}, {"text": "recovered fixture"}], "assert": [{"event": {"type": "turn", "usage_complete": false, "unreported_failed_attempts": 1, "api_calls": 1}}, {"final_text_contains": "recovered fixture"}]}
+{"id":"atomic-edit-batch-rejects-later-span","why":"A later ambiguous edit span must reject the entire batch without leaving earlier spans on disk; a corrected dependent batch then commits once and verifies.","args":["--old"],"env":{"GRAFF_NO_CODEDB_GUARD":"1"},"workspace_seed":{"f.txt":"alpha beta\nreturn v\nreturn v\n"},"prompt":"Apply the three edits to f.txt, check that a rejected batch left the file unchanged, then correct the ambiguous span and verify the final contents.","script":[{"tool":"edit_file","arguments":{"path":"f.txt","edits":[{"old_string":"alpha","new_string":"ALPHA"},{"old_string":"beta","new_string":"BETA"},{"old_string":"return v","new_string":"return value"}]}},{"tool":"bash","arguments":{"command":"python3 -c \"from pathlib import Path; assert Path('f.txt').read_text() == 'alpha beta\\nreturn v\\nreturn v\\n'; print('UNCHANGED_AFTER_REJECTION')\""}},{"tool":"edit_file","arguments":{"path":"f.txt","edits":[{"old_string":"alpha","new_string":"ALPHA"},{"old_string":"beta","new_string":"BETA"},{"old_string":"return v\nreturn v","new_string":"return value\nreturn value"}]}},{"tool":"bash","arguments":{"command":"python3 -c \"from pathlib import Path; assert Path('f.txt').read_text() == 'ALPHA BETA\\nreturn value\\nreturn value\\n'; print('CORRECTED_BATCH_VERIFIED')\""}},{"text":"The corrected batch passed both file checks."}],"assert":[{"event":{"type":"tool_call_finished","name":"edit_file","is_error":true}},{"event":{"type":"tool_call_finished","name":"edit_file","is_error":false}},{"events_at_most":{"match":{"type":"tool_call_finished","name":"edit_file","is_error":true},"count":1}},{"request_contains":{"index":1,"text":"edit span 3/3 failed"}},{"request_contains":{"index":1,"text":"no batch changes written"}},{"event":{"type":"tool_result","name":"bash","text":"UNCHANGED_AFTER_REJECTION\n"}},{"event":{"type":"tool_result","name":"bash","text":"CORRECTED_BATCH_VERIFIED\n"}},{"file_equals":{"path":"f.txt","content":"ALPHA BETA\nreturn value\nreturn value\n"}},{"final_text_contains":"The corrected batch passed both file checks."}]}
diff --git a/src/edit_batch.zig b/src/edit_batch.zig
index cf186eb5..321ff61c 100644
--- a/src/edit_batch.zig
+++ b/src/edit_batch.zig
@@ -1,11 +1,9 @@
//! Batched edit_file: several spans, one call (#476 — the apply_patch
//! mechanic from the opencode session anatomy: their feature run paid 2
//! patch calls where graff paid 8-10 single-span edit_file calls; one
-//! batched call per file is the 1:1). Spans apply SEQUENTIALLY through
-//! edit_verify.applyEdit, so each one gets the same lock, drift check,
-//! mode preservation and post-write verify as a single edit. A failing
-//! span stops the batch and the result says how many earlier spans DID
-//! apply — no silent partial state.
+//! batched call per file is the 1:1). Spans apply sequentially to an in-memory
+//! draft, then one verified write commits the complete batch. An invalid span
+//! leaves the file unchanged.
const std = @import("std");
const Io = std.Io;
@@ -14,6 +12,7 @@ const Allocator = std.mem.Allocator;
const tools = @import("tools.zig");
const approvals = @import("approvals.zig");
const edit_verify = @import("edit_verify.zig");
+const credential_store = @import("credential_store.zig");
const ToolCtx = tools.ToolCtx;
const ToolOutput = tools.ToolOutput;
@@ -36,29 +35,71 @@ pub fn execBatch(ctx: ToolCtx, input: Value) !ToolOutput {
const resolved = try @import("codedbpro_paths.zig").sessionAbs(gpa, ctx.io, ctx.agent_cwd, path);
defer gpa.free(resolved);
- var applied: usize = 0;
- for (list.items, 0..) |item, i| {
- if (item != .object) return spanErr(gpa, i, list.items.len, "span is not an object", applied, path);
- const old = tools.strField(item, "old_string") orelse return spanErr(gpa, i, list.items.len, "missing old_string", applied, path);
- const new = tools.strField(item, "new_string") orelse return spanErr(gpa, i, list.items.len, "missing new_string", applied, path);
- if (old.len == 0) return spanErr(gpa, i, list.items.len, "old_string must not be empty", applied, path);
- const all = tools.json_args.flag(item, "replace_all");
- const r = try edit_verify.applyEdit(ctx, path, resolved, old, new, all);
- if (r.is_error) return spanErr(gpa, i, list.items.len, r.text, applied, path);
- applied += 1;
+ const lock = edit_verify.lockPath(ctx.io, resolved);
+ defer lock.unlock(ctx.io);
+
+ var attempt: u8 = 0;
+ while (true) : (attempt += 1) {
+ const before = Io.Dir.cwd().readFileAlloc(ctx.io, resolved, gpa, .limited(edit_verify.edit_read_cap)) catch |err| {
+ if (edit_verify.fsErrorText(gpa, .edit, path, err)) |message| return .{ .text = message, .is_error = true };
+ return err;
+ };
+ defer gpa.free(before);
+ const prev_stat = Io.Dir.cwd().statFile(ctx.io, resolved, .{}) catch null;
+
+ var draft: []const u8 = before;
+ var owned_draft: ?[]u8 = null;
+ defer if (owned_draft) |bytes| gpa.free(bytes);
+ for (list.items, 0..) |item, i| {
+ // A separate applyEdit would re-read the result before this span.
+ // Keep that source-size ceiling without writing an oversized draft.
+ if (i > 0 and draft.len > edit_verify.edit_read_cap)
+ return spanErr(gpa, i, list.items.len, "intermediate content exceeds the edit source limit");
+ if (item != .object) return spanErr(gpa, i, list.items.len, "span is not an object");
+ const old = tools.strField(item, "old_string") orelse return spanErr(gpa, i, list.items.len, "missing old_string");
+ const new = tools.strField(item, "new_string") orelse return spanErr(gpa, i, list.items.len, "missing new_string");
+ if (old.len == 0) return spanErr(gpa, i, list.items.len, "old_string must not be empty");
+
+ const count = std.mem.count(u8, draft, old);
+ if (count == 0) {
+ const why = try std.fmt.allocPrint(gpa, "old_string not found in {s} — read_file it and match the existing text exactly", .{path});
+ defer gpa.free(why);
+ return spanErr(gpa, i, list.items.len, why);
+ }
+ if (count > 1 and !tools.json_args.flag(item, "replace_all")) {
+ const why = try std.fmt.allocPrint(gpa, "old_string matches {d} places in {s} — include more surrounding context to make it unique, or set replace_all", .{ count, path });
+ defer gpa.free(why);
+ return spanErr(gpa, i, list.items.len, why);
+ }
+ const replaced = try gpa.alloc(u8, std.mem.replacementSize(u8, draft, old, new));
+ _ = std.mem.replace(u8, draft, old, new, replaced);
+ if (owned_draft) |bytes| gpa.free(bytes);
+ owned_draft = replaced;
+ draft = replaced;
+ }
+
+ if (attempt == 0 and edit_verify.drifted(ctx.io, resolved, prev_stat)) continue;
+ if (ctx.snapshots) |snaps| if (!ctx.from_sub) snaps.record(path, .{ .content = before });
+
+ // Stage the complete draft in the destination directory, then rename
+ // it into place. This keeps a reader from seeing a truncated batch and
+ // preserves the old mode (and a final symlink) like the companion path.
+ try credential_store.replaceFile(ctx.io, Io.Dir.cwd(), resolved, draft, .default_file);
+ const after = Io.Dir.cwd().readFileAlloc(ctx.io, resolved, gpa, .limited(edit_verify.verify_read_cap)) catch {
+ return .{ .text = try edit_verify.verdictText(gpa, path, .unreadable, "the write"), .is_error = true };
+ };
+ defer gpa.free(after);
+ const verdict = edit_verify.verifyNative(before, after, draft);
+ if (verdict != .ok) return .{ .text = try edit_verify.verdictText(gpa, path, verdict, "the write"), .is_error = true };
+ return .{ .text = try std.fmt.allocPrint(gpa, "applied {d} edit span(s) to {s} (verified)", .{ list.items.len, path }) };
}
- return .{ .text = try std.fmt.allocPrint(gpa, "applied {d} edit span(s) to {s} (each verified)", .{ applied, path }), .is_error = false };
}
-fn spanErr(gpa: Allocator, idx: usize, total: usize, why: []const u8, applied: usize, path: []const u8) !ToolOutput {
- const suffix: []const u8 = if (applied > 0)
- try std.fmt.allocPrint(gpa, " ({d} earlier span(s) DID apply to {s} — read it before retrying)", .{ applied, path })
- else
- "";
- return .{ .text = try std.fmt.allocPrint(gpa, "edit span {d}/{d} failed: {s}{s}", .{ idx + 1, total, why, suffix }), .is_error = true };
+fn spanErr(gpa: Allocator, idx: usize, total: usize, why: []const u8) !ToolOutput {
+ return .{ .text = try std.fmt.allocPrint(gpa, "edit span {d}/{d} failed: {s} (no batch changes written)", .{ idx + 1, total, why }), .is_error = true };
}
-test "execBatch: two spans apply in one call; a bad span reports its index and prior applies" {
+test "execBatch: dependent spans commit together; a bad span leaves the file unchanged" {
if (@import("builtin").os.tag == .windows) return error.SkipZigTest;
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
@@ -72,14 +113,14 @@ test "execBatch: two spans apply in one call; a bad span reports its index and p
const ctx: tools.ToolCtx = .{ .gpa = a, .io = io, .client = &client, .provider = undefined, .registry = null, .from_sub = false, .approvals = null, .tracer = null };
var good = try std.json.parseFromSliceLeaky(Value, a,
- \\{"path":"P","edits":[{"old_string":"one","new_string":"1"},{"old_string":"two","new_string":"2"}]}
+ \\{"path":"P","edits":[{"old_string":"one","new_string":"1"},{"old_string":"alpha 1","new_string":"ALPHA 1"}]}
, .{ .allocate = .alloc_always });
good.object.put(a, "path", .{ .string = rel }) catch unreachable;
const ok = try execBatch(ctx, good);
try std.testing.expect(!ok.is_error);
try std.testing.expect(std.mem.indexOf(u8, ok.text, "2 edit span(s)") != null);
const data = try tmp.dir.readFileAlloc(io, "f.txt", a, .limited(4096));
- try std.testing.expect(std.mem.indexOf(u8, data, "alpha 1\nbeta 2") != null);
+ try std.testing.expectEqualStrings("ALPHA 1\nbeta two\ngamma three\n", data);
var bad = try std.json.parseFromSliceLeaky(Value, a,
\\{"path":"P","edits":[{"old_string":"gamma","new_string":"3"},{"old_string":"NOT PRESENT","new_string":"x"}]}
@@ -88,9 +129,9 @@ test "execBatch: two spans apply in one call; a bad span reports its index and p
const err = try execBatch(ctx, bad);
try std.testing.expect(err.is_error);
try std.testing.expect(std.mem.indexOf(u8, err.text, "span 2/2") != null);
- try std.testing.expect(std.mem.indexOf(u8, err.text, "1 earlier span(s) DID apply") != null);
+ try std.testing.expect(std.mem.indexOf(u8, err.text, "no batch changes written") != null);
const after = try tmp.dir.readFileAlloc(io, "f.txt", a, .limited(4096));
- try std.testing.expect(std.mem.indexOf(u8, after, "3 three") != null); // span 1 landed
+ try std.testing.expectEqualStrings(data, after);
}
test "execBatch dispatch rejects malformed edits then accepts a corrected array" {
@@ -124,3 +165,209 @@ test "execBatch dispatch rejects malformed edits then accepts a corrected array"
const changed = try tmp.dir.readFileAlloc(io, "f.txt", a, .limited(4096));
try std.testing.expectEqualStrings("ALPHA\nBETA\n", changed);
}
+
+test "execBatch rejects a later ambiguous span without partial writes or snapshots" {
+ if (@import("builtin").os.tag == .windows) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const original = "alpha beta\nreturn v\nreturn v\n";
+ try tmp.dir.writeFile(io, .{ .sub_path = "f.txt", .data = original });
+ const rel = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}/f.txt", .{&tmp.sub_path});
+ defer gpa.free(rel);
+
+ var input_arena = std.heap.ArenaAllocator.init(gpa);
+ defer input_arena.deinit();
+ const a = input_arena.allocator();
+ var input = try std.json.parseFromSliceLeaky(Value, a,
+ \\{"path":"P","edits":[
+ \\{"old_string":"alpha","new_string":"ALPHA"},
+ \\{"old_string":"beta","new_string":"BETA"},
+ \\{"old_string":"return v","new_string":"return value"},
+ \\{"old_string":"x4","new_string":"y4"},
+ \\{"old_string":"x5","new_string":"y5"},
+ \\{"old_string":"x6","new_string":"y6"},
+ \\{"old_string":"x7","new_string":"y7"},
+ \\{"old_string":"x8","new_string":"y8"},
+ \\{"old_string":"x9","new_string":"y9"}]}
+ , .{ .allocate = .alloc_always });
+ try input.object.put(a, "path", .{ .string = rel });
+
+ var client: std.http.Client = undefined;
+ var snapshots: tools.Snapshots = .{ .gpa = gpa, .io = io };
+ defer snapshots.deinit();
+ var ctx = edit_verify.testCtx(&client);
+ ctx.snapshots = &snapshots;
+ const result = try execBatch(ctx, input);
+ defer gpa.free(result.text);
+ try std.testing.expect(result.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, result.text, "edit span 3/9 failed: old_string matches 2 places") != null);
+ try std.testing.expect(std.mem.endsWith(u8, result.text, "(no batch changes written)"));
+ try std.testing.expectEqual(@as(usize, 0), snapshots.list.items.len);
+ const after = try tmp.dir.readFileAlloc(io, "f.txt", gpa, .limited(4096));
+ defer gpa.free(after);
+ try std.testing.expectEqualStrings(original, after);
+}
+
+test "execBatch uses selected worktree, replace_all, one snapshot, and preserves mode" {
+ if (@import("builtin").os.tag == .windows) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var other = std.testing.tmpDir(.{});
+ defer other.cleanup();
+ var selected = std.testing.tmpDir(.{});
+ defer selected.cleanup();
+ try other.dir.writeFile(io, .{ .sub_path = "task.sh", .data = "old old\n" });
+ try selected.dir.writeFile(io, .{
+ .sub_path = "task.sh",
+ .data = "old old\n",
+ .flags = .{ .permissions = @enumFromInt(0o755) },
+ });
+ var root_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const root_len = try selected.dir.realPath(io, &root_buf);
+ const root = try gpa.dupe(u8, root_buf[0..root_len]);
+ defer gpa.free(root);
+
+ var input_arena = std.heap.ArenaAllocator.init(gpa);
+ defer input_arena.deinit();
+ const input = try std.json.parseFromSliceLeaky(Value, input_arena.allocator(),
+ \\{"path":"task.sh","edits":[{"old_string":"old","new_string":"new","replace_all":true},{"old_string":"new new","new_string":"done"}]}
+ , .{});
+ var client: std.http.Client = undefined;
+ var snapshots: tools.Snapshots = .{ .gpa = gpa, .io = io };
+ defer snapshots.deinit();
+ var ctx = edit_verify.testCtx(&client);
+ ctx.agent_cwd = root;
+ ctx.snapshots = &snapshots;
+ const result = try execBatch(ctx, input);
+ defer gpa.free(result.text);
+ try std.testing.expect(!result.is_error);
+ try std.testing.expectEqual(@as(usize, 1), snapshots.list.items.len);
+ try std.testing.expectEqualStrings("old old\n", snapshots.list.items[0].before.content);
+
+ const on_selected = try selected.dir.readFileAlloc(io, "task.sh", gpa, .limited(4096));
+ defer gpa.free(on_selected);
+ const on_other = try other.dir.readFileAlloc(io, "task.sh", gpa, .limited(4096));
+ defer gpa.free(on_other);
+ try std.testing.expectEqualStrings("done\n", on_selected);
+ try std.testing.expectEqualStrings("old old\n", on_other);
+ try std.testing.expectEqual(@as(std.posix.mode_t, 0o755), (try selected.dir.statFile(io, "task.sh", .{})).permissions.toMode() & 0o777);
+}
+
+test "execBatch replaces without truncating open readers and rejects symlink paths" {
+ if (@import("builtin").os.tag == .windows) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "real.txt", .data = "before\n" });
+ try tmp.dir.symLink(io, "real.txt", "link.txt", .{});
+ const held = try tmp.dir.openFile(io, "real.txt", .{});
+ defer held.close(io);
+ var root_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const root_len = try tmp.dir.realPath(io, &root_buf);
+ const root = try gpa.dupe(u8, root_buf[0..root_len]);
+ defer gpa.free(root);
+
+ var input_arena = std.heap.ArenaAllocator.init(gpa);
+ defer input_arena.deinit();
+ const input = try std.json.parseFromSliceLeaky(Value, input_arena.allocator(),
+ \\{"path":"real.txt","edits":[{"old_string":"before","new_string":"after"}]}
+ , .{});
+ var client: std.http.Client = undefined;
+ var ctx = edit_verify.testCtx(&client);
+ ctx.agent_cwd = root;
+ const result = try execBatch(ctx, input);
+ defer gpa.free(result.text);
+ try std.testing.expect(!result.is_error);
+
+ var old_bytes: [32]u8 = undefined;
+ const old_len = try held.readPositionalAll(io, &old_bytes, 0);
+ try std.testing.expectEqualStrings("before\n", old_bytes[0..old_len]);
+ const new_bytes = try tmp.dir.readFileAlloc(io, "real.txt", gpa, .limited(4096));
+ defer gpa.free(new_bytes);
+ try std.testing.expectEqualStrings("after\n", new_bytes);
+ const via_link = try tmp.dir.readFileAlloc(io, "link.txt", gpa, .limited(4096));
+ defer gpa.free(via_link);
+ try std.testing.expectEqualStrings("after\n", via_link);
+ var link_target: [std.fs.max_path_bytes]u8 = undefined;
+ const link_len = try tmp.dir.readLink(io, "link.txt", &link_target);
+ try std.testing.expectEqualStrings("real.txt", link_target[0..link_len]);
+
+ const linked_input = try std.json.parseFromSliceLeaky(Value, input_arena.allocator(),
+ \\{"path":"link.txt","edits":[{"old_string":"after","new_string":"escaped"}]}
+ , .{});
+ const refused = try execBatch(ctx, linked_input);
+ defer gpa.free(refused.text);
+ try std.testing.expect(refused.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, refused.text, "outside the working directory") != null);
+ const unchanged = try tmp.dir.readFileAlloc(io, "real.txt", gpa, .limited(4096));
+ defer gpa.free(unchanged);
+ try std.testing.expectEqualStrings("after\n", unchanged);
+}
+
+test "execBatch and single edit share the same-file write lock" {
+ if (@import("builtin").os.tag == .windows or @import("builtin").single_threaded) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{
+ .sub_path = "slow",
+ .data = "#!/bin/sh\ndir=$(dirname \"$0\")\n: > \"$dir/entered\"\nwhile [ ! -e \"$dir/release\" ]; do /bin/sleep 0.01; done\nexit 1\n",
+ .flags = .{ .permissions = @enumFromInt(0o755) },
+ });
+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const real_len = try tmp.dir.realPath(io, &real_buf);
+ const stub = try std.fmt.allocPrint(gpa, "{s}/slow", .{real_buf[0..real_len]});
+ defer gpa.free(stub);
+ const saved = edit_verify.companion_bin;
+ defer edit_verify.companion_bin = saved;
+ edit_verify.companion_bin = stub;
+
+ const rel = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}/f.txt", .{&tmp.sub_path});
+ defer gpa.free(rel);
+ const resolved = try @import("codedbpro_paths.zig").sessionAbs(gpa, io, null, rel);
+ defer gpa.free(resolved);
+ var input_arena = std.heap.ArenaAllocator.init(gpa);
+ defer input_arena.deinit();
+ const a = input_arena.allocator();
+ var input = try std.json.parseFromSliceLeaky(Value, a,
+ \\{"path":"P","edits":[{"old_string":"first","new_string":"FIRST"},{"old_string":"second","new_string":"SECOND"}]}
+ , .{});
+ try input.object.put(a, "path", .{ .string = rel });
+ var client: std.http.Client = undefined;
+ const ctx = edit_verify.testCtx(&client);
+
+ try tmp.dir.writeFile(io, .{ .sub_path = "f.txt", .data = "first\nsecond\nthird\n" });
+ var single = try io.concurrent(edit_verify.applyEdit, .{ ctx, rel, resolved, "third", "THIRD", false });
+ var entered = false;
+ for (0..500) |_| {
+ if (tmp.dir.statFile(io, "entered", .{})) |_| {
+ entered = true;
+ break;
+ } else |_| {}
+ try io.sleep(.fromMilliseconds(1), .awake);
+ }
+ if (!entered) try tmp.dir.writeFile(io, .{ .sub_path = "release", .data = "" });
+ try std.testing.expect(entered);
+
+ var batch = try io.concurrent(execBatch, .{ ctx, input });
+ // The single edit is inside its companion call while holding the stripe.
+ // A batch that ignores that stripe would finish and change the file here.
+ try io.sleep(.fromMilliseconds(50), .awake);
+ const while_blocked = try tmp.dir.readFileAlloc(io, "f.txt", gpa, .limited(4096));
+ defer gpa.free(while_blocked);
+ try tmp.dir.writeFile(io, .{ .sub_path = "release", .data = "" });
+ const single_result = try single.await(io);
+ defer gpa.free(single_result.text);
+ const batch_result = try batch.await(io);
+ defer gpa.free(batch_result.text);
+ try std.testing.expectEqualStrings("first\nsecond\nthird\n", while_blocked);
+ try std.testing.expect(!single_result.is_error);
+ try std.testing.expect(!batch_result.is_error);
+ const after = try tmp.dir.readFileAlloc(io, "f.txt", gpa, .limited(4096));
+ defer gpa.free(after);
+ try std.testing.expectEqualStrings("FIRST\nSECOND\nTHIRD\n", after);
+}
diff --git a/src/edit_verify.zig b/src/edit_verify.zig
index f2a343b3..0ceb7117 100644
--- a/src/edit_verify.zig
+++ b/src/edit_verify.zig
@@ -31,11 +31,11 @@ const runCapped = @import("jobs.zig").runCapped;
const codedbpro_report = @import("codedbpro_report.zig"); // persistent-daemon splice fast path
/// Whole-file read ceiling for the splice source (unchanged from exec.zig).
-const edit_read_cap: usize = 1024 * 1024;
+pub const edit_read_cap: usize = 1024 * 1024;
/// The verification re-read is deliberately looser than the source cap: a
/// `replace_all` can grow a file past it, and a re-read that failed on size
/// alone would report a false "did not persist".
-const verify_read_cap: usize = 16 * 1024 * 1024;
+pub const verify_read_cap: usize = 16 * 1024 * 1024;
/// The companion binary the premium splice shells out to. `pub var` purely so
/// a test can point it at a stub that CLAIMS success without writing — the
@@ -168,7 +168,7 @@ fn verifyOnDisk(
/// Has anything touched the file since `prev` was taken? Size or mtime is
/// enough: an in-place truncate changes the size, an atomic tmp+rename changes
/// the mtime. A missing baseline (the stat failed) can never claim drift.
-fn drifted(io: Io, resolved: []const u8, prev: ?Io.Dir.Stat) bool {
+pub fn drifted(io: Io, resolved: []const u8, prev: ?Io.Dir.Stat) bool {
const base = prev orelse return false;
const now = Io.Dir.cwd().statFile(io, resolved, .{}) catch return false;
return now.size != base.size or now.mtime.nanoseconds != base.mtime.nanoseconds;