From 5d37a992581aac633c002191bd23d86e9fa89126 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Wed, 25 Nov 2026 14:21:49 +0000 Subject: [PATCH 1/2] fix: return a failed close from state.writePrivate before the rename writePrivate closed the temporary file in a defer that ran after the rename and dropped the result of close. On a network file system (NFS) a write the server loses can be reported by close alone, so the name was replaced with a file whose bytes may be gone and the call returned success. The Python tools this port follows close before os.replace and raise on a failed close, so they never replace the name in that case. The temporary file is synced and closed before the rename. A failed fsync or close is returned as sys.Error with sys.last_errno set to its errno, the name is left as it was, and the temporary file is removed. The removal keeps that errno, so sys.describe names the failed call. The descriptor is closed once on every path: by the close before the rename, or by the cleanup when an earlier call fails. close is called once and its result goes through sys.result. `EINTR` is not retried, because Linux frees the descriptor before close returns and a retry could close a descriptor another thread has just opened. sys.result returns null for `EINTR` rather than an error, so that close is not an error either. The fsync before it has flushed the bytes, so that close has nothing left to lose. fsync and close go through state.write_ops, replaceable in the same builds as state.lock_ops and constant real calls in any other build. --- changelog.d/+write-private-close.bugfix.md | 1 + .../howto/keep-private-state-in-tmp.org | 2 +- src/state.zig | 45 +++++++++++++++++-- 3 files changed, 43 insertions(+), 5 deletions(-) create mode 100644 changelog.d/+write-private-close.bugfix.md diff --git a/changelog.d/+write-private-close.bugfix.md b/changelog.d/+write-private-close.bugfix.md new file mode 100644 index 0000000..7bd2fa5 --- /dev/null +++ b/changelog.d/+write-private-close.bugfix.md @@ -0,0 +1 @@ +`state.writePrivate` syncs and closes the temporary file before it renames it over the name. A failed fsync or close is returned as `sys.Error`, the name is left as it was, and the temporary file is removed. Before this change the file was closed after the rename and the close error was dropped, so a write that a network file system (NFS) reported lost at the close replaced the name and was returned as success. A close that `EINTR` interrupts is not retried and is not an error, as `sys.result` treats `EINTR`. The calls are replaceable through `state.write_ops` in the same builds as `state.lock_ops`. diff --git a/docs/orgmode/howto/keep-private-state-in-tmp.org b/docs/orgmode/howto/keep-private-state-in-tmp.org index 604adc8..751c822 100644 --- a/docs/orgmode/howto/keep-private-state-in-tmp.org +++ b/docs/orgmode/howto/keep-private-state-in-tmp.org @@ -65,7 +65,7 @@ Use this when a tool keeps a small file between runs in a directory every user m #+end_src [[zig:zig_common.state.readPrivate]] returns null for a file that is absent, larger than the limit or not private, so the tool starts over instead of trusting it. - [[zig:zig_common.state.writePrivate]] writes =.NAME.PID.RANDOM.tmp= with mode 0600 and renames it over the name. + [[zig:zig_common.state.writePrivate]] writes =.NAME.PID.RANDOM.tmp= with mode 0600, syncs and closes it, and renames it over the name only when the sync and the close both succeed. ** Check that it worked diff --git a/src/state.zig b/src/state.zig index d8e9528..72e8daa 100644 --- a/src/state.zig +++ b/src/state.zig @@ -199,7 +199,14 @@ pub fn createPrivateAt(dir: fsx.fd_t, name: []const u8, bytes: []const u8, mode: } /// Replace `dir/name` with `bytes`: written to `.NAME.PID.RANDOM.tmp` with -/// mode 0600, then renamed over the name. +/// mode 0600, flushed with fsync and closed, then renamed over the name. +/// A failed write, fchmod, fsync or close is returned with `sys.last_errno` +/// set to its errno; the name is left as it was and the temporary file is +/// removed. A write lost on NFS may be reported only by the close. The +/// descriptor is closed once on every path. A close that EINTR +/// interrupts is not retried, as Linux has freed the descriptor, and is +/// not an error, as `sys.result` treats EINTR; the fsync before it has +/// already flushed the bytes. pub fn writePrivate(gpa: Allocator, dir: fsx.fd_t, name: []const u8, bytes: []const u8) (Error || Allocator.Error)!void { var rnd: [6]u8 = undefined; _ = try sys.call(linux.getrandom, .{ &rnd, rnd.len, 0 }); @@ -208,17 +215,47 @@ pub fn writePrivate(gpa: Allocator, dir: fsx.fd_t, name: []const u8, bytes: []co const tmp = try gpa.print("{s}/.{s}.{d}.{x}.tmp", .{ parent, base, linux.getpid(), rnd }); defer gpa.free(tmp); const fd = try sys.openat(dir, tmp, .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true, .NOFOLLOW = true }, 0o600); + var open = true; var done = false; defer { - sys.close(fd); - if (!done) sys.unlinkat(dir, tmp, 0) catch {}; + if (open) _ = write_ops.close(fd); + if (!done) { + // The error being returned keeps its errno. + const saved = sys.last_errno; + defer sys.last_errno = saved; + sys.unlinkat(dir, tmp, 0) catch {}; + } } try sys.writeAll(fd, bytes); try sys.fchmod(fd, 0o600); + _ = try lockCall(write_ops.fsync, .{fd}); + open = false; + _ = try sys.result(write_ops.close(fd)); try sys.renameat(dir, tmp, dir, name); done = true; } +/// The calls `writePrivate` makes on the temporary file, as raw +/// system-call results. Replaceable in the same builds as `lock_ops`; +/// constant real calls in any other build. +pub const WriteOps = struct { + fsync: *const fn (fd: fsx.fd_t) usize = realFsync, + close: *const fn (fd: fsx.fd_t) usize = realClose, +}; + +var test_write_ops: WriteOps = .{}; +const real_write_ops: WriteOps = .{}; +/// The calls in use. A replaceable build may assign through it +/// (`write_ops.* = ...`); any other build points it at constant real calls. +pub const write_ops = if (@import("atomic.zig").replaceable) &test_write_ops else &real_write_ops; + +fn realFsync(fd: fsx.fd_t) usize { + return linux.fsync(fd); +} +fn realClose(fd: fsx.fd_t) usize { + return linux.close(fd); +} + test "createPrivateAt creates without clobbering" { const gpa = std.testing.allocator; var pb: [sys.path_max]u8 = undefined; @@ -655,7 +692,7 @@ fn realOpenLock(dir: fsx.fd_t, name: [*:0]const u8) usize { return linux.openat(dir, name, .{ .ACCMODE = .RDWR, .CREAT = true, .NOFOLLOW = true, .NONBLOCK = true, .CLOEXEC = true }, 0o600); } -/// One of `lock_ops`, retrying on EINTR. +/// One of `lock_ops` or `write_ops`, retrying on EINTR. fn lockCall(f: anytype, args: anytype) Error!usize { while (true) { if (try sys.result(@call(.auto, f, args))) |rc| return rc; From 1c6bf4dd504f6d417821b728b8316c85713c89ab Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Wed, 25 Nov 2026 14:21:49 +0000 Subject: [PATCH 2/2] test: check that state.writePrivate returns a failed fsync or close Through state.write_ops, the cases make fsync fail with `EIO` or `ENOSPC`, and close with `EIO`, `ENOSPC` or `EDQUOT`. Those are the errors a network file system (NFS) reports for a lost write. Each case runs over an existing name and over a name that does not exist yet. Each expects the mapped error with sys.last_errno and sys.describe naming that errno, one close of the descriptor, the descriptor count from before the call, the existing name with its old bytes, no new name and no temporary file. A close that reports `EINTR` expects success, one close and the new bytes. A sync that reports `EINTR` once expects a second sync, one close and the new bytes. A plain write expects one close. The close hook closes the descriptor for real before it reports its errno, as Linux does, so a leak or a second close shows in the counts. On develop before this series the tests fail to build, as it has no state.write_ops. --- changelog.d/+write-private-close-test.misc.md | 1 + src/state_test.zig | 141 ++++++++++++++++++ 2 files changed, 142 insertions(+) create mode 100644 changelog.d/+write-private-close-test.misc.md diff --git a/changelog.d/+write-private-close-test.misc.md b/changelog.d/+write-private-close-test.misc.md new file mode 100644 index 0000000..11dbbf8 --- /dev/null +++ b/changelog.d/+write-private-close-test.misc.md @@ -0,0 +1 @@ +Add tests that `state.writePrivate` returns a failed `fsync` or `close` injected through `state.write_ops`, closes the descriptor once, leaves the name and no temporary file, retries an `fsync` that `EINTR` interrupts, and treats a `close` that `EINTR` interrupts as success without a retry. diff --git a/src/state_test.zig b/src/state_test.zig index d1dbc4e..c96e97f 100644 --- a/src/state_test.zig +++ b/src/state_test.zig @@ -548,3 +548,144 @@ test "acquire tightens existing owned lock files to mode 0600" { try testing.expectEqual(@as(u32, 0o600), (try fsx.fstat(l.gate)).perm()); try testing.expectEqual(@as(u32, 0o600), (try fsx.fstat(l.posix)).perm()); } + +// ---- writePrivate: the sync and the close come before the rename ---------- + +const WriteHooks = struct { + var closes: usize = 0; + var close_errno: linux.E = .SUCCESS; + var fsync_errno: linux.E = .SUCCESS; + + fn set(fsync_e: linux.E, close_e: linux.E) void { + closes = 0; + fsync_errno = fsync_e; + close_errno = close_e; + state.write_ops.* = .{ .fsync = fsync, .close = close }; + } + fn fsync(fd: fsx.fd_t) usize { + if (fsync_errno != .SUCCESS) return err(fsync_errno); + return linux.fsync(fd); + } + /// Linux frees the descriptor whatever close returns, so the hook + /// closes it for real and then reports the errno it was given, on the + /// first call only: a second close of the descriptor is EBADF. + fn close(fd: fsx.fd_t) usize { + closes += 1; + const rc = linux.close(fd); + if (close_errno == .SUCCESS or closes > 1) return rc; + return err(close_errno); + } +}; + +fn expectNoTemporary(gpa: std.mem.Allocator, dir: fsx.fd_t) !void { + var it = try fsx.DirIter.init(gpa, dir); + defer it.deinit(gpa); + while (try it.next()) |e| try testing.expect(!std.mem.endsWith(u8, e.name, ".tmp")); +} + +const WriteCase = struct { fsync: linux.E = .SUCCESS, close: linux.E = .SUCCESS, want: sys.Error }; + +fn expectWriteRefused(gpa: std.mem.Allocator, cases: []const WriteCase) !void { + const root = try scratchRoot(gpa); + defer removeRoot(gpa, root); + defer state.write_ops.* = .{}; + const dir = try fsx.openDir(fsx.cwd, root, false); + defer sys.close(dir); + try state.writePrivate(gpa, dir, "c.json", "old\n"); + for (cases) |c| { + const code = if (c.close != .SUCCESS) c.close else c.fsync; + for ([_][]const u8{ "c.json", "fresh.json" }) |name| { + const before = try test_support.fdCount(gpa); + WriteHooks.set(c.fsync, c.close); + sys.last_errno = .SUCCESS; + const wrote = state.writePrivate(gpa, dir, name, "new\n"); + state.write_ops.* = .{}; + try testing.expectError(c.want, wrote); + try testing.expectEqual(code, sys.last_errno); + try testing.expectEqualStrings(sys.describeErrno(code), sys.describe(c.want)); + try testing.expectEqual(@as(usize, 1), WriteHooks.closes); + try testing.expectEqual(before, try test_support.fdCount(gpa)); + try expectNoTemporary(gpa, dir); + } + try expectContents(gpa, dir, "c.json", "old\n"); + try testing.expectError(error.NotFound, fsx.statAt(dir, "fresh.json", false)); + } +} + +test "a failed close of the written file is returned and the name is not replaced" { + try expectWriteRefused(testing.allocator, &.{ + .{ .close = .IO, .want = error.Unexpected }, + .{ .close = .NOSPC, .want = error.NoSpace }, + .{ .close = .DQUOT, .want = error.NoSpace }, + }); +} + +test "a failed fsync of the written file is returned and the file is closed once" { + try expectWriteRefused(testing.allocator, &.{ + .{ .fsync = .IO, .want = error.Unexpected }, + .{ .fsync = .NOSPC, .want = error.NoSpace }, + }); +} + +test "a close that EINTR interrupts is not retried and is not an error" { + const gpa = testing.allocator; + const root = try scratchRoot(gpa); + defer removeRoot(gpa, root); + defer state.write_ops.* = .{}; + const dir = try fsx.openDir(fsx.cwd, root, false); + defer sys.close(dir); + try state.writePrivate(gpa, dir, "c.json", "old\n"); + const before = try test_support.fdCount(gpa); + WriteHooks.set(.SUCCESS, .INTR); + try state.writePrivate(gpa, dir, "c.json", "new\n"); + state.write_ops.* = .{}; + try testing.expectEqual(@as(usize, 1), WriteHooks.closes); + try testing.expectEqual(before, try test_support.fdCount(gpa)); + try expectContents(gpa, dir, "c.json", "new\n"); + try expectNoTemporary(gpa, dir); +} + +test "a sync that EINTR interrupts is retried" { + const gpa = testing.allocator; + const root = try scratchRoot(gpa); + defer removeRoot(gpa, root); + defer state.write_ops.* = .{}; + const dir = try fsx.openDir(fsx.cwd, root, false); + defer sys.close(dir); + const Intr = struct { + var syncs: usize = 0; + fn fsync(fd: fsx.fd_t) usize { + syncs += 1; + if (syncs == 1) return err(.INTR); + return linux.fsync(fd); + } + }; + const before = try test_support.fdCount(gpa); + WriteHooks.set(.SUCCESS, .SUCCESS); + Intr.syncs = 0; + state.write_ops.fsync = Intr.fsync; + try state.writePrivate(gpa, dir, "c.json", "new\n"); + state.write_ops.* = .{}; + try testing.expectEqual(@as(usize, 2), Intr.syncs); + try testing.expectEqual(@as(usize, 1), WriteHooks.closes); + try testing.expectEqual(before, try test_support.fdCount(gpa)); + try expectContents(gpa, dir, "c.json", "new\n"); + try expectNoTemporary(gpa, dir); +} + +test "writePrivate closes the written file once when it succeeds" { + const gpa = testing.allocator; + const root = try scratchRoot(gpa); + defer removeRoot(gpa, root); + defer state.write_ops.* = .{}; + const dir = try fsx.openDir(fsx.cwd, root, false); + defer sys.close(dir); + const before = try test_support.fdCount(gpa); + WriteHooks.set(.SUCCESS, .SUCCESS); + try state.writePrivate(gpa, dir, "c.json", "new\n"); + state.write_ops.* = .{}; + try testing.expectEqual(@as(usize, 1), WriteHooks.closes); + try testing.expectEqual(before, try test_support.fdCount(gpa)); + try expectContents(gpa, dir, "c.json", "new\n"); + try expectNoTemporary(gpa, dir); +}