carlos / platform Public

Managed fleets 1b task 6a: the box reports held leases and failed final syncs

The drain rule's box half. Every heartbeat now carries leases_held and
replication_failures (status.Box, always on the wire, never copied into
fleet.json), filled by drainReport from the activator with no bucket
request.

Held leases: ExecBackend.Acquire tracks each lease it hands out; one
counts while its renewer runs (lease.Held.Holding), through Replicate and
until the release, the replicator's Close or Abandon stops it.

Failed final syncs: lease.Replicator.Close (and closeHA) now mark a
failed final sync as a *lease.FinalSyncError, text unchanged, so it is
told apart from a failed lease delete; releaseHAClean marks its database
and files failures the same way. finishStop, the failed-wake cleanup and
the unproven-wake reaper record such a failure durably at
<DataDir>/.replication-failures/<host>.json (writeDurable, parent synced
first), and clear it when a later final sync of the host lands or the
host is restored fresh from the bucket. The record survives an agent
restart. An unreadable record directory reports at least 1. A record
that cannot be written is logged and changes nothing else: stop, release
and the entry's removal are as before.

Tests: TestHeartbeatCountsHeldLeases (real leases, 2 then 1 then 0),
TestHeartbeatReportsReplicationFailures, and
TestFailedFinalSyncIsReportedUntilReplicated (real lease and litestream
against the lock fixture, replica PUTs refused: lease released, 1
reported, still 1 after a restart, 0 after a sync that lands), plus the
record, classification and lease-level FinalSyncError/Holding tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 91d4092eac1b44c29c5d71d96590e24154fada31 parent 1c1b3ca
17 files changed, +1,088 −22
  • internal/activator/activator.go +13 −1
  • internal/activator/backend_exec.go +13 −0
  • internal/activator/drainreport.go +320 −0
  • internal/activator/drainreport_linux_test.go +38 −0
  • internal/activator/drainreport_test.go +272 −0
  • internal/activator/harelease.go +5 −2
  • internal/activator/maintenance.go +3 −1
  • internal/activator/opset.go +1 −0
  • internal/host/agent.go +4 −0
  • internal/host/drainreport.go +30 −0
  • internal/host/drainreport_test.go +137 −0
  • internal/lease/finalsync.go +37 −0
  • internal/lease/finalsync_test.go +158 −0
  • internal/lease/lease.go +4 −1
  • internal/lease/release.go +1 −1
  • internal/status/contract_test.go +15 −3
  • internal/status/snapshot.go +37 −13
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 4812abc73..a74e6824a 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -4806,6 +4806,11 @@ func (a *Service) retryPendingStop(e *actEntry) {
a.mu.Unlock()
}
+// finalCheckpointBudget is finishStop's budget for the final checkpoint
+// and lease release. A seam, so a test's refused final sync gives up
+// promptly; production never changes it.
+var finalCheckpointBudget = 30 * time.Second
+
// finishStop is stop()'s (and finishPendingStop's) tail: the final
// checkpoint, lease release, and forgetting the entry. Split out (design
// ยง6.3, codex R2-5) so a pendingStop entry's eventual finish shares it with
@@ -4856,7 +4861,7 @@ func (a *Service) finishStop(e *actEntry, outcome *stopObservation) {
// Close = final sync + lease release. After a lost lease the release part
// fails harmlessly (someone else owns the lock); the sync still preserves
// a local checkpoint.
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), finalCheckpointBudget)
defer cancel()
repErr := ErrStopUnproven
if _, ha := haEntryRep(e); ha {
@@ -4879,6 +4884,13 @@ func (a *Service) finishStop(e *actEntry, outcome *stopObservation) {
if repErr != nil {
log.Printf("activator: final checkpoint %s: %v", e.host, repErr)
}
+ // The release ran a final sync (an HA release, or a replica's Close):
+ // its outcome is the host's replication failure record, written or
+ // cleared before the entry goes (drainreport.go). No sync ran without
+ // a replica, so nothing is recorded then.
+ if _, ha := haEntryRep(e); ha || e.rep != nil {
+ a.noteFinalReplication(e.host, repErr)
+ }
a.mu.Lock()
outcome.uncertain = !outcome.complete()
e.stopOutcome = outcome
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index 759041a5f..13e46f2bc 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -355,6 +355,9 @@ type ExecBackend struct {
sameBox sameBoxState
// haWakes is each host's last Acquire classification (hawake.go).
haWakes haWakes
+ // drain is the drain rule's box facts (drainreport.go): the leases
+ // Acquire handed out, and the replication failure records' lock.
+ drain drainState
// entryFiles is the Service's lookup of an awake entry's files
// publisher (hasecrets.go), installed by New. Nil: none.
entryFiles func(host string) *hostFiles
@@ -775,6 +778,9 @@ func (b *ExecBackend) Acquire(ctx context.Context, rt registry.Route) (Lease, er
l, err := b.acquireClassified(ctx, rt)
if err == nil {
markAcquiredHere(b, rt.Host)
+ // Counted in the heartbeat's leases_held until it stops holding
+ // (drainreport.go).
+ b.trackHeld(l)
}
return l, err
}
@@ -979,6 +985,13 @@ func (b *ExecBackend) restorePlain(ctx context.Context, rt registry.Route) (bool
if err := b.establishAssignment(rt, dbPath); err != nil {
return false, err
}
+ // The copy that runs is the bucket's now, so an earlier failed
+ // final sync of the host on this box no longer stands between
+ // the box and a drain (drainreport.go). A record that cannot be
+ // removed stays: the box keeps reporting it.
+ if err := b.clearFailedFinalSync(host); err != nil {
+ log.Printf("activator: %s: restored from the bucket, but its earlier final sync failure record could not be cleared: %v", host, err)
+ }
} else {
// Never replicated: a brand-new instance boots fresh and creates its
// own DB โ€” the register-only create path (provisioning as a metadata
diff --git a/internal/activator/drainreport.go b/internal/activator/drainreport.go
new file mode 100644
index 000000000..4fdde173f
--- /dev/null
+++ b/internal/activator/drainreport.go
@@ -0,0 +1,320 @@
+package activator
+
+// The drain rule's box facts (managed fleets 1b, rule 5; Task 6a). A fleet
+// box is drained only when it has stopped everything AND its last writes
+// reached the bucket, so its heartbeat reports two counts, both read here
+// and neither costing a bucket request:
+//
+// - LeasesHeld: the instance leases this process holds right now, every
+// 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.
+//
+// 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.
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/lease"
+)
+
+// 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"
+
+// failedSyncErrMax bounds the error text a record keeps.
+const failedSyncErrMax = 1024
+
+// failedSyncRecord is a record's content, for an operator reading it. Only
+// the file's presence counts.
+type failedSyncRecord struct {
+ Host string `json:"host"`
+ FailedAt time.Time `json:"failed_at"`
+ Error string `json:"error"`
+}
+
+// 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.
+type drainState struct {
+ mu sync.Mutex
+ held map[*lease.Held]struct{}
+ 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) {
+ el, ok := l.(*execLease)
+ if !ok || el.held == nil {
+ return
+ }
+ b.drain.mu.Lock()
+ defer b.drain.mu.Unlock()
+ if b.drain.held == nil {
+ b.drain.held = map[*lease.Held]struct{}{}
+ }
+ b.pruneHeldLocked()
+ b.drain.held[el.held] = struct{}{}
+}
+
+// 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()
+}
+
+// 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 {
+ if h.Holding() {
+ n++
+ } else {
+ delete(b.drain.held, h)
+ }
+ }
+ return n
+}
+
+// failedSyncDir is <DataDir>/.replication-failures. The DataDir is the
+// agent's own root, never a tenant's instance directory.
+func (b *ExecBackend) failedSyncDir() (string, error) {
+ if b.DataDir == "" || !filepath.IsAbs(b.DataDir) {
+ return "", fmt.Errorf("no absolute data directory to keep replication failures under (%q)", b.DataDir)
+ }
+ return filepath.Join(filepath.Clean(b.DataDir), ReplicationFailuresDir), nil
+}
+
+// failedSyncName is host's record name, refusing a host that is not one
+// file name.
+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)
+ }
+ return host + failedSyncSuffix, nil
+}
+
+// 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
+// replaces it.
+func (b *ExecBackend) noteFailedFinalSync(host string, cause error) error {
+ name, err := failedSyncName(host)
+ if err != nil {
+ return err
+ }
+ dir, err := b.failedSyncDir()
+ if err != nil {
+ return err
+ }
+ msg := ""
+ if cause != nil {
+ msg = cause.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'))
+}
+
+// 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.
+func (b *ExecBackend) clearFailedFinalSync(host string) error {
+ name, err := failedSyncName(host)
+ if err != nil {
+ return err
+ }
+ dir, err := b.failedSyncDir()
+ if err != nil {
+ return nil
+ }
+ 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
+ }
+ return err
+ }
+ if err := durableSync(dir); err != nil {
+ return fmt.Errorf("sync %s: %w", dir, err)
+ }
+ 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".
+func (b *ExecBackend) failedFinalSyncs() (int, error) {
+ dir, err := b.failedSyncDir()
+ if err != nil {
+ return 0, err
+ }
+ b.drain.rec.Lock()
+ defer b.drain.rec.Unlock()
+ ents, err := os.ReadDir(dir)
+ if errors.Is(err, os.ErrNotExist) {
+ return 0, nil
+ }
+ if err != nil {
+ return 0, err
+ }
+ n := 0
+ for _, e := range ents {
+ if name := e.Name(); !strings.HasPrefix(name, ".") && strings.HasSuffix(name, failedSyncSuffix) {
+ n++
+ }
+ }
+ return n, nil
+}
+
+// drainFacts is the backend half the Service reads the drain facts
+// through: ExecBackend's, and SplitBackend's dispatch to its exec half
+// (a unit-backed row takes no lease and replicates nothing).
+type drainFacts interface {
+ heldLeases() int
+ noteFailedFinalSync(host string, cause error) error
+ clearFailedFinalSync(host string) error
+ failedFinalSyncs() (int, error)
+}
+
+var (
+ _ drainFacts = (*ExecBackend)(nil)
+ _ drainFacts = (*SplitBackend)(nil)
+)
+
+// errNoDrainFacts is a backend that keeps no record: it cannot answer
+// "no failures".
+var errNoDrainFacts = errors.New("this backend keeps no replication failure records")
+
+func (b *SplitBackend) execFacts() (drainFacts, bool) {
+ f, ok := b.Exec.(drainFacts)
+ return f, ok
+}
+
+func (b *SplitBackend) heldLeases() int {
+ if f, ok := b.execFacts(); ok {
+ return f.heldLeases()
+ }
+ return 0
+}
+
+func (b *SplitBackend) noteFailedFinalSync(host string, cause error) error {
+ if f, ok := b.execFacts(); ok {
+ return f.noteFailedFinalSync(host, cause)
+ }
+ return errNoDrainFacts
+}
+
+func (b *SplitBackend) clearFailedFinalSync(host string) error {
+ if f, ok := b.execFacts(); ok {
+ return f.clearFailedFinalSync(host)
+ }
+ return errNoDrainFacts
+}
+
+func (b *SplitBackend) failedFinalSyncs() (int, error) {
+ if f, ok := b.execFacts(); ok {
+ return f.failedFinalSyncs()
+ }
+ return 0, errNoDrainFacts
+}
+
+// LeasesHeld is how many instance leases this process holds right now
+// (the heartbeat's leases_held). A backend that takes no leases of its
+// own holds none.
+func (a *Service) LeasesHeld() int {
+ if f, ok := a.backend.(drainFacts); ok {
+ return f.heldLeases()
+ }
+ return 0
+}
+
+// ReplicationFailures is how many hosts' final syncs failed on this box
+// and have not been replicated since (the heartbeat's
+// replication_failures). An error means the count is unknown, never zero.
+func (a *Service) ReplicationFailures() (int, error) {
+ if f, ok := a.backend.(drainFacts); ok {
+ return f.failedFinalSyncs()
+ }
+ return 0, errNoDrainFacts
+}
+
+// finalReplicationError marks an HA release's error as one that left the
+// host's last writes, database or files, short of the bucket
+// (releaseHAClean). Error is the wrapped text, unchanged.
+type finalReplicationError struct{ err error }
+
+func (e *finalReplicationError) Error() string { return e.err.Error() }
+func (e *finalReplicationError) Unwrap() error { return e.err }
+
+// finalReplicationFailed reports whether a release's error says its final
+// replication failed: a legacy replicator's *lease.FinalSyncError, or an
+// HA release's finalReplicationError.
+func finalReplicationFailed(err error) bool {
+ var fs *lease.FinalSyncError
+ var fr *finalReplicationError
+ return errors.As(err, &fs) || errors.As(err, &fr)
+}
+
+// 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.
+func (a *Service) noteFinalReplication(host string, err error) {
+ f, ok := a.backend.(drainFacts)
+ if !ok {
+ return
+ }
+ switch {
+ case err == nil:
+ 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)
+ }
+ case finalReplicationFailed(err):
+ if nerr := f.noteFailedFinalSync(host, err); nerr != nil {
+ log.Printf("activator: %s: FINAL SYNC FAILED and the failure could not be recorded: %v (its last writes may not be in the bucket; the box's heartbeat cannot report it)", host, nerr)
+ } else {
+ log.Printf("activator: %s: final sync failed; recorded until a later replication of it lands: %v", host, err)
+ }
+ }
+}
diff --git a/internal/activator/drainreport_linux_test.go b/internal/activator/drainreport_linux_test.go
new file mode 100644
index 000000000..dd47538bb
--- /dev/null
+++ b/internal/activator/drainreport_linux_test.go
@@ -0,0 +1,38 @@
+//go:build linux
+
+package activator
+
+import (
+ "errors"
+ "os"
+ "testing"
+)
+
+// Linux only: it wakes through the start rule's harness (startrule_test.go).
+// A host restored fresh from the bucket on this box clears its record: the
+// copy whose writes did not reach the bucket is not the one that runs. A
+// warm wake (the same local copy) does not.
+func TestFreshRestoreClearsTheRecord(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetUnlabelled(fleetRoute(b, "", false))
+ if err := b.noteFailedFinalSync(rt.Host, errors.New("x")); err != nil {
+ t.Fatal(err)
+ }
+ writeUsableDB(t, rt.DBPath)
+ replicaCalls(t, true)
+ if _, err := wakeOn(t, b, rt, nil); err != nil {
+ t.Fatalf("warm wake: %v", err)
+ }
+ if n, _ := b.failedFinalSyncs(); n != 1 {
+ t.Fatalf("a warm wake cleared the record: %d", n)
+ }
+ if err := os.Remove(rt.DBPath); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := wakeOn(t, b, rt, nil); err != nil {
+ t.Fatalf("restoring wake: %v", err)
+ }
+ if n, _ := b.failedFinalSyncs(); n != 0 {
+ t.Fatalf("a fresh restore left the record: %d", n)
+ }
+}
diff --git a/internal/activator/drainreport_test.go b/internal/activator/drainreport_test.go
new file mode 100644
index 000000000..34c479fe4
--- /dev/null
+++ b/internal/activator/drainreport_test.go
@@ -0,0 +1,272 @@
+package activator
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/lease"
+)
+
+// legacyService is haService for a host that is not HA: the real legacy
+// lease against the lock fixture and real litestream replication of the
+// host's database to the fixture, released by the replicator's Close
+// (finishStop's non-HA arm). The final checkpoint's budget is cut to two
+// seconds, so a refused final sync gives up promptly.
+func legacyService(t *testing.T, host string) *haSvc {
+ t.Helper()
+ s := haService(t, host)
+ h := haFixOf(s.b)
+ h.mu.Lock()
+ h.records[host] = haRecord(host, false)
+ h.mu.Unlock()
+ s.b.Lifetimes = nil
+ old := finalCheckpointBudget
+ finalCheckpointBudget = 2 * time.Second
+ t.Cleanup(func() { finalCheckpointBudget = old })
+ return s
+}
+
+// refuseReplicaPuts makes the fixture refuse every replica write under the
+// host's prefix while the returned switch is on (403: the SDK does not
+// retry it). The lock's own writes are never refused.
+func refuseReplicaPuts(s *haSvc) *atomic.Bool {
+ var on atomic.Bool
+ prefix := s.b.Cfg.hibernatePrefix(s.rt.Host) + "/"
+ lock := s.lockKey()
+ for i := 0; i < 5000; i++ {
+ s.fx.FailNextMatching("PUT", 403, func(k string, _ []byte) bool {
+ return on.Load() && strings.HasPrefix(k, prefix) && k != lock
+ })
+ }
+ return &on
+}
+
+func failures(t *testing.T, a *Service) int {
+ t.Helper()
+ n, err := a.ReplicationFailures()
+ if err != nil {
+ t.Fatalf("ReplicationFailures: %v", err)
+ }
+ return n
+}
+
+// The box half of TestDrainDoneNeedsNoFailedReplication (managed fleets
+// 1b, the drain rule): the final sync is refused but the lease is
+// released anyway, through the real lease and litestream. The box reports
+// one failure; a fresh agent over the same data directory still does; a
+// later replication of the host that succeeds clears it.
+func TestFailedFinalSyncIsReportedUntilReplicated(t *testing.T) {
+ s := legacyService(t, "shop.example.com")
+ refuse := refuseReplicaPuts(s)
+ e, err := s.wakeForTest(context.Background())
+ if err != nil {
+ t.Fatalf("wake: %v", err)
+ }
+ if _, ha := s.b.haAcquired(s.rt.Host); ha {
+ t.Fatal("the host woke HA; this test is about the legacy release")
+ }
+ if n := s.a.LeasesHeld(); n != 1 {
+ t.Fatalf("awake: LeasesHeld = %d, want 1", n)
+ }
+ if n := failures(t, s.a); n != 0 {
+ t.Fatalf("awake: ReplicationFailures = %d, want 0", n)
+ }
+ if err := ensureDB(s.b.pathsFor(s.rt).dbPath); err != nil {
+ t.Fatal(err)
+ }
+ refuse.Store(true)
+ s.stopForTest(e)
+ if !s.stoppedFor(e) {
+ t.Fatal("the stop went pending; the final sync's failure must not hold the stop")
+ }
+ if body := s.fx.LockBody(s.b.Cfg.hibernatePrefix(s.rt.Host)); body != nil {
+ t.Fatalf("the lease was not released after the failed final sync: %s", body)
+ }
+ if n := s.a.LeasesHeld(); n != 0 {
+ t.Fatalf("stopped: LeasesHeld = %d, want 0", n)
+ }
+ if n := failures(t, s.a); n != 1 {
+ t.Fatalf("after the failed final sync: ReplicationFailures = %d, want 1", n)
+ }
+
+ // The agent restarts: the record is on disk, not in memory.
+ s2 := s.restart(t)
+ if n := failures(t, s2.a); n != 1 {
+ t.Fatalf("a fresh agent over the same data: ReplicationFailures = %d, want 1", n)
+ }
+
+ // The bucket takes writes again; the host wakes from its warm copy and
+ // sleeps with a final sync that lands.
+ refuse.Store(false)
+ e2, err := s2.wakeForTest(context.Background())
+ if err != nil {
+ t.Fatalf("second wake: %v", err)
+ }
+ if n := failures(t, s2.a); n != 1 {
+ t.Fatalf("a warm wake cleared the record before anything replicated: %d", n)
+ }
+ s2.stopForTest(e2)
+ if !s2.stoppedFor(e2) {
+ t.Fatal("the second stop went pending")
+ }
+ if n := failures(t, s2.a); n != 0 {
+ t.Fatalf("after a final sync that landed: ReplicationFailures = %d, want 0", n)
+ }
+ if n := s2.a.LeasesHeld(); n != 0 {
+ t.Fatalf("after the second stop: LeasesHeld = %d, want 0", n)
+ }
+}
+
+// A release whose final sync worked but whose lease delete did not is not
+// a replication failure: the writes are in the bucket.
+func TestFailedReleaseAloneIsNotAReplicationFailure(t *testing.T) {
+ s := legacyService(t, "shop.example.com")
+ e, err := s.wakeForTest(context.Background())
+ if err != nil {
+ t.Fatalf("wake: %v", err)
+ }
+ s.fx.FailNextMatching("DELETE", 403, func(k string, _ []byte) bool { return k == s.lockKey() })
+ s.stopForTest(e)
+ if n := failures(t, s.a); n != 0 {
+ t.Fatalf("ReplicationFailures = %d, want 0", n)
+ }
+}
+
+// The record: one durable file per host under the data directory, written
+// through writeDurable, counted, cleared, and never confused with a temp
+// file or anything else in the directory.
+func TestReplicationFailureRecord(t *testing.T) {
+ b := testExecBackend(t)
+ if n, err := b.failedFinalSyncs(); err != nil || n != 0 {
+ t.Fatalf("no directory: %d, %v", n, err)
+ }
+ if err := b.noteFailedFinalSync("shop.example.com", errors.New("bucket said no")); err != nil {
+ t.Fatal(err)
+ }
+ if err := b.noteFailedFinalSync("shop.example.com", errors.New("again")); err != nil {
+ t.Fatal(err)
+ }
+ if err := b.noteFailedFinalSync("cafe.example.com", errors.New("bucket said no")); err != nil {
+ t.Fatal(err)
+ }
+ dir := filepath.Join(b.DataDir, ReplicationFailuresDir)
+ raw, err := os.ReadFile(filepath.Join(dir, "shop.example.com.json"))
+ if err != nil || !bytes.Contains(raw, []byte(`"again"`)) || !bytes.Contains(raw, []byte(`"host": "shop.example.com"`)) {
+ t.Fatalf("record: %s, %v", raw, err)
+ }
+ // A temp file left by an interrupted write and a stray file do not count.
+ if err := os.WriteFile(filepath.Join(dir, ".x.json.tmp-0011"), nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "README"), nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if n, err := b.failedFinalSyncs(); err != nil || n != 2 {
+ t.Fatalf("two hosts: %d, %v", n, err)
+ }
+ if err := b.clearFailedFinalSync("shop.example.com"); err != nil {
+ t.Fatal(err)
+ }
+ if err := b.clearFailedFinalSync("shop.example.com"); err != nil {
+ t.Fatalf("a second clear: %v", err)
+ }
+ if n, err := b.failedFinalSyncs(); err != nil || n != 1 {
+ t.Fatalf("one host left: %d, %v", n, err)
+ }
+ for _, bad := range []string{"", ".", "..", "a/b", `a\b`} {
+ if err := b.noteFailedFinalSync(bad, errors.New("x")); err == nil {
+ t.Fatalf("host %q was filed", bad)
+ }
+ }
+ // A directory that cannot be read is an error, never "none".
+ b2 := testExecBackend(t)
+ if err := os.WriteFile(filepath.Join(b2.DataDir, ReplicationFailuresDir), nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := b2.failedFinalSyncs(); err == nil {
+ t.Fatal("an unreadable record directory counted as none")
+ }
+ // No absolute data directory: nothing can be kept, and the count says so.
+ b3 := testExecBackend(t)
+ b3.DataDir = ""
+ if _, err := b3.failedFinalSyncs(); err == nil {
+ t.Fatal("a backend with no data directory counted none")
+ }
+ if err := b3.noteFailedFinalSync("shop.example.com", errors.New("x")); err == nil {
+ t.Fatal("a backend with no data directory filed a record")
+ }
+}
+
+// The record's write is durable: the directory is synced after the rename,
+// and a failed sync fails the write.
+func TestReplicationFailureRecordIsDurable(t *testing.T) {
+ b := testExecBackend(t)
+ dir := filepath.Join(b.DataDir, ReplicationFailuresDir)
+ var synced []string
+ old := durableSync
+ durableSync = func(d string) error {
+ synced = append(synced, d)
+ if d == dir {
+ return errors.New("synthetic sync failure")
+ }
+ return old(d)
+ }
+ t.Cleanup(func() { durableSync = old })
+ if err := b.noteFailedFinalSync("shop.example.com", errors.New("x")); err == nil {
+ t.Fatal("a record whose directory would not sync was reported written")
+ }
+ if len(synced) < 2 || synced[0] != b.DataDir || synced[len(synced)-1] != dir {
+ t.Fatalf("syncs %v: want the data directory (the record directory's creation), then the record directory", synced)
+ }
+}
+
+// The Service reaches the record and the held leases through a
+// SplitBackend, as the agent wires it; a backend that keeps no record
+// cannot answer "none".
+func TestDrainFactsThroughTheSplitBackend(t *testing.T) {
+ eb := testExecBackend(t)
+ a := New(Config{Bucket: "test-bucket"}, &SplitBackend{Exec: eb, Unit: &UnitBackend{}}, nil)
+ if err := eb.noteFailedFinalSync("shop.example.com", errors.New("x")); err != nil {
+ t.Fatal(err)
+ }
+ if n, err := a.ReplicationFailures(); err != nil || n != 1 {
+ t.Fatalf("ReplicationFailures = %d, %v", n, err)
+ }
+ if n := a.LeasesHeld(); n != 0 {
+ t.Fatalf("LeasesHeld = %d", n)
+ }
+ fake := New(Config{Bucket: "test-bucket"}, &fakeBackend{}, nil)
+ if _, err := fake.ReplicationFailures(); err == nil {
+ t.Fatal("a backend with no record answered none")
+ }
+}
+
+// Which release errors are a failed final replication: a legacy
+// replicator's *lease.FinalSyncError and an HA release's database or files
+// failure, however joined; never a failed lease delete or marker alone.
+func TestFinalReplicationFailedClassifies(t *testing.T) {
+ other := errors.New("marker PUT refused")
+ for _, c := range []struct {
+ err error
+ want bool
+ }{
+ {nil, false},
+ {other, false},
+ {ErrStopUnproven, false},
+ {&lease.FinalSyncError{Err: errors.New("sync")}, true},
+ {errors.Join(&lease.FinalSyncError{Err: errors.New("sync")}, other), true},
+ {errors.Join(nil, &finalReplicationError{errors.New("final sync: x")}, nil, other), true},
+ {errors.Join(&finalReplicationError{errors.New("files: x")}, nil, nil, nil), true},
+ } {
+ if got := finalReplicationFailed(c.err); got != c.want {
+ t.Errorf("finalReplicationFailed(%v) = %v, want %v", c.err, got, c.want)
+ }
+ }
+}
diff --git a/internal/activator/harelease.go b/internal/activator/harelease.go
index f07e3d136..9d4496bcb 100644
--- a/internal/activator/harelease.go
+++ b/internal/activator/harelease.go
@@ -215,11 +215,14 @@ func (a *Service) releaseHAClean(ctx context.Context, e *actEntry) error {
if merr == nil {
log.Printf("activator: %s: released with a marker (clean %v, txid %d, files %s)", rt.Host, m.Clean, txid, gen)
}
+ // The files' and the database's final publish are the host's final
+ // replication: either failing is recorded until a later one lands
+ // (finalReplicationError, drainreport.go).
if ferr != nil {
- ferr = fmt.Errorf("files: %w", ferr)
+ ferr = &finalReplicationError{fmt.Errorf("files: %w", ferr)}
}
if finErr != nil {
- finErr = fmt.Errorf("final sync: %w", finErr)
+ finErr = &finalReplicationError{fmt.Errorf("final sync: %w", finErr)}
}
return errors.Join(ferr, finErr, rerr, merr)
}
diff --git a/internal/activator/maintenance.go b/internal/activator/maintenance.go
index f28083592..0f42d8959 100644
--- a/internal/activator/maintenance.go
+++ b/internal/activator/maintenance.go
@@ -473,8 +473,10 @@ func (a *Service) cleanupFailedWake(ctx context.Context, e *actEntry, rt registr
if w.rep != nil {
closeCtx, closeCancel := context.WithTimeout(context.Background(), 30*time.Second)
defer closeCancel()
- w.stopOutcome.replicaClosed = w.rep.Close(closeCtx) == nil
+ err := w.rep.Close(closeCtx)
+ w.stopOutcome.replicaClosed = err == nil
w.stopOutcome.leaseReleased = w.stopOutcome.replicaClosed
+ a.noteFinalReplication(rt.Host, err)
return
}
w.stopOutcome.leaseReleased = a.giveBack(ctx, rt.Host, lease)
diff --git a/internal/activator/opset.go b/internal/activator/opset.go
index b89ffe798..24f2fc1bb 100644
--- a/internal/activator/opset.go
+++ b/internal/activator/opset.go
@@ -922,6 +922,7 @@ func (a *Service) reapUnprovenWake(host string, u *unprovenWake) {
if u.rep != nil {
err = u.rep.Close(ctx)
outcome.replicaClosed = err == nil
+ a.noteFinalReplication(host, err)
} else if u.lease != nil {
err = releaseLease(ctx, u.lease)
if err != nil {
diff --git a/internal/host/agent.go b/internal/host/agent.go
index a70819f03..a69be1c9d 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -4397,6 +4397,10 @@ func statusLoop(reg *registry.Registry, svc *activator.Service, buildStates func
// pass still says something rather than nothing.
Layout: layoutStatusReport(routes),
}
+ // The drain rule's facts (managed fleets 1b): the instance leases
+ // this box holds and its unresolved failed final syncs, from the
+ // activator's memory and its data directory. No store request.
+ drainReport(&p, svc)
// The hosts this box is refusing because it cannot provide their
// config (amadan #213): private Metrics only, nothing public.
claimReport(&p)
diff --git a/internal/host/drainreport.go b/internal/host/drainreport.go
new file mode 100644
index 000000000..a03889538
--- /dev/null
+++ b/internal/host/drainreport.go
@@ -0,0 +1,30 @@
+package host
+
+import (
+ "log"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// drainReport fills the heartbeat's drain rule facts (managed fleets 1b,
+// rule 5) from the box's activator: the instance leases it holds right
+// now, and the hosts whose final sync failed here with no later
+// replication landing since. Both are read from the process and the
+// box's disk, never the bucket. A count of failures the activator cannot
+// read is reported as at least 1, so a console never reads it as drained.
+// A box with no activator (svc nil) takes no instance leases and reports
+// 0 for both.
+func drainReport(p *status.Probes, svc *activator.Service) {
+ if svc == nil {
+ p.LeasesHeld, p.ReplicationFailures = 0, 0
+ return
+ }
+ p.LeasesHeld = svc.LeasesHeld()
+ n, err := svc.ReplicationFailures()
+ if err != nil {
+ log.Printf("agent: status tick: replication failures unreadable: %v (reported as at least 1)", err)
+ n = max(n, 1)
+ }
+ p.ReplicationFailures = n
+}
diff --git a/internal/host/drainreport_test.go b/internal/host/drainreport_test.go
new file mode 100644
index 000000000..1d6a1d9bf
--- /dev/null
+++ b/internal/host/drainreport_test.go
@@ -0,0 +1,137 @@
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/lease/locktest"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// drainBox is a fleet box's activator wired as RunAgent wires it (a
+// SplitBackend over an ExecBackend), and the heartbeat statusLoop
+// composes from it: drainReport, then statusTick under the box's label.
+type drainBox struct {
+ eb *activator.ExecBackend
+ svc *activator.Service
+ reg *registry.Registry
+ store release.Store
+}
+
+func newDrainBox(t *testing.T, bucket string) *drainBox {
+ t.Helper()
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ cfg := activator.Config{Bucket: bucket}
+ eb := &activator.ExecBackend{Cfg: cfg, OptDir: t.TempDir(), DataDir: t.TempDir()}
+ svc := activator.New(cfg, &activator.SplitBackend{Exec: eb, Unit: &activator.UnitBackend{OptDir: eb.OptDir}}, reg)
+ return &drainBox{eb: eb, svc: svc, reg: reg, store: release.NewDirStore(t.TempDir())}
+}
+
+// heartbeat composes and writes one heartbeat under the label pi-1 and
+// returns it as written, raw and decoded.
+func (d *drainBox) heartbeat(t *testing.T, svc *activator.Service) (string, status.Box) {
+ t.Helper()
+ ctx := context.Background()
+ p := status.Probes{MachineID: "test-machine"}
+ drainReport(&p, svc)
+ if err := statusTick(ctx, d.store, d.reg, p, false, "pi-1"); err != nil {
+ t.Fatalf("statusTick: %v", err)
+ }
+ raw, _, err := d.store.Get(ctx, "status/boxes/pi-1.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var box status.Box
+ if err := json.Unmarshal(raw, &box); err != nil {
+ t.Fatal(err)
+ }
+ return string(raw), box
+}
+
+// The drain rule's lease half (managed fleets 1b): a box holding two
+// instance leases reports 2 in its heartbeat, and 0 once both are given
+// back. Real leases, against the lock fixture.
+func TestHeartbeatCountsHeldLeases(t *testing.T) {
+ fx := locktest.NewLockFixture(t) // sets env: not parallel
+ d := newDrainBox(t, fx.Bucket)
+ ctx := context.Background()
+ var held []activator.Lease
+ for _, host := range []string{"shop.example.com", "cafe.example.com"} {
+ l, err := d.eb.Acquire(ctx, registry.Route{Host: host, Kind: "instance"})
+ if err != nil {
+ t.Fatalf("acquire %s: %v", host, err)
+ }
+ held = append(held, l)
+ }
+ raw, box := d.heartbeat(t, d.svc)
+ if box.LeasesHeld != 2 || box.ReplicationFailures != 0 {
+ t.Fatalf("holding two leases: leases_held %d, replication_failures %d\n%s", box.LeasesHeld, box.ReplicationFailures, raw)
+ }
+ if err := held[0].Release(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if _, box := d.heartbeat(t, d.svc); box.LeasesHeld != 1 {
+ t.Fatalf("after one release: leases_held %d, want 1", box.LeasesHeld)
+ }
+ if err := held[1].Release(ctx); err != nil {
+ t.Fatal(err)
+ }
+ raw, box = d.heartbeat(t, d.svc)
+ if box.LeasesHeld != 0 {
+ t.Fatalf("after both releases: leases_held %d, want 0\n%s", box.LeasesHeld, raw)
+ }
+ var keys map[string]any
+ if err := json.Unmarshal([]byte(raw), &keys); err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := keys["leases_held"]; !ok {
+ t.Fatalf("a zero count is not on the wire: %s", raw)
+ }
+ if _, ok := keys["replication_failures"]; !ok {
+ t.Fatalf("a zero count is not on the wire: %s", raw)
+ }
+}
+
+// The drain rule's replication half: a failed final sync recorded by an
+// earlier agent on this box's data directory is in the heartbeat; a
+// record directory that cannot be read reports at least one, never none.
+// A box with no activator holds nothing.
+func TestHeartbeatReportsReplicationFailures(t *testing.T) {
+ t.Parallel()
+ d := newDrainBox(t, "test-bucket")
+ dir := filepath.Join(d.eb.DataDir, activator.ReplicationFailuresDir)
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "shop.example.com.json"), []byte(`{"host":"shop.example.com"}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, box := d.heartbeat(t, d.svc); box.ReplicationFailures != 1 {
+ t.Fatalf("one record: replication_failures %d, want 1", box.ReplicationFailures)
+ }
+ if err := os.RemoveAll(dir); err != nil {
+ t.Fatal(err)
+ }
+ if _, box := d.heartbeat(t, d.svc); box.ReplicationFailures != 0 {
+ t.Fatalf("no records: replication_failures %d, want 0", box.ReplicationFailures)
+ }
+ if err := os.WriteFile(dir, nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, box := d.heartbeat(t, d.svc); box.ReplicationFailures < 1 {
+ t.Fatalf("an unreadable record directory: replication_failures %d, want at least 1", box.ReplicationFailures)
+ }
+ if _, box := d.heartbeat(t, nil); box.LeasesHeld != 0 || box.ReplicationFailures != 0 {
+ t.Fatalf("no activator: leases_held %d, replication_failures %d", box.LeasesHeld, box.ReplicationFailures)
+ }
+}
diff --git a/internal/lease/finalsync.go b/internal/lease/finalsync.go
new file mode 100644
index 000000000..29abe6fb5
--- /dev/null
+++ b/internal/lease/finalsync.go
@@ -0,0 +1,37 @@
+package lease
+
+// FinalSyncError is a replicator release (Close) whose final sync failed:
+// the database's last writes may not have reached the replica. Close
+// releases the lease either way, so the error is the one record that the
+// box still holds writes the bucket does not (managed fleets 1b, the drain
+// rule: the activator keeps it on disk until a later replication of the
+// host lands). A release that failed after a sync that worked is not one.
+// Error is the failure's own text, unchanged.
+type FinalSyncError struct{ Err error }
+
+func (e *FinalSyncError) Error() string { return e.Err.Error() }
+func (e *FinalSyncError) Unwrap() error { return e.Err }
+
+// finalSyncErr wraps a store close's error as a *FinalSyncError; nil
+// stays nil.
+func finalSyncErr(err error) error {
+ if err == nil {
+ return nil
+ }
+ return &FinalSyncError{Err: err}
+}
+
+// Holding reports whether this lease is still held by this process: its
+// renewer runs, for this handle or for the replicator Replicate traded it
+// for. It is true from Acquire until Release, the replicator's Close or
+// Abandon stops the renewer, and stays true for a lease whose renewal has
+// failed until one of those stands it down. The status heartbeat counts it
+// (the drain rule's held leases); it authorizes nothing.
+func (h *Held) Holding() bool { return h.rn.running() }
+
+// running reports whether stop has not been called.
+func (rn *renewer) running() bool {
+ rn.mu.Lock()
+ defer rn.mu.Unlock()
+ return !rn.stopped
+}
diff --git a/internal/lease/finalsync_test.go b/internal/lease/finalsync_test.go
new file mode 100644
index 000000000..34a2422b8
--- /dev/null
+++ b/internal/lease/finalsync_test.go
@@ -0,0 +1,158 @@
+package lease
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/benbjohnson/litestream"
+ lsfile "github.com/benbjohnson/litestream/file"
+ "github.com/superfly/ltx"
+)
+
+// refusingReplica is a file replica whose writes fail while refuse is set:
+// the bucket refusing the final sync.
+type refusingReplica struct {
+ litestream.ReplicaClient
+ refuse atomic.Bool
+}
+
+func (r *refusingReplica) WriteLTXFile(ctx context.Context, level int, min, max ltx.TXID, rd io.Reader) (*ltx.FileInfo, error) {
+ if r.refuse.Load() {
+ return nil, errors.New("synthetic replica write refusal")
+ }
+ return r.ReplicaClient.WriteLTXFile(ctx, level, min, max, rd)
+}
+
+// refusingDeletes is the lock store with every DELETE refused: a release
+// that fails after a final sync that worked.
+type refusingDeletes struct{ *lockStore }
+
+func (s refusingDeletes) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodDelete {
+ w.WriteHeader(http.StatusForbidden)
+ return
+ }
+ s.lockStore.ServeHTTP(w, r)
+}
+
+func heldOn(t *testing.T, h http.Handler) *Held {
+ t.Helper()
+ srv := httptest.NewServer(h)
+ t.Cleanup(srv.Close)
+ fakeCreds(t)
+ t.Setenv("CARLOS_S3_ENDPOINT", srv.URL)
+ held, err := AcquireTTL(context.Background(), "test-bucket", "one.example", "test-region", 10*time.Second)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = held.Release(context.Background()) })
+ return held
+}
+
+func writeRow(t *testing.T, path string) {
+ t.Helper()
+ db, err := sql.Open("sqlite", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ if _, err := db.Exec(`INSERT INTO t (body) VALUES ('tail')`); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// A Close whose final sync fails says so with a *FinalSyncError, whose text
+// is the failure's own; the lease is released anyway. A Close whose sync
+// worked but whose release failed is not one: the database's writes are in
+// the replica. Holding follows the renewer from Acquire to the Close.
+func TestCloseSaysWhenTheFinalSyncFailed(t *testing.T) {
+ t.Run("sync fails", func(t *testing.T) {
+ backend := &lockStore{}
+ h := heldOn(t, backend)
+ if !h.Holding() {
+ t.Fatal("a fresh lease is not holding")
+ }
+ path := filepath.Join(t.TempDir(), "source.db")
+ seedDB(t, path)
+ replica := &refusingReplica{ReplicaClient: lsfile.NewReplicaClient(t.TempDir())}
+ h.replicaClient = replica
+ r, err := h.Replicate(context.Background(), path, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !h.Holding() {
+ t.Fatal("the lease stopped holding when replication took it over")
+ }
+ writeRow(t, path)
+ replica.refuse.Store(true)
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ err = r.Close(ctx)
+ var fs *FinalSyncError
+ if !errors.As(err, &fs) {
+ t.Fatalf("Close = %v, want a *FinalSyncError", err)
+ }
+ if fs.Error() != fs.Err.Error() {
+ t.Fatalf("the error's text changed: %q, want %q", fs.Error(), fs.Err.Error())
+ }
+ if h.Holding() {
+ t.Fatal("the lease is still holding after Close")
+ }
+ if _, deletes := backend.counts(); deletes != 1 {
+ t.Fatalf("the lease was not released after the failed sync: %d deletes", deletes)
+ }
+ })
+ t.Run("release fails", func(t *testing.T) {
+ backend := &lockStore{}
+ h := heldOn(t, refusingDeletes{backend})
+ path := filepath.Join(t.TempDir(), "source.db")
+ seedDB(t, path)
+ h.replicaClient = lsfile.NewReplicaClient(t.TempDir())
+ r, err := h.Replicate(context.Background(), path, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ writeRow(t, path)
+ err = r.Close(context.Background())
+ var fs *FinalSyncError
+ if err == nil || errors.As(err, &fs) {
+ t.Fatalf("Close = %v, want a release failure that is not a *FinalSyncError", err)
+ }
+ if h.Holding() {
+ t.Fatal("the lease is still holding after Close")
+ }
+ })
+ t.Run("clean", func(t *testing.T) {
+ h := heldOn(t, &lockStore{})
+ path := filepath.Join(t.TempDir(), "source.db")
+ seedDB(t, path)
+ h.replicaClient = lsfile.NewReplicaClient(t.TempDir())
+ r, err := h.Replicate(context.Background(), path, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := r.Close(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.Holding() {
+ t.Fatal("the lease is still holding after Close")
+ }
+ })
+ t.Run("released", func(t *testing.T) {
+ h := heldOn(t, &lockStore{})
+ if err := h.Release(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.Holding() {
+ t.Fatal("the lease is still holding after Release")
+ }
+ })
+}
diff --git a/internal/lease/lease.go b/internal/lease/lease.go
index 3c786b0d3..1bbcb0265 100644
--- a/internal/lease/lease.go
+++ b/internal/lease/lease.go
@@ -555,7 +555,10 @@ func (r *Replicator) Close(ctx context.Context) error {
// the DB now initialized, store.Close's own final sync is the one that
// counts, and its error is returned.
_ = r.db.SyncAndWait(ctx)
- err := r.store.Close(ctx)
+ // A failed final sync is a *FinalSyncError (finalsync.go), so a caller
+ // can tell it from a failed release below: the lease is released either
+ // way, but only the first leaves writes the bucket does not hold.
+ err := finalSyncErr(r.store.Close(ctx))
lease := r.rn.stop()
if lease != nil {
diff --git a/internal/lease/release.go b/internal/lease/release.go
index e50cfcfc6..dbead2678 100644
--- a/internal/lease/release.go
+++ b/internal/lease/release.go
@@ -226,7 +226,7 @@ func (r *Replicator) closeHA(ctx context.Context) error {
lease := r.rn.stop()
relCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
- return errors.Join(r.storeCloseErr(), releaseWithMarker(relCtx, r.leaser, r.region, lease, uncleanMarker(r.base, txid)))
+ return errors.Join(finalSyncErr(r.storeCloseErr()), releaseWithMarker(relCtx, r.leaser, r.region, lease, uncleanMarker(r.base, txid)))
}
func (r *Replicator) storeCloseErr() error {
diff --git a/internal/status/contract_test.go b/internal/status/contract_test.go
index e2686bfc9..7afe8bb5c 100644
--- a/internal/status/contract_test.go
+++ b/internal/status/contract_test.go
@@ -79,7 +79,14 @@ var allowedBoxKeys = map[string][]string{
// Safe on the identical structural ground: BuildFleet's field-by-field
// copy never names "metrics", so no hostname here can reach FleetBox or
// fleet.json regardless of what this map holds.
- "": {"generated_at", "label", "name", "region", "routes", "load", "capacity", "replication", "adoption_running", "config_path_running", "restart_path_running", "expired_canaries", "metrics"},
+ //
+ // "leases_held" and "replication_failures" (managed fleets 1b, the drain
+ // rule) are COUNTS, like expired_canaries: how many instance leases the
+ // box holds, and how many hosts' final syncs failed there unresolved.
+ // No hostname, no tenant. Bucket-private like everything on Box: the
+ // console reads them to decide a drain is done, and allowedFleetKeys
+ // below names neither, so BuildFleet can never copy them into fleet.json.
+ "": {"generated_at", "label", "name", "region", "routes", "load", "capacity", "replication", "adoption_running", "config_path_running", "restart_path_running", "expired_canaries", "metrics", "leases_held", "replication_failures"},
"routes": {"static", "resident", "hibernating", "awake", "asleep"},
"replication": {"healthy", "lag_seconds"},
"metrics": {"mem_total_bytes", "mem_avail_bytes", "load1", "disk_free_bytes", "release", "tunnel", "route_versions", "upstreams", "layout", "config_refusals", "config_refusals_total", "release_refusals", "proof_waits", "config_guard", "build_states", "build_states_err", "update_settings", "updates", "egress", "size_committed_mib"},
@@ -344,8 +351,13 @@ func fixtureProbes() status.Probes {
return status.Probes{
MachineID: "test-machine-id",
Region: "us-west-1",
- Upstreams: upstreams,
- Layout: layoutReport,
+ // Non-zero drain facts, so leases_held and replication_failures
+ // are walked with a value in them, and the fleet walk proves
+ // neither reaches fleet.json.
+ LeasesHeld: 2,
+ ReplicationFailures: 1,
+ Upstreams: upstreams,
+ Layout: layoutReport,
// One refusal so metrics.config_refusals is exercised by the
// allowlist walk and not merely permitted by it.
ConfigRefusals: []status.ConfigRefusal{
diff --git a/internal/status/snapshot.go b/internal/status/snapshot.go
index 5335a80ff..c39e3a98c 100644
--- a/internal/status/snapshot.go
+++ b/internal/status/snapshot.go
@@ -99,6 +99,14 @@ type Probes struct {
// zero; 0 is itself a real, confident answer when every canary route on
// the box is fresh, or there are none at all.
ExpiredCanaries *int
+ // LeasesHeld and ReplicationFailures are the drain rule's box facts
+ // (managed fleets 1b, rule 5), read from the box's activator by the
+ // caller: the instance leases this process holds right now, and the
+ // hosts whose final sync failed on this box with no later replication
+ // landing since. Copied to Box as they are; a box with no activator
+ // reports 0 for both.
+ LeasesHeld int
+ ReplicationFailures int
// Alerts is the box's alert-sink answer (see AlertDelivery), carried
// into Box.Metrics. nil means "never asked".
Alerts *AlertDelivery
@@ -802,7 +810,9 @@ type Replication struct {
// meant for the public page; Metrics and Sidecars are the two places that
// default is intentionally suspended, gated by staying bucket-private (see
// the package doc) and excluded from FleetBox by construction (fleet.go's
-// BuildFleet copies fields one at a time and never names either).
+// BuildFleet copies fields one at a time and never names either). The drain
+// rule's two counts (LeasesHeld, ReplicationFailures) name nothing, but are
+// bucket-private on the same ground: BuildFleet never names them either.
type Box struct {
GeneratedAt time.Time `json:"generated_at"`
Label string `json:"label"`
@@ -865,6 +875,18 @@ type Box struct {
// must not reach fleet.json. omitempty keeps a box with no sidecars
// byte-identical to one written before this field existed.
Sidecars int `json:"sidecars,omitempty"`
+ // LeasesHeld and ReplicationFailures are the drain rule's two box facts
+ // (managed fleets 1b, rule 5): how many instance leases this box's
+ // activator holds right now, and how many hosts' final syncs failed
+ // here with no later replication landing since (a durable record on
+ // the box's disk, so an agent restart does not forget it). The console
+ // detaches a draining box only on a heartbeat composed after the drain
+ // began with both at 0. Counts only, no host; always on the wire, a
+ // zero included, and, like Metrics and Sidecars, never copied into
+ // FleetBox. A ReplicationFailures the box cannot read is reported as at
+ // least 1, never 0.
+ LeasesHeld int `json:"leases_held"`
+ ReplicationFailures int `json:"replication_failures"`
}
// replHealthyWithin is the lag under which replication counts as healthy.
@@ -1103,18 +1125,20 @@ func CollectBox(routes []registry.Route, p Probes, now time.Time) Box {
}
box := Box{
- GeneratedAt: now,
- Label: Label(p.MachineID),
- Region: p.Region,
- Routes: counts,
- Load: bandWord(p.MemFrac, loadWords),
- Capacity: bandWord(worst, capacityWords),
- Replication: Replication{Healthy: healthy, LagSecs: p.LagSecs},
- AdoptionRunning: p.AdoptRunning,
- ConfigPathRunning: p.ConfigPathRunning,
- RestartPathRunning: p.RestartPathRunning,
- ExpiredCanaries: p.ExpiredCanaries,
- Sidecars: sidecars,
+ GeneratedAt: now,
+ Label: Label(p.MachineID),
+ Region: p.Region,
+ Routes: counts,
+ Load: bandWord(p.MemFrac, loadWords),
+ Capacity: bandWord(worst, capacityWords),
+ Replication: Replication{Healthy: healthy, LagSecs: p.LagSecs},
+ AdoptionRunning: p.AdoptRunning,
+ ConfigPathRunning: p.ConfigPathRunning,
+ RestartPathRunning: p.RestartPathRunning,
+ ExpiredCanaries: p.ExpiredCanaries,
+ Sidecars: sidecars,
+ LeasesHeld: p.LeasesHeld,
+ ReplicationFailures: p.ReplicationFailures,
}
// Metrics attaches only when something is known โ€” an all-unknown Probes,