Skip to content

fix(file): fsync file and directory in atomic writes; sync the CNI plugin install dir (#772) - #779

Merged
bpalermo merged 2 commits into
mainfrom
fix/772-a6c-atomic-write-fsync
Sep 15, 2026
Merged

bpalermo merged 2 commits into
mainfrom
fix/772-a6c-atomic-write-fsync

Conversation

@bpalermo

Copy link
Copy Markdown
Owner

Phase A6c of #772. Data-path adjacent (mesh-DNS snapshot + CNI conflist writers); gets the batch hitless-rollout validation on talos-main with the rest of Phase A.

fix(common/file): fsync the file before the rename and the directory after (#772)

S23: AtomicWriteReader renamed the temp file into place without fsyncing it,
and neither it nor its sibling WriteFileAtomic ever fsynced the parent
directory. The rename is atomic for readers, but atomicity is not durability:
after a power cut the destination can come back zero-length, or the directory
entry can be rolled back entirely. That path writes the mesh-DNS record
snapshot (meshdns/server.go:438) and the CNI conflist
(cniconflist/reassert.go:255, cni/internal/install/cniconfig.go:101) — the
two artefacts whose loss took the fleet out on 2026-08-29 (#645), on a cluster
with four power incidents on record.

  • common/file/file.go: collapse WriteFileAtomic and AtomicWriteReader
    onto one writeAtomic body. The bug existed precisely because two
    near-identical copies drifted and only one of them synced; there is now one
    place to drift from. Both fsync the temp file before Close/Rename and
    fsync the destination directory after the rename, and a failure of either is
    returned rather than swallowed. Temp-file naming, permissions (0600 default
    for WriteFileAtomic, explicit mode for AtomicWrite*) and the
    FADV_DONTNEED hint are unchanged; the hint now runs after the fsync, where
    it actually evicts (it only drops clean pages).
  • common/file/dirsync_unix.go / dirsync_windows.go: new syncDir, keeping
    the package's platform-file structure. Opening the directory O_RDONLY and
    fsyncing it is the portable POSIX form. A filesystem that does not implement
    it (EINVAL/ENOTSUP/ENOSYS/EPERM/EACCES) is best-effort — the added durability
    is not worth failing a CNI conflist write over — while real I/O failures
    (EIO, ENOSPC) surface. No-op on Windows, which cannot open a directory.
  • common/file/fadvise_{linux,unspecified}.go: markNotNeeded takes the fd
    instead of *os.File, so the write path can go through the small syncFile
    interface the tests substitute.
  • common/file/sync_test.go: asserts the fsync actually happens (after the
    payload, before Close), that the directory fsync happens after the rename,
    and that a failing file or directory fsync surfaces as an error with the
    destination left untouched and no temp file behind — an unsynced rename must
    never be reported as a successful write. All three exported writers are
    pinned to the contract.
  • cni/internal/install/install.go: the one caller that bypasses this package.
    renameio's CloseAtomicallyReplace fsyncs the file but never the parent
    directory, so the newly installed plugin binary's directory entry was not
    durable; it now calls the exported file.SyncDir.

Caller audit / cost. Measured on the workstation NVMe (ext4) and tmpfs, 300
writes, 512 B and 8 KiB payloads:

ext4/NVMe no sync 98 us | file fsync 3.43 ms | + dir fsync 6.77 ms (148/s)
tmpfs no sync 57 us | file fsync 46 us | + dir fsync 67 us (14.9k/s)

Each fsync on this disk costs ~3.3 ms. The hot caller is agent/storage
(local.go:91), one write per CNI ADD/DEL under f.mu; at the observed
17 writes/s that is ~116 ms/s of blocking I/O against a ~148 writes/s ceiling,
and only +3.3 ms/write versus today since WriteFileAtomic already fsynced the
file. The other callers are cold: the mesh-DNS snapshot writes on a record
change plus one 60 s freshness heartbeat, the observed-upstreams store is
debounced, and the conflist/plugin installs are one-shot. No WithoutSync
escape hatch is warranted.

Bypass grep (os.Rename|renameio outside common/file): cni/internal/install
fixed here; agent/internal/proxy/hotrestart/coordination.go:132 and
agent/internal/cmd/supervisor.go:131 (S24/S25) are deliberately left alone —
they belong to the supervisor work in phase A5 of #772.

Verification: bazel build //... //test/e2e:e2e_test, bazel test //...
(100 pass), bazel run //:format.check, bazel build --config=lint --@aspect_rules_lint//lint:fail_on_violation //..., bazel run //:gazelle no
churn, bazel mod tidy idempotent, scripts/go-deps-audit.sh exit 0.

🤖 Generated with Claude Code

https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

bpalermo and others added 2 commits September 15, 2026 19:40
…after (#772)

S23: `AtomicWriteReader` renamed the temp file into place without fsyncing it,
and neither it nor its sibling `WriteFileAtomic` ever fsynced the parent
directory. The rename is atomic for readers, but atomicity is not durability:
after a power cut the destination can come back zero-length, or the directory
entry can be rolled back entirely. That path writes the mesh-DNS record
snapshot (`meshdns/server.go:438`) and the CNI conflist
(`cniconflist/reassert.go:255`, `cni/internal/install/cniconfig.go:101`) — the
two artefacts whose loss took the fleet out on 2026-08-29 (#645), on a cluster
with four power incidents on record.

- `common/file/file.go`: collapse `WriteFileAtomic` and `AtomicWriteReader`
  onto one `writeAtomic` body. The bug existed precisely because two
  near-identical copies drifted and only one of them synced; there is now one
  place to drift from. Both fsync the temp file before `Close`/`Rename` and
  fsync the destination directory after the rename, and a failure of either is
  returned rather than swallowed. Temp-file naming, permissions (0600 default
  for `WriteFileAtomic`, explicit mode for `AtomicWrite*`) and the
  `FADV_DONTNEED` hint are unchanged; the hint now runs after the fsync, where
  it actually evicts (it only drops clean pages).
- `common/file/dirsync_unix.go` / `dirsync_windows.go`: new `syncDir`, keeping
  the package's platform-file structure. Opening the directory O_RDONLY and
  fsyncing it is the portable POSIX form. A filesystem that does not implement
  it (EINVAL/ENOTSUP/ENOSYS/EPERM/EACCES) is best-effort — the added durability
  is not worth failing a CNI conflist write over — while real I/O failures
  (EIO, ENOSPC) surface. No-op on Windows, which cannot open a directory.
- `common/file/fadvise_{linux,unspecified}.go`: `markNotNeeded` takes the fd
  instead of `*os.File`, so the write path can go through the small `syncFile`
  interface the tests substitute.
- `common/file/sync_test.go`: asserts the fsync actually happens (after the
  payload, before `Close`), that the directory fsync happens after the rename,
  and that a failing file or directory fsync surfaces as an error with the
  destination left untouched and no temp file behind — an unsynced rename must
  never be reported as a successful write. All three exported writers are
  pinned to the contract.
- `cni/internal/install/install.go`: the one caller that bypasses this package.
  renameio's `CloseAtomicallyReplace` fsyncs the file but never the parent
  directory, so the newly installed plugin binary's directory entry was not
  durable; it now calls the exported `file.SyncDir`.

Caller audit / cost. Measured on the workstation NVMe (ext4) and tmpfs, 300
writes, 512 B and 8 KiB payloads:

  ext4/NVMe  no sync 98 us  | file fsync 3.43 ms | + dir fsync 6.77 ms (148/s)
  tmpfs      no sync 57 us  | file fsync 46 us   | + dir fsync 67 us  (14.9k/s)

Each fsync on this disk costs ~3.3 ms. The hot caller is `agent/storage`
(`local.go:91`), one write per CNI ADD/DEL under `f.mu`; at the observed
17 writes/s that is ~116 ms/s of blocking I/O against a ~148 writes/s ceiling,
and only +3.3 ms/write versus today since `WriteFileAtomic` already fsynced the
file. The other callers are cold: the mesh-DNS snapshot writes on a record
change plus one 60 s freshness heartbeat, the observed-upstreams store is
debounced, and the conflist/plugin installs are one-shot. No `WithoutSync`
escape hatch is warranted.

Bypass grep (`os.Rename|renameio` outside `common/file`): `cni/internal/install`
fixed here; `agent/internal/proxy/hotrestart/coordination.go:132` and
`agent/internal/cmd/supervisor.go:131` (S24/S25) are deliberately left alone —
they belong to the supervisor work in phase A5 of #772.

Verification: `bazel build //... //test/e2e:e2e_test`, `bazel test //...`
(100 pass), `bazel run //:format.check`, `bazel build --config=lint
--@aspect_rules_lint//lint:fail_on_violation //...`, `bazel run //:gazelle` no
churn, `bazel mod tidy` idempotent, `scripts/go-deps-audit.sh` exit 0.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
@bpalermo
bpalermo merged commit 87945fd into main Sep 15, 2026
19 checks passed
@bpalermo
bpalermo deleted the fix/772-a6c-atomic-write-fsync branch September 15, 2026 23:43
bpalermo added a commit that referenced this pull request Sep 16, 2026
)

S24/S25 from the 2026-09-15 race review.

S24 CONFIRMED, two sites, both bypassing common/file with a FIXED temp filename
and no fsync:

- agent/internal/cmd/supervisor.go installFile staged at `dest + ".tmp"` and
  renamed without flushing. What it publishes is an EXECUTABLE that the proxy
  container then runs as its entrypoint, so an un-fsynced rename can survive a
  node crash as a directory entry pointing at data that was never written, and
  a fixed temp path is a collision waiting for any second writer.
- agent/internal/proxy/hotrestart/coordination.go writeState staged at
  `<statePath>.tmp` on the SHARED hostPath StateDir. The flock around the
  read-check-write is explicitly best-effort ("a lock failure falls back to the
  unlocked behavior"), and on that fallback two overlapping supervisor pods
  write the same temp path — so the rename can publish the other process's
  half-written bytes into the file that decides the next pod's restart epoch.

Both now go through common/file (AtomicWriteReader / AtomicWrite): os.CreateTemp
for a per-writer name, and the flush-before-rename that PR #779 is adding there,
which both sites then inherit for free.

S25 REFUTED as a defect, and annotated in place: coordination.go setReady's
plain os.WriteFile on the readiness marker is correct. The marker is a pod-local
emptyDir file whose only reader (//agent/cmd/proxy-ready via readymarker.Check)
tests for existence and never reads a byte — no torn read to prevent, no second
writer, and nothing worth making durable across a crash. An atomic write would
add a temp file and an fsync to the supervisor's hottest path for no observable
gain. Left as is with a comment saying why.

Tests: TestInstallFile gains a concurrent-installs case (8 writers, same
destination, a payload large enough to splice) asserting the published file is
whole and that no staging file of ANY name survives — the previous assertion
only knew to look for the old fixed `dest + ".tmp"`.

Verification: bazel test //agent/internal/cmd/... //agent/internal/proxy/...
passes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
bpalermo added a commit that referenced this pull request Sep 16, 2026
… the grace budget, fix epoch bookkeeping, atomic file publishes (#771, #772) (#785)

* fix(proxy-supervisor): probe the admin endpoint on a detached ctx at shutdown (#771) (#772)

handleShutdown has exactly one call site — `case <-lp.ctx.Done()` in
restartLoop.run — so the context it is handed is ALWAYS already cancelled by
controller-runtime's signal handler. It passed that context straight into the
epoch-identity probe (adminLiveAtEpoch -> adminServerInfo ->
context.WithTimeout on an already-cancelled parent), so http.Client.Do failed
with "context canceled" in microseconds without ever opening a socket.
`!adminLiveAtEpoch(...)` was therefore true on every SIGTERM regardless of
Envoy's actual state, and the "termination requested mid-handoff; waiting for
successor" branch was taken unconditionally — including when Envoy was LIVE at
our own epoch and no successor existed, in which case Envoy was never drained.

Measured on talos-main (issue #771 reproduction): both sampled pods recorded
`aether_supervisor_admin_probes_total{probe_endpoint="server_info",
result="unreachable"}` exactly once in a 2d21h lifetime — at their SIGTERM —
while `result="live"` was still climbing +10/30s on the same series and
`envoy_server_state` was 0 (LIVE). The mid-handoff line was logged 194ms/195ms
after the delete, 4.3-6.3s before any successor Envoy started.

Fix: run the probe on a context detached from the caller's, keeping its values
but not its cancellation, bounded by shutdownProbeTimeout. This is the same
trap and the same idiom as common/telemetry/setup/lifecycle.go's
DetachedTimeout (issue #662). The branch semantics are unchanged: admin LIVE at
our epoch -> drain; not LIVE at our epoch (a successor has taken the admin
port) -> leave Envoy alone for the successor's parent-shutdown protocol.

Tests (agent/internal/proxy/hotrestart/shutdown_test.go), both driving
handleShutdown with an already-cancelled context against a production-shaped
supervisor (StateDir set, real admin address, a live tracked child at epoch 0):
- LIVE at our own epoch -> drain branch taken, child SIGTERMed and reaped, and
  the fake admin's /server_info hit counter advanced (i.e. the probe really
  reached the network).
- LIVE at epoch 1 -> the genuine mid-handoff case: still blocks, child
  untouched, and the decision was again made off a real probe.
Reverting the WithoutCancel makes the first test fail with "handleShutdown
blocked: the drain branch was not taken", which is the production bug verbatim.

Verification: bazel test //agent/internal/proxy/... passes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

* fix(proxy-supervisor,chart): bound the mid-handoff wait by the pod's own grace period (#771) (#772)

awaitProtocolTermination was a bare `<-s.childExited` loop with no deadline and
no context, so a termination where no successor can ever appear — graceful node
shutdown, node deletion / scale-down, `kubectl delete daemonset` or a chart
uninstall, or a replacement stuck Pending/ImagePullBackOff/unschedulable —
blocked until the kubelet's SIGKILL at terminationGracePeriodSeconds with Envoy
never SIGTERMed and connections still open. With #771's ctx fix that branch is
now entered only when admin really answers at another epoch, but the residual
exposure is real, and it is precisely the case a `kubectl delete pod` cannot
reproduce (the DaemonSet's replacement hot-restarts the parent within ~1s, so a
delete self-rescues into the surge path).

The fix is deliberately NOT a blind timer. The function's own comment explains
why there wasn't one: the successor's parent-shutdown timer starts only after
its xDS-gated, unbounded init, and it keeps using the parent socket for stat
merges right up to protocol-terminate, so cutting a healthy handoff short
aborts the successor with errno 111 (the 2026-06-11 node data-plane gap). The
only non-arbitrary bound is the pod's own death sentence, so the supervisor is
now told what it is:

- Config.TerminationGrace / --termination-grace, passed by the chart from the
  same value it sets on terminationGracePeriodSeconds (0 = unknown = wait
  indefinitely, i.e. the previous behavior, which is what every older chart
  and every unit-test supervisor gets).
- successorWaitBudget = TerminationGrace - (DrainTime + shutdownGrace) -
  terminationFallbackMargin(10s): wait as long as the pod has, minus what the
  drain will then cost, minus head-room. Deployed values give 155s of 180s. A
  grace period too small to fit a drain yields 0 and keeps waiting rather than
  guaranteeing an errno-111 abort.
- On expiry: log at WARN with the epoch state observed at that moment (a fresh
  probe, again on a detached context), then s.shutdown() — SIGTERM every
  tracked epoch and reap, so Envoy drains and exits 0 before the SIGKILL.

Also fixes the stale comment at the top of handleShutdown, which promised "a
deadline fallback" that did not exist; the function comment on
awaitProtocolTermination said the opposite. Both now describe the same thing.

Chart: proxy.terminationGracePeriodSeconds (default 180, unchanged behavior)
replaces the hard-coded literal and feeds both the pod spec and the new flag.
charts/aether bumped 0.92.19 -> 0.92.20.

Tests:
- TestSuccessorWaitBudget pins the arithmetic at the deployed values, at an
  unset grace, and at a grace too small to fit a drain.
- TestHandleShutdownFallsBackToDrainWhenNoSuccessorComes: admin LIVE at a newer
  epoch (mid-handoff branch correctly entered) with nothing ever terminating
  our Envoy — the wait expires at the budget, not before it, and the child is
  drained and reaped.

Verification: bazel test //agent/internal/proxy/... //agent/internal/cmd/...
passes; `helm template` renders terminationGracePeriodSeconds: 180 and
--termination-grace=180s.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

* fix(proxy-supervisor): epoch bookkeeping — no key reuse, no epoch bump before fork, atomic gate publish, readiness held across retries (#772)

The four epoch findings from the 2026-09-15 race review (S14-S17), all four
confirmed from the code and all four reachable only through the bind-collision
retry path, which is why none of them shows up in a normal roll.

S14 (supervisor.go, hotRestart): `s.children[epoch] = cmd` could reuse a key
whose child is still tracked. resetEpochForRetry rewinds nextEpoch to 0 on every
retry and initStartEpoch leaves it there when the heartbeat is stale, so a
relaunch overwrote the *exec.Cmd of a still-draining epoch-0 Envoy. The draining
process was then orphaned (signalEpoch resolves epoch 0 to the new cmd, so
shutdown() never signals it), awaitProtocolTermination's pending count
undercounted it, and its eventual exit could take the container down non-zero
while the new Envoy was healthy. Fix: reserveEpoch() advances past any epoch
still present in children and logs when it does. A tracked child at E also means
E's base-id domain socket is still held, so E+1 is both the safe map key and the
correct hot-restart epoch to attach at — no restructuring of the children map.

S15 (same function): nextEpoch was incremented BEFORE cmd.Start(), with no
rollback. A fork failure is non-fatal on the handleDebounce path ("keeping
current epoch"), so currentEpoch() was left naming an epoch with no child — and
both wedge watchdogs and the readiness hold are gated on childTracked(epoch), so
none of them could fire again: pod NotReady forever, no watchdog, old Envoy
still serving. Fix: publish nextEpoch only after Start() succeeds.

S16 (coordination.go, initStartEpoch): the successor readiness gate was set by a
separate gateReadinessIfSuccessor() call AFTER nextEpoch was published. A
watchLiveness tick landing in that window reads the successor epoch E and finds
the PREDECESSOR's Envoy answering LIVE at exactly E, so it marks the pod Ready
before this pod's Envoy has been forked — #132's hazard re-entering through the
retry path, where the previous gate is certainly stale (retries run up to 4.5min
against a 15s parent-shutdown-time). Fix: nextEpoch and readyGate are now
published in one critical section; gateReadinessIfSuccessor and setReadyGate are
gone.

S17 (coordination.go, onNotLiveEpoch): the readiness hold asked
childTracked(currentEpoch()). Between resetEpochForRetry and the relaunch —
which includes initStartEpoch's up-to-8s re-probe loop — currentEpoch() is -1,
an epoch that never had a child, so a supervisor that was Ready on epoch 0 and
lost a just-forked epoch 1 to a bind collision cleared its ready marker (and
recorded ready_transitions{ready=false}) for the whole retry while its epoch-0
Envoy was still serving every request on the node. Fix: hold on
anyChildTracked() — "is one of our Envoy processes still serving this node?" —
which is the question the hold was always documented to be asking. This is a
candidate mechanism for the still-open proxy readiness-marker flap seen on
w01/w05 in the 2026-09-03 soak.

Tests (agent/internal/proxy/hotrestart/epoch_test.go), one per finding:
- TestReserveEpochNeverReusesATrackedEpoch: relaunch with epoch 0 still tracked
  lands on epoch 1, both children stay independently addressable.
- TestHotRestartDoesNotAdvanceEpochWhenStartFails: after a failed fork,
  currentEpoch() still names a tracked child.
- TestInitStartEpochPublishesEpochAndGateTogether (+ a no-predecessor control):
  initStartEpoch alone must leave the gate in the future.
- TestReadinessHeldWhileAnEarlierEpochStillServes: hold at epoch -1 with epoch 0
  tracked; clear once nothing of ours is left.

Verification: bazel test //agent/internal/proxy/... passes, including the
existing #132 hold test (TestReadinessHeldWhileServingParentMidHandoff) and the
bind-collision retry test.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

* fix(proxy-supervisor): route the atomic writes through common/file (#772)

S24/S25 from the 2026-09-15 race review.

S24 CONFIRMED, two sites, both bypassing common/file with a FIXED temp filename
and no fsync:

- agent/internal/cmd/supervisor.go installFile staged at `dest + ".tmp"` and
  renamed without flushing. What it publishes is an EXECUTABLE that the proxy
  container then runs as its entrypoint, so an un-fsynced rename can survive a
  node crash as a directory entry pointing at data that was never written, and
  a fixed temp path is a collision waiting for any second writer.
- agent/internal/proxy/hotrestart/coordination.go writeState staged at
  `<statePath>.tmp` on the SHARED hostPath StateDir. The flock around the
  read-check-write is explicitly best-effort ("a lock failure falls back to the
  unlocked behavior"), and on that fallback two overlapping supervisor pods
  write the same temp path — so the rename can publish the other process's
  half-written bytes into the file that decides the next pod's restart epoch.

Both now go through common/file (AtomicWriteReader / AtomicWrite): os.CreateTemp
for a per-writer name, and the flush-before-rename that PR #779 is adding there,
which both sites then inherit for free.

S25 REFUTED as a defect, and annotated in place: coordination.go setReady's
plain os.WriteFile on the readiness marker is correct. The marker is a pod-local
emptyDir file whose only reader (//agent/cmd/proxy-ready via readymarker.Check)
tests for existence and never reads a byte — no torn read to prevent, no second
writer, and nothing worth making durable across a crash. An atomic write would
add a temp file and an fsync to the supervisor's hottest path for no observable
gain. Left as is with a comment saying why.

Tests: TestInstallFile gains a concurrent-installs case (8 writers, same
destination, a payload large enough to splice) asserting the published file is
whole and that no staging file of ANY name survives — the previous assertion
only knew to look for the old fixed `dest + ".tmp"`.

Verification: bazel test //agent/internal/cmd/... //agent/internal/proxy/...
passes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

* chore(charts): re-bump aether chart to 0.92.21 after the proxy-pin bump on main (#772)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
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.

1 participant