From c89aa23b257d3055297caa2b3fce4709f9b321c6 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 20 Nov 2026 10:01:43 +0000 Subject: [PATCH 1/7] fix: name the file a failed replacement reports A failed open of the temporary file named the destination. A failed write or flush named it as well, and a failed rename named only that destination. Python names the temporary file, no file, or both files. The message follows Python. --- .../+atomic-write-oserror-text.bugfix.md | 1 + src/atomic.zig | 73 +++++++++++++++++-- 2 files changed, 66 insertions(+), 8 deletions(-) create mode 100644 changelog.d/+atomic-write-oserror-text.bugfix.md diff --git a/changelog.d/+atomic-write-oserror-text.bugfix.md b/changelog.d/+atomic-write-oserror-text.bugfix.md new file mode 100644 index 0000000..7760f67 --- /dev/null +++ b/changelog.d/+atomic-write-oserror-text.bugfix.md @@ -0,0 +1 @@ +A failed replacement names the temporary file when the open fails, names both files when the rename fails, and names no file when the write or the flush fails. diff --git a/src/atomic.zig b/src/atomic.zig index c99dc6f..7ce705b 100644 --- a/src/atomic.zig +++ b/src/atomic.zig @@ -9,6 +9,7 @@ const builtin = @import("builtin"); const linux = std.os.linux; const sys = @import("sys.zig"); const fsx = @import("fsx.zig"); +const pytext = @import("pytext.zig"); const Allocator = std.mem.Allocator; @@ -124,6 +125,26 @@ pub fn describe(err: Error) []const u8 { }; } +/// Python's text for an OSError from a step of `atomicWrite`. `path` is the +/// filename and `path2` the second filename of a rename. A null path is a +/// call that carries none, such as write or fsync of an open descriptor. +/// The error itself is unchanged; `why.msg` holds the text. +fn failOs(a: Allocator, why: *Why, err: sys.Error, path: ?[]const u8, path2: ?[]const u8) Error { + const text = sys.describe(err); + if (path2) |second| { + const q1 = pytext.reprStrAlloc(a, path orelse "") catch return error.OutOfMemory; + defer a.free(q1); + const q2 = pytext.reprStrAlloc(a, second) catch return error.OutOfMemory; + defer a.free(q2); + why.msg = a.print("{s}: {s} -> {s}", .{ text, q1, q2 }) catch unallocated_refusal; + } else if (path) |one| { + const q1 = pytext.reprStrAlloc(a, one) catch return error.OutOfMemory; + defer a.free(q1); + why.msg = a.print("{s}: {s}", .{ text, q1 }) catch unallocated_refusal; + } else why.msg = a.print("{s}", .{text}) catch unallocated_refusal; + return err; +} + /// Why a replacement was refused; filled in when an error is returned. The /// message is allocated from the allocator given with `why` and belongs to /// the caller: `deinit` frees it. @@ -505,7 +526,7 @@ pub const WriteOptions = struct { pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: WriteOptions, why: *Why) Error!void { sys.last_errno = .SUCCESS; const parent = if (std.fs.path.dirname(path)) |d| (if (d.len > 0) d else ".") else "."; - try makedirs(parent); + makedirs(parent) catch |err| return failOs(a, why, err, parent, null); if (fsx.statAt(fsx.cwd, path, false)) |st| { if (st.isLink()) return refuse(a, why, "refusing to replace a symlink: {s}", .{path}); } else |_| {} @@ -527,7 +548,7 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write const owner_ok = stale.uid == euid or (metadata != null and stale.uid == metadata.?.info.uid); if (!stale.isReg() or !owner_ok or stale.nlink != 1) return refuse(a, why, "temporary file must be an owned regular file with one link: {s}", .{tmp}); - try sys.unlinkat(fsx.cwd, tmp, 0); + sys.unlinkat(fsx.cwd, tmp, 0) catch |err| return failOs(a, why, err, tmp, null); } else |_| {} { @@ -535,18 +556,21 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write defer a.free(step); if (opts.faults.fails(step)) return injected(a, why, step); } - const fd = try openTemp(tmp, .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true, .NOFOLLOW = true }, 0o600); + const fd = openTemp(tmp, .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true, .NOFOLLOW = true }, 0o600) catch |err| + return failOs(a, why, err, tmp, null); const created = fsx.fstat(fd) catch |err| { + // os.fstat names no path. Record that before the cleanup calls. + const failed = failOs(a, why, err, null, null); sys.close(fd); // Created above with O_EXCL, so it is this call's file. sys.unlinkat(fsx.cwd, tmp, 0) catch {}; - return err; + return failed; }; ops.created(fd); errdefer discard(tmp, created); { defer sys.close(fd); - try writeTemp(fd, data); + writeTemp(fd, data) catch |err| return failOs(a, why, err, null, null); var inner: Why = .{}; defer inner.deinit(a); restoreMetadata(a, fd, metadata, mode, &inner) catch |err| return refuse(a, why, "cannot preserve access metadata for {s}: {s}", .{ path, if (err == error.Refused) inner.msg else describe(err) }); @@ -555,7 +579,7 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write defer a.free(step); if (opts.faults.fails(step)) return injected(a, why, step); } - _ = try op(ops.fsync, .{fd}); + _ = op(ops.fsync, .{fd}) catch |err| return failOs(a, why, err, null, null); } if (metadata) |m| { var inner: Why = .{}; @@ -569,8 +593,11 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write defer a.free(step); if (opts.faults.fails(step)) return injected(a, why, step); } - try renameTemp(tmp, path); - try fsyncDir(parent); + renameTemp(tmp, path) catch |err| return failOs(a, why, err, tmp, path); + // Opening the directory names it. Flushing the descriptor names no file. + const directory = sys.openat(fsx.cwd, parent, .{}, 0) catch |err| return failOs(a, why, err, parent, null); + defer sys.close(directory); + sys.fsync(directory) catch |err| return failOs(a, why, err, null, null); } /// atomic_write pinned to an open directory: replace `dir/name` with @@ -684,6 +711,36 @@ test "a step a test makes fail leaves the destination and no temporary file" { } } +test "opening a file in an unwritable directory names the temporary file" { + if (linux.geteuid() == 0) return; + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + var cwd_buf: [sys.path_max]u8 = undefined; + const cwd = try fsx.realpath(fsx.cwd, ".", &cwd_buf); + const dir = try a.print("{s}/.zig-cache/atomic-ro-{d}", .{ cwd, linux.getpid() }); + try makedirs(dir); + const directory = try sys.openat(fsx.cwd, dir, .{ .DIRECTORY = true }, 0); + _ = linux.fchmod(directory, 0o555); + sys.close(directory); + defer { + const again = sys.openat(fsx.cwd, dir, .{ .DIRECTORY = true }, 0) catch unreachable; + _ = linux.fchmod(again, 0o755); + sys.close(again); + fsx.deleteTree(a, fsx.cwd, dir) catch {}; + } + const path = try a.print("{s}/metrics.prom", .{dir}); + var why: Why = .{}; + defer why.deinit(a); + try std.testing.expectError(error.AccessDenied, atomicWrite(a, path, "x\n", .{}, &why)); + const tmp = try a.print("{s}/.metrics.prom.new", .{dir}); + const quoted = try pytext.reprStrAlloc(a, tmp); + defer a.free(quoted); + const want = try a.print("[Errno 13] Permission denied: {s}", .{quoted}); + try std.testing.expectEqualStrings(want, why.msg); + try std.testing.expectError(error.NotFound, fsx.statAt(fsx.cwd, tmp, false)); +} + test "atomicWrite frees what it allocates" { const gpa = std.testing.allocator; var cwd_buf: [sys.path_max]u8 = undefined; From 903847a38c6ea8c38c6e8fcfb1c7507d840ee01c Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 20 Nov 2026 10:02:12 +0000 Subject: [PATCH 2/7] fix: record the text of a failed state lock A failed open of .lock named the state root, and so did a failed pid write. Python names .lock, .lock.posix, the directory, or no file. The acquisition snapshots that text before a later close. --- changelog.d/+lock-acquire-filename.bugfix.md | 1 + src/state.zig | 99 +++++++++++++++++--- 2 files changed, 87 insertions(+), 13 deletions(-) create mode 100644 changelog.d/+lock-acquire-filename.bugfix.md diff --git a/changelog.d/+lock-acquire-filename.bugfix.md b/changelog.d/+lock-acquire-filename.bugfix.md new file mode 100644 index 0000000..7c79b66 --- /dev/null +++ b/changelog.d/+lock-acquire-filename.bugfix.md @@ -0,0 +1 @@ +A failed lock acquisition records the OSError text and whether Python names .lock, .lock.posix, the state directory, or no file. diff --git a/src/state.zig b/src/state.zig index 5a1e5ec..a953b28 100644 --- a/src/state.zig +++ b/src/state.zig @@ -12,6 +12,50 @@ const Allocator = std.mem.Allocator; /// The errors of this module's calls: `sys.Error`. pub const Error = sys.Error; +/// Python's text for the OSError that made the latest `RootLock.acquire` +/// fail, snapshotted before a later close. `path` is empty when Python +/// names no file (a write, flush, or lock on an open descriptor). Absent +/// when the failure was not an operating-system error. +pub const OsFailure = struct { text: []const u8, path: []const u8 }; + +threadlocal var os_noted: bool = false; +threadlocal var os_text: [128]u8 = undefined; +threadlocal var os_text_len: usize = 0; +threadlocal var os_path: [sys.path_max]u8 = undefined; +threadlocal var os_path_len: usize = 0; + +pub fn osFailure() ?OsFailure { + if (!os_noted) return null; + return .{ .text = os_text[0..os_text_len], .path = os_path[0..os_path_len] }; +} + +fn clearOsFailure() void { + os_noted = false; + os_text_len = 0; + os_path_len = 0; +} + +fn noteText(text: []const u8, path: ?[]const u8) void { + const n = @min(text.len, os_text.len); + @memcpy(os_text[0..n], text[0..n]); + os_text_len = n; + if (path) |p| { + const m = @min(p.len, os_path.len); + @memcpy(os_path[0..m], p[0..m]); + os_path_len = m; + } else os_path_len = 0; + os_noted = true; +} + +fn noted(err: Error, path: ?[]const u8) Error { + noteText(sys.describe(err), path); + return err; +} + +fn noteErrno(e: linux.E, path: ?[]const u8) void { + noteText(sys.describeErrno(e), path); +} + /// Regular, owned by `uid`, one link, mode & 0o077 == 0. pub fn privateOk(st: fsx.Stat, uid: linux.uid_t) bool { return st.isReg() and st.uid == uid and st.nlink == 1 and st.mode & 0o077 == 0; @@ -391,7 +435,7 @@ pub const RootLock = struct { fn takeFlock(fd: fsx.fd_t, deadline_ms: ?i64) AcquireError!void { const d = deadline_ms orelse { - _ = try lockCall(lock_ops.flock, .{ fd, @as(i32, std.posix.LOCK.EX) }); + _ = lockCall(lock_ops.flock, .{ fd, @as(i32, std.posix.LOCK.EX) }) catch |err| return noted(err, null); return; }; while (true) { @@ -400,7 +444,7 @@ pub const RootLock = struct { .SUCCESS => return, .INTR => continue, .AGAIN, .ACCES => {}, - else => return mapped(rc), + else => return noted(mapped(rc), null), } if (try pause(d)) return error.Busy; } @@ -418,8 +462,11 @@ pub const RootLock = struct { .INTR => continue, .AGAIN, .ACCES => if (deadline_ms) |d| { if (try pause(d)) return error.Busy; - } else return error.Unexpected, - else => return mapped(rc), + } else { + noteErrno(linux.errno(rc), null); + return error.Unexpected; + }, + else => return noted(mapped(rc), null), } } } @@ -453,10 +500,11 @@ pub const RootLock = struct { // would say. A root that is a directory once links are followed // passes this and is refused below only when the root itself is // a link, as the root is opened without following it. + clearOsFailure(); try preflightRoot(root); - try atomic.makedirs(root); + atomic.makedirs(root) catch |err| return noted(err, root); const deadline: ?i64 = if (timeout_ms) |t| nowMs() + t else null; - const dir = try fsx.openDir(fsx.cwd, root, false); + const dir = fsx.openDir(fsx.cwd, root, false) catch |err| return noted(err, root); defer sys.close(dir); const gate = (try openLockFile(dir, gate_name, realOpenLock)) orelse return error.GateNotPrivate; errdefer sys.close(gate); @@ -465,10 +513,11 @@ pub const RootLock = struct { errdefer sys.close(posix); try takeRecord(posix, deadline); if (!try isSoleLink(dir, gate_name, gate)) return error.GateNotPrivate; - _ = try lockCall(lock_ops.ftruncate, .{ gate, @as(i64, 0) }); + _ = lockCall(lock_ops.ftruncate, .{ gate, @as(i64, 0) }) catch |err| return noted(err, null); var buf: [24]u8 = undefined; const line = std.mem.print(&buf, "{d}\n", .{linux.getpid()}) catch unreachable; - if ((try lockCall(lock_ops.write, .{ gate, line })) != line.len) return error.NoSpace; + const n = lockCall(lock_ops.write, .{ gate, line }) catch |err| return noted(err, null); + if (n != line.len) return noted(error.NoSpace, null); return .{ .gate = gate, .posix = posix, .owner = linux.getpid() }; } @@ -481,15 +530,15 @@ pub const RootLock = struct { if (!st.isReg() or st.nlink != 1 or st.uid != linux.geteuid()) return null; } else |err| switch (err) { error.NotFound => {}, - else => |e| return e, + else => |e| return noted(e, name), } const fd: fsx.fd_t = @intCast(lockCall(open, .{ dir, name.ptr }) catch |err| switch (err) { error.SymLink, error.IsDir => return null, - else => |e| return e, + else => |e| return noted(e, name), }); errdefer sys.close(fd); if (try isSoleLink(dir, name, fd)) { - try sys.fchmod(fd, 0o600); + sys.fchmod(fd, 0o600) catch |err| return noted(err, null); return fd; } sys.close(fd); @@ -501,11 +550,11 @@ pub const RootLock = struct { /// planted hard link unlinked while the lock is awaited leaves the /// descriptor on the other name's file, with one link. fn isSoleLink(dir: fsx.fd_t, name: []const u8, fd: fsx.fd_t) Error!bool { - const st = try fsx.fstat(fd); + const st = fsx.fstat(fd) catch |err| return noted(err, null); if (!st.isReg() or st.nlink != 1 or st.uid != linux.geteuid()) return false; const at = fsx.statAt(dir, name, false) catch |err| switch (err) { error.NotFound => return false, - else => |e| return e, + else => |e| return noted(e, name), }; return at.dev == st.dev and at.ino == st.ino and at.nlink == 1; } @@ -741,3 +790,27 @@ test "lockExclusive covers timeout 0, bounded timeout, and unsupported flock" { } } } + +test "creating the gate in a read-only directory names .lock" { + if (linux.geteuid() == 0) return; + const gpa = std.testing.allocator; + var pb: [sys.path_max]u8 = undefined; + var cwd_buf: [sys.path_max]u8 = undefined; + const cwd = try fsx.realpath(fsx.cwd, ".", &cwd_buf); + const base = try std.mem.print(&pb, "{s}/.zig-cache/zig-common-ro-{d}", .{ cwd, linux.getpid() }); + const held = try RootLock.acquire(gpa, base, 0); + held.release(); + var zb: [sys.path_max:0]u8 = undefined; + const gate = try std.mem.print(zb[0..zb.len], "{s}/.lock", .{base}); + try sys.unlinkat(fsx.cwd, gate, 0); + const sidecar = try std.mem.print(zb[0..zb.len], "{s}/.lock.posix", .{base}); + sys.unlinkat(fsx.cwd, sidecar, 0) catch {}; + const zbase = try sys.z(&zb, base); + try std.testing.expect(linux.errno(linux.fchmodat(fsx.cwd, zbase.ptr, 0o555)) == .SUCCESS); + defer _ = linux.fchmodat(fsx.cwd, zbase.ptr, 0o755); + defer fsx.deleteTree(gpa, fsx.cwd, base) catch {}; + try std.testing.expectError(error.AccessDenied, RootLock.acquire(gpa, base, 0)); + const note = osFailure() orelse unreachable; + try std.testing.expectEqualStrings(".lock", note.path); + try std.testing.expectEqualStrings("[Errno 13] Permission denied", note.text); +} From 540a354d9990c8eeb75cf1f6b223657b23bfc78e Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 20 Nov 2026 15:01:00 +0000 Subject: [PATCH 3/7] fix: retain state lock failure details State-root preflight failures now populate osFailure. Lock-file errors carry their full joined paths, while non-operating-system lock refusals leave osFailure empty. --- .../+rootlock-preflight-osfailure.bugfix.md | 1 + src/state.zig | 67 +++++++++++++++---- src/state_test.zig | 30 ++++++++- 3 files changed, 85 insertions(+), 13 deletions(-) create mode 100644 changelog.d/+rootlock-preflight-osfailure.bugfix.md diff --git a/changelog.d/+rootlock-preflight-osfailure.bugfix.md b/changelog.d/+rootlock-preflight-osfailure.bugfix.md new file mode 100644 index 0000000..2b22899 --- /dev/null +++ b/changelog.d/+rootlock-preflight-osfailure.bugfix.md @@ -0,0 +1 @@ +Record the state-root path and error text when lock acquisition rejects a non-directory or broken symbolic link. diff --git a/src/state.zig b/src/state.zig index a953b28..355aa2c 100644 --- a/src/state.zig +++ b/src/state.zig @@ -52,6 +52,20 @@ fn noted(err: Error, path: ?[]const u8) Error { return err; } +fn notedUnder(err: Error, root: []const u8, name: []const u8) Error { + noteText(sys.describe(err), null); + var n: usize = 0; + const root_part = if (std.mem.eql(u8, root, "/")) "" else root; + const parts = [_][]const u8{ root_part, "/", name }; + for (parts) |part| { + const take = @min(part.len, os_path.len - n); + @memcpy(os_path[n..][0..take], part[0..take]); + n += take; + } + os_path_len = n; + return err; +} + fn noteErrno(e: linux.E, path: ?[]const u8) void { noteText(sys.describeErrno(e), path); } @@ -501,18 +515,18 @@ pub const RootLock = struct { // passes this and is refused below only when the root itself is // a link, as the root is opened without following it. clearOsFailure(); - try preflightRoot(root); + preflightRoot(root) catch |err| return noted(err, root); atomic.makedirs(root) catch |err| return noted(err, root); const deadline: ?i64 = if (timeout_ms) |t| nowMs() + t else null; const dir = fsx.openDir(fsx.cwd, root, false) catch |err| return noted(err, root); defer sys.close(dir); - const gate = (try openLockFile(dir, gate_name, realOpenLock)) orelse return error.GateNotPrivate; + const gate = (try openLockFile(dir, root, gate_name, realOpenLock)) orelse return error.GateNotPrivate; errdefer sys.close(gate); try takeFlock(gate, deadline); - const posix = (try openLockFile(dir, sidecar_name, lock_ops.open_sidecar)) orelse return error.NotPrivate; + const posix = (try openLockFile(dir, root, sidecar_name, lock_ops.open_sidecar)) orelse return error.NotPrivate; errdefer sys.close(posix); try takeRecord(posix, deadline); - if (!try isSoleLink(dir, gate_name, gate)) return error.GateNotPrivate; + if (!try isSoleLink(dir, root, gate_name, gate)) return error.GateNotPrivate; _ = lockCall(lock_ops.ftruncate, .{ gate, @as(i64, 0) }) catch |err| return noted(err, null); var buf: [24]u8 = undefined; const line = std.mem.print(&buf, "{d}\n", .{linux.getpid()}) catch unreachable; @@ -525,19 +539,19 @@ pub const RootLock = struct { /// absent or a regular file of this user with one link before the open, /// so a FIFO, device or symbolic link there is never opened, and the /// descriptor is that file after it. - fn openLockFile(dir: fsx.fd_t, name: [:0]const u8, open: *const fn (dir: fsx.fd_t, name: [*:0]const u8) usize) Error!?fsx.fd_t { + fn openLockFile(dir: fsx.fd_t, root: []const u8, name: [:0]const u8, open: *const fn (dir: fsx.fd_t, name: [*:0]const u8) usize) Error!?fsx.fd_t { if (fsx.statAt(dir, name, false)) |st| { if (!st.isReg() or st.nlink != 1 or st.uid != linux.geteuid()) return null; } else |err| switch (err) { error.NotFound => {}, - else => |e| return noted(e, name), + else => |e| return notedUnder(e, root, name), } const fd: fsx.fd_t = @intCast(lockCall(open, .{ dir, name.ptr }) catch |err| switch (err) { error.SymLink, error.IsDir => return null, - else => |e| return noted(e, name), + else => |e| return notedUnder(e, root, name), }); errdefer sys.close(fd); - if (try isSoleLink(dir, name, fd)) { + if (try isSoleLink(dir, root, name, fd)) { sys.fchmod(fd, 0o600) catch |err| return noted(err, null); return fd; } @@ -549,12 +563,12 @@ pub const RootLock = struct { /// `dir/name`. The name is looked up as well as the descriptor: a /// planted hard link unlinked while the lock is awaited leaves the /// descriptor on the other name's file, with one link. - fn isSoleLink(dir: fsx.fd_t, name: []const u8, fd: fsx.fd_t) Error!bool { + fn isSoleLink(dir: fsx.fd_t, root: []const u8, name: []const u8, fd: fsx.fd_t) Error!bool { const st = fsx.fstat(fd) catch |err| return noted(err, null); if (!st.isReg() or st.nlink != 1 or st.uid != linux.geteuid()) return false; const at = fsx.statAt(dir, name, false) catch |err| switch (err) { error.NotFound => return false, - else => |e| return noted(e, name), + else => |e| return notedUnder(e, root, name), }; return at.dev == st.dev and at.ino == st.ino and at.nlink == 1; } @@ -676,6 +690,16 @@ test "the state root preflight matches lexists and isdir" { try std.testing.expectError(error.NotDir, preflightRoot(at.at(base, "link-loop", &nb))); } +test "lock filenames are joined to every state-root spelling without allocation" { + try std.testing.expectEqual(error.Unexpected, notedUnder(error.Unexpected, "/", ".lock.posix")); + var failure = osFailure() orelse unreachable; + try std.testing.expectEqualStrings("/.lock.posix", failure.path); + + try std.testing.expectEqual(error.Unexpected, notedUnder(error.Unexpected, ".lock", ".lock")); + failure = osFailure() orelse unreachable; + try std.testing.expectEqualStrings(".lock/.lock", failure.path); +} + test "RootLock refuses a non-directory state root with NotDir" { const gpa = std.testing.allocator; var pb: [sys.path_max]u8 = undefined; @@ -692,13 +716,27 @@ test "RootLock refuses a non-directory state root with NotDir" { const fd = try sys.openat(fsx.cwd, file_root, .{ .ACCMODE = .WRONLY, .CREAT = true }, 0o644); sys.close(fd); try std.testing.expectError(error.NotDir, RootLock.acquire(gpa, file_root, 0)); - try std.testing.expectEqualStrings("[Errno 20] Not a directory", sys.describe(error.NotDir)); + var failure = osFailure() orelse unreachable; + try std.testing.expectEqualStrings(file_root, failure.path); + try std.testing.expectEqualStrings("[Errno 20] Not a directory", failure.text); // a dangling symbolic link as the root const dangling_root = try std.fmt.allocPrint(gpa, "{s}/dangling-root", .{base}); defer gpa.free(dangling_root); _ = linux.symlinkat("nowhere", fsx.cwd, (try sys.z(&zb, dangling_root)).ptr); try std.testing.expectError(error.NotDir, RootLock.acquire(gpa, dangling_root, 0)); + failure = osFailure() orelse unreachable; + try std.testing.expectEqualStrings(dangling_root, failure.path); + try std.testing.expectEqualStrings("[Errno 20] Not a directory", failure.text); + + // a symbolic-link loop as the root + const loop_root = try std.fmt.allocPrint(gpa, "{s}/loop-root", .{base}); + defer gpa.free(loop_root); + _ = linux.symlinkat("loop-root", fsx.cwd, (try sys.z(&zb, loop_root)).ptr); + try std.testing.expectError(error.NotDir, RootLock.acquire(gpa, loop_root, 0)); + failure = osFailure() orelse unreachable; + try std.testing.expectEqualStrings(loop_root, failure.path); + try std.testing.expectEqualStrings("[Errno 20] Not a directory", failure.text); // a symlink to a directory as the root: the Python tool refuses it // as unsafe through its component check, RootLock with the NotDir @@ -710,6 +748,9 @@ test "RootLock refuses a non-directory state root with NotDir" { defer gpa.free(link_root); _ = linux.symlinkat("real-root", fsx.cwd, (try sys.z(&zb, link_root)).ptr); try std.testing.expectError(error.NotDir, RootLock.acquire(gpa, link_root, 0)); + failure = osFailure() orelse unreachable; + try std.testing.expectEqualStrings(link_root, failure.path); + try std.testing.expectEqualStrings("[Errno 20] Not a directory", failure.text); } test "RootLock refuses a second holder and is free after release" { @@ -811,6 +852,8 @@ test "creating the gate in a read-only directory names .lock" { defer fsx.deleteTree(gpa, fsx.cwd, base) catch {}; try std.testing.expectError(error.AccessDenied, RootLock.acquire(gpa, base, 0)); const note = osFailure() orelse unreachable; - try std.testing.expectEqualStrings(".lock", note.path); + const want_gate = try std.fmt.allocPrint(gpa, "{s}/.lock", .{base}); + defer gpa.free(want_gate); + try std.testing.expectEqualStrings(want_gate, note.path); try std.testing.expectEqualStrings("[Errno 13] Permission denied", note.text); } diff --git a/src/state_test.zig b/src/state_test.zig index ff719df..f6a8b45 100644 --- a/src/state_test.zig +++ b/src/state_test.zig @@ -102,7 +102,10 @@ test "failed local contenders keep the record lock" { defer end(root); const holder = try RootLock.acquire(A, root, 0); defer holder.release(); - for (0..4) |_| try testing.expectError(error.Busy, RootLock.acquire(A, root, 0)); + for (0..4) |_| { + try testing.expectError(error.Busy, RootLock.acquire(A, root, 0)); + try testing.expect(state.osFailure() == null); + } try assertRemoteExcluded(root); } @@ -176,6 +179,9 @@ test "acquisition errors release the descriptors and the gate" { l.release(); return error.TestUnexpectedResult; } else |_| {} + const failure = state.osFailure() orelse unreachable; + try testing.expectEqualStrings("", failure.path); + try testing.expectEqualStrings("[Errno 5] Input/output error", failure.text); state.lock_ops.* = .{}; try testing.expectEqual(before, fdCount(A)); try acquireAndRelease(root); @@ -187,10 +193,30 @@ test "a sidecar open failure releases the local gate" { defer end(root); state.lock_ops.open_sidecar = eioOpen; try testing.expectError(error.Unexpected, RootLock.acquire(A, root, 0)); + const failure = state.osFailure() orelse unreachable; + try testing.expectEqualStrings(try A.print("{s}/.lock.posix", .{root}), failure.path); + try testing.expectEqualStrings("[Errno 5] Input/output error", failure.text); state.lock_ops.* = .{}; try acquireAndRelease(root); } +fn oPathOpen(dir: fsx.fd_t, name: [*:0]const u8) usize { + return linux.openat(dir, name, .{ .PATH = true, .NOFOLLOW = true, .CLOEXEC = true }, 0); +} + +test "an fchmod failure carries no filename" { + const root = begin(); + defer end(root); + const dir = try fsx.openDir(fsx.cwd, root, false); + defer sys.close(dir); + try createFile(dir, ".lock.posix", ""); + state.lock_ops.open_sidecar = oPathOpen; + try testing.expectError(error.InvalidArgument, RootLock.acquire(A, root, 0)); + const failure = state.osFailure() orelse unreachable; + try testing.expectEqualStrings("", failure.path); + try testing.expectEqualStrings("[Errno 9] Bad file descriptor", failure.text); +} + test "a forked child's release does not unlock the parent" { const root = begin(); defer end(root); @@ -229,6 +255,7 @@ test "a hard-linked sidecar is refused" { var zb: [sys.path_max:0]u8 = undefined; _ = linux.linkat(linux.AT.FDCWD, (try sys.z(&za, sidecar)).ptr, linux.AT.FDCWD, (try sys.z(&zb, try A.print("{s}/sidecar-alias", .{root}))).ptr, 0); try testing.expectError(error.NotPrivate, RootLock.acquire(A, root, 0)); + try testing.expect(state.osFailure() == null); } test "a timed acquire does not wait forever" { @@ -330,6 +357,7 @@ test "a gate hard-linked to another file is refused and the file keeps its bytes try createFile(dir, "victim", "secret"); _ = try sys.call(linux.linkat, .{ dir, "victim", dir, ".lock", @as(u32, 0) }); try testing.expectError(error.GateNotPrivate, RootLock.acquire(gpa, root, 0)); + try testing.expect(state.osFailure() == null); try expectContents(gpa, dir, "victim", "secret"); } From 21665894fb91f7fa6d68a6cf89926c975e88a014 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 20 Nov 2026 15:02:00 +0000 Subject: [PATCH 4/7] fix: report the failing makedirs ancestor Recursive directory creation now carries the path passed to the system call that failed. Atomic writes and state locks use that ancestor in their OSError diagnostics. --- .../+makedirs-failed-ancestor.bugfix.md | 1 + src/atomic.zig | 52 ++++++++++++++++--- src/state.zig | 13 ++++- 3 files changed, 58 insertions(+), 8 deletions(-) create mode 100644 changelog.d/+makedirs-failed-ancestor.bugfix.md diff --git a/changelog.d/+makedirs-failed-ancestor.bugfix.md b/changelog.d/+makedirs-failed-ancestor.bugfix.md new file mode 100644 index 0000000..7247385 --- /dev/null +++ b/changelog.d/+makedirs-failed-ancestor.bugfix.md @@ -0,0 +1 @@ +Report the ancestor that actually failed when recursive state-root or atomic-write directory creation stops. diff --git a/src/atomic.zig b/src/atomic.zig index 7ce705b..5fad098 100644 --- a/src/atomic.zig +++ b/src/atomic.zig @@ -438,27 +438,49 @@ pub fn fsyncDir(path: []const u8) sys.Error!void { /// when that name is absent, as Python checks `exists(head)` first and /// swallows the recursion's FileExistsError. pub fn makedirs(path: []const u8) sys.Error!void { + var failed_path: ?[]const u8 = null; + return makedirsTracked(path, &failed_path); +} + +/// `makedirs`, also returning the path passed to the system call that +/// failed. The slice points into `path` and remains null on success. +pub fn makedirsTracked(path: []const u8, failed_path: *?[]const u8) sys.Error!void { + failed_path.* = null; if (fsx.statAt(fsx.cwd, path, true)) |st| { if (st.isDir()) return; + failed_path.* = path; return error.Exists; } else |_| {} if (std.fs.path.dirname(path)) |parent| if (parent.len > 0) { if (fsx.statAt(fsx.cwd, parent, true)) |_| {} else |_| { - makedirs(parent) catch |err| switch (err) { - error.Exists => {}, + makedirsTracked(parent, failed_path) catch |err| switch (err) { + error.Exists => failed_path.* = null, else => return err, }; } }; var zb: [sys.path_max:0]u8 = undefined; - _ = sys.call(linux.mkdirat, .{ fsx.cwd, (try sys.z(&zb, path)).ptr, @as(linux.mode_t, 0o777) }) catch |err| switch (err) { + const zpath = sys.z(&zb, path) catch |err| { + failed_path.* = path; + return err; + }; + _ = sys.call(linux.mkdirat, .{ fsx.cwd, zpath.ptr, @as(linux.mode_t, 0o777) }) catch |err| switch (err) { error.Exists => { // A name another process created meanwhile passes only when // it is a directory; anything else keeps Python's EEXIST. - const st = fsx.statAt(fsx.cwd, path, true) catch return error.Exists; - if (!st.isDir()) return error.Exists; + const st = fsx.statAt(fsx.cwd, path, true) catch { + failed_path.* = path; + return error.Exists; + }; + if (!st.isDir()) { + failed_path.* = path; + return error.Exists; + } + }, + else => { + failed_path.* = path; + return err; }, - else => return err, }; } @@ -498,6 +520,21 @@ test "makedirs surfaces the errnos of os.makedirs with exist_ok" { defer gpa.free(below_dangling); try std.testing.expectError(error.NotFound, makedirs(below_dangling)); try std.testing.expectEqualStrings("[Errno 2] No such file or directory", sys.describe(error.NotFound)); + + // A caller receives the ancestor passed to the mkdir that failed, not + // the deeper leaf whose recursive creation was requested. + const nested_target = try std.fmt.allocPrint(gpa, "{s}/dangling/child/grandchild/file", .{base}); + defer gpa.free(nested_target); + const failed_ancestor = try std.fmt.allocPrint(gpa, "{s}/dangling/child", .{base}); + defer gpa.free(failed_ancestor); + var why: Why = .{}; + defer why.deinit(gpa); + try std.testing.expectError(error.NotFound, atomicWrite(gpa, nested_target, "x", .{}, &why)); + const quoted = try pytext.reprStrAlloc(gpa, failed_ancestor); + defer gpa.free(quoted); + const want = try std.fmt.allocPrint(gpa, "[Errno 2] No such file or directory: {s}", .{quoted}); + defer gpa.free(want); + try std.testing.expectEqualStrings(want, why.msg); } /// What `atomicWrite` gives the new file besides its bytes, and the names @@ -526,7 +563,8 @@ pub const WriteOptions = struct { pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: WriteOptions, why: *Why) Error!void { sys.last_errno = .SUCCESS; const parent = if (std.fs.path.dirname(path)) |d| (if (d.len > 0) d else ".") else "."; - makedirs(parent) catch |err| return failOs(a, why, err, parent, null); + var failed_path: ?[]const u8 = null; + makedirsTracked(parent, &failed_path) catch |err| return failOs(a, why, err, failed_path orelse parent, null); if (fsx.statAt(fsx.cwd, path, false)) |st| { if (st.isLink()) return refuse(a, why, "refusing to replace a symlink: {s}", .{path}); } else |_| {} diff --git a/src/state.zig b/src/state.zig index 355aa2c..da35e6c 100644 --- a/src/state.zig +++ b/src/state.zig @@ -516,7 +516,8 @@ pub const RootLock = struct { // a link, as the root is opened without following it. clearOsFailure(); preflightRoot(root) catch |err| return noted(err, root); - atomic.makedirs(root) catch |err| return noted(err, root); + var failed_path: ?[]const u8 = null; + atomic.makedirsTracked(root, &failed_path) catch |err| return noted(err, failed_path orelse root); const deadline: ?i64 = if (timeout_ms) |t| nowMs() + t else null; const dir = fsx.openDir(fsx.cwd, root, false) catch |err| return noted(err, root); defer sys.close(dir); @@ -729,6 +730,16 @@ test "RootLock refuses a non-directory state root with NotDir" { try std.testing.expectEqualStrings(dangling_root, failure.path); try std.testing.expectEqualStrings("[Errno 20] Not a directory", failure.text); + // Recursive creation names the ancestor at which mkdir failed. + const nested_root = try std.fmt.allocPrint(gpa, "{s}/child/grandchild", .{dangling_root}); + defer gpa.free(nested_root); + const failed_ancestor = try std.fmt.allocPrint(gpa, "{s}/child", .{dangling_root}); + defer gpa.free(failed_ancestor); + try std.testing.expectError(error.NotFound, RootLock.acquire(gpa, nested_root, 0)); + failure = osFailure() orelse unreachable; + try std.testing.expectEqualStrings(failed_ancestor, failure.path); + try std.testing.expectEqualStrings("[Errno 2] No such file or directory", failure.text); + // a symbolic-link loop as the root const loop_root = try std.fmt.allocPrint(gpa, "{s}/loop-root", .{base}); defer gpa.free(loop_root); From 675f454cbf88d507c3b60914bd55eef8e819f223 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 20 Nov 2026 15:03:00 +0000 Subject: [PATCH 5/7] fix: preserve current operating-system errno Lock acquisition starts with a clean errno before synthesizing a short-write failure. Atomic replacement cleanup no longer probes a temporary path after that path has been renamed away. --- changelog.d/+oserror-errno-lifetime.bugfix.md | 1 + src/atomic.zig | 54 ++++++++++++++++++- src/state.zig | 1 + src/state_test.zig | 16 ++++++ 4 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 changelog.d/+oserror-errno-lifetime.bugfix.md diff --git a/changelog.d/+oserror-errno-lifetime.bugfix.md b/changelog.d/+oserror-errno-lifetime.bugfix.md new file mode 100644 index 0000000..77325ad --- /dev/null +++ b/changelog.d/+oserror-errno-lifetime.bugfix.md @@ -0,0 +1 @@ +Reset stale lock errno state and preserve the parent-directory errno after an atomic replacement has been renamed. diff --git a/src/atomic.zig b/src/atomic.zig index 5fad098..dc29667 100644 --- a/src/atomic.zig +++ b/src/atomic.zig @@ -605,7 +605,8 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write return failed; }; ops.created(fd); - errdefer discard(tmp, created); + var renamed = false; + errdefer if (!renamed) discard(tmp, created); { defer sys.close(fd); writeTemp(fd, data) catch |err| return failOs(a, why, err, null, null); @@ -632,6 +633,7 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write if (opts.faults.fails(step)) return injected(a, why, step); } renameTemp(tmp, path) catch |err| return failOs(a, why, err, tmp, path); + renamed = true; // Opening the directory names it. Flushing the descriptor names no file. const directory = sys.openat(fsx.cwd, parent, .{}, 0) catch |err| return failOs(a, why, err, parent, null); defer sys.close(directory); @@ -678,6 +680,24 @@ fn discard(tmp: []const u8, created: fsx.Stat) void { if (cur.dev == created.dev and cur.ino == created.ino) sys.unlinkat(fsx.cwd, tmp, 0) catch {}; } +var saved_nofile: linux.rlimit = undefined; +var nofile_lowered = false; + +fn renameThenExhaustFiles(old_dir: sys.fd_t, old_path: [*:0]const u8, new_dir: sys.fd_t, new_path: [*:0]const u8) usize { + const rc = linux.renameat(old_dir, old_path, new_dir, new_path); + if (linux.errno(rc) != .SUCCESS) return rc; + if (linux.errno(linux.prlimit(0, .NOFILE, null, &saved_nofile)) != .SUCCESS) return @bitCast(-@as(isize, @backingInt(linux.E.IO))); + const none: linux.rlimit = .{ .cur = 0, .max = saved_nofile.max }; + if (linux.errno(linux.prlimit(0, .NOFILE, &none, null)) != .SUCCESS) return @bitCast(-@as(isize, @backingInt(linux.E.IO))); + nofile_lowered = true; + return rc; +} + +fn restoreFileLimit() void { + if (nofile_lowered) _ = linux.prlimit(0, .NOFILE, &saved_nofile, null); + nofile_lowered = false; +} + test "Why.deinit frees a refusal's message only when it was allocated" { const gpa = std.testing.allocator; var why: Why = .{}; @@ -795,6 +815,38 @@ test "atomicWrite frees what it allocates" { try std.testing.expectEqual(@as(usize, 0), why.msg.len); } +test "a post-rename parent-open failure keeps its errno" { + const gpa = std.testing.allocator; + var cwd_buf: [sys.path_max]u8 = undefined; + const cwd = try fsx.realpath(fsx.cwd, ".", &cwd_buf); + const dir = try std.fmt.allocPrint(gpa, "{s}/.zig-cache/atomic-parent-open-{d}", .{ cwd, linux.getpid() }); + defer gpa.free(dir); + try makedirs(dir); + defer fsx.deleteTree(gpa, fsx.cwd, dir) catch {}; + const path = try std.fmt.allocPrint(gpa, "{s}/f", .{dir}); + defer gpa.free(path); + var why: Why = .{}; + defer why.deinit(gpa); + const old_ops = ops.*; + defer ops.* = old_ops; + ops.renameat = renameThenExhaustFiles; + defer restoreFileLimit(); + + try std.testing.expectError(error.Unexpected, atomicWrite(gpa, path, "new\n", .{}, &why)); + try std.testing.expectEqual(linux.E.MFILE, sys.last_errno); + const quoted = try pytext.reprStrAlloc(gpa, dir); + defer gpa.free(quoted); + const want = try std.fmt.allocPrint(gpa, "[Errno 24] Too many open files: {s}", .{quoted}); + defer gpa.free(want); + try std.testing.expectEqualStrings(want, why.msg); + restoreFileLimit(); + const live = try fsx.openRegular(fsx.cwd, path, false); + defer sys.close(live.fd); + const bytes = try fsx.readAll(gpa, live.fd, 16); + defer gpa.free(bytes); + try std.testing.expectEqualStrings("new\n", bytes); +} + test "an interrupted ACL read is retried" { const gpa = std.testing.allocator; var cwd_buf: [sys.path_max]u8 = undefined; diff --git a/src/state.zig b/src/state.zig index da35e6c..c8b518d 100644 --- a/src/state.zig +++ b/src/state.zig @@ -509,6 +509,7 @@ pub const RootLock = struct { _ = gpa; const atomic = @import("atomic.zig"); const root = withoutTrailingSlashes(state_root); + sys.last_errno = .SUCCESS; // The Python tool pre-checks the root before makedirs; a // non-directory root is ENOTDIR here whatever makedirs alone // would say. A root that is a directory once links are followed diff --git a/src/state_test.zig b/src/state_test.zig index f6a8b45..bc26724 100644 --- a/src/state_test.zig +++ b/src/state_test.zig @@ -162,6 +162,9 @@ fn eioFtruncate(_: fsx.fd_t, _: i64) usize { fn eioWrite(_: fsx.fd_t, _: []const u8) usize { return err(.IO); } +fn shortWrite(_: fsx.fd_t, bytes: []const u8) usize { + return bytes.len - 1; +} fn eioOpen(_: fsx.fd_t, _: [*:0]const u8) usize { return err(.IO); } @@ -188,6 +191,19 @@ test "acquisition errors release the descriptors and the gate" { } } +test "a short pid write does not reuse a stale errno" { + const root = begin(); + defer end(root); + const initialized = try RootLock.acquire(A, root, 0); + initialized.release(); + sys.last_errno = .DQUOT; + state.lock_ops.write = shortWrite; + try testing.expectError(error.NoSpace, RootLock.acquire(A, root, 0)); + const failure = state.osFailure() orelse unreachable; + try testing.expectEqualStrings("", failure.path); + try testing.expectEqualStrings("[Errno 28] No space left on device", failure.text); +} + test "a sidecar open failure releases the local gate" { const root = begin(); defer end(root); From b33ecb07be08697918ebc5dce83a636b97bcdcb2 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 20 Nov 2026 15:04:00 +0000 Subject: [PATCH 6/7] fix: keep system errors when diagnostics exhaust memory Every allocation failure while formatting an OSError now keeps that system error and uses the static fallback message. Atomic-write callers deinitialize diagnostics after any failure. --- changelog.d/+atomic-oserror-oom.bugfix.md | 1 + .../howto/replace-a-file-keeping-its-acls.org | 17 +-- src/atomic.zig | 56 +++++++-- src/atomic_test.zig | 109 +++++++++++++++++- tests/fs_lock_parity_probe.zig | 1 + 5 files changed, 158 insertions(+), 26 deletions(-) create mode 100644 changelog.d/+atomic-oserror-oom.bugfix.md diff --git a/changelog.d/+atomic-oserror-oom.bugfix.md b/changelog.d/+atomic-oserror-oom.bugfix.md new file mode 100644 index 0000000..dfc0fe0 --- /dev/null +++ b/changelog.d/+atomic-oserror-oom.bugfix.md @@ -0,0 +1 @@ +Keep the original operating-system error when allocation fails while formatting its atomic-write diagnostic. diff --git a/docs/orgmode/howto/replace-a-file-keeping-its-acls.org b/docs/orgmode/howto/replace-a-file-keeping-its-acls.org index 4bc9677..d5ba304 100644 --- a/docs/orgmode/howto/replace-a-file-keeping-its-acls.org +++ b/docs/orgmode/howto/replace-a-file-keeping-its-acls.org @@ -26,24 +26,19 @@ A reader sees the old file or the new one, never a part of either, and never the The steps that follow use =atomicWrite=. -2. Call it with a [[zig:zig_common.atomic.Why]], which receives the reason for a refusal, and free that with =deinit=: +2. Call it with a [[zig:zig_common.atomic.Why]], which receives the reason for any failure, and free that with =deinit=: #+begin_src zig var why: common.atomic.Why = .{}; defer why.deinit(gpa); - common.atomic.atomicWrite(gpa, path, bytes, .{}, &why) catch |err| switch (err) { - error.Refused => { - common.cli.err("tool: {s}\n", .{why.msg}); - return 1; - }, - else => |e| { - common.cli.err("tool: {s}: {s}\n", .{ path, common.atomic.describe(e) }); - return 1; - }, + common.atomic.atomicWrite(gpa, path, bytes, .{}, &why) catch |err| { + const message = if (why.msg.len > 0) why.msg else common.atomic.describe(err); + common.cli.err("tool: {s}\n", .{message}); + return 1; }; #+end_src - [[zig:zig_common.atomic.describe]] words any other error as Python's =OSError= does, such as =[Errno 28] No space left on device=. + =why.msg= includes the filename or filenames of an operating-system error. If a failure happened before it could be filled, [[zig:zig_common.atomic.describe]] supplies text such as =[Errno 12] Cannot allocate memory=. 3. To give the new file the access of another file, such as a file prepared beside the live one it is to replace, name that file in [[zig:zig_common.atomic.WriteOptions]]: diff --git a/src/atomic.zig b/src/atomic.zig index dc29667..6b44504 100644 --- a/src/atomic.zig +++ b/src/atomic.zig @@ -132,24 +132,33 @@ pub fn describe(err: Error) []const u8 { fn failOs(a: Allocator, why: *Why, err: sys.Error, path: ?[]const u8, path2: ?[]const u8) Error { const text = sys.describe(err); if (path2) |second| { - const q1 = pytext.reprStrAlloc(a, path orelse "") catch return error.OutOfMemory; + const q1 = pytext.reprStrAlloc(a, path orelse "") catch { + why.msg = unallocated_refusal; + return err; + }; defer a.free(q1); - const q2 = pytext.reprStrAlloc(a, second) catch return error.OutOfMemory; + const q2 = pytext.reprStrAlloc(a, second) catch { + why.msg = unallocated_refusal; + return err; + }; defer a.free(q2); why.msg = a.print("{s}: {s} -> {s}", .{ text, q1, q2 }) catch unallocated_refusal; } else if (path) |one| { - const q1 = pytext.reprStrAlloc(a, one) catch return error.OutOfMemory; + const q1 = pytext.reprStrAlloc(a, one) catch { + why.msg = unallocated_refusal; + return err; + }; defer a.free(q1); why.msg = a.print("{s}: {s}", .{ text, q1 }) catch unallocated_refusal; } else why.msg = a.print("{s}", .{text}) catch unallocated_refusal; return err; } -/// Why a replacement was refused; filled in when an error is returned. The -/// message is allocated from the allocator given with `why` and belongs to -/// the caller: `deinit` frees it. +/// Why a replacement failed; filled in when an error is returned. The +/// message may be allocated from the allocator given with `why` and belongs +/// to the caller: call `deinit` after any error. pub const Why = struct { - /// The reason for the refusal; empty until there is one. + /// The reason for the failure; empty until there is one. msg: []const u8 = "", /// Free the message when it was allocated from `a`, and empty it. An @@ -160,9 +169,9 @@ pub const Why = struct { } }; -/// The errors of this module: `error.Refused`, with the reason in the -/// caller's `Why`; `error.OutOfMemory`; or the `sys.Error` of a failed -/// call, which `describe` words as Python does. +/// The errors of this module: `error.Refused`, `error.OutOfMemory`, or the +/// `sys.Error` of a failed call, which `describe` words as Python does. +/// `atomicWrite` callers deinitialize `Why` after any error. pub const Error = error{ Refused, OutOfMemory } || sys.Error; /// The message of a refusal that could not allocate its own. @@ -558,8 +567,8 @@ pub const WriteOptions = struct { /// metadata to apply. Fault points STEP.write, STEP.fsync and STEP.rename /// precede those operations, and in a replaceable build can fail them /// (Faults.fails); the destination is never unlinked first. Everything it -/// allocates from `a` is freed before it returns, except the message of a -/// refusal (see `Why`). +/// allocates from `a` is freed before it returns, except the failure message +/// in `why`. Call `why.deinit(a)` after any error. pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: WriteOptions, why: *Why) Error!void { sys.last_errno = .SUCCESS; const parent = if (std.fs.path.dirname(path)) |d| (if (d.len > 0) d else ".") else "."; @@ -712,6 +721,26 @@ test "Why.deinit frees a refusal's message only when it was allocated" { try std.testing.expectEqualStrings("", why.msg); } +test "an OOM while formatting any OSError path keeps the system error" { + const gpa = std.testing.allocator; + var why: Why = .{}; + try std.testing.expectEqual(error.NoSpace, failOs(std.testing.failing_allocator, &why, error.NoSpace, "path", null)); + try std.testing.expectEqualStrings("refused", why.msg); + why.deinit(gpa); + + var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 1 }); + try std.testing.expectEqual(error.NoSpace, failOs(failing.allocator(), &why, error.NoSpace, "path", null)); + try std.testing.expectEqualStrings("refused", why.msg); + why.deinit(gpa); + + for (0..3) |fail_index| { + var two_path_failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = fail_index }); + try std.testing.expectEqual(error.NoSpace, failOs(two_path_failing.allocator(), &why, error.NoSpace, "old", "new")); + try std.testing.expectEqualStrings("refused", why.msg); + why.deinit(gpa); + } +} + test "atomicWrite keeps the mode and refuses a symlink" { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); @@ -724,6 +753,7 @@ test "atomicWrite keeps the mode and refuses a symlink" { defer fsx.deleteTree(a, fsx.cwd, base) catch {}; const p = try a.print("{s}/j.json", .{base}); var why: Why = .{}; + defer why.deinit(a); try atomicWrite(a, p, "one\n", .{ .mode = 0o640 }, &why); try std.testing.expectEqual(@as(u32, 0o640), (try fsx.statAt(fsx.cwd, p, false)).perm()); try atomicWrite(a, p, "two\n", .{}, &why); @@ -756,6 +786,7 @@ test "a step a test makes fail leaves the destination and no temporary file" { defer fsx.deleteTree(a, fsx.cwd, dir) catch {}; const path = try a.print("{s}/f", .{dir}); var why: Why = .{}; + defer why.deinit(a); try atomicWrite(a, path, "old\n", .{}, &why); for ([_][]const u8{ "j.write", "j.fsync", "j.rename" }) |step| { var want: []const u8 = step; @@ -766,6 +797,7 @@ test "a step a test makes fail leaves the destination and no temporary file" { defer sys.close(f.fd); try std.testing.expectEqualStrings("old\n", try fsx.readAll(a, f.fd, 16)); try std.testing.expectError(error.NotFound, fsx.statAt(fsx.cwd, try a.print("{s}/.f.new", .{dir}), false)); + why.deinit(a); } } diff --git a/src/atomic_test.zig b/src/atomic_test.zig index ab233f7..d0e13c0 100644 --- a/src/atomic_test.zig +++ b/src/atomic_test.zig @@ -133,8 +133,9 @@ fn touch(fd: sys.fd_t) void { fn write(path: []const u8, data: []const u8, opts: atomic.WriteOptions) atomic.Error!void { var why: atomic.Why = .{}; + defer why.deinit(A); atomic.atomicWrite(A, path, data, opts, &why) catch |e| { - last_why = why.msg; + last_why = A.dupe(u8, why.msg) catch "out of memory"; return e; }; } @@ -1716,16 +1717,17 @@ test "atomicWrite frees what it allocates but a refusal's message" { const s = scenario(&m); defer cleanup(s.dir); var why: atomic.Why = .{}; + defer why.deinit(gpa); try atomic.atomicWrite(gpa, s.path, "new", replace, &why); try atomic.atomicWrite(gpa, join(s.dir, "copy.lua"), "copy", .{ .metadata_from = s.path }, &why); try testing.expectEqualStrings("", why.msg); try testing.expectError(error.Refused, atomic.atomicWrite(gpa, s.path, "x", .{ .step = "replace", .faults = .{ .fail_fn = failFsync } }, &why)); - gpa.free(why.msg); + why.deinit(gpa); target = s.path; hook_errno = .STALE; m.hooks.get = hFail; try testing.expectError(error.Refused, atomic.atomicWrite(gpa, s.path, "x", replace, &why)); - gpa.free(why.msg); + why.deinit(gpa); reset(&m); try testing.expectEqualStrings("new", readFile(s.path)); try expectAttrs(s.expected, m.getPath(s.path)); @@ -1744,6 +1746,104 @@ fn exdevRenameat(_: sys.fd_t, _: [*:0]const u8, _: sys.fd_t, _: [*:0]const u8) u return err(.XDEV); } +fn eioFsync(_: sys.fd_t) usize { + return err(.IO); +} + +fn closedOpenat(dir: sys.fd_t, path: [*:0]const u8, flags: sys.O, mode: linux.mode_t) usize { + const rc = linux.openat(dir, path, flags, mode); + if (linux.errno(rc) == .SUCCESS) sys.close(@intCast(rc)); + return rc; +} + +var stale_path: []const u8 = ""; +var parent_path: []const u8 = ""; +var moved_parent_path: []const u8 = ""; + +fn replaceStaleWithDirectory() linux.uid_t { + sys.unlinkat(fsx.cwd, stale_path, 0) catch unreachable; + var zb: [sys.path_max:0]u8 = undefined; + _ = linux.mkdirat(fsx.cwd, (sys.z(&zb, stale_path) catch unreachable).ptr, 0o700); + return linux.geteuid(); +} + +fn renameThenUseProcParent(old_dir: sys.fd_t, old_path: [*:0]const u8, new_dir: sys.fd_t, new_path: [*:0]const u8) usize { + const rc = linux.renameat(old_dir, old_path, new_dir, new_path); + if (linux.errno(rc) != .SUCCESS) return rc; + _ = linux.renameat(fsx.cwd, z(parent_path).ptr, fsx.cwd, z(moved_parent_path).ptr); + _ = linux.symlinkat("/proc", fsx.cwd, z(parent_path).ptr); + return rc; +} + +fn restoreProcParent() void { + _ = linux.unlinkat(fsx.cwd, z(parent_path).ptr, 0); + _ = linux.renameat(fsx.cwd, z(moved_parent_path).ptr, fsx.cwd, z(parent_path).ptr); +} + +test "OSError messages cover write, fsync, fstat, and stale unlink failures" { + begin(); + defer end(); + const dir = tmpdir(); + defer cleanup(dir); + const path = join(dir, "fresh"); + const tmp = join(dir, ".fresh.new"); + + atomic.ops.write = enospcWrite; + try testing.expectError(error.NoSpace, write(path, "new", replace)); + try testing.expectEqualStrings("[Errno 28] No space left on device", last_why); + + atomic.ops.* = .{}; + atomic.ops.fsync = eioFsync; + try testing.expectError(error.Unexpected, write(path, "new", replace)); + try testing.expectEqualStrings("[Errno 5] Input/output error", last_why); + + atomic.ops.* = .{}; + atomic.ops.openat = closedOpenat; + try testing.expectError(error.InvalidArgument, write(path, "new", replace)); + try testing.expectEqualStrings("[Errno 9] Bad file descriptor", last_why); + + atomic.ops.* = .{}; + writeFile(tmp, "stale"); + stale_path = tmp; + atomic.ops.geteuid = replaceStaleWithDirectory; + try testing.expectError(error.IsDir, write(path, "new", replace)); + try testing.expectEqualStrings(try A.print("[Errno 21] Is a directory: '{s}'", .{tmp}), last_why); +} + +test "a parent fsync failure carries no filename and keeps its errno" { + begin(); + defer end(); + const dir = tmpdir(); + defer cleanup(dir); + parent_path = dir; + moved_parent_path = A.print("{s}.moved", .{dir}) catch unreachable; + const path = join(dir, "fresh"); + atomic.ops.renameat = renameThenUseProcParent; + const result = write(path, "new", replace); + const kept_errno = sys.last_errno; + restoreProcParent(); + try testing.expectError(error.InvalidArgument, result); + try testing.expectEqual(linux.E.INVAL, kept_errno); + try testing.expectEqualStrings("[Errno 22] Invalid argument", last_why); + try testing.expectEqualStrings("new", readFile(path)); +} + +test "a sys-error message can be released with a general-purpose allocator" { + begin(); + defer end(); + const gpa = testing.allocator; + const dir = tmpdir(); + defer cleanup(dir); + const path = join(dir, "fresh"); + atomic.ops.write = enospcWrite; + var why: atomic.Why = .{}; + defer why.deinit(gpa); + try testing.expectError(error.NoSpace, atomic.atomicWrite(gpa, path, "new", replace, &why)); + try testing.expectEqualStrings("[Errno 28] No space left on device", why.msg); + why.deinit(gpa); + try testing.expectEqualStrings("", why.msg); +} + test "atomicWrite returns NoSpace, ReadOnly, and CrossDevice without touching the live file" { begin(); defer end(); @@ -1754,6 +1854,7 @@ test "atomicWrite returns NoSpace, ReadOnly, and CrossDevice without touching th atomic.ops.write = enospcWrite; try testing.expectError(error.NoSpace, write(pt[0], "new", replace)); try testing.expectEqualStrings("[Errno 28] No space left on device", atomic.describe(error.NoSpace)); + try testing.expectEqualStrings("[Errno 28] No space left on device", last_why); try testing.expect(!exists(pt[1])); try testing.expectEqualStrings("old", readFile(pt[0])); @@ -1761,6 +1862,7 @@ test "atomicWrite returns NoSpace, ReadOnly, and CrossDevice without touching th atomic.ops.openat = erofsOpenat; try testing.expectError(error.ReadOnly, write(pt[0], "new", replace)); try testing.expectEqualStrings("[Errno 30] Read-only file system", atomic.describe(error.ReadOnly)); + try testing.expectEqualStrings(try A.print("[Errno 30] Read-only file system: '{s}'", .{pt[1]}), last_why); try testing.expect(!exists(pt[1])); try testing.expectEqualStrings("old", readFile(pt[0])); @@ -1768,6 +1870,7 @@ test "atomicWrite returns NoSpace, ReadOnly, and CrossDevice without touching th atomic.ops.renameat = exdevRenameat; try testing.expectError(error.CrossDevice, write(pt[0], "new", replace)); try testing.expectEqualStrings("[Errno 18] Invalid cross-device link", atomic.describe(error.CrossDevice)); + try testing.expectEqualStrings(try A.print("[Errno 18] Invalid cross-device link: '{s}' -> '{s}'", .{ pt[1], pt[0] }), last_why); try testing.expect(!exists(pt[1])); try testing.expectEqualStrings("old", readFile(pt[0])); diff --git a/tests/fs_lock_parity_probe.zig b/tests/fs_lock_parity_probe.zig index 54387ff..c4e1f9e 100644 --- a/tests/fs_lock_parity_probe.zig +++ b/tests/fs_lock_parity_probe.zig @@ -176,6 +176,7 @@ fn atomicMode() void { for (aw_cases) |c| { var why: common.atomic.Why = .{}; opLine("atomicwrite", c.name, common.atomic.atomicWrite(A, c.name, c.data, c.opts, &why)); + why.deinit(A); } const rc_cases = [_]struct { name: []const u8, data: []const u8 }{ .{ .name = "rc-keep", .data = "replaced\n" }, From 6939a09cd7204f222028cd0778f899521f860f08 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 20 Nov 2026 06:36:00 +0000 Subject: [PATCH 7/7] fix: report a failed release of the state-root lock RootLock.release ignored a failed flock(LOCK_UN), so the caller exited successfully. The Python reference raises the operating-system error after it closes both descriptors. The release now does the same and returns the error after closing them. --- changelog.d/+lock-release-error.bugfix.md | 1 + docs/orgmode/reference/api.org | 2 +- src/state.zig | 23 +++++++++++----- src/state_test.zig | 32 +++++++++++------------ 4 files changed, 34 insertions(+), 24 deletions(-) create mode 100644 changelog.d/+lock-release-error.bugfix.md diff --git a/changelog.d/+lock-release-error.bugfix.md b/changelog.d/+lock-release-error.bugfix.md new file mode 100644 index 0000000..ceb6f7b --- /dev/null +++ b/changelog.d/+lock-release-error.bugfix.md @@ -0,0 +1 @@ +A failed unlock of the state-root lock is returned to the caller instead of being ignored. diff --git a/docs/orgmode/reference/api.org b/docs/orgmode/reference/api.org index 7bafcc4..916a936 100644 --- a/docs/orgmode/reference/api.org +++ b/docs/orgmode/reference/api.org @@ -123,7 +123,7 @@ Error sets: [[zig:zig_common.state.Error]], [[zig:zig_common.state.RootLock.Acqu | Function | Error set | |---------------------------------------------+---------------------------------------------------| | [[zig:zig_common.state.RootLock.acquire]] | [[zig:zig_common.state.RootLock.AcquireError]] | -| [[zig:zig_common.state.RootLock.release]] | none | +| [[zig:zig_common.state.RootLock.release]] | [[zig:zig_common.state.Error]] | | [[zig:zig_common.state.privateOk]] | none | | [[zig:zig_common.state.openPrivate]] | [[zig:zig_common.state.Error]] | | [[zig:zig_common.state.lockExclusive]] | [[zig:zig_common.state.LockError]] | diff --git a/src/state.zig b/src/state.zig index c8b518d..2cd3f82 100644 --- a/src/state.zig +++ b/src/state.zig @@ -584,16 +584,25 @@ pub const RootLock = struct { /// Unlock the record lock, close its descriptor, then unlock and close /// the gate. Both descriptors are closed whatever an unlock returns; a - /// forked child only closes them. - pub fn release(l: RootLock) void { + /// forked child only closes them. The first unlock error is returned + /// after both closes, as Python's release lets the OSError out. + pub fn release(l: RootLock) sys.Error!void { + var first: ?sys.Error = null; if (linux.getpid() == l.owner) { var fl: linux.Flock = std.mem.zeroes(linux.Flock); fl.type = linux.F.UNLCK; - _ = lock_ops.fcntl(l.posix, linux.F.SETLK, @intFromPtr(&fl)); + _ = lockCall(lock_ops.fcntl, .{ l.posix, linux.F.SETLK, @intFromPtr(&fl) }) catch |err| { + first = err; + }; } sys.close(l.posix); - if (linux.getpid() == l.owner) _ = lock_ops.flock(l.gate, std.posix.LOCK.UN); + if (linux.getpid() == l.owner) { + _ = lockCall(lock_ops.flock, .{ l.gate, std.posix.LOCK.UN }) catch |err| { + if (first == null) first = err; + }; + } sys.close(l.gate); + if (first) |err| return err; } }; @@ -774,9 +783,9 @@ test "RootLock refuses a second holder and is free after release" { defer fsx.deleteTree(gpa, fsx.cwd, base) catch {}; const first = try RootLock.acquire(gpa, base, 0); try std.testing.expectError(error.Busy, RootLock.acquire(gpa, base, 0)); - first.release(); + first.release() catch unreachable; const again = try RootLock.acquire(gpa, base, 0); - again.release(); + again.release() catch unreachable; } test "lockExclusiveCancel returns Canceled when cancel is set" { @@ -852,7 +861,7 @@ test "creating the gate in a read-only directory names .lock" { const cwd = try fsx.realpath(fsx.cwd, ".", &cwd_buf); const base = try std.mem.print(&pb, "{s}/.zig-cache/zig-common-ro-{d}", .{ cwd, linux.getpid() }); const held = try RootLock.acquire(gpa, base, 0); - held.release(); + held.release() catch unreachable; var zb: [sys.path_max:0]u8 = undefined; const gate = try std.mem.print(zb[0..zb.len], "{s}/.lock", .{base}); try sys.unlinkat(fsx.cwd, gate, 0); diff --git a/src/state_test.zig b/src/state_test.zig index bc26724..27d489b 100644 --- a/src/state_test.zig +++ b/src/state_test.zig @@ -65,7 +65,7 @@ fn assertRemoteExcluded(root: []const u8) !void { if (pid == 0) { state.lock_ops.flock = noFlock; if (RootLock.acquire(A, root, 0)) |l| { - l.release(); + l.release() catch unreachable; linux.exit_group(1); } else |e| linux.exit_group(if (e == error.Busy) 0 else 2); } @@ -82,7 +82,7 @@ fn assertGateHeld(root: []const u8) !void { fn acquireAndRelease(root: []const u8) !void { const l = try RootLock.acquire(A, root, 0); - l.release(); + l.release() catch unreachable; } test "the record lock excludes an independent kernel gate" { @@ -90,10 +90,10 @@ test "the record lock excludes an independent kernel gate" { defer end(root); const holder = try RootLock.acquire(A, root, 0); assertRemoteExcluded(root) catch |e| { - holder.release(); + holder.release() catch unreachable; return e; }; - holder.release(); + holder.release() catch unreachable; try acquireAndRelease(root); } @@ -101,7 +101,7 @@ test "failed local contenders keep the record lock" { const root = begin(); defer end(root); const holder = try RootLock.acquire(A, root, 0); - defer holder.release(); + defer holder.release() catch unreachable; for (0..4) |_| { try testing.expectError(error.Busy, RootLock.acquire(A, root, 0)); try testing.expect(state.osFailure() == null); @@ -125,7 +125,7 @@ test "an interrupted non-blocking flock is retried" { eintr_left = 1; state.lock_ops.flock = eintrFlock; const held = try RootLock.acquire(A, root, 0); - held.release(); + held.release() catch unreachable; try testing.expectEqual(@as(u8, 0), eintr_left); eintr_left = 1; @@ -142,7 +142,7 @@ test "a second acquire by the holder keeps both locks" { const root = begin(); defer end(root); const holder = try RootLock.acquire(A, root, 0); - defer holder.release(); + defer holder.release() catch unreachable; try testing.expectError(error.Busy, RootLock.acquire(A, root, 0)); try assertGateHeld(root); try assertRemoteExcluded(root); @@ -179,7 +179,7 @@ test "acquisition errors release the descriptors and the gate" { if (comptime std.mem.eql(u8, target, "ftruncate")) state.lock_ops.ftruncate = eioFtruncate; if (comptime std.mem.eql(u8, target, "write")) state.lock_ops.write = eioWrite; if (RootLock.acquire(A, root, null)) |l| { - l.release(); + l.release() catch unreachable; return error.TestUnexpectedResult; } else |_| {} const failure = state.osFailure() orelse unreachable; @@ -195,7 +195,7 @@ test "a short pid write does not reuse a stale errno" { const root = begin(); defer end(root); const initialized = try RootLock.acquire(A, root, 0); - initialized.release(); + initialized.release() catch unreachable; sys.last_errno = .DQUOT; state.lock_ops.write = shortWrite; try testing.expectError(error.NoSpace, RootLock.acquire(A, root, 0)); @@ -237,10 +237,10 @@ test "a forked child's release does not unlock the parent" { const root = begin(); defer end(root); const holder = try RootLock.acquire(A, root, 0); - defer holder.release(); + defer holder.release() catch unreachable; const pid: isize = @bitCast(linux.fork()); if (pid == 0) { - holder.release(); + holder.release() catch unreachable; linux.exit_group(0); } try testing.expectEqual(@as(u32, 0), waitExit(pid)); @@ -255,7 +255,7 @@ test "a release error still closes both layers" { const holder = try RootLock.acquire(A, root, 0); const before = fdCount(A); state.lock_ops.fcntl = eioFcntl; - holder.release(); + try testing.expectError(error.Unexpected, holder.release()); state.lock_ops.* = .{}; try testing.expectEqual(before - 2, fdCount(A)); try acquireAndRelease(root); @@ -278,7 +278,7 @@ test "a timed acquire does not wait forever" { const root = begin(); defer end(root); const holder = try RootLock.acquire(A, root, 0); - defer holder.release(); + defer holder.release() catch unreachable; var t0: linux.timespec = undefined; _ = linux.clock_gettime(.MONOTONIC, &t0); try testing.expectError(error.Busy, RootLock.acquire(A, root, 200)); @@ -393,7 +393,7 @@ test "a hard link planted while the gate is awaited stops the truncate" { state.lock_ops.* = .{}; try sys.unlinkat(dir, "alias", 0); const l = try RootLock.acquire(gpa, root, 0); - l.release(); + l.release() catch unreachable; } test "a gate moved to another name while it is awaited is not truncated" { @@ -463,7 +463,7 @@ test "both lock files are created mode 0600" { const root = try scratchRoot(gpa); defer removeRoot(gpa, root); const l = try RootLock.acquire(gpa, root, 0); - defer l.release(); + defer l.release() catch unreachable; try testing.expectEqual(@as(u32, 0o600), (try fsx.fstat(l.gate)).perm()); try testing.expectEqual(@as(u32, 0o600), (try fsx.fstat(l.posix)).perm()); } @@ -483,7 +483,7 @@ test "acquire tightens existing owned lock files to mode 0600" { try testing.expectEqual(@as(u32, 0o644), (try fsx.statAt(dir, ".lock.posix", false)).perm()); const l = try RootLock.acquire(gpa, root, 0); - defer l.release(); + defer l.release() catch unreachable; try testing.expectEqual(@as(u32, 0o600), (try fsx.fstat(l.gate)).perm()); try testing.expectEqual(@as(u32, 0o600), (try fsx.fstat(l.posix)).perm()); }