Repository navigation
Harden background daemon: stdout integrity, lifecycle, and single-instance lock - #274
Conversation
…e lock Deep review of internal/daemon (worker pool, launcher, control server, session fan-out, single-instance lock) found and fixes a stdout-integrity bug plus several lifecycle/locking hazards. Each fix has a regression test; the daemon suite passes under -race. Worker stdout integrity - Replace the capped bufio.Scanner (64 KiB) on a worker's stdout with an uncapped bufio.Reader: a legitimately large stream-json line from our own trusted worker is no longer silently dropped (the 1 MiB cap belongs to untrusted network frames, not this local pipe). - Surface a stdout read error as a run failure instead of swallowing it as a clean success, and kill the worker first so it can't block writing to the now-unread pipe and hang Wait. Control-server lifecycle - Track open connections and close them on Shutdown so a single idle/hostile client can no longer wedge drain (and SIGTERM cleanup) forever. - Guard the listener with a mutex and re-check the shutdown signal after bind so a shutdown requested in the bind window is not lost. - Honor shutdown during buffered-history replay too. Session fan-out - A slow subscriber that drops live lines now receives a namespaced gap notice when its channel drains, instead of silently losing output. - Hold the session lock across the (non-blocking) broadcast sends to close a latent send-on-closed-channel panic when a subscriber cancels mid-send. Single-instance lock - Reclaim a stale lock with an atomic rename-with-verify instead of a blind remove, so two instances starting at once cannot both reclaim and end up both holding the lock; a holder that reacquires in the gap is restored. Client + pool - Bound the control handshake with an I/O deadline so a peer that never replies can't wedge Dial/NewClientConn. - Key the active-worker map by a monotonic id rather than PID (the OS reuses PIDs the instant a worker exits). - Group-terminate on context cancel so a stuck worker's children are not orphaned.
ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Free Run ID: 📒 Files selected for processing (1)
WalkthroughSix hardening changes to ChangesDaemon Robustness Hardening
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Note 🎁 Summarized by CodeRabbit FreeYour organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login. Comment |
Zero automated PR reviewVerdict: No blockers found Blockers
Validation
ScopeHead: This deterministic review checks validation status and basic diff hygiene. A human reviewer still owns product judgment and design quality. |
…riant Session.Line holds s.mu across its non-blocking subscriber sends so cancel()/ finish() cannot close a subscriber channel mid-send (send-on-closed-channel panic). That invariant had no concurrency test. Add one that drives Line concurrently with Subscribe/cancel and finish; it panics with a data race if the lock-hold is reverted and passes with it (verified both ways under -race).
Vasanthdev2004
left a comment
There was a problem hiding this comment.
Reviewed the daemon hardening closely — this is the riskiest of the three and it holds up well. The bulk is materially safer than main and well-tested. Approving. One narrow P2 and one P3 are follow-ups, not blockers (details below).
Non-blocking follow-ups
[P2 — concurrency] reclaimStaleLock restore-rename can clobber a third daemon's fresh lock.
The restore at internal/daemon/lock.go:91 uses os.Rename(reclaimed, path), which on POSIX replaces whatever now sits at path. With 3 concurrent starts against a stale lock:
- Daemon A reads stale→dead, about to reclaim.
- Daemon C wins its own reclaim and creates a fresh O_EXCL lock at
path(C's live pid). - A runs
os.Rename(path, reclaimed)(lock.go:85), moving C's live lock aside. While it's sidelined, daemon D's O_EXCL create succeeds (path is empty) → D holds a lock. - A re-reads
reclaimed, sees C's live pid (lock.go:88), restores viaos.Rename(reclaimed, path)(lock.go:91) — replacing D's lock. Now C (restored pid) and D (create succeeded) both believe they hold it.
Needs 3 concurrent starts + a two-file-op window, and it's strictly less likely than the blind-Remove race this PR fixes — so the PR is a clear net improvement and I don't think it should block. Suggested fix: make the restore non-replacing (restore only if the target doesn't exist — os.Link/O_EXCL semantics — else os.Remove(reclaimed)), or read the pid before renaming and only rename-aside a confirmed-dead pid.
[P3 — comment] gapNotice/subscriber doc overstates recoverability. The comments say dropped lines "remain available via a fresh attach." The buffer is a ring capped at defaultSessionBuffer = 1024 that drops oldest lines once full, so a far-behind subscriber can lose lines that also aged out — a fresh attach won't recover them. The gap notice itself is the honest signal and is correct; just soften the comment to "available via a fresh attach if still within the ring window." No functional bug.
Verified-good (the substance)
- Lock writer: a partial pid write removes the file and fails (
lock.go:43-46), so no malformed lock is left to be misread as stale; the per-process sideline name (%s.stale.%d-%dwith pid + atomic seq) avoids self-collision. - Stdout integrity:
readerLinesswaps the cappedbufio.Scannerfor an uncappedbufio.Reader, so a large stream-json line from the trusted worker isn't dropped (the 1 MiB cap is only right for untrusted frames).TestReaderLinesHandlesLargeLine(2 MiB + no-trailing-newline) covers it. - Pool:
runOncenow Kills-then-Waits on a stdout read error and surfaces it instead of a bogus clean success (TestPoolRunSurfacesStdoutReadError); pid→monotonic-worker-id re-keying eliminates a pid-reuse map collision (D10). - Session fan-out: the lock is held across the non-blocking sends (every case has
default), closing the send-on-closed-channel race vscancel()/finish();TestSessionSlowSubscriberGetsGapNoticecovers the drop-count + gap flush. - Server lifecycle:
connstracking + Shutdown closing the listener and every tracked conn so blocked reads unblock andwg.Wait()finishes; the bind-window<-s.donecloses the shutdown-during-bind hole. Leak- and deadlock-free. - Client handshake deadline bounds only the hello exchange and clears before streaming (
TestClientHandshakeTimesOut); launchercmd.Cancelkills the whole process group instead of orphaning children.
Solid work — the one P2 is a narrower residual race than what's fixed. Recommend a fast follow-up on lock.go:91, but it shouldn't gate the merge.
A focused deep review of
internal/daemon— the worker pool, launcher, control server, session fan-out, and single-instance lock — surfaced a stdout-integrity bug plus several lifecycle and locking hazards. Each fix ships with a regression test; the daemon suite passes under-race, andgo build ./.../go vet/gofmtare clean.Worker stdout integrity
bufio.Scanner(64 KiB grow, 1 MiB hard cap). A legitimately large stream-json line from our own trusted worker (a big final answer or tool result) over the cap was dropped — the output simply vanished. Replaced with an uncappedbufio.Reader; the 1 MiB cap is correct only for untrusted network frames, not this local pipe.Wait.Control-server lifecycle
Shutdownclosed the listener but not in-flight connections, so a handler blocked on an idle/hostile client's read never returned andwg.Wait()hung (taking SIGTERM cleanup with it). Open connections are now tracked and closed on shutdown.Shutdownin the bind→serve window left the accept loop blocking forever on a connection that never comes. The listener is now mutex-guarded and the shutdown signal re-checked right after bind.Session fan-out
send on closed channel). The lock is now held across the non-blocking sends (which never block).Single-instance lock
Client + pool
Dial/NewClientConn.Tests
New/extended:
TestReaderLinesHandlesLargeLine,TestPoolRunSurfacesStdoutReadError,TestReclaimStaleLockRemovesDeadHolder,TestReclaimStaleLockRestoresLiveHolder,TestClientHandshakeTimesOut,TestSessionSlowSubscriberGetsGapNotice; shutdown/listener races are covered by the existing suite run under-race.Summary by CodeRabbit