carlos / platform Public

Managed fleets 1b task 6a, ruling: a host left awake by a crash is reported

Controller ruling: an agent that dies while a host is awake runs no stop
and no final sync, so the failed-sync record alone missed it. Every wake
now writes <DataDir>/.replication-failures/<host>.unsynced through
writeDurable once the lease is held and the restore is done, before the
seed or the spawn can write the database; a record that cannot be
written refuses the wake and gives the lease back. It is cleared with the
failed-sync record by a final sync that lands (any release whose error is
not a failed final replication) or a fresh restore of the host here.

ReplicationFailures now counts hosts: every failed-sync record, plus every
awake record whose host this process holds no lease for (a held, awake
host is LeasesHeld's), each host once. A unit-backed row, and a backend
with no absolute data directory, write no awake record; the latter's
count stays an error, so its heartbeat reports at least 1.

TestCrashWhileAwakeIsReported: woken, agent dropped without a stop, a
fresh agent holding no lease reports 1; after it takes the host and stops
it cleanly, 0. TestWakeSleepCycleLeavesNoRecord and
TestUnwritableAwakeRecordRefusesTheWake cover the normal cycle and the
write-before-start order.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 43372c3e07c180dac14ff12dc9f3950d832032a8 parent 91d4092
4 files changed, +299 −62
  • internal/activator/activator.go +10 −0
  • internal/activator/backend_exec.go +1 −1
  • internal/activator/drainreport.go +165 −61
  • internal/activator/drainreport_test.go +123 −0
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index a74e6824a..61b3840f3 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -2717,6 +2717,16 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro
}
w.steps.mark(a.now(), "identity")
+ // 2c. The host's awake record (drainreport.go), durable before the
+ // seed or the spawn can write its database: an agent that dies while
+ // the host is awake leaves no final sync, and only this record tells
+ // the box's heartbeat that writes may be missing from the bucket. A
+ // record that cannot be written refuses the wake, nothing having run.
+ if err := a.noteUnsynced(rt); err != nil {
+ w.stopOutcome.leaseReleased = a.giveBack(ctx, host, lease)
+ return w, fmt.Errorf("start %s: refusing to start: %w", host, err)
+ }
+
// 3. First-boot seed, strictly between the restore and the spawn — so it
// runs before Start's first health probe, and a brand-new instance is born
// seeded rather than briefly serving an empty database. fresh is the
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index 13e46f2bc..f9706d5ca 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -780,7 +780,7 @@ func (b *ExecBackend) Acquire(ctx context.Context, rt registry.Route) (Lease, er
markAcquiredHere(b, rt.Host)
// Counted in the heartbeat's leases_held until it stops holding
// (drainreport.go).
- b.trackHeld(l)
+ b.trackHeld(rt.Host, l)
}
return l, err
}
diff --git a/internal/activator/drainreport.go b/internal/activator/drainreport.go
index 4fdde173f..915ad176e 100644
--- a/internal/activator/drainreport.go
+++ b/internal/activator/drainreport.go
@@ -9,18 +9,30 @@ package activator
// lease ExecBackend.Acquire handed out whose renewer still runs
// (lease.Held.Holding), through Replicate and until the release, the
// replicator's Close or Abandon stops it.
-// - ReplicationFailures: the hosts whose final sync failed while their
-// lease was released anyway (lease.Replicator.Close releases whatever
-// the sync did; an HA release writes its marker whatever the sync did).
-// Each is a durable record, <DataDir>/.replication-failures/<host>.json,
-// written through writeDurable when the release reports the failure,
-// and removed when a later final sync of the host on this box lands or
-// the host is restored fresh from the bucket here. It survives an agent
-// restart; nothing else removes it.
+// - ReplicationFailures: the hosts whose last local writes are not known
+// to be in the bucket, from two durable records per host in
+// <DataDir>/.replication-failures/, each written through writeDurable:
+// - <host>.unsynced, written at every wake once the lease is held and
+// before the seed or the spawn, so before anything of the host can
+// write its database (controller ruling, Task 6a). It covers an agent
+// that dies while the host is awake: there is then no stop and no
+// final sync, and only the record says so. It counts only while this
+// process does not hold the host's lease (an awake, held host is
+// LeasesHeld's).
+// - <host>.json, written when a release reports a failed final sync
+// while the lease was released anyway (lease.Replicator.Close releases
+// whatever the sync did; an HA release writes its marker whatever the
+// sync did). It counts whatever is held.
+// A host counts once, whichever records it has. Both are removed when a
+// later final sync of the host on this box lands or the host is
+// restored fresh from the bucket here. They survive an agent restart;
+// nothing else removes them.
//
-// A failure to write the record is logged loudly and changes nothing else:
-// the stop, the lease release and the entry's removal are exactly as they
-// were. The record is evidence for the drain, not a lock.
+// A wake whose unsynced record cannot be written is refused before anything
+// runs, the lease given back. A failed-sync record that cannot be written
+// is logged loudly and changes nothing else: the stop, the lease release
+// and the entry's removal are exactly as they were. The records are
+// evidence for the drain, not a lock.
import (
"encoding/json"
@@ -34,14 +46,19 @@ import (
"time"
"github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/registry"
)
// ReplicationFailuresDir is the directory under the box's DataDir that
// holds one record per host whose final sync failed.
const ReplicationFailuresDir = ".replication-failures"
-// failedSyncSuffix names a host's record in ReplicationFailuresDir.
-const failedSyncSuffix = ".json"
+// failedSyncSuffix names a host's failed-final-sync record in
+// ReplicationFailuresDir, and unsyncedSuffix its awake record.
+const (
+ failedSyncSuffix = ".json"
+ unsyncedSuffix = ".unsynced"
+)
// failedSyncErrMax bounds the error text a record keeps.
const failedSyncErrMax = 1024
@@ -54,19 +71,25 @@ type failedSyncRecord struct {
Error string `json:"error"`
}
+// unsyncedRecord is an awake record's content, for an operator reading it.
+type unsyncedRecord struct {
+ Host string `json:"host"`
+ WokenAt time.Time `json:"woken_at"`
+}
+
// drainState is ExecBackend's share of the drain facts: the leases it has
-// handed out (pruned as they stop holding) and the lock that serialises
-// the record's writes.
+// handed out, with their hosts (pruned as they stop holding), and the lock
+// that serialises the records' writes.
type drainState struct {
mu sync.Mutex
- held map[*lease.Held]struct{}
+ held map[*lease.Held]string
rec sync.Mutex
}
-// trackHeld remembers a lease Acquire handed out, forgetting those that
-// no longer hold, so the set stays the size of what is held on a box
-// whose heartbeat never asks.
-func (b *ExecBackend) trackHeld(l Lease) {
+// trackHeld remembers a lease Acquire handed out for host, forgetting
+// those that no longer hold, so the set stays the size of what is held on
+// a box whose heartbeat never asks.
+func (b *ExecBackend) trackHeld(host string, l Lease) {
el, ok := l.(*execLease)
if !ok || el.held == nil {
return
@@ -74,31 +97,32 @@ func (b *ExecBackend) trackHeld(l Lease) {
b.drain.mu.Lock()
defer b.drain.mu.Unlock()
if b.drain.held == nil {
- b.drain.held = map[*lease.Held]struct{}{}
+ b.drain.held = map[*lease.Held]string{}
}
b.pruneHeldLocked()
- b.drain.held[el.held] = struct{}{}
+ b.drain.held[el.held] = host
}
// heldLeases counts the leases Acquire handed out that still hold.
func (b *ExecBackend) heldLeases() int {
b.drain.mu.Lock()
defer b.drain.mu.Unlock()
- return b.pruneHeldLocked()
+ return len(b.pruneHeldLocked())
}
// pruneHeldLocked forgets the tracked leases that no longer hold and
-// returns how many do. Under drain.mu.
-func (b *ExecBackend) pruneHeldLocked() int {
- n := 0
- for h := range b.drain.held {
+// returns the hosts of those that do, one entry per held lease. Under
+// drain.mu.
+func (b *ExecBackend) pruneHeldLocked() []string {
+ var hosts []string
+ for h, host := range b.drain.held {
if h.Holding() {
- n++
+ hosts = append(hosts, host)
} else {
delete(b.drain.held, h)
}
}
- return n
+ return hosts
}
// failedSyncDir is <DataDir>/.replication-failures. The DataDir is the
@@ -110,8 +134,8 @@ func (b *ExecBackend) failedSyncDir() (string, error) {
return filepath.Join(filepath.Clean(b.DataDir), ReplicationFailuresDir), nil
}
-// failedSyncName is host's record name, refusing a host that is not one
-// file name.
+// failedSyncName is host's failed-sync record name, refusing a host that
+// is not one file name; the awake record is the same with unsyncedSuffix.
func failedSyncName(host string) (string, error) {
if host == "" || host == "." || host == ".." || strings.HasPrefix(host, ".") || strings.ContainsAny(host, `/\`) {
return "", fmt.Errorf("%q is not a host a replication failure can be filed under", host)
@@ -119,6 +143,44 @@ func failedSyncName(host string) (string, error) {
return host + failedSyncSuffix, nil
}
+// writeRecordLocked writes name in the record directory durably: the
+// directory created and its parent synced, then the record through
+// writeDurable (temp file, fsync, rename, directory fsync). Under
+// drain.rec.
+func writeRecordLocked(dir, name string, v any) error {
+ body, err := json.MarshalIndent(v, "", " ")
+ if err != nil {
+ return err
+ }
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return err
+ }
+ if err := durableSync(filepath.Dir(dir)); err != nil {
+ return fmt.Errorf("sync %s: %w", filepath.Dir(dir), err)
+ }
+ return writeDurable(dir, name, append(body, '\n'))
+}
+
+// noteUnsynced writes host's awake record durably, before anything of the
+// host can write its database. A later wake replaces it. A backend with no
+// absolute data directory keeps no records at all: the wake goes ahead as
+// today, and its count is an error, so the heartbeat reports at least 1
+// and such a box never reads as drained.
+func (b *ExecBackend) noteUnsynced(rt registry.Route) error {
+ name, err := failedSyncName(rt.Host)
+ if err != nil {
+ return err
+ }
+ dir, err := b.failedSyncDir()
+ if err != nil {
+ return nil
+ }
+ b.drain.rec.Lock()
+ defer b.drain.rec.Unlock()
+ return writeRecordLocked(dir, strings.TrimSuffix(name, failedSyncSuffix)+unsyncedSuffix,
+ unsyncedRecord{Host: rt.Host, WokenAt: time.Now().UTC()})
+}
+
// noteFailedFinalSync writes host's record durably: the directory created
// and its parent synced, then the record through writeDurable (temp file,
// fsync, rename, directory fsync). A later failure of the same host
@@ -139,24 +201,14 @@ func (b *ExecBackend) noteFailedFinalSync(host string, cause error) error {
if len(msg) > failedSyncErrMax {
msg = msg[:failedSyncErrMax]
}
- body, err := json.MarshalIndent(failedSyncRecord{Host: host, FailedAt: time.Now().UTC(), Error: msg}, "", " ")
- if err != nil {
- return err
- }
b.drain.rec.Lock()
defer b.drain.rec.Unlock()
- if err := os.MkdirAll(dir, 0o700); err != nil {
- return err
- }
- if err := durableSync(filepath.Dir(dir)); err != nil {
- return fmt.Errorf("sync %s: %w", filepath.Dir(dir), err)
- }
- return writeDurable(dir, name, append(body, '\n'))
+ return writeRecordLocked(dir, name, failedSyncRecord{Host: host, FailedAt: time.Now().UTC(), Error: msg})
}
-// clearFailedFinalSync removes host's record, if there is one, and syncs
-// the directory after a removal. A backend with no absolute data directory
-// can have written no record, so there is nothing to clear.
+// clearFailedFinalSync removes both of host's records, if it has any, and
+// syncs the directory after a removal. A backend with no absolute data
+// directory can have written no record, so there is nothing to clear.
func (b *ExecBackend) clearFailedFinalSync(host string) error {
name, err := failedSyncName(host)
if err != nil {
@@ -168,11 +220,18 @@ func (b *ExecBackend) clearFailedFinalSync(host string) error {
}
b.drain.rec.Lock()
defer b.drain.rec.Unlock()
- if err := os.Remove(filepath.Join(dir, name)); err != nil {
- if errors.Is(err, os.ErrNotExist) {
- return nil
+ removed := false
+ for _, n := range []string{name, strings.TrimSuffix(name, failedSyncSuffix) + unsyncedSuffix} {
+ if err := os.Remove(filepath.Join(dir, n)); err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ continue
+ }
+ return err
}
- return err
+ removed = true
+ }
+ if !removed {
+ return nil
}
if err := durableSync(dir); err != nil {
return fmt.Errorf("sync %s: %w", dir, err)
@@ -180,14 +239,22 @@ func (b *ExecBackend) clearFailedFinalSync(host string) error {
return nil
}
-// failedFinalSyncs counts the records: every <host>.json in the directory,
-// never a temp file (WriteAtomic's start with a dot). No directory is
-// none; any other read failure is returned, never "none".
+// failedFinalSyncs counts the hosts whose writes are not known to be in
+// the bucket: every <host>.json, and every <host>.unsynced whose host this
+// process holds no lease for, each host once; never a temp file
+// (WriteAtomic's start with a dot). No directory is none; any other read
+// failure is returned, never "none".
func (b *ExecBackend) failedFinalSyncs() (int, error) {
dir, err := b.failedSyncDir()
if err != nil {
return 0, err
}
+ b.drain.mu.Lock()
+ held := map[string]bool{}
+ for _, h := range b.pruneHeldLocked() {
+ held[h] = true
+ }
+ b.drain.mu.Unlock()
b.drain.rec.Lock()
defer b.drain.rec.Unlock()
ents, err := os.ReadDir(dir)
@@ -197,13 +264,19 @@ func (b *ExecBackend) failedFinalSyncs() (int, error) {
if err != nil {
return 0, err
}
- n := 0
+ hosts := map[string]bool{}
for _, e := range ents {
- if name := e.Name(); !strings.HasPrefix(name, ".") && strings.HasSuffix(name, failedSyncSuffix) {
- n++
+ name := e.Name()
+ if strings.HasPrefix(name, ".") {
+ continue
+ }
+ if host, ok := strings.CutSuffix(name, failedSyncSuffix); ok {
+ hosts[host] = true
+ } else if host, ok := strings.CutSuffix(name, unsyncedSuffix); ok && !held[host] {
+ hosts[host] = true
}
}
- return n, nil
+ return len(hosts), nil
}
// drainFacts is the backend half the Service reads the drain facts
@@ -211,6 +284,7 @@ func (b *ExecBackend) failedFinalSyncs() (int, error) {
// (a unit-backed row takes no lease and replicates nothing).
type drainFacts interface {
heldLeases() int
+ noteUnsynced(rt registry.Route) error
noteFailedFinalSync(host string, cause error) error
clearFailedFinalSync(host string) error
failedFinalSyncs() (int, error)
@@ -237,6 +311,21 @@ func (b *SplitBackend) heldLeases() int {
return 0
}
+// noteUnsynced dispatches on Backing: a unit-backed row takes no lease of
+// this backend's and replicates nothing, so it records nothing. An exec
+// half that keeps no records (a test double) records nothing either, as
+// Service.noteUnsynced treats such a backend; its count still answers
+// errNoDrainFacts, never "none".
+func (b *SplitBackend) noteUnsynced(rt registry.Route) error {
+ if rt.Backing == registry.BackingUnit {
+ return nil
+ }
+ if f, ok := b.execFacts(); ok {
+ return f.noteUnsynced(rt)
+ }
+ return nil
+}
+
func (b *SplitBackend) noteFailedFinalSync(host string, cause error) error {
if f, ok := b.execFacts(); ok {
return f.noteFailedFinalSync(host, cause)
@@ -295,20 +384,35 @@ func finalReplicationFailed(err error) bool {
return errors.As(err, &fs) || errors.As(err, &fr)
}
+// noteUnsynced writes rt's awake record before anything of the host can
+// write (doWake, after the lease and the restore, before the seed and the
+// spawn). An error refuses the wake. A backend that keeps no records
+// (a test double) records nothing.
+func (a *Service) noteUnsynced(rt registry.Route) error {
+ f, ok := a.backend.(drainFacts)
+ if !ok {
+ return nil
+ }
+ if err := f.noteUnsynced(rt); err != nil {
+ return fmt.Errorf("the record that it is awake could not be written: %w", err)
+ }
+ return nil
+}
+
// noteFinalReplication records the outcome of a release that ran a final
// sync of host (err is the release's error): a failed final sync is
-// recorded, a release with none clears the record, and a release that
-// failed for another reason (the lease delete, the marker) changes
-// nothing. Never called with a.mu held: it touches the disk.
+// recorded; any other outcome, a clean release or one that failed after
+// the sync landed (the lease delete, the marker), clears both records.
+// Never called with a.mu held: it touches the disk.
func (a *Service) noteFinalReplication(host string, err error) {
f, ok := a.backend.(drainFacts)
if !ok {
return
}
switch {
- case err == nil:
+ case !finalReplicationFailed(err):
if cerr := f.clearFailedFinalSync(host); cerr != nil {
- log.Printf("activator: %s: the final sync landed, but its earlier failure record could not be cleared: %v (the box still reports it)", host, cerr)
+ log.Printf("activator: %s: the final sync landed, but its replication records could not be cleared: %v (the box still reports them)", host, cerr)
}
case finalReplicationFailed(err):
if nerr := f.noteFailedFinalSync(host, err); nerr != nil {
diff --git a/internal/activator/drainreport_test.go b/internal/activator/drainreport_test.go
index 34c479fe4..ebcf9f065 100644
--- a/internal/activator/drainreport_test.go
+++ b/internal/activator/drainreport_test.go
@@ -12,6 +12,7 @@ import (
"time"
"github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/registry"
)
// legacyService is haService for a host that is not HA: the real legacy
@@ -202,6 +203,11 @@ func TestReplicationFailureRecord(t *testing.T) {
if err := b3.noteFailedFinalSync("shop.example.com", errors.New("x")); err == nil {
t.Fatal("a backend with no data directory filed a record")
}
+ // Its wakes go ahead (no awake record can be kept), and the count stays
+ // an error, so the box never reads as drained.
+ if err := b3.noteUnsynced(fleetlessRoute("shop.example.com")); err != nil {
+ t.Fatalf("a backend with no data directory refused the awake record: %v", err)
+ }
}
// The record's write is durable: the directory is synced after the rename,
@@ -270,3 +276,120 @@ func TestFinalReplicationFailedClassifies(t *testing.T) {
}
}
}
+
+// The crash the stop never saw (controller ruling, Task 6a): the host is
+// woken and the agent dies without a stop, so there is no final sync and
+// no failure record. A fresh agent over the same data directory, holding
+// no lease of the host, reports 1 from the awake record alone. Once it
+// takes the host (the dead agent's lock expired), the held host is
+// LeasesHeld's, not a failure; a clean stop with a final sync that lands
+// leaves 0.
+func TestCrashWhileAwakeIsReported(t *testing.T) {
+ s := legacyService(t, "shop.example.com")
+ e, err := s.wakeForTest(context.Background())
+ if err != nil || e == nil {
+ t.Fatalf("wake: %v", err)
+ }
+ if n := failures(t, s.a); n != 0 {
+ t.Fatalf("awake and held: ReplicationFailures = %d, want 0", n)
+ }
+ if err := ensureDB(s.b.pathsFor(s.rt).dbPath); err != nil {
+ t.Fatal(err)
+ }
+ prefix := s.b.Cfg.hibernatePrefix(s.rt.Host)
+ owner := s.fx.LockOwner(prefix)
+
+ // The crash: no stop, no final sync, no release.
+ s2 := s.restart(t)
+ if n := s2.a.LeasesHeld(); n != 0 {
+ t.Fatalf("a fresh agent: LeasesHeld = %d, want 0", n)
+ }
+ if n := failures(t, s2.a); n != 1 {
+ t.Fatalf("a fresh agent over a host left awake: ReplicationFailures = %d, want 1", n)
+ }
+
+ // The dead agent's lock runs out; the fresh agent takes the host.
+ putLockFor(t, s2.b, s2.rt, leaseBody(t, owner, time.Now().Add(-time.Minute)))
+ e2, err := s2.wakeForTest(context.Background())
+ if err != nil || e2 == nil {
+ t.Fatalf("wake after the crash: %v", err)
+ }
+ if n := s2.a.LeasesHeld(); n != 1 {
+ t.Fatalf("taken again: LeasesHeld = %d, want 1", n)
+ }
+ if n := failures(t, s2.a); n != 0 {
+ t.Fatalf("taken again: ReplicationFailures = %d, want 0 (the held host is LeasesHeld's)", n)
+ }
+ s2.stopForTest(e2)
+ if !s2.stoppedFor(e2) {
+ t.Fatal("the stop went pending")
+ }
+ if n, h := failures(t, s2.a), s2.a.LeasesHeld(); n != 0 || h != 0 {
+ t.Fatalf("after a clean stop: ReplicationFailures = %d, LeasesHeld = %d, want 0 and 0", n, h)
+ }
+}
+
+// A normal wake and sleep leaves nothing: the awake record is written at
+// the wake and cleared by the final sync.
+func TestWakeSleepCycleLeavesNoRecord(t *testing.T) {
+ s := legacyService(t, "shop.example.com")
+ dir := filepath.Join(s.b.DataDir, ReplicationFailuresDir)
+ e, err := s.wakeForTest(context.Background())
+ if err != nil || e == nil {
+ t.Fatalf("wake: %v", err)
+ }
+ if _, err := os.Stat(filepath.Join(dir, s.rt.Host+unsyncedSuffix)); err != nil {
+ t.Fatalf("no awake record while awake: %v", err)
+ }
+ s.stopForTest(e)
+ if !s.stoppedFor(e) {
+ t.Fatal("the stop went pending")
+ }
+ ents, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(ents) != 0 || failures(t, s.a) != 0 {
+ t.Fatalf("after a wake and a sleep: %v left, ReplicationFailures %d", ents, failures(t, s.a))
+ }
+}
+
+// The awake record is written before anything of the host runs, and a
+// record that cannot be written refuses the wake with nothing started and
+// the lease given back.
+func TestUnwritableAwakeRecordRefusesTheWake(t *testing.T) {
+ s := legacyService(t, "shop.example.com")
+ dir := filepath.Join(s.b.DataDir, ReplicationFailuresDir)
+ var started bool
+ start := s.ctl.onStart
+ s.ctl.onStart = func() {
+ if _, err := os.Stat(filepath.Join(dir, s.rt.Host+unsyncedSuffix)); err != nil {
+ t.Errorf("the host started before its awake record existed: %v", err)
+ }
+ started = true
+ start()
+ }
+ old := durableSync
+ durableSync = func(d string) error {
+ if d == dir {
+ return errors.New("synthetic sync failure")
+ }
+ return old(d)
+ }
+ _, err := s.wakeForTest(context.Background())
+ durableSync = old
+ if err == nil || started {
+ t.Fatalf("wake = %v, started %v: want refused, nothing started", err, started)
+ }
+ if body := s.fx.LockBody(s.b.Cfg.hibernatePrefix(s.rt.Host)); body != nil {
+ t.Fatalf("the refused wake kept the lease: %s", body)
+ }
+ e, err := s.wakeForTest(context.Background())
+ if err != nil || !started || e == nil {
+ t.Fatalf("a wake once the record writes: %v, started %v", err, started)
+ }
+}
+
+func fleetlessRoute(host string) registry.Route {
+ return registry.Route{Host: host, Kind: "instance"}
+}