szn

Bug 510 — non-atomic log fd behind an atomic gate

510. Atomic flag used as a mutual-exclusion primitive

Severity: LOW (safety)
Status: ✅ FIXED
Files: src/log.zig:36-38, src/log.zig:149-163, src/log.zig:194-207

Problem

The three log globals are declared with mixed concurrency discipline:

// src/log.zig:36-38
var log_fd: ?std.posix.fd_t = null;
var log_fd_failed: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
var log_enabled: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);

log_enabled is read as the entry gate and log_fd is dereferenced immediately afterwards:

// src/log.zig:138, 149-163
if (!log_enabled.load(.seq_cst)) return;
...
if (log_fd == null) {
    if (log_fd_failed.load(.seq_cst)) return;
    ...
    log_fd = fd;
}
const fd = log_fd.?;

Meanwhile the lifecycle functions close and swap the descriptor:

// src/log.zig:194-197
if (log_fd) |old| _ = c.close(old);
log_fd = fd;
log_fd_failed.store(false, .seq_cst);
log_enabled.store(true, .seq_cst);

A .seq_cst store is a release, and a .seq_cst load is an acquire, so the flag establishes happens-before for writes made before it. It does not establish mutual exclusion. Nothing prevents a writer that has already passed the log_enabled gate at line 138 from reaching line 163 after deinitLog/disableLog has closed the descriptor at line 194 and stored null at line 205. The writer would then c.write to a closed descriptor, which the OS may have already reassigned to an unrelated file, socket, or PTY.

This is a data race on a non-atomic global under the Zig memory model, and a file-descriptor-reuse hazard in the ordinary sense.

Why it is filed as LOW rather than higher

The hazard is currently unreachable: enable() / enableClientLog() are documented as “Called once from enable() / enableClientLog() after log_fd is set” (src/log.zig:114), and the server event loop is single-threaded by design (AGENTS.md principle 6). No background thread calls logFd(). So today there is no concurrent writer, and no user-visible defect.

It is filed because the pattern is fragile and this file has a poor history in exactly this area — bugs #357 (cmdLoadBuffer invalid free), #358 (name_buf-owned string double free), and #365 (kill-window leaks pty poll registrations) are all fd/resource-lifetime defects. A future background thread (a libthai worker, a metrics timer) would silently reintroduce the race, and the .seq_cst annotations make the code look thread-safe when it is not.

Proposed Fix

Cheapest correct change: make the fd itself atomic, matching the flags that already guard it, so the gate and the guarded value share a discipline.

var log_fd: std.atomic.Value(std.posix.fd_t) =
    std.atomic.Value(std.posix.fd_t).init(-1);

with -1 meaning “closed” and a separate log_enabled flag retained for the fast path. Reads become const fd = log_fd.load(.seq_cst); if (fd < 0) return; and writes become compare-exchange or a store ordered before the enabling flag. That closes the reuse window without introducing a full mutex.

A mutex around the {log_fd, log_enabled, log_fd_failed} triple would be equivalent and easier to reason about, at the cost of an uncontended lock per log line — measurable on a hot path that already formats per-cell SGR.

Related: the globals themselves are catalogued in bug #507, which recommends folding them into a Logger passed by pointer. Doing that first would make this fix a local change rather than another process-global.

Resolution

Fixed. log_fd is now std.atomic.Value(std.posix.fd_t), giving the guarded value the same discipline as the flags that guard it, and the lifecycle no longer has a window where the flag and the descriptor disagree.

Regression test enable/disable swap the fd exactly once and disable is idempotent — bug #510 covers re-enable (old fd closed, new fd live, write lands in the new file), disable (gate cleared, fd retired), and a second disable (no double-close).

Residual, stated plainly: the atomic removes the data race, so the access is well-defined rather than undefined. It does not by itself close the close-vs-use ordering window — a writer that read the fd before a concurrent disable swapped it can still write to a descriptor retired a moment later. Closing that fully needs either a dup() per write, or a mutex around the triple. Neither is warranted today: the server event loop is single-threaded, enable is called once at startup, and no background thread calls logFn. The .seq_cst annotations plus the corrected ordering mean that if a future thread does appear, the failure mode is bounded rather than a torn read — but the honest statement is that this bug is hardened, not fully closed, and the follow-up is the Logger-by-pointer refactor already noted in bug #507.