carlos / platform Public

Managed fleets 1b task 7: a real two-box fleet test

TestTwoBoxFleetEndToEnd_Real and its two siblings run fleet pi's two
boxes against one fake S3 fleet bucket with real ExecBackend lease takes,
real restores and the console in process: spread at create, each box
minting and locking only its own, a partitioned box that keeps renewing
while its instance moves, the move once it heals, a drain back with the
detach held until the box reports nothing, no stale read after A, B, A,
a first labelling that moves and loses nothing, and failover from a dead
box once its lease lapses.

The seams, inert in production:
- lease.AcquireAs: AcquireTTL with the lock's box given; nil is the
  process's own, exactly AcquireTTL.
- activator.ExecBackend.LeaseIdentity and LeaseTTL: unset (as the agent
  leaves them, pinned by TestAgentLeavesTheLeaseIdentityToTheProcess and
  TestExecBackendLeaseIdentityDefaultsToTheProcess) is lease.Acquire.
- console.Server.RunFleetRelabelPass(ctx, now): one worker iteration as
  of now; the worker calls it with time.Now().
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 10facfde846a12789be8d644b24b3cdb2dd46630 parent 6457152
11 files changed, +1,291 −34
  • .amadan/test-weights.tsv +2 −0
  • internal/activator/backend_exec.go +11 −0
  • internal/activator/hawake.go +23 −3
  • internal/activator/leaseidentity_test.go +82 −0
  • internal/console/fleetbox.go +11 −6
  • internal/console/fleetrelabel.go +36 −18
  • internal/console/fleetrelabel_test.go +3 −3
  • internal/host/fleettwobox_e2e_test.go +1,035 −0
  • internal/host/leaseidentity_wiring_test.go +66 −0
  • internal/lease/lease.go +16 −1
  • internal/lease/legacytake.go +6 −3

CI failed — run details

diff --git a/.amadan/test-weights.tsv b/.amadan/test-weights.tsv
index 6db1edb71..7331e0e5f 100644
--- a/.amadan/test-weights.tsv
+++ b/.amadan/test-weights.tsv
@@ -158,6 +158,8 @@ github.com/carlosframework/platform/internal/console TestPlacementFleetButtonSay
github.com/carlosframework/platform/internal/console TestLivePlacesNamedAndFleetAppRegions 0.29
github.com/carlosframework/platform/internal/console TestMoveViewsCarryLabels 0.26
github.com/carlosframework/platform/internal/host TestClaimAckRefreshProductionClient 20.09
+github.com/carlosframework/platform/internal/host TestTwoBoxFleetEndToEnd_Real 6.27
+github.com/carlosframework/platform/internal/host TestTwoBoxFleetEndToEnd_RealLostBox 6.12
github.com/carlosframework/platform/internal/host TestStalledIndexGetKeepsReconcileWalking 5.03
github.com/carlosframework/platform/internal/host TestPlan14Fix5MainEquivalence 4.37
github.com/carlosframework/platform/internal/host TestPlan9D3ProbeReadinessRefusesOutsideTheContract 3.60
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index f9706d5ca..f7ec623eb 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -25,6 +25,7 @@ import (
"github.com/carlosframework/platform/internal/applog"
"github.com/carlosframework/platform/internal/cgroup"
"github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/hafresh"
"github.com/carlosframework/platform/internal/instancectl"
"github.com/carlosframework/platform/internal/instancekey"
"github.com/carlosframework/platform/internal/instanceupdates"
@@ -74,6 +75,16 @@ const quarantineSuffix = ".corrupt"
// `<DataDir>/<host>.env` EnvironmentFile.
type ExecBackend struct {
Cfg Config
+ // LeaseIdentity and LeaseTTL are the instance lease's owner and term
+ // for a process that stands in for more than one box (the two-box
+ // fleet test, internal/host): the lock names LeaseIdentity rather than
+ // the process-global identity (lease.SetSelf), and lasts LeaseTTL. Nil
+ // and 0, as the agent leaves them, are lease.Acquire exactly: the
+ // process's own identity and lease.LeaseTTL
+ // (TestAgentLeavesTheLeaseIdentityToTheProcess). An HA acquire is not
+ // affected.
+ LeaseIdentity *hafresh.Self
+ LeaseTTL time.Duration
// OptDir is the on-box install root: the version store and the
// per-instance "live" symlinks live under it (/opt/carlos in production;
// a struct field, never hardcoded, so tests point it at a temp dir).
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go
index b643dd40e..fad03e261 100644
--- a/internal/activator/hawake.go
+++ b/internal/activator/hawake.go
@@ -236,14 +236,34 @@ func (b *ExecBackend) restoredReplication(rt registry.Route) (string, bool) {
return b.haWakes.class(rt.Host)
}
-// self is this box's lease identity: Config.Self, else lease's own.
+// self is this box's lease identity: Config.Self, else the backend's
+// LeaseIdentity, else lease's own.
func (b *ExecBackend) self() hafresh.Self {
if b.Cfg.Self != nil {
return b.Cfg.Self()
}
+ if b.LeaseIdentity != nil {
+ return *b.LeaseIdentity
+ }
return lease.CurrentSelf()
}
+// acquireLegacy is the legacy acquire of the lock under prefix. With
+// neither LeaseIdentity nor LeaseTTL set (production) it is
+// acquireLegacyLease exactly, lease.Acquire: the process's own identity and
+// lease.LeaseTTL. Either set, the lock names LeaseIdentity (nil: the
+// process's own) and lasts LeaseTTL (0: lease.LeaseTTL).
+func (b *ExecBackend) acquireLegacy(ctx context.Context, prefix string) (*lease.Held, error) {
+ if b.LeaseIdentity == nil && b.LeaseTTL == 0 {
+ return acquireLegacyLease(ctx, b.Cfg.Bucket, prefix, b.Cfg.Region)
+ }
+ ttl := b.LeaseTTL
+ if ttl == 0 {
+ ttl = lease.LeaseTTL
+ }
+ return lease.AcquireAs(ctx, b.Cfg.Bucket, prefix, b.Cfg.Region, ttl, b.LeaseIdentity)
+}
+
// leaseError maps a lease package error onto the activator's: a held lease
// is errLeaseHeld (503 with the holder's Retry-After), an HA acquire's
// refusal errLeaseRefused, and anything else as it is (an obligation that
@@ -280,7 +300,7 @@ func (b *ExecBackend) acquireClassified(ctx context.Context, rt registry.Route)
prefix := b.Cfg.hibernatePrefix(host)
b.haWakes.forget(host)
if haLegacyRoute(rt) {
- held, err := acquireLegacyLease(ctx, b.Cfg.Bucket, prefix, b.Cfg.Region)
+ held, err := b.acquireLegacy(ctx, prefix)
if err != nil {
var hl *lease.HALockError
if errors.As(err, &hl) {
@@ -296,7 +316,7 @@ func (b *ExecBackend) acquireClassified(ctx context.Context, rt registry.Route)
return nil, fmt.Errorf("refusing to wake: %w", err)
}
if !ha {
- held, err := acquireLegacyLease(ctx, b.Cfg.Bucket, prefix, b.Cfg.Region)
+ held, err := b.acquireLegacy(ctx, prefix)
if err == nil {
b.haWakes.set(host, haWake{entry: entry})
return &execLease{held: held, defaultDB: b.pathsFor(rt).dbPath}, nil
diff --git a/internal/activator/leaseidentity_test.go b/internal/activator/leaseidentity_test.go
new file mode 100644
index 000000000..a1abb184f
--- /dev/null
+++ b/internal/activator/leaseidentity_test.go
@@ -0,0 +1,82 @@
+package activator
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/lease/locktest"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// lockOf is the owner and expiry of host's lock in the fixture.
+func lockOf(t *testing.T, fx *locktest.LockFixture, host string) (string, time.Time) {
+ t.Helper()
+ var l struct {
+ Owner string `json:"owner"`
+ ExpiresAt time.Time `json:"expires_at"`
+ }
+ if err := json.Unmarshal(fx.LockBody(HibernatePrefix("instances", host)), &l); err != nil {
+ t.Fatalf("lock of %s: %v", host, err)
+ }
+ return l.Owner, l.ExpiresAt
+}
+
+// The two-box fleet test's seam (ExecBackend.LeaseIdentity and LeaseTTL)
+// is inert unset: the lock an ExecBackend with neither set writes is the
+// one lease.Acquire writes in this process, its owner and its term.
+// Set, the lock names the identity and lasts the TTL. Not parallel: the
+// lock fixture sets the environment.
+func TestExecBackendLeaseIdentityDefaultsToTheProcess(t *testing.T) {
+ fx := locktest.NewLockFixture(t)
+ ctx := context.Background()
+ cfg := Config{Bucket: fx.Bucket, Prefix: "instances"}
+
+ // What this process's own lease writes.
+ ref, err := lease.Acquire(ctx, fx.Bucket, HibernatePrefix("instances", "ref.example.com"), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ref.Release(ctx)
+ wantOwner, refExpiry := lockOf(t, fx, "ref.example.com")
+
+ plain := &ExecBackend{Cfg: cfg, DataDir: t.TempDir(), OptDir: t.TempDir()}
+ l, err := plain.Acquire(ctx, registry.Route{Host: "shop.example.com", Kind: "instance"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer l.Release(ctx)
+ owner, exp := lockOf(t, fx, "shop.example.com")
+ if owner != wantOwner {
+ t.Fatalf("unset, the lock names %q; lease.Acquire in this process names %q", owner, wantOwner)
+ }
+ if d := exp.Sub(refExpiry); d < -time.Minute || d > time.Minute {
+ t.Fatalf("unset, the lock expires at %s; lease.Acquire's at %s (lease.LeaseTTL)", exp, refExpiry)
+ }
+ if plain.self() != lease.CurrentSelf() {
+ t.Fatalf("unset, the backend's identity is %+v, not the process's %+v", plain.self(), lease.CurrentSelf())
+ }
+
+ id := hafresh.Self{Ref: "pi-1", IID: "i-pi-1", Account: "123456789012", Region: "eu-west-1", Boot: "boot-pi-1"}
+ named := &ExecBackend{Cfg: cfg, DataDir: t.TempDir(), OptDir: t.TempDir(), LeaseIdentity: &id, LeaseTTL: 30 * time.Second}
+ before := time.Now()
+ l2, err := named.Acquire(ctx, registry.Route{Host: "cafe.example.com", Kind: "instance"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer l2.Release(ctx)
+ owner, exp = lockOf(t, fx, "cafe.example.com")
+ if want := hafresh.OwnerFor(id, os.Getpid(), false); owner != want {
+ t.Fatalf("set, the lock names %q, want %q", owner, want)
+ }
+ if exp.Before(before.Add(30*time.Second)) || exp.After(time.Now().Add(30*time.Second)) {
+ t.Fatalf("set, the lock expires at %s, want 30s after the take", exp)
+ }
+ if named.self() != id {
+ t.Fatalf("set, the backend's identity is %+v, want %+v", named.self(), id)
+ }
+}
diff --git a/internal/console/fleetbox.go b/internal/console/fleetbox.go
index 31d77d934..8f3989105 100644
--- a/internal/console/fleetbox.go
+++ b/internal/console/fleetbox.go
@@ -245,12 +245,17 @@ func (s *Server) loadDeploymentBoxesComplete(ctx context.Context) (boxes []statu
return boxes, complete, nil
}
-// loadFleetView reads fleet as a labelling decision needs it. Only a
-// registry that cannot be read is an error. A fleet with fewer than two
-// active boxes reads nothing more and is not Active; otherwise anything
-// that could not be read whole (the fleet's heartbeats, the deployment's,
-// the inventory) leaves Active false.
+// loadFleetView is loadFleetViewAt as of time.Now().
func (s *Server) loadFleetView(ctx context.Context, fleet string) (fleetView, error) {
+ return s.loadFleetViewAt(ctx, fleet, time.Now())
+}
+
+// loadFleetViewAt reads fleet as a labelling decision needs it, judging
+// each box's heartbeat as of now. Only a registry that cannot be read is an
+// error. A fleet with fewer than two active boxes reads nothing more and is
+// not Active; otherwise anything that could not be read whole (the fleet's
+// heartbeats, the deployment's, the inventory) leaves Active false.
+func (s *Server) loadFleetViewAt(ctx context.Context, fleet string, now time.Time) (fleetView, error) {
v := fleetView{Load: map[string]int{}}
reg, err := s.openPassRegistry()
if err != nil {
@@ -285,7 +290,7 @@ func (s *Server) loadFleetView(ctx context.Context, fleet string) (fleetView, er
// Every active box must have said which release it runs: one with no
// heartbeat at all (attached and never reported, or silent past the
// listing's horizon) is a version the gate cannot read.
- unheard := joinBeats(v.Boxes, hbs, time.Now())
+ unheard := joinBeats(v.Boxes, hbs, now)
deploy, deployComplete, err := s.loadDeploymentBoxesComplete(ctx)
if err != nil || !deployComplete {
diff --git a/internal/console/fleetrelabel.go b/internal/console/fleetrelabel.go
index 799ee7a30..dcd7b43de 100644
--- a/internal/console/fleetrelabel.go
+++ b/internal/console/fleetrelabel.go
@@ -65,26 +65,45 @@ const fleetRelabelInterval = 5 * time.Minute
// only partitioned has lost its leases too, plus a margin.
const fleetBoxLostAfter = lease.LeaseTTL + 5*time.Minute
-// StartFleetRelabel runs fleetRelabelPass every fleetRelabelInterval. It is
-// off on a host-claim console, where no claim operation gates the record
-// writes it makes.
+// StartFleetRelabel runs RunFleetRelabelPass every fleetRelabelInterval,
+// as of the time of each pass. It is off on a host-claim console, where no
+// claim operation gates the record writes it makes.
func (s *Server) StartFleetRelabel(ctx context.Context) {
if s.cfg.HostClaim {
log.Printf("console: fleet relabel: off on a host-claim console, where no claim operation gates a relabel")
return
}
lifetimesWorker(ctx, fleetRelabelInterval, func(ctx context.Context) {
- // Each pass is a unit of record work (lifetimes_cutover.go).
- s.lifetimesIteration(ctx, "fleet relabel", true, false, func(ctx context.Context) {
- _ = s.jobs.Run(ctx, "FleetRelabel", s.fleetRelabelPass)
- })
+ _ = s.RunFleetRelabelPass(ctx, time.Now())
})
}
-// fleetRelabelPass is one pass over every fleet. A fleet whose view cannot
-// be read is logged and skipped; the others still run. The deployment's
-// heartbeat listing is read once for the whole pass.
-func (s *Server) fleetRelabelPass(ctx context.Context) error {
+// errFleetRelabelHostClaim is RunFleetRelabelPass's answer on a host-claim
+// console.
+var errFleetRelabelHostClaim = errors.New("fleet relabel is off on a host-claim console")
+
+// RunFleetRelabelPass is one iteration of the relabel worker, judged as of
+// now: whether a box is lost or fresh, and the assignment time each label
+// it writes carries. The worker calls it with time.Now(); a test drives the
+// clock with explicit times. Each pass is a unit of record work
+// (lifetimes_cutover.go) and a run of the FleetRelabel job. The answer is
+// the pass's own error (a failed fleet listing); a fleet that cannot be
+// read or a write that fails is logged and fails the job, not the call.
+func (s *Server) RunFleetRelabelPass(ctx context.Context, now time.Time) error {
+ if s.cfg.HostClaim {
+ return errFleetRelabelHostClaim
+ }
+ var err error
+ s.lifetimesIteration(ctx, "fleet relabel", true, false, func(ctx context.Context) {
+ err = s.jobs.Run(ctx, "FleetRelabel", func(ctx context.Context) error { return s.fleetRelabelPass(ctx, now) })
+ })
+ return err
+}
+
+// fleetRelabelPass is one pass over every fleet, as of now. A fleet whose
+// view cannot be read is logged and skipped; the others still run. The
+// deployment's heartbeat listing is read once for the whole pass.
+func (s *Server) fleetRelabelPass(ctx context.Context, now time.Time) error {
if s.cfg.Releases == nil || s.cfg.Registry == "" {
return nil
}
@@ -95,14 +114,14 @@ func (s *Server) fleetRelabelPass(ctx context.Context) error {
ctx = withWriteMemo(ctx)
for _, f := range fleets {
unlock := s.lockFleet(f.Name)
- v, err := s.loadFleetView(ctx, f.Name)
+ v, err := s.loadFleetViewAt(ctx, f.Name, now)
if err != nil {
log.Printf("console: fleet relabel %s: view: %v", f.Name, err)
jobFailed(ctx, err)
unlock()
continue
}
- if _, err := s.relabelFleet(ctx, f.Name, v); err != nil {
+ if _, err := s.relabelFleet(ctx, f.Name, v, now); err != nil {
log.Printf("console: fleet relabel %s: %v", f.Name, err)
jobFailed(ctx, err)
}
@@ -119,10 +138,10 @@ type relabel struct {
}
// relabelFleet is one fleet's pass, from v (read under the fleet's lock by
-// the caller). moved counts the records written. err is a read that was
-// not whole, which writes nothing; a write that fails is logged and the
-// others still run.
-func (s *Server) relabelFleet(ctx context.Context, fleet string, v fleetView) (moved int, err error) {
+// the caller), as of now. moved counts the records written. err is a read
+// that was not whole, which writes nothing; a write that fails is logged
+// and the others still run.
+func (s *Server) relabelFleet(ctx context.Context, fleet string, v fleetView, now time.Time) (moved int, err error) {
if box, rel := v.labelsPausedBy(); box != "" {
log.Printf("console: ERROR fleet %s: box %s reports release %s, below the label floor %s: relabelling is paused until it is updated",
fleet, box, releaseOrUnknown(rel), release.FleetBoxLabelFloor)
@@ -131,7 +150,6 @@ func (s *Server) relabelFleet(ctx context.Context, fleet string, v fleetView) (m
if !v.Active {
return 0, nil
}
- now := time.Now()
var plan []relabel
if v.labelActive() {
first, err := s.planFirstLabelling(ctx, fleet, v)
diff --git a/internal/console/fleetrelabel_test.go b/internal/console/fleetrelabel_test.go
index 6604a8972..85b21f0b6 100644
--- a/internal/console/fleetrelabel_test.go
+++ b/internal/console/fleetrelabel_test.go
@@ -48,7 +48,7 @@ func shopRec(t *testing.T, fx *consoleFixture, h string) *provision.Record {
// relabelPass runs one worker pass.
func relabelPass(t *testing.T, fx *consoleFixture) {
t.Helper()
- if err := fx.srv.fleetRelabelPass(context.Background()); err != nil {
+ if err := fx.srv.fleetRelabelPass(context.Background(), time.Now()); err != nil {
t.Fatalf("relabel pass: %v", err)
}
}
@@ -197,7 +197,7 @@ func TestRelabelLosesToAPlacementChange(t *testing.T) {
if err := provision.SetRecordRegion(ctx, fx.rel, fx.sqid, "shop", "a.example.com", "fleet/other"); err != nil {
t.Fatal(err)
}
- moved, err := fx.srv.relabelFleet(ctx, "pi", v)
+ moved, err := fx.srv.relabelFleet(ctx, "pi", v, time.Now())
if err != nil || moved != 0 {
t.Fatalf("relabelFleet = %d, %v; want nothing moved and no error", moved, err)
}
@@ -704,7 +704,7 @@ func TestIdlePassJudgesEveryRecord(t *testing.T) {
ctx := provision.WithLifetimes(context.Background(), provision.NewLifetimeJudge())
pass := func() {
t.Helper()
- if err := fx.srv.fleetRelabelPass(ctx); err != nil {
+ if err := fx.srv.fleetRelabelPass(ctx, time.Now()); err != nil {
t.Fatalf("relabel pass: %v", err)
}
}
diff --git a/internal/host/fleettwobox_e2e_test.go b/internal/host/fleettwobox_e2e_test.go
new file mode 100644
index 000000000..6b536417a
--- /dev/null
+++ b/internal/host/fleettwobox_e2e_test.go
@@ -0,0 +1,1035 @@
+//go:build linux
+
+package host
+
+import (
+ "context"
+ "database/sql"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/benbjohnson/litestream"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/console"
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/lease/leasetest"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+ "github.com/carlosframework/platform/internal/version"
+)
+
+// The real two-box fleet (managed fleets 1b, Task 7; spec "1b addendum").
+// TestTwoBoxFleetEndToEnd in internal/edge models the lease; these tests
+// take it for real: one fake S3 (leasetest.NewS3Server) holding fleet pi's
+// one data bucket, two boxes pi-1 and pi-2 with their own data directories,
+// registries, real activator.ExecBackends and their own lease identities,
+// and the console in process over the one deployment store. Production
+// code throughout:
+//
+// - the console's doors (fleet create, add box, place, instance create,
+// drain, detach) over HTTP with an operator's CLI token, and its
+// relabel worker's pass (Server.RunFleetRelabelPass) at explicit times;
+// - each box's reconcile (BoxProvisionConfig from the box's own
+// environment, reconcileSerializedWith), and the hub's, whose forward
+// rows carry the label;
+// - ExecBackend.Acquire and Restore (the lease take, the start rule, the
+// set-aside and the restore from the fleet bucket), the lease's renewal
+// and release, litestream replication (Lease.Replicate, Rep.Close);
+// - the heartbeat's drain facts (drainReport over a Service on the
+// backend) and the binding a wake publishes (fleetBindingHook).
+//
+// What is modelled, and why:
+// - the activator's orchestration around the backend: a wake is Acquire,
+// Restore, the app opening its database, Replicate (doWake's order);
+// a stop is Rep.Close (the final sync and the release); the edge's
+// reload retiring a host whose row is gone is a stop after reconcile
+// (RetireExcept). Spawning a child needs a version store, cgroups and
+// a binary; the start decisions this test is about are all the
+// backend's.
+// - the app: the test reads and writes the instance's database at the
+// row's DBPath while it is awake, as the app would.
+// - the heartbeat is composed as statusTick composes it
+// (status.CollectBox, the box's label, status.WriteBox under
+// fleets/pi/), with a chosen time so the console's clock can be driven;
+// - a partition is the box's view of the deployment store refusing every
+// request (records, heartbeats); its data bucket, and so its lease
+// renewal, still answers;
+// - a dead agent is Replicator.Abandon: renewal and replication stop,
+// nothing is released, the lock lapses on its TTL.
+//
+// Every lease is fleetTTL long (ExecBackend.LeaseTTL), so an expiry fits
+// in a test; the activator's own start rules do not read the TTL.
+
+const (
+ fleetName = "pi"
+ fleetBucket = "pi-fleet-data"
+ fleetRegion = "eu-west-1"
+ fleetPrefix = "instances"
+ fleetTTL = 6 * time.Second
+ fleetAddr = "ops@example.com"
+ fleetA = "a.example.com"
+ fleetB = "b.example.com"
+)
+
+// cutStore is a box's view of the deployment store: while cut, every
+// request fails, as a box partitioned from the store sees it.
+type cutStore struct {
+ release.Store
+ cut atomic.Bool
+}
+
+var errPartitioned = errors.New("partitioned: the deployment store is unreachable from this box")
+
+func (c *cutStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if c.cut.Load() {
+ return nil, "", errPartitioned
+ }
+ return c.Store.Get(ctx, key)
+}
+
+func (c *cutStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ if c.cut.Load() {
+ return "", errPartitioned
+ }
+ return c.Store.Put(ctx, key, body, ifMatch)
+}
+
+func (c *cutStore) List(ctx context.Context, prefix string) ([]string, error) {
+ if c.cut.Load() {
+ return nil, errPartitioned
+ }
+ return c.Store.List(ctx, prefix)
+}
+
+func (c *cutStore) ListDirs(ctx context.Context, prefix string) ([]string, error) {
+ if c.cut.Load() {
+ return nil, errPartitioned
+ }
+ return c.Store.ListDirs(ctx, prefix)
+}
+
+func (c *cutStore) Delete(ctx context.Context, key string) error {
+ if c.cut.Load() {
+ return errPartitioned
+ }
+ return c.Store.Delete(ctx, key)
+}
+
+// fleetWorld is the deployment: the console, the hub's registry, the fleet
+// bucket and the two boxes.
+type fleetWorld struct {
+ t *testing.T
+ s3 *leasetest.VersionedBucket
+ store release.Store // the deployment store
+ srv *console.Server
+ base string // the console's URL
+ token string
+ acct string
+ hub *registry.Registry
+ // regPath is the console's registry file.
+ regPath string
+ // now is the console's and the heartbeats' clock: it starts at the wall
+ // clock and only moves forward, by advance.
+ now time.Time
+ pi1, pi2 *fleetBox
+}
+
+// fleetBox is one box of fleet pi.
+type fleetBox struct {
+ w *fleetWorld
+ label string
+ self hafresh.Self
+ dd string
+ reg *registry.Registry
+ store *cutStore
+ eb *activator.ExecBackend
+ svc *activator.Service // the heartbeat's drain facts (DrainFacts)
+ awake map[string]activator.Rep
+}
+
+// fleetOpts shapes the fixture: rel is the release every box reports.
+type fleetOpts struct{ rel string }
+
+func newFleetWorld(t *testing.T, opts fleetOpts) *fleetWorld {
+ t.Helper()
+ ctx := context.Background()
+ if opts.rel == "" {
+ opts.rel = release.FleetBoxLabelFloor
+ }
+ t.Setenv("CARLOS_HOST_CLAIM", "")
+ // The console runs the label floor (gate d).
+ prevBuild := version.Build
+ version.Build = release.FleetBoxLabelFloor
+ t.Cleanup(func() { version.Build = prevBuild })
+
+ // The fleet's data bucket over the S3 wire protocol, on loopback.
+ fake := leasetest.NewVersionedBucket()
+ fake.AddBucket(fleetBucket)
+ h, _ := leasetest.NewS3Server(fake)
+ s3srv := httptest.NewServer(h)
+ t.Cleanup(s3srv.Close)
+ t.Setenv("AWS_ACCESS_KEY_ID", "test-key")
+ t.Setenv("AWS_SECRET_ACCESS_KEY", "test-secret")
+ t.Setenv("AWS_SESSION_TOKEN", "")
+ t.Setenv("AWS_EC2_METADATA_DISABLED", "true")
+ t.Setenv("AWS_CONFIG_FILE", filepath.Join(t.TempDir(), "absent"))
+ t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(t.TempDir(), "absent"))
+ t.Setenv("CARLOS_S3_ENDPOINT", s3srv.URL)
+
+ store := release.NewDirStore(t.TempDir())
+ keyB64, _, err := appconfig.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ priv, err := appconfig.ParsePrivateKey(keyB64, "test key")
+ if err != nil {
+ t.Fatal(err)
+ }
+ seed, pubB64, err := release.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ relPriv, err := release.ParseSigningKey(seed, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ relPub, err := release.ParsePublicKey(pubB64, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // The console, an operator and its CLI token, shop in the ops account.
+ dir := t.TempDir()
+ cst, err := console.Open(filepath.Join(dir, "console.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { cst.Close() })
+ var srv *console.Server
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv.ServeHTTP(w, r) }))
+ t.Cleanup(ts.Close)
+ if srv, err = console.NewServer(console.Config{Origin: ts.URL, Keymail: "http://keymail.invalid",
+ Registry: filepath.Join(dir, "registry.db"), Releases: store, ReleasePub: relPub, Key: relPriv, AppScheme: "http",
+ HomeRegion: "ie", SecretsPub: base64.StdEncoding.EncodeToString(priv.PublicKey().Bytes())}, cst); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ if err := cst.AddMember(console.OpsAccountID, fleetAddr, console.RoleOwner, now); err != nil {
+ t.Fatal(err)
+ }
+ if err := cst.SetOperator(fleetAddr, true); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := cst.CreateAppIn(console.OpsAccountID, "shop", fleetAddr, now); err != nil {
+ t.Fatal(err)
+ }
+ userCode, deviceCode, err := cst.NewCLIAuth("ops@laptop", "127.0.0.1", now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := cst.ApproveCLIAuth(userCode, fleetAddr, now); err != nil {
+ t.Fatal(err)
+ }
+ _, token, _, err := cst.PollCLIAuth(deviceCode, now)
+ if err != nil || token == "" {
+ t.Fatalf("no CLI token: %v", err)
+ }
+ acct := release.OpsAccount
+ if _, _, err := store.Get(ctx, domains.AccountManifestKey(acct)); errors.Is(err, os.ErrNotExist) {
+ manifest, _ := json.Marshal(map[string]any{"id": console.OpsAccountID, "sqid": acct, "name": "ops", "created_at": now})
+ if _, err := store.Put(ctx, domains.AccountManifestKey(acct), manifest, ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := provision.PutManifest(ctx, store, acct, "shop", provision.Manifest{Schema: 1, App: "shop", Domain: "example.com", Channel: "edge"}); err != nil {
+ t.Fatal(err)
+ }
+ w := &fleetWorld{t: t, s3: fake, store: store, srv: srv, base: ts.URL, token: token, acct: acct, now: now,
+ regPath: filepath.Join(dir, "registry.db")}
+
+ // Fleet pi with its data bucket, its two boxes, and shop placed on it,
+ // all through the doors.
+ w.mustDo(http.MethodPost, "/api/cli/fleets/"+acct+"/new", `{"name":"pi","bucket":"`+fleetBucket+`"}`, http.StatusOK)
+ for _, label := range []string{"pi-1", "pi-2"} {
+ w.mustDo(http.MethodPost, "/api/cli/fleets/"+acct+"/pi/boxes", `{"label":"`+label+`"}`, http.StatusOK)
+ }
+ w.mustDo(http.MethodPost, "/api/cli/apps/"+acct+"/shop/place", `{"target":"fleet/pi"}`, http.StatusOK)
+
+ // The hub: its own registry, with the fleets table it serves forward
+ // rows by.
+ hub, err := registry.Open(filepath.Join(t.TempDir(), "hub.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { hub.Close() })
+ if err := hub.UpsertFleet(registry.Fleet{Name: fleetName, Account: acct, Bucket: fleetBucket}); err != nil {
+ t.Fatal(err)
+ }
+ w.hub = hub
+
+ w.pi1 = w.newBox("pi-1")
+ w.pi2 = w.newBox("pi-2")
+ for _, b := range []*fleetBox{w.pi1, w.pi2} {
+ b.heartbeatRel(w.now, opts.rel)
+ }
+ return w
+}
+
+func (w *fleetWorld) newBox(label string) *fleetBox {
+ t := w.t
+ t.Helper()
+ b := &fleetBox{w: w, label: label, dd: t.TempDir(), store: &cutStore{Store: w.store}, awake: map[string]activator.Rep{},
+ self: hafresh.Self{Ref: label, IID: "i-" + label, Account: "123456789012", Region: fleetRegion, Boot: "boot-" + label}}
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ b.reg = reg
+ b.start()
+ t.Cleanup(func() {
+ for host, rep := range b.awake {
+ if r, ok := rep.(*lease.Replicator); ok {
+ r.Abandon(context.Background())
+ }
+ delete(b.awake, host)
+ }
+ })
+ return b
+}
+
+// start is the box's agent starting: a fresh backend and activator over
+// the box's data directory and registry, nothing awake.
+func (b *fleetBox) start() {
+ cfg := activator.Config{Bucket: fleetBucket, Region: fleetRegion, Prefix: fleetPrefix}
+ id := b.self
+ b.eb = &activator.ExecBackend{Cfg: cfg, DataDir: b.dd, OptDir: b.w.t.TempDir(), LeaseIdentity: &id, LeaseTTL: fleetTTL}
+ b.svc = activator.New(cfg, b.eb, b.reg)
+ b.awake = map[string]activator.Rep{}
+}
+
+// getenv is the box's agent environment.
+func (b *fleetBox) getenv(k string) string {
+ switch k {
+ case "CARLOS_REGION":
+ return registry.PlacementTarget(fleetName)
+ case "CARLOS_FLEET":
+ return fleetName
+ case "CARLOS_FLEET_BOX":
+ return b.label
+ case "CARLOS_DATA_DIR":
+ return b.dd
+ case "CARLOS_HIBERNATE_BUCKET":
+ return fleetBucket
+ }
+ return ""
+}
+
+// reconcile is one instances pass on the box, configured as the agent
+// configures it from its environment, then the edge reload's retire: a
+// host awake here whose row is gone is stopped.
+func (b *fleetBox) reconcile() error {
+ b.w.t.Helper()
+ cfg := BoxProvisionConfig(b.reg, b.getenv, nil, nil)
+ cfg.Lifetimes = &provision.LifetimeIndex{} // the box's own process's index
+ cfg.Layout = flatLayout
+ if cfg.FleetBox != b.label {
+ b.w.t.Fatalf("%s: the pass config names box %q", b.label, cfg.FleetBox)
+ }
+ err := reconcileSerializedWith(context.Background(), b.store, b.reg, cfg, nil)
+ for host := range b.awake {
+ if rt, gerr := b.reg.Get(host); gerr == nil && rt == nil {
+ if serr := b.stop(host); serr != nil {
+ b.w.t.Fatalf("%s: retire %s: %v", b.label, host, serr)
+ }
+ }
+ }
+ return err
+}
+
+func (b *fleetBox) mustReconcile() {
+ b.w.t.Helper()
+ if err := b.reconcile(); err != nil {
+ b.w.t.Fatalf("%s: reconcile: %v", b.label, err)
+ }
+}
+
+func (b *fleetBox) row(host string) *registry.Route {
+ b.w.t.Helper()
+ rt, err := b.reg.Get(host)
+ if err != nil {
+ b.w.t.Fatal(err)
+ }
+ return rt
+}
+
+func (b *fleetBox) hosts() []string {
+ b.w.t.Helper()
+ routes, err := b.reg.List()
+ if err != nil {
+ b.w.t.Fatal(err)
+ }
+ var out []string
+ for _, rt := range routes {
+ out = append(out, rt.Host)
+ }
+ return out
+}
+
+// wake is the activator's wake of host on this box, in doWake's order:
+// the lease, the restore, the app opening its database, replication. On
+// success the box publishes its binding, as the wake hook does.
+func (b *fleetBox) wake(host string) error {
+ b.w.t.Helper()
+ ctx := context.Background()
+ rt := b.row(host)
+ if rt == nil {
+ return fmt.Errorf("%s: no row for %s", b.label, host)
+ }
+ l, err := b.eb.Acquire(ctx, *rt)
+ if err != nil {
+ return err
+ }
+ if _, err := b.eb.Restore(ctx, *rt); err != nil {
+ _ = l.Release(ctx)
+ return err
+ }
+ db, err := sql.Open("sqlite", rt.DBPath)
+ if err != nil {
+ _ = l.Release(ctx)
+ return err
+ }
+ for _, q := range []string{`PRAGMA journal_mode=WAL`, `CREATE TABLE IF NOT EXISTS kv (k TEXT PRIMARY KEY, v TEXT)`} {
+ if _, err := db.Exec(q); err != nil {
+ db.Close()
+ _ = l.Release(ctx)
+ return err
+ }
+ }
+ if err := db.Close(); err != nil {
+ _ = l.Release(ctx)
+ return err
+ }
+ rep, err := l.Replicate(ctx, rt.DBPath, 0)
+ if err != nil {
+ _ = l.Release(ctx)
+ return err
+ }
+ b.awake[host] = rep
+ fleetBindingHook(b.store, fleetName, b.label)(*rt)
+ return nil
+}
+
+func (b *fleetBox) mustWake(host string) {
+ b.w.t.Helper()
+ if err := b.wake(host); err != nil {
+ b.w.t.Fatalf("%s: wake %s: %v", b.label, host, err)
+ }
+}
+
+// stop is the activator's stop: the final sync and the lease's release.
+func (b *fleetBox) stop(host string) error {
+ rep, ok := b.awake[host]
+ if !ok {
+ return fmt.Errorf("%s: %s is not awake", b.label, host)
+ }
+ delete(b.awake, host)
+ return rep.Close(context.Background())
+}
+
+func (b *fleetBox) mustStop(host string) {
+ b.w.t.Helper()
+ if err := b.stop(host); err != nil {
+ b.w.t.Fatalf("%s: stop %s: %v", b.label, host, err)
+ }
+}
+
+// crash is the box's agent dying with host awake: no final sync, no
+// release.
+func (b *fleetBox) crash() {
+ for host, rep := range b.awake {
+ rep.(*lease.Replicator).Abandon(context.Background())
+ delete(b.awake, host)
+ }
+}
+
+// dbPath is the database of host's row here.
+func (b *fleetBox) dbPath(host string) string {
+ b.w.t.Helper()
+ if rt := b.row(host); rt != nil && rt.DBPath != "" {
+ return rt.DBPath
+ }
+ return provision.DefaultDBPath(b.dd, host)
+}
+
+// write is the app on this box setting the instance's value, then waiting
+// for the replica to have it.
+func (b *fleetBox) write(host, v string) {
+ t := b.w.t
+ t.Helper()
+ rep, ok := b.awake[host]
+ if !ok {
+ t.Fatalf("%s: write %s: not awake", b.label, host)
+ }
+ db, err := sql.Open("sqlite", b.dbPath(host))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := db.Exec(`INSERT INTO kv (k, v) VALUES ('n', ?) ON CONFLICT (k) DO UPDATE SET v = excluded.v`, v); err != nil {
+ t.Fatal(err)
+ }
+ if err := db.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if err := rep.(*lease.Replicator).SyncAndWait(context.Background()); err != nil {
+ t.Fatalf("%s: sync %s: %v", b.label, host, err)
+ }
+}
+
+// read is the app on this box reading the instance's value ("" for none).
+func (b *fleetBox) read(host string) string {
+ t := b.w.t
+ t.Helper()
+ if _, ok := b.awake[host]; !ok {
+ t.Fatalf("%s: read %s: not awake", b.label, host)
+ }
+ db, err := sql.Open("sqlite", b.dbPath(host))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ var v string
+ err = db.QueryRow(`SELECT v FROM kv WHERE k = 'n'`).Scan(&v)
+ if errors.Is(err, sql.ErrNoRows) {
+ return ""
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ return v
+}
+
+// setAside is the host's set-aside entries on this box.
+func (b *fleetBox) setAside(host string) []string {
+ b.w.t.Helper()
+ ents, err := os.ReadDir(filepath.Join(b.dd, ".superseded", host))
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ b.w.t.Fatal(err)
+ }
+ var out []string
+ for _, e := range ents {
+ out = append(out, e.Name())
+ }
+ return out
+}
+
+// heartbeat writes the box's heartbeat composed at at, at the label floor.
+func (b *fleetBox) heartbeat(at time.Time) status.Box {
+ return b.heartbeatRel(at, release.FleetBoxLabelFloor)
+}
+
+// heartbeatRel is statusTick's composition with a chosen time and
+// release: the box's routes, the drain facts, its label, written under
+// fleets/pi/.
+func (b *fleetBox) heartbeatRel(at time.Time, rel string) status.Box {
+ t := b.w.t
+ t.Helper()
+ routes, err := b.reg.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ p := status.Probes{MachineID: "machine-" + b.label, Release: rel}
+ drainReport(&p, b.svc, b.dd)
+ box := status.CollectBox(routes, p, at)
+ box.Label = b.label
+ if err := status.WriteBox(context.Background(), release.NewPrefixStore(b.store, "fleets/"+fleetName+"/"), box); err != nil {
+ t.Fatalf("%s: heartbeat: %v", b.label, err)
+ }
+ return box
+}
+
+// lock is the lock of host in the fleet bucket: its owner's box ref and
+// its expiry, ok false when there is none.
+func (w *fleetWorld) lock(host string) (ref string, expires time.Time, ok bool) {
+ w.t.Helper()
+ body, ok := w.s3.Current(fleetBucket, fleetPrefix+"/"+host+"/lock.json")
+ if !ok {
+ return "", time.Time{}, false
+ }
+ var l litestream.Lease
+ if err := json.Unmarshal(body, &l); err != nil {
+ w.t.Fatal(err)
+ }
+ o, parsed := hafresh.ParseOwner(l.Owner)
+ if !parsed {
+ w.t.Fatalf("lock of %s names %q, not a box", host, l.Owner)
+ }
+ return o.Ref, l.ExpiresAt, true
+}
+
+func (w *fleetWorld) wantLock(host, box string) time.Time {
+ w.t.Helper()
+ ref, exp, ok := w.lock(host)
+ if !ok || ref != box {
+ w.t.Fatalf("lock of %s: box %q (present %v), want %s", host, ref, ok, box)
+ }
+ return exp
+}
+
+func (w *fleetWorld) wantNoLock(host string) {
+ w.t.Helper()
+ if ref, _, ok := w.lock(host); ok {
+ w.t.Fatalf("lock of %s still names %s", host, ref)
+ }
+}
+
+func (w *fleetWorld) do(method, path, body string) (int, string) {
+ w.t.Helper()
+ req, err := http.NewRequest(method, w.base+path, strings.NewReader(body))
+ if err != nil {
+ w.t.Fatal(err)
+ }
+ req.Header.Set("Authorization", "Bearer "+w.token)
+ req.Header.Set("Content-Type", "application/json")
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ w.t.Fatal(err)
+ }
+ defer res.Body.Close()
+ raw, _ := io.ReadAll(res.Body)
+ return res.StatusCode, string(raw)
+}
+
+func (w *fleetWorld) mustDo(method, path, body string, want int) string {
+ w.t.Helper()
+ code, out := w.do(method, path, body)
+ if code != want {
+ w.t.Fatalf("%s %s = %d %s, want %d", method, path, code, out, want)
+ }
+ return out
+}
+
+// create is `carlos instances create` of shop at host.
+func (w *fleetWorld) create(host string) provision.Record {
+ w.t.Helper()
+ w.mustDo(http.MethodPost, "/api/cli/apps/"+w.acct+"/shop/instances", `{"host":"`+host+`"}`, http.StatusCreated)
+ return w.record(host)
+}
+
+func (w *fleetWorld) record(host string) provision.Record {
+ w.t.Helper()
+ rec, err := provision.GetRecord(context.Background(), w.store, w.acct, "shop", host)
+ if err != nil {
+ w.t.Fatal(err)
+ }
+ return *rec
+}
+
+func (w *fleetWorld) wantRecord(host, box string, moved bool) provision.Record {
+ w.t.Helper()
+ rec := w.record(host)
+ if rec.FleetBox != box || rec.FleetBoxMoved != moved || (box != "" && rec.FleetBoxAt == "") {
+ w.t.Fatalf("record %s: box %q at %q moved %v; want box %q moved %v", host, rec.FleetBox, rec.FleetBoxAt, rec.FleetBoxMoved, box, moved)
+ }
+ return rec
+}
+
+// relabel is one pass of the console's relabel worker at the world's clock.
+func (w *fleetWorld) relabel() {
+ w.t.Helper()
+ if err := w.srv.RunFleetRelabelPass(context.Background(), w.now); err != nil {
+ w.t.Fatalf("relabel pass: %v", err)
+ }
+}
+
+func (w *fleetWorld) advance(d time.Duration) { w.now = w.now.Add(d) }
+
+// forwards runs the hub's instances pass and answers each forward row's
+// box.
+func (w *fleetWorld) forwards() map[string]string {
+ w.t.Helper()
+ env := map[string]string{"CARLOS_TUNNEL_HOST": "tunnel.example.com", "CARLOS_DATA_DIR": w.t.TempDir()}
+ getenv := func(k string) string { return env[k] }
+ cfg := BoxProvisionConfig(w.hub, getenv, nil, nil)
+ cfg.Lifetimes = &provision.LifetimeIndex{}
+ cfg.Layout = flatLayout
+ if cfg.FleetOwners == nil {
+ w.t.Fatal("the hub's pass is not armed for forward rows")
+ }
+ if err := reconcileSerializedWith(context.Background(), w.store, w.hub, cfg, nil); err != nil {
+ w.t.Fatalf("hub reconcile: %v", err)
+ }
+ routes, err := w.hub.List()
+ if err != nil {
+ w.t.Fatal(err)
+ }
+ out := map[string]string{}
+ for _, rt := range routes {
+ if rt.IsForward() {
+ out[rt.Host] = rt.FleetBox
+ }
+ }
+ return out
+}
+
+func (w *fleetWorld) wantForwards(want map[string]string) {
+ w.t.Helper()
+ got := w.forwards()
+ if len(got) != len(want) {
+ w.t.Fatalf("forward rows %v, want %v", got, want)
+ }
+ for h, b := range want {
+ if got[h] != b {
+ w.t.Fatalf("forward rows %v, want %v", got, want)
+ }
+ }
+}
+
+// boxRow is fleet pi's console registry row for label, read on a fresh
+// handle.
+func (w *fleetWorld) boxRow(label string) registry.FleetBox {
+ w.t.Helper()
+ boxes, err := w.fleetBoxes()
+ if err != nil {
+ w.t.Fatal(err)
+ }
+ for _, b := range boxes {
+ if b.Label == label {
+ return b
+ }
+ }
+ w.t.Fatalf("no box %s", label)
+ return registry.FleetBox{}
+}
+
+func (w *fleetWorld) fleetBoxes() ([]registry.FleetBox, error) {
+ reg, err := registry.Open(w.regPath)
+ if err != nil {
+ return nil, err
+ }
+ defer reg.Close()
+ return reg.ListFleetBoxes(fleetName)
+}
+
+func wantOnly(t *testing.T, b *fleetBox, hosts ...string) {
+ t.Helper()
+ got := b.hosts()
+ if len(got) != len(hosts) {
+ t.Fatalf("%s holds rows %v, want %v", b.label, got, hosts)
+ }
+ for i := range hosts {
+ if got[i] != hosts[i] {
+ t.Fatalf("%s holds rows %v, want %v", b.label, got, hosts)
+ }
+ }
+}
+
+// waitUntil polls ok every 100ms until it holds or limit passes.
+func waitUntil(t *testing.T, limit time.Duration, what string, ok func() bool) {
+ t.Helper()
+ deadline := time.Now().Add(limit)
+ for !ok() {
+ if time.Now().After(deadline) {
+ t.Fatalf("after %s: %s", limit, what)
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+}
+
+// TestTwoBoxFleetEndToEnd_Real is the scenario's main line: spread at
+// create, each box minting and locking only its own, a partitioned box
+// that keeps renewing while its instance moves, the move once it heals, a
+// drain back, and no stale read after A, then B, then A.
+func TestTwoBoxFleetEndToEnd_Real(t *testing.T) {
+ w := newFleetWorld(t, fleetOpts{})
+ pi1, pi2 := w.pi1, w.pi2
+
+ // (1) Two instances land one per box (the fewest records, ties by
+ // label), and the hub's forward rows name them.
+ w.create(fleetA)
+ w.wantRecord(fleetA, "pi-1", false)
+ w.create(fleetB)
+ w.wantRecord(fleetB, "pi-2", false)
+ w.wantForwards(map[string]string{fleetA: "pi-1", fleetB: "pi-2"})
+
+ // (2) Each box mints only its own, and each lock names its box.
+ pi1.mustReconcile()
+ pi2.mustReconcile()
+ wantOnly(t, pi1, fleetA)
+ wantOnly(t, pi2, fleetB)
+ pi1.mustWake(fleetA)
+ pi2.mustWake(fleetB)
+ w.wantLock(fleetA, "pi-1")
+ w.wantLock(fleetB, "pi-2")
+ if err := pi2.wake(fleetA); err == nil || !strings.Contains(err.Error(), "no row") {
+ t.Fatalf("pi-2 woke a, which is pi-1's: %v", err)
+ }
+
+ // (3) a on pi-1 writes 1; b on pi-2 writes b1 and sleeps.
+ pi1.write(fleetA, "1")
+ pi2.write(fleetB, "b1")
+ pi2.mustStop(fleetB)
+ w.wantNoLock(fleetB)
+ pi1.heartbeat(w.now)
+ pi2.heartbeat(w.now)
+
+ // pi-1 is partitioned from the deployment store. Its heartbeat stops;
+ // its lease, on the data bucket, keeps renewing. Past the lost-box
+ // horizon the relabel moves a to pi-2, the one fresh box.
+ pi1.store.cut.Store(true)
+ w.advance(25 * time.Minute)
+ pi2.heartbeat(w.now)
+ w.relabel()
+ moved := w.wantRecord(fleetA, "pi-2", true)
+ w.wantRecord(fleetB, "pi-2", false)
+ w.wantForwards(map[string]string{fleetA: "pi-2", fleetB: "pi-2"})
+
+ // pi-1 cannot read the relabel: it keeps a's row, awake.
+ if err := pi1.reconcile(); err == nil {
+ t.Fatal("pi-1's pass read the store through the partition")
+ }
+ wantOnly(t, pi1, fleetA)
+ // pi-2 mints a and waits: the lease is pi-1's, and pi-1 renews it past
+ // the expiry it had when pi-2 first asked.
+ pi2.mustReconcile()
+ wantOnly(t, pi2, fleetA, fleetB)
+ if rt := pi2.row(fleetA); rt.Assigned != moved.FleetBoxAt || !rt.Moved {
+ t.Fatalf("pi-2's row of a: assigned %q moved %v, want %q moved", rt.Assigned, rt.Moved, moved.FleetBoxAt)
+ }
+ first := w.wantLock(fleetA, "pi-1")
+ if err := pi2.wake(fleetA); err == nil || !strings.Contains(err.Error(), "lease held") {
+ t.Fatalf("pi-2 woke a under pi-1's lease: %v", err)
+ }
+ waitUntil(t, 3*fleetTTL, "pi-1 renewed a's lease past its first expiry", func() bool {
+ _, exp, ok := w.lock(fleetA)
+ return ok && exp.After(first) && time.Now().After(first)
+ })
+ if err := pi2.wake(fleetA); err == nil || !strings.Contains(err.Error(), "lease held") {
+ t.Fatalf("pi-2 woke a under pi-1's renewed lease: %v", err)
+ }
+ w.wantLock(fleetA, "pi-1")
+ if _, err := os.Stat(pi2.dbPath(fleetA)); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("pi-2 has a copy of a while waiting: %v", err)
+ }
+
+ // Heal: pi-1 reads the relabel, drops the row, stops a (its final sync)
+ // and releases the lease.
+ pi1.store.cut.Store(false)
+ pi1.mustReconcile()
+ wantOnly(t, pi1)
+ if len(pi1.awake) != 0 {
+ t.Fatalf("pi-1 still has %d awake", len(pi1.awake))
+ }
+ w.wantNoLock(fleetA)
+ pi1.heartbeat(w.now)
+ // pi-2 takes the lease, restores, reads 1, writes 2.
+ pi2.mustWake(fleetA)
+ w.wantLock(fleetA, "pi-2")
+ if got := pi2.read(fleetA); got != "1" {
+ t.Fatalf("pi-2 read %q from a after the move, want 1", got)
+ }
+ pi2.write(fleetA, "2")
+
+ // (4) Drain pi-2: a and b move to pi-1. pi-2 stays attached until its
+ // heartbeat says it holds nothing.
+ w.mustDo(http.MethodPost, "/api/cli/fleets/"+w.acct+"/pi/boxes/pi-2/drain", `{}`, http.StatusOK)
+ w.wantRecord(fleetA, "pi-1", true)
+ w.wantRecord(fleetB, "pi-1", true)
+ w.wantForwards(map[string]string{fleetA: "pi-1", fleetB: "pi-1"})
+ row := w.boxRow("pi-2")
+ if row.DrainingSince == 0 || row.Status != "active" {
+ t.Fatalf("pi-2 after the drain: %+v, want active and draining", row)
+ }
+ since := time.Unix(0, row.DrainingSince)
+ w.advance(time.Minute)
+ if hb := pi2.heartbeat(w.now); hb.LeasesHeld != 1 {
+ t.Fatalf("pi-2 reports %d leases held, want 1 (a)", hb.LeasesHeld)
+ }
+ w.mustDo(http.MethodPost, "/api/cli/fleets/"+w.acct+"/pi/boxes/pi-2/detach", `{}`, http.StatusConflict)
+ pi2.mustReconcile()
+ wantOnly(t, pi2)
+ w.wantNoLock(fleetA)
+ at := w.now.Add(3 * time.Minute)
+ if since.Add(3 * time.Minute).After(at) {
+ at = since.Add(3 * time.Minute)
+ }
+ w.now = at
+ if hb := pi2.heartbeat(w.now); hb.LeasesHeld != 0 || hb.ReplicationFailures != 0 || hb.Routes.Resident+hb.Routes.Hibernating != 0 {
+ t.Fatalf("drained pi-2 reports %+v routes, %d leases, %d failures", hb.Routes, hb.LeasesHeld, hb.ReplicationFailures)
+ }
+ w.mustDo(http.MethodPost, "/api/cli/fleets/"+w.acct+"/pi/boxes/pi-2/detach", `{}`, http.StatusOK)
+
+ // pi-1 wakes a under the new assignment: its old copy (written under
+ // the first) is set aside, the bucket's restored, and it reads 2, not
+ // the 1 it left behind.
+ pi1.mustReconcile()
+ wantOnly(t, pi1, fleetA, fleetB)
+ if n := len(pi1.setAside(fleetA)); n != 0 {
+ t.Fatalf("pi-1 set aside %d copies of a before the wake", n)
+ }
+ pi1.mustWake(fleetA)
+ if got := pi1.read(fleetA); got != "2" {
+ t.Fatalf("pi-1 read %q from a after A, B, A; want 2", got)
+ }
+ if n := len(pi1.setAside(fleetA)); n != 1 {
+ t.Fatalf("pi-1 set aside %d copies of a, want 1 (the copy kept under the first assignment)", n)
+ }
+ w.wantLock(fleetA, "pi-1")
+ // b, never on pi-1 before, restores the copy pi-2 left.
+ pi1.mustWake(fleetB)
+ if got := pi1.read(fleetB); got != "b1" {
+ t.Fatalf("pi-1 read %q from b, want b1", got)
+ }
+ if n := len(pi1.setAside(fleetB)); n != 0 {
+ t.Fatalf("pi-1 set aside %d copies of b, which it never had", n)
+ }
+ pi1.mustStop(fleetA)
+ pi1.mustStop(fleetB)
+}
+
+// TestTwoBoxFleetEndToEnd_RealFirstLabelling is step 5: a fleet whose
+// instances were created and served unlabelled (its boxes below the label
+// floor) is labelled once every box is on the floor, each record to the
+// box its binding names. Nothing moves and nothing is lost: each box sets
+// its copy aside once and restores the same data.
+func TestTwoBoxFleetEndToEnd_RealFirstLabelling(t *testing.T) {
+ w := newFleetWorld(t, fleetOpts{rel: "v0.32.9"})
+ pi1, pi2 := w.pi1, w.pi2
+ w.create(fleetA)
+ w.wantRecord(fleetA, "", false)
+ w.create(fleetB)
+ w.wantRecord(fleetB, "", false)
+
+ // Unlabelled, as on main: both boxes mint both, the lease picks the
+ // writer, and the winning wake publishes its binding.
+ pi1.mustReconcile()
+ pi2.mustReconcile()
+ wantOnly(t, pi1, fleetA, fleetB)
+ wantOnly(t, pi2, fleetA, fleetB)
+ pi1.mustWake(fleetA)
+ pi1.write(fleetA, "1")
+ pi1.mustStop(fleetA)
+ pi2.mustWake(fleetB)
+ pi2.write(fleetB, "b1")
+ pi2.mustStop(fleetB)
+
+ // While the boxes run an older release the pass labels nothing.
+ pi1.heartbeatRel(w.now, "v0.32.9")
+ pi2.heartbeatRel(w.now, "v0.32.9")
+ w.relabel()
+ w.wantRecord(fleetA, "", false)
+ w.wantRecord(fleetB, "", false)
+
+ // Both boxes reach the floor: the first labelling follows the bindings.
+ w.advance(time.Minute)
+ pi1.heartbeat(w.now)
+ pi2.heartbeat(w.now)
+ w.relabel()
+ w.wantRecord(fleetA, "pi-1", false)
+ w.wantRecord(fleetB, "pi-2", false)
+ w.wantForwards(map[string]string{fleetA: "pi-1", fleetB: "pi-2"})
+
+ pi1.mustReconcile()
+ pi2.mustReconcile()
+ wantOnly(t, pi1, fleetA)
+ wantOnly(t, pi2, fleetB)
+ for _, c := range []struct {
+ b *fleetBox
+ host, val string
+ }{{pi1, fleetA, "1"}, {pi2, fleetB, "b1"}} {
+ c.b.mustWake(c.host)
+ if got := c.b.read(c.host); got != c.val {
+ t.Fatalf("%s read %q from %s after the first labelling, want %s", c.b.label, got, c.host, c.val)
+ }
+ if n := len(c.b.setAside(c.host)); n != 1 {
+ t.Fatalf("%s set aside %d copies of %s, want 1", c.b.label, n, c.host)
+ }
+ w.wantLock(c.host, c.b.label)
+ c.b.write(c.host, c.val+"+")
+ c.b.mustStop(c.host)
+ // The next wake keeps the copy: it was kept under this assignment.
+ c.b.mustWake(c.host)
+ if got := c.b.read(c.host); got != c.val+"+" {
+ t.Fatalf("%s read %q from %s on a warm wake, want %s+", c.b.label, got, c.host, c.val)
+ }
+ if n := len(c.b.setAside(c.host)); n != 1 {
+ t.Fatalf("%s set aside %d copies of %s after a warm wake, want still 1", c.b.label, n, c.host)
+ }
+ c.b.mustStop(c.host)
+ }
+}
+
+// TestTwoBoxFleetEndToEnd_RealLostBox is step 6: pi-1's agent dies with a
+// awake, without releasing. Its records move once it has been silent past
+// the lost-box horizon, and pi-2 takes the lease when it lapses (the short
+// TTL), restores and serves. When pi-1 comes back it drops a.
+func TestTwoBoxFleetEndToEnd_RealLostBox(t *testing.T) {
+ w := newFleetWorld(t, fleetOpts{})
+ pi1, pi2 := w.pi1, w.pi2
+ w.create(fleetA)
+ w.wantRecord(fleetA, "pi-1", false)
+ pi1.mustReconcile()
+ pi2.mustReconcile()
+ wantOnly(t, pi1, fleetA)
+ wantOnly(t, pi2)
+ pi1.mustWake(fleetA)
+ pi1.write(fleetA, "1")
+ pi1.heartbeat(w.now)
+ pi2.heartbeat(w.now)
+
+ pi1.crash()
+ expires := w.wantLock(fleetA, "pi-1")
+ w.advance(25 * time.Minute)
+ pi2.heartbeat(w.now)
+ w.relabel()
+ w.wantRecord(fleetA, "pi-2", true)
+ pi2.mustReconcile()
+ wantOnly(t, pi2, fleetA)
+ if time.Now().Before(expires) {
+ if err := pi2.wake(fleetA); err == nil || !strings.Contains(err.Error(), "lease held") {
+ t.Fatalf("pi-2 woke a before pi-1's lease lapsed: %v", err)
+ }
+ }
+ for deadline := time.Now().Add(3 * fleetTTL); ; time.Sleep(100 * time.Millisecond) {
+ err := pi2.wake(fleetA)
+ if err == nil {
+ break
+ }
+ if !strings.Contains(err.Error(), "lease held") || time.Now().After(deadline) {
+ t.Fatalf("pi-2's wake of a, %s after pi-1's lease was due to lapse: %v", time.Since(expires).Round(time.Millisecond), err)
+ }
+ }
+ w.wantLock(fleetA, "pi-2")
+ if got := pi2.read(fleetA); got != "1" {
+ t.Fatalf("pi-2 read %q from a after the failover, want 1", got)
+ }
+ pi2.write(fleetA, "2")
+
+ // pi-1 comes back: a new agent over the same disk. Its pass no longer
+ // admits a and drops the row; it never takes the lease.
+ pi1.start()
+ pi1.mustReconcile()
+ wantOnly(t, pi1)
+ w.wantLock(fleetA, "pi-2")
+ pi2.mustStop(fleetA)
+}
diff --git a/internal/host/leaseidentity_wiring_test.go b/internal/host/leaseidentity_wiring_test.go
new file mode 100644
index 000000000..4364b69e6
--- /dev/null
+++ b/internal/host/leaseidentity_wiring_test.go
@@ -0,0 +1,66 @@
+package host
+
+import (
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "os"
+ "strings"
+ "testing"
+)
+
+// TestAgentLeavesTheLeaseIdentityToTheProcess pins the production side of
+// the two-box fleet test's seam (activator.ExecBackend.LeaseIdentity and
+// LeaseTTL, fleettwobox_e2e_test.go): no ExecBackend this package builds
+// outside its tests sets either, and nothing assigns them, so every box's
+// instance lease names the process's own identity (lease.SetSelf) and lasts
+// lease.LeaseTTL.
+func TestAgentLeavesTheLeaseIdentityToTheProcess(t *testing.T) {
+ t.Parallel()
+ entries, err := os.ReadDir(".")
+ if err != nil {
+ t.Fatal(err)
+ }
+ seam := map[string]bool{"LeaseIdentity": true, "LeaseTTL": true}
+ literals := 0
+ for _, e := range entries {
+ name := e.Name()
+ if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
+ continue
+ }
+ fset := token.NewFileSet()
+ f, err := parser.ParseFile(fset, name, nil, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ast.Inspect(f, func(n ast.Node) bool {
+ switch n := n.(type) {
+ case *ast.CompositeLit:
+ sel, ok := n.Type.(*ast.SelectorExpr)
+ if !ok || sel.Sel.Name != "ExecBackend" {
+ return true
+ }
+ literals++
+ for _, elt := range n.Elts {
+ if kv, ok := elt.(*ast.KeyValueExpr); ok {
+ if k, ok := kv.Key.(*ast.Ident); ok && seam[k.Name] {
+ t.Errorf("%s: an ExecBackend sets %s", fset.Position(kv.Pos()), k.Name)
+ }
+ }
+ }
+ case *ast.SelectorExpr:
+ // lease.LeaseTTL is the constant itself, not the field.
+ if pkg, ok := n.X.(*ast.Ident); ok && pkg.Name == "lease" {
+ return true
+ }
+ if seam[n.Sel.Name] {
+ t.Errorf("%s: production code reaches .%s", fset.Position(n.Pos()), n.Sel.Name)
+ }
+ }
+ return true
+ })
+ }
+ if literals == 0 {
+ t.Fatal("no ExecBackend literal found in the package: the agent's wiring moved, and this test no longer sees it")
+ }
+}
diff --git a/internal/lease/lease.go b/internal/lease/lease.go
index 1bbcb0265..3ce6de7c9 100644
--- a/internal/lease/lease.go
+++ b/internal/lease/lease.go
@@ -182,6 +182,17 @@ func Acquire(ctx context.Context, bucket, prefix, region string) (*Held, error)
// proportionally often and lapses proportionally fast, which is what
// makes "the holder went dark" observable.
func AcquireTTL(ctx context.Context, bucket, prefix, region string, ttl time.Duration) (*Held, error) {
+ return AcquireAs(ctx, bucket, prefix, region, ttl, nil)
+}
+
+// AcquireAs is AcquireTTL with the box the lock names given, instead of the
+// process's own (SetSelf). nil is the process's own, exactly AcquireTTL:
+// the owner currentOwner writes, and the previous-boot take judged against
+// CurrentSelf. Production passes nil everywhere. A non-nil self is for a
+// process that stands in for more than one box (the two-box fleet test),
+// where the process-global identity cannot say which box is taking the
+// lock: the lock names self, and only self's earlier boot is taken early.
+func AcquireAs(ctx context.Context, bucket, prefix, region string, ttl time.Duration, self *hafresh.Self) (*Held, error) {
// The leaser wants a ready-made S3 client (unlike the replica client,
// which builds its own). Default AWS credential chain, and the
// CARLOS_S3_ENDPOINT override applied — see endpoint.go for why the lock
@@ -201,6 +212,10 @@ func AcquireTTL(ctx context.Context, bucket, prefix, region string, ttl time.Dur
leaser.Path = prefix // lock lives at <prefix>/lock.json, colocated with the replica
leaser.TTL = ttl
leaser.Owner = currentOwner(false) // the box, once agentEntry named it (self.go)
+ judgeAs := CurrentSelf()
+ if self != nil {
+ leaser.Owner, judgeAs = hafresh.OwnerFor(*self, os.Getpid(), false), *self
+ }
started := time.Now()
lease, err := createLease(ctx, client, leaser)
@@ -209,7 +224,7 @@ func AcquireTTL(ctx context.Context, bucket, prefix, region string, ttl time.Dur
// does (legacytake.go): an HA-format lock is *HALockError and a
// live one *HeldError, both with nothing written; an expired one
// is taken conditional on the ETag it was read at.
- lease, err = takeLegacy(ctx, client, leaser)
+ lease, err = takeLegacy(ctx, client, leaser, judgeAs)
}
if err != nil {
return nil, fmt.Errorf("acquire lease: %w", err)
diff --git a/internal/lease/legacytake.go b/internal/lease/legacytake.go
index 4d41042b1..0b13f88fc 100644
--- a/internal/lease/legacytake.go
+++ b/internal/lease/legacytake.go
@@ -50,7 +50,10 @@ const takeRounds = 3
// (If-None-Match: * when it was gone).
//
// A lost condition re-reads and reclassifies, at most takeRounds times.
-func takeLegacy(ctx context.Context, client lss3.S3API, l *lss3.Leaser) (*litestream.Lease, error) {
+//
+// self is the box the take is for (AcquireAs; CurrentSelf in production):
+// only a lock it wrote under an earlier boot is taken before its expiry.
+func takeLegacy(ctx context.Context, client lss3.S3API, l *lss3.Leaser, self hafresh.Self) (*litestream.Lease, error) {
key := lss3.DefaultLeasePath
if l.Path != "" {
key = l.Path + "/" + lss3.DefaultLeasePath
@@ -63,9 +66,9 @@ func takeLegacy(ctx context.Context, client lss3.S3API, l *lss3.Leaser) (*litest
return &HALockError{View: v}
}
if !leaseFree(v.Lock.ExpiresAt, time.Now()) {
- if o, ok := hafresh.ParseOwner(v.Lock.Owner); ok && hafresh.PreviousBoot(o, CurrentSelf()) {
+ if o, ok := hafresh.ParseOwner(v.Lock.Owner); ok && hafresh.PreviousBoot(o, self) {
log.Printf("lease: taking %s from this box's previous boot (%s -> %s); the lock would have expired at %s",
- key, o.Boot, CurrentSelf().Boot, v.Lock.ExpiresAt.UTC().Format(time.RFC3339))
+ key, o.Boot, self.Boot, v.Lock.ExpiresAt.UTC().Format(time.RFC3339))
return nil
}
return &HeldError{Owner: v.Lock.Owner, ExpiresAt: v.Lock.ExpiresAt}