carlos / platform Public

HA P1a #433: the startup sweep survives an agent restart

Root's cached view of the edge's main pid lagged each agent restart, so
the new agent's first call, the startup sweep, was refused with "peer
pid <new> is not the edge's main pid <previous>" and the box never
counted as swept: same-box recovery of an HA host could never run.

Root (instancectl): the peer decision moves into edgePeer. A peer the
cached answer refuses (a stale pid or a cached failure) is checked once
against a fresh systemctl read and accepted only if systemd names it
now; forced reads are at most one per 100 ms. Nothing wider is accepted.

Agent (belt): startActivator retries a failed sweep up to five tries
(1, 2, 4, 8 s waits, within 20 s of the first) before recovery and Start,
so no wake can begin while one is pending. A box with no control socket
is not retried. On final failure it serves unswept as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev d12b1d3593e0ed6a2b3551d9004aa8aac2e59402 parent fc30b42
5 files changed, +385 −54
  • internal/host/agent_layout_test.go +87 −4
  • internal/host/layoutleg.go +43 −0
  • internal/instancectl/peer_edge.go +115 −0
  • internal/instancectl/peer_edge_test.go +120 −0
  • internal/instancectl/peer_linux.go +20 −50
diff --git a/internal/host/agent_layout_test.go b/internal/host/agent_layout_test.go
index 849a38bc0..b354e7861 100644
--- a/internal/host/agent_layout_test.go
+++ b/internal/host/agent_layout_test.go
@@ -3,6 +3,7 @@ package host
import (
"context"
"errors"
+ "fmt"
"os"
"path/filepath"
"reflect"
@@ -244,16 +245,33 @@ func TestLayoutLegNeverLosesAKick(t *testing.T) {
}
}
+// fastSweepRetries makes startActivator's retry waits a millisecond each
+// for one test, and puts them back after it.
+func fastSweepRetries(t *testing.T) {
+ t.Helper()
+ backoff, window := startupSweepBackoff, startupSweepWindow
+ startupSweepBackoff = []time.Duration{time.Millisecond, time.Millisecond, time.Millisecond, time.Millisecond}
+ startupSweepWindow = time.Minute
+ t.Cleanup(func() { startupSweepBackoff, startupSweepWindow = backoff, window })
+}
+
// Recovery runs after the startup unit sweep and before the activator
-// starts, and it runs even when the sweep failed, told so.
+// starts, and it runs even when the sweep failed, told so. A sweep that
+// keeps failing is tried once and retried len(startupSweepBackoff) times
+// first (#433).
func TestStartActivatorRecoversAfterTheSweepAndBeforeStart(t *testing.T) {
+ fastSweepRetries(t)
for _, tc := range []struct {
name string
sweepErr error
swept bool
+ sweeps int
}{
- {"sweep ok", nil, true},
- {"sweep failed", errors.New("channel down"), false},
+ {"sweep ok", nil, true, 1},
+ {"sweep failed", errors.New("channel down"), false, 5},
+ // No control socket at all: a box without the channel, not a
+ // refusal that may clear, so it is not retried.
+ {"no socket", fmt.Errorf("instance control socket /run/x.sock: %w", os.ErrNotExist), false, 1},
} {
t.Run(tc.name, func(t *testing.T) {
var events []string
@@ -262,7 +280,11 @@ func TestStartActivatorRecoversAfterTheSweepAndBeforeStart(t *testing.T) {
func(context.Context) error { events = append(events, "sweep"); return tc.sweepErr },
func(_ context.Context, swept bool) { events = append(events, "recover"); gotSwept = swept },
func() { events = append(events, "start") })
- if want := []string{"sweep", "recover", "start"}; !reflect.DeepEqual(events, want) {
+ var want []string
+ for range tc.sweeps {
+ want = append(want, "sweep")
+ }
+ if want = append(want, "recover", "start"); !reflect.DeepEqual(events, want) {
t.Fatalf("order = %v, want %v", events, want)
}
if gotSwept != tc.swept {
@@ -272,6 +294,67 @@ func TestStartActivatorRecoversAfterTheSweepAndBeforeStart(t *testing.T) {
}
}
+// #433: root refused the new agent's first call, the startup sweep,
+// because its view of the edge's main pid lagged the restart. The sweep is
+// retried before anything can wake, so the box counts as swept
+// (seedSweptAtStart, which same-box recovery of an HA host needs) and the
+// activator starts only after the sweep that succeeded.
+func TestStartupSweepRetriesARefusalBeforeAnyWake(t *testing.T) {
+ fastSweepRetries(t)
+ prev := seedSweptAtStart.Load()
+ t.Cleanup(func() { seedSweptAtStart.Store(prev) })
+ seedSweptAtStart.Store(false)
+ var events []string
+ sweeps := 0
+ done := activatorStart{
+ Sweep: func(context.Context) error {
+ sweeps++
+ events = append(events, "sweep")
+ if sweeps == 1 {
+ return errors.New("instance control socket /run/carlos/control.sock: EOF")
+ }
+ return nil
+ },
+ Recover: func(_ context.Context, swept bool) *layout.Pass {
+ seedSweptAtStart.Store(swept)
+ events = append(events, "recover")
+ return nil
+ },
+ Publish: func(*layout.Pass) {},
+ Start: func() {
+ if !seedSweptAtStart.Load() {
+ t.Error("the activator started with the box unswept")
+ }
+ events = append(events, "start")
+ },
+ Ready: func() { events = append(events, "ready") },
+ Routes: func() ([]registry.Route, error) { return nil, nil },
+ }.Run(t.Context())
+ <-done
+ if want := []string{"sweep", "sweep", "recover", "start", "ready"}; !reflect.DeepEqual(events, want) {
+ t.Fatalf("events = %v, want %v", events, want)
+ }
+ if !seedSweptAtStart.Load() {
+ t.Fatal("seedSweptAtStart false after the retried sweep succeeded")
+ }
+}
+
+// The retries stop at the window: a sweep that hangs to its own deadline
+// is not tried again, so the box never waits minutes before it serves.
+func TestStartupSweepRetriesStopAtTheWindow(t *testing.T) {
+ fastSweepRetries(t)
+ startupSweepWindow = 0
+ sweeps := 0
+ var gotSwept = true
+ startActivator(context.Background(),
+ func(context.Context) error { sweeps++; return errors.New("refused") },
+ func(_ context.Context, swept bool) { gotSwept = swept },
+ func() {})
+ if sweeps != 1 || gotSwept {
+ t.Fatalf("sweeps = %d, swept = %v; want one sweep, unswept", sweeps, gotSwept)
+ }
+}
+
// The intent recovery runs under at start: "" when none applies, the
// recorded mode when one does, and IntentUnreadable whenever the box
// cannot be sure, which holds a completed revert fenced.
diff --git a/internal/host/layoutleg.go b/internal/host/layoutleg.go
index 5974e697f..96a069325 100644
--- a/internal/host/layoutleg.go
+++ b/internal/host/layoutleg.go
@@ -9,7 +9,9 @@ package host
import (
"context"
+ "errors"
"fmt"
+ "io/fs"
"log"
"os"
"os/user"
@@ -350,13 +352,54 @@ func newLayoutPass(reg *registry.Registry, svc *activator.Service, dd string, ne
return p
}
+// startupSweepBackoff is the wait before each retry of a failed startup
+// sweep: five tries over 15 s of waiting. startupSweepWindow bounds them
+// from the first try, so a sweep that hangs to its own deadline is not
+// tried again. Variables only so tests can shorten them.
+var (
+ startupSweepBackoff = []time.Duration{time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second}
+ startupSweepWindow = 20 * time.Second
+)
+
// startActivator is the order the activator comes up in. The startup unit
// sweep first, so nothing an earlier agent left is running. Then layout
// recovery, which runs even when the sweep failed (completing a journal
// is exact) and is told whether it succeeded. Then Start, so no host is
// woken while a journal says its files are between two directories.
+//
+// A failed sweep is retried (#433): root refused the new agent's first
+// call while its view of the edge's main pid lagged the restart, and a box
+// whose sweep failed can never retake an HA host on its own (same-box
+// recovery needs the sweep). The retries all run here, before Start, so
+// no wake can begin while one is pending: a sweep stops every instance
+// unit, and it must never run after wakes may have started. They wait
+// startupSweepBackoff between tries and stop once the next try would
+// begin past startupSweepWindow from the first, or when ctx ends; then
+// the box carries on unswept, as before, and same-box recovery stays
+// refused (and alarmed by the activator) until the agent restarts. A box
+// with no control socket at all is not retried: that is not a refusal
+// that can clear.
func startActivator(ctx context.Context, sweep func(context.Context) error, recoverLayout func(ctx context.Context, swept bool), start func()) {
+ deadline := time.Now().Add(startupSweepWindow)
err := sweep(ctx)
+ tries := 1
+retry:
+ for _, wait := range startupSweepBackoff {
+ if err == nil || ctx.Err() != nil || errors.Is(err, fs.ErrNotExist) || time.Now().Add(wait).After(deadline) {
+ break
+ }
+ log.Printf("agent: startup sweep try %d failed: %v; trying again in %s", tries, err, wait)
+ select {
+ case <-ctx.Done():
+ break retry
+ case <-time.After(wait):
+ }
+ err = sweep(ctx)
+ tries++
+ }
+ if err != nil && tries > 1 {
+ log.Printf("agent: startup sweep failed %d times, last: %v; serving unswept, so same-box recovery of HA hosts stays refused until the agent restarts", tries, err)
+ }
recoverLayout(ctx, err == nil)
start()
}
diff --git a/internal/instancectl/peer_edge.go b/internal/instancectl/peer_edge.go
new file mode 100644
index 000000000..7a48ac846
--- /dev/null
+++ b/internal/instancectl/peer_edge.go
@@ -0,0 +1,115 @@
+package instancectl
+
+import (
+ "fmt"
+ "sync"
+ "time"
+)
+
+// edgePeer decides whether a connecting peer is the edge's main process
+// (design §5.4): uid carlos AND the MainPID systemd reports for
+// carlos-edge.service. It is productionPeerOK's decision, apart from the
+// socket and from systemctl, so it can be tested on any platform.
+//
+// mainPID asks systemd. Its answer, a pid or a failure, is cached for
+// edgePIDCache: while the edge has no MainPID (a restart window) every
+// refused connect would otherwise re-exec systemctl, and the accept loop
+// waits on each check.
+//
+// A cached answer can predate an agent restart (#433): the old agent's
+// last calls cache its pid, and the new agent's first call, the startup
+// sweep, arrives within the second and was refused against it. So a peer
+// the cache refuses is checked once more against a fresh read before it is
+// refused, and accepted only if systemd names it now. That widens nothing:
+// the peer must still be the main pid systemd reports. Forced reads are
+// at most one per edgePIDForceEvery, so a refused peer connecting in a
+// loop cannot make every connect exec systemctl.
+type edgePeer struct {
+ carlosUID int
+ mainPID func() (int, error)
+ now func() time.Time
+
+ mu sync.Mutex
+ pid int
+ lastErr error
+ at time.Time
+ forced time.Time // the last forced read
+}
+
+// edgePIDCache is how long one systemd answer is reused.
+const edgePIDCache = time.Second
+
+// edgePIDForceEvery is the least time between two forced reads.
+const edgePIDForceEvery = 100 * time.Millisecond
+
+// cached is the edge's main pid, from the cache while it is fresh; read is
+// whether systemd was asked for it.
+func (p *edgePeer) cached() (pid int, read bool, err error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.now().Sub(p.at) < edgePIDCache {
+ if p.pid > 0 {
+ return p.pid, false, nil
+ }
+ if p.lastErr != nil {
+ return 0, false, p.lastErr
+ }
+ }
+ pid, err = p.readLocked()
+ return pid, true, err
+}
+
+// fresh asks systemd again, past the cache, unless a forced read ran less
+// than edgePIDForceEvery ago; then it is the cached answer. read is
+// whether systemd was asked.
+func (p *edgePeer) fresh() (pid int, read bool, err error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ now := p.now()
+ if !p.forced.IsZero() && now.Sub(p.forced) < edgePIDForceEvery {
+ return p.pid, false, p.lastErr
+ }
+ p.forced = now
+ pid, err = p.readLocked()
+ return pid, true, err
+}
+
+// readLocked asks systemd and caches the answer. p.mu is held.
+func (p *edgePeer) readLocked() (int, error) {
+ pid, err := p.mainPID()
+ if err == nil && pid <= 0 {
+ err = fmt.Errorf("carlos-edge.service has no MainPID")
+ }
+ if err != nil {
+ p.pid, p.lastErr, p.at = 0, err, p.now()
+ return 0, err
+ }
+ p.pid, p.lastErr, p.at = pid, nil, p.now()
+ return pid, nil
+}
+
+// check accepts the peer only when uid is carlos and pid is the edge's
+// main pid.
+func (p *edgePeer) check(uid uint32, pid int32) error {
+ if int(uid) != p.carlosUID {
+ return fmt.Errorf("peer uid %d is not carlos", uid)
+ }
+ main, read, err := p.cached()
+ if err == nil && int(pid) == main {
+ return nil
+ }
+ // A cached answer refuses: ask systemd now (#433), once. An answer
+ // cached() has just read is already fresh.
+ if !read {
+ if fmain, asked, ferr := p.fresh(); asked {
+ main, err = fmain, ferr
+ }
+ }
+ if err != nil {
+ return err
+ }
+ if int(pid) != main {
+ return fmt.Errorf("peer pid %d is not the edge's main pid %d", pid, main)
+ }
+ return nil
+}
diff --git a/internal/instancectl/peer_edge_test.go b/internal/instancectl/peer_edge_test.go
new file mode 100644
index 000000000..ae505d347
--- /dev/null
+++ b/internal/instancectl/peer_edge_test.go
@@ -0,0 +1,120 @@
+package instancectl
+
+import (
+ "errors"
+ "strings"
+ "testing"
+ "time"
+)
+
+// fakeSystemd answers MainPID from a value the test moves, and counts the
+// reads.
+type fakeSystemd struct {
+ pid int
+ err error
+ reads int
+}
+
+func (f *fakeSystemd) mainPID() (int, error) {
+ f.reads++
+ return f.pid, f.err
+}
+
+func newTestEdgePeer(sd *fakeSystemd, clock *time.Time) *edgePeer {
+ return &edgePeer{carlosUID: 990, mainPID: sd.mainPID, now: func() time.Time { return *clock }}
+}
+
+// #433: root's cached main pid lags an agent restart. The new agent's
+// first call is checked against a fresh read before it is refused, and
+// accepted only when systemd names it; a fresh read that still names
+// another pid refuses.
+func TestEdgePeerRereadsAStaleMainPID(t *testing.T) {
+ clock := time.Unix(1_700_000_000, 0)
+ sd := &fakeSystemd{pid: 100}
+ p := newTestEdgePeer(sd, &clock)
+ if err := p.check(990, 100); err != nil {
+ t.Fatalf("the edge's main pid refused: %v", err)
+ }
+ // The agent restarts inside the cache window: systemd now says 200.
+ sd.pid = 200
+ clock = clock.Add(300 * time.Millisecond)
+ if err := p.check(990, 200); err != nil {
+ t.Fatalf("the new main pid refused against a stale cache: %v", err)
+ }
+ // The refreshed answer is cached: the old pid is refused now.
+ if err := p.check(990, 100); err == nil || !strings.Contains(err.Error(), "is not the edge's main pid 200") {
+ t.Fatalf("the old main pid after the restart: %v", err)
+ }
+
+ // A peer systemd does not name is refused after the fresh read too.
+ clock = clock.Add(2 * time.Second)
+ sd.pid = 300
+ if err := p.check(990, 300); err != nil {
+ t.Fatalf("main pid 300: %v", err)
+ }
+ clock = clock.Add(300 * time.Millisecond)
+ before := sd.reads
+ if err := p.check(990, 301); err == nil || !strings.Contains(err.Error(), "peer pid 301 is not the edge's main pid 300") {
+ t.Fatalf("a child of the edge: %v", err)
+ }
+ if sd.reads != before+1 {
+ t.Fatalf("the mismatch made %d systemd reads, want one fresh read", sd.reads-before)
+ }
+}
+
+// A cached failure (the edge had no MainPID during its restart) does not
+// refuse the new main process either: systemd is asked again.
+func TestEdgePeerRereadsACachedFailure(t *testing.T) {
+ clock := time.Unix(1_700_000_000, 0)
+ sd := &fakeSystemd{pid: 0}
+ p := newTestEdgePeer(sd, &clock)
+ if err := p.check(990, 200); err == nil {
+ t.Fatal("a peer accepted while the edge has no MainPID")
+ }
+ sd.pid = 200
+ clock = clock.Add(200 * time.Millisecond)
+ if err := p.check(990, 200); err != nil {
+ t.Fatalf("the new main pid refused against a cached failure: %v", err)
+ }
+ sd.err = errors.New("systemctl: timeout")
+ clock = clock.Add(2 * time.Second)
+ if err := p.check(990, 200); err == nil {
+ t.Fatal("a peer accepted when systemd could not be read")
+ }
+}
+
+// Forced reads are rate-limited: a peer that keeps connecting with a pid
+// that is not the edge's does not exec systemctl on every connect.
+func TestEdgePeerForcedReadsAreRateLimited(t *testing.T) {
+ clock := time.Unix(1_700_000_000, 0)
+ sd := &fakeSystemd{pid: 100}
+ p := newTestEdgePeer(sd, &clock)
+ if err := p.check(990, 100); err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 50; i++ {
+ clock = clock.Add(time.Millisecond)
+ if err := p.check(990, 666); err == nil {
+ t.Fatal("a stranger accepted")
+ }
+ }
+ // 50 ms of a refused peer: the first mismatch forces a read, the rest
+ // fall inside edgePIDForceEvery.
+ if sd.reads != 2 {
+ t.Fatalf("systemd reads = %d, want 2 (the first check and one forced read)", sd.reads)
+ }
+}
+
+// The uid is checked first and never widened: a non-carlos peer is refused
+// without asking systemd, even when its pid is the main pid.
+func TestEdgePeerRefusesAnotherUID(t *testing.T) {
+ clock := time.Unix(1_700_000_000, 0)
+ sd := &fakeSystemd{pid: 100}
+ p := newTestEdgePeer(sd, &clock)
+ if err := p.check(0, 100); err == nil || !strings.Contains(err.Error(), "peer uid 0 is not carlos") {
+ t.Fatalf("uid 0: %v", err)
+ }
+ if sd.reads != 0 {
+ t.Fatalf("systemd asked %d times for a wrong uid", sd.reads)
+ }
+}
diff --git a/internal/instancectl/peer_linux.go b/internal/instancectl/peer_linux.go
index 11ee0e45f..6678a0218 100644
--- a/internal/instancectl/peer_linux.go
+++ b/internal/instancectl/peer_linux.go
@@ -13,7 +13,6 @@ import (
"os/user"
"strconv"
"strings"
- "sync"
"syscall"
"time"
@@ -43,8 +42,8 @@ func peerCred(conn net.Conn) (*unix.Ucred, error) {
// productionPeerOK requires the peer to be uid carlos AND the main process
// of carlos-edge.service as systemd reports it (design §5.4): a flat tenant
// is a child of that pid, never the pid itself, and a nested tenant cannot
-// reach the socket at all. MainPID is asked of systemctl and cached for one
-// second, because the agent restarts and the pid changes.
+// reach the socket at all. The decision is edgePeer's; MainPID is asked of
+// systemctl.
func productionPeerOK() func(net.Conn) error {
// A missing carlos user or an unparsable uid is fatal at startup, not a
// permanent refusal cached into the returned closure: socket activation
@@ -60,59 +59,30 @@ func productionPeerOK() func(net.Conn) error {
if err != nil {
log.Fatalf("instance-control: carlos uid %q: %v", u.Uid, err)
}
- var mu sync.Mutex
- var mainPID int
- var lastErr error
- var at time.Time
- edgePID := func() (int, error) {
- mu.Lock()
- defer mu.Unlock()
- // Cache both a success and a failure for one second: while the
- // edge has no MainPID yet (a restart window), every refused
- // connect would otherwise re-exec systemctl under this mutex —
- // the negative case needs the same cache the positive one always
- // had (codex review fix round 2 item 5).
- if time.Since(at) < time.Second {
- if mainPID > 0 {
- return mainPID, nil
- }
- if lastErr != nil {
- return 0, lastErr
- }
- }
- ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
- defer cancel()
- out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "MainPID", "--value", edgeUnit).Output()
- if err != nil {
- mainPID, lastErr, at = 0, err, time.Now()
- return 0, err
- }
- pid, err := strconv.Atoi(strings.TrimSpace(string(out)))
- if err != nil || pid <= 0 {
- err = fmt.Errorf("carlos-edge.service has no MainPID")
- mainPID, lastErr, at = 0, err, time.Now()
- return 0, err
- }
- mainPID, lastErr, at = pid, nil, time.Now()
- return pid, nil
- }
+ peer := &edgePeer{carlosUID: carlosUID, mainPID: systemdEdgeMainPID, now: time.Now}
return func(conn net.Conn) error {
cred, err := peerCred(conn)
if err != nil {
return err
}
- if int(cred.Uid) != carlosUID {
- return fmt.Errorf("peer uid %d is not carlos", cred.Uid)
- }
- pid, err := edgePID()
- if err != nil {
- return err
- }
- if int(cred.Pid) != pid {
- return fmt.Errorf("peer pid %d is not the edge's main pid %d", cred.Pid, pid)
- }
- return nil
+ return peer.check(cred.Uid, cred.Pid)
+ }
+}
+
+// systemdEdgeMainPID is carlos-edge.service's MainPID as systemd reports
+// it now; 0 when the unit has none.
+func systemdEdgeMainPID() (int, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+ out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "MainPID", "--value", edgeUnit).Output()
+ if err != nil {
+ return 0, err
+ }
+ pid, err := strconv.Atoi(strings.TrimSpace(string(out)))
+ if err != nil {
+ return 0, nil
}
+ return pid, nil
}
// activatedListener returns the socket-activated listener when systemd