Skip to content

Harden background daemon: stdout integrity, lifecycle, and single-instance lock - #274

Merged
gnanam1990 merged 2 commits into
mainfrom
fix/daemon-hardening
Jun 20, 2026
Merged

gnanam1990 merged 2 commits into
mainfrom
fix/daemon-hardening

Conversation

@gnanam1990

@gnanam1990 gnanam1990 commented Jun 20, 2026 •

Copy link
Copy Markdown
Collaborator

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, and go build ./... / go vet / gofmt are clean.

Worker stdout integrity

  • Large lines were silently dropped. A worker's stdout was read with a capped 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 uncapped bufio.Reader; the 1 MiB cap is correct only for untrusted network frames, not this local pipe.
  • Read errors were swallowed as success. A stdout read error ended the pump and the run reported a clean exit. It now surfaces as a run failure, and the worker is killed first so it can't block writing to the now-unread pipe and hang Wait.

Control-server lifecycle

  • An idle client could wedge shutdown forever. Shutdown closed the listener but not in-flight connections, so a handler blocked on an idle/hostile client's read never returned and wg.Wait() hung (taking SIGTERM cleanup with it). Open connections are now tracked and closed on shutdown.
  • A shutdown requested at startup could be lost. A Shutdown in 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.
  • Buffered-history replay now honors shutdown too, so a large buffer can't delay drain.

Session fan-out

  • Slow subscribers silently lost output. A subscriber whose channel filled had lines dropped with no indication. It now receives a namespaced gap notice when the channel drains, so a lagging consumer learns its stream is incomplete (full output remains available via a fresh attach).
  • Latent panic. The broadcast copied the subscriber set outside the lock, so a subscriber cancelling mid-send could close a channel the broadcaster was about to send on (send on closed channel). The lock is now held across the non-blocking sends (which never block).

Single-instance lock

  • Two instances could both "hold" the lock. Stale-lock reclaim did a blind remove, so two daemons starting at once could both remove-and-recreate and end up both holding the single-instance lock. Reclaim now uses an atomic rename-with-verify: only one racer wins the rename, and a holder that reacquires in the gap is restored rather than stolen.

Client + pool

  • Bound the control handshake with an I/O deadline so a peer that accepts but never replies can't wedge Dial/NewClientConn.
  • Key the active-worker map by a monotonic worker id rather than PID — the OS reuses a PID the instant a worker exits, which could drop the wrong handle.
  • Group-terminate on context cancel so a stuck worker's children aren't orphaned.

Tests

New/extended: TestReaderLinesHandlesLargeLine, TestPoolRunSurfacesStdoutReadError, TestReclaimStaleLockRemovesDeadHolder, TestReclaimStaleLockRestoresLiveHolder, TestClientHandshakeTimesOut, TestSessionSlowSubscriberGetsGapNotice; shutdown/listener races are covered by the existing suite run under -race.

Summary by CodeRabbit

  • Bug Fixes
    • Improved stale lock reclamation to avoid conflicting lock states
    • Enhanced process group termination and stdout error handling to prevent hanging workers
  • New Features
    • Added timeout protection to control connection handshakes
    • Slow session subscribers now receive gap notifications for missed output
  • Improvements
    • Strengthened server shutdown coordination with active connection tracking
    • Improved handling of large streamed lines and tighter worker output failure detection

…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.
@coderabbitai

coderabbitai Bot commented Jun 20, 2026 •

Copy link
Copy Markdown

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: c47723a5-b3bd-4d03-8a2e-cd73924b1ee7

📥 Commits

Reviewing files that changed from the base of the PR and between 49e8317 and 09e6ec1.

📒 Files selected for processing (1)
  • internal/daemon/session_race_test.go

Walkthrough

Six hardening changes to internal/daemon: a 10-second handshake timeout on the client control socket; race-safe stale-lock reclamation via atomic rename; process-group cancellation and a bufio.Reader-based line reader without token size limits; pool worker tracking keyed by monotonic id with stdout-error propagation; server connection tracking enabling clean shutdown draining; and session gap notices emitted to slow subscribers.

Changes

Daemon Robustness Hardening

Layer / File(s) Summary
Session slow-subscriber gap notices
internal/daemon/session.go, internal/daemon/session_test.go, internal/daemon/session_race_test.go
Introduces subscriber struct with dropped counter and gapNotice() helper emitting daemon_gap JSON events. Session.Line holds mu across non-blocking sends, flushes a gap notice before the next line when drops are pending, and increments the counter on channel-full. finish and Subscribe updated to use *subscriber. Functional test verifies a slow subscriber receives exactly one gap notice then the resumed line. Race test exercises concurrent subscribe/cancel with Line pumping and finish.
Server connection tracking and shutdown draining
internal/daemon/server.go
Adds mu sync.Mutex and conns map[net.Conn]struct{} to Server, initialized in NewServer. Accept loop calls trackConn/untrackConn per connection. Shutdown closes all tracked connections under the mutex to unblock any blocked reads. Serve checks for already-fired shutdown after binding and closes listener early if needed. streamToClient ends history replay early with CtrlEnd on shutdown.
Pool id-keyed tracking and stdout-error surfacing
internal/daemon/pool.go, internal/daemon/pool_test.go
Switches active map from OS-pid keys to monotonic pool worker ids in track/untrack and runOnce. Stdout read errors now force-kill the worker, wait for exit, and return (-1, error) instead of proceeding normally. WorkerStats iterates map values for Pid(). Test double updated with outErr field; new test asserts pool.Run returns non-nil and worker is killed on stdout read failure.
Launcher: readerLines and process-group cancellation
internal/daemon/launcher.go, internal/daemon/readerlines_test.go
Replaces bufio.Scanner-based scannerLines with readerLines using bufio.Reader: no token size cap, strips \r\n, returns final unterminated line at EOF. execWorker.lines field uses the Lines interface. cmd.Cancel overridden to call background.TerminateProcess on the full process group instead of context's default leader-only kill. Worker wired with bufio.NewReaderSize(stdout, 64*1024). Test validates lines larger than 1 MiB read cleanly.
Client handshake timeout
internal/daemon/client.go, internal/daemon/client_test.go
Adds handshakeTimeout (10 s) and sets a connection deadline in Client.handshake() before CtrlHello send/reply, cleared via defer so downstream streaming is unaffected. Test uses net.Pipe with a server that never responds, asserting NewClientConn returns an error before the deadline.
Race-safe stale-lock reclamation
internal/daemon/lock.go, internal/daemon/lock_test.go
Imports sync/atomic for a per-process sequence counter. Replaces blind-delete retry in acquireLock with reclaimStaleLock: renames to a unique sidelined path, re-reads the PID, removes if dead or restores if alive in the race window, returning whether reclamation succeeded. Two tests cover dead-holder (file removed) and live-holder (file restored, no stale side files).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes


Note

🎁 Summarized by CodeRabbit Free

Your 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 @coderabbitai help to get the list of available commands and usage tips.

@github-actions

github-actions Bot commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor

Zero automated PR review

Verdict: No blockers found

Blockers

  • None found.

Validation

  • [pass] Diff hygiene: git diff --check
  • [pass] Tests: go test ./...
  • [pass] Build: go run ./cmd/zero-release build
  • [pass] Smoke build: go run ./cmd/zero-release smoke

Scope

Head: 09e6ec127aee
Changed files (12): internal/daemon/client.go, internal/daemon/client_test.go, internal/daemon/launcher.go, internal/daemon/lock.go, internal/daemon/lock_test.go, internal/daemon/pool.go, internal/daemon/pool_test.go, internal/daemon/readerlines_test.go, internal/daemon/server.go, internal/daemon/session.go, internal/daemon/session_race_test.go, internal/daemon/session_test.go

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 Vasanthdev2004 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 via os.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-%d with pid + atomic seq) avoids self-collision.
  • Stdout integrity: readerLines swaps the capped bufio.Scanner for an uncapped bufio.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: runOnce now 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 vs cancel()/finish(); TestSessionSlowSubscriberGetsGapNotice covers the drop-count + gap flush.
  • Server lifecycle: conns tracking + Shutdown closing the listener and every tracked conn so blocked reads unblock and wg.Wait() finishes; the bind-window <-s.done closes the shutdown-during-bind hole. Leak- and deadlock-free.
  • Client handshake deadline bounds only the hello exchange and clears before streaming (TestClientHandshakeTimesOut); launcher cmd.Cancel kills 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.

@gnanam1990
gnanam1990 merged commit fbbfdbf into main Jun 20, 2026
11 of 12 checks passed
@Vasanthdev2004
Vasanthdev2004 deleted the fix/daemon-hardening branch June 28, 2026 08:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants