carlos / platform Public

Managed fleets 1b task 4: the start rule (rule 6, #470)

A labelled fleet row starts only from a local copy kept under its
current assignment (the <db>.assigned marker names rt.Assigned), a
replica restored from the bucket, or empty when its record never moved
and no set-aside copy of it exists on this box. A stale or unmarked
local copy is moved, never deleted, into
<DataDir>/.superseded/<host>/<unix nanos>/ (built as .partial, renamed
when complete); a set-aside entry, complete or partial, is the
standing reason to refuse an empty start (ErrNothingToRestore), so a
second wake and an agent restart refuse again.

startAllowed is the one rule: restorePlain's warm, restored and fresh
returns and seededRestore's keep and placement paths consult it, and a
guard test checks every fresh-boot sink in the package does. The
marker is written atomically by doWake only after the start succeeded,
through the SplitBackend the agent runs. Unlabelled rows and HA hosts
are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 27b351825b2f90c28d8479c43c50c1e997ae12fb parent 85c383e
5 files changed, +1,197 −1
  • internal/activator/activator.go +12 −0
  • internal/activator/backend_exec.go +25 −1
  • internal/activator/seedplace.go +30 −0
  • internal/activator/startrule.go +340 −0
  • internal/activator/startrule_test.go +790 −0
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 994d6a85d..88f748408 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -2960,6 +2960,18 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro
}
w.steps.mark(a.now(), "settle")
}
+ // 4c. The start rule's marker (startrule.go): the restore passed
+ // startAllowed and the start succeeded, so a labelled row's local
+ // copy is now kept under its current assignment. Written only here; a
+ // failed write only logs, and the next wake sets the copy aside and
+ // restores (nothing is lost by a missing marker).
+ if rt.Assigned != "" {
+ if n, ok := a.backend.(assignmentNoter); ok {
+ if err := n.NoteAssignment(ctx, rt); err != nil {
+ log.Printf("activator: ERROR %s: assignment marker not written (%v); the next wake sets this copy aside", host, err)
+ }
+ }
+ }
if ctx.Err() != nil || !a.wakeAllowed(host) {
a.cleanupFailedWake(ctx, e, rt, w, lease)
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index 3bde4f030..6b773d34b 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -876,11 +876,25 @@ func (b *ExecBackend) restorePlain(ctx context.Context, rt registry.Route) (bool
if err := b.settleSeedObligation(ctx, rt, dbPath); err != nil {
return false, err
}
+ // The start rule (startrule.go, managed fleets 1b rule 6): a labelled
+ // row's local copy that is not kept under its current assignment is
+ // set aside, never deleted, before it can count as a warm cache or be
+ // purged by the seed marker check below. An unlabelled row is not
+ // touched.
+ if err := b.reconcileAssignment(rt, dbPath); err != nil {
+ return false, err
+ }
if err := reconcileSeedMarker(rt, dbPath); err != nil {
return false, err
}
if _, err := os.Stat(dbPath); err == nil {
- return false, nil // warm cache — see doWake
+ // Warm cache — see doWake. On a labelled row it is a copy kept
+ // under the current assignment, or reconcileAssignment would have
+ // set it aside.
+ if err := b.startAllowed(rt, true, false); err != nil {
+ return false, err
+ }
+ return false, nil
} else if !os.IsNotExist(err) {
return false, err
}
@@ -959,11 +973,21 @@ func (b *ExecBackend) restorePlain(ctx context.Context, rt registry.Route) (bool
if len(promoted) > 0 {
b.dropStagedReplica(ctx, promoted)
}
+ if err := b.startAllowed(rt, false, true); err != nil {
+ return false, err
+ }
} else {
// Never replicated: a brand-new instance boots fresh and creates its
// own DB — the register-only create path (provisioning as a metadata
// write) landing on its first wake. This — DB absent AND no replica —
// is the ONLY fresh boot, and the one moment the route's seed runs.
+ // On a fleet box the start rule decides it first: a labelled row
+ // whose record has moved, or of which a copy was set aside here,
+ // refuses (ErrNothingToRestore) rather than boot empty.
+ if err := b.startAllowed(rt, false, false); err != nil {
+ log.Printf("activator: no replica for %s in s3://%s/%s — NOT booting fresh: %v", host, b.Cfg.Bucket, b.Cfg.hibernatePrefix(host), err)
+ return false, err
+ }
log.Printf("activator: no replica for %s in s3://%s/%s — booting fresh", host, b.Cfg.Bucket, b.Cfg.hibernatePrefix(host))
}
return !restored, nil
diff --git a/internal/activator/seedplace.go b/internal/activator/seedplace.go
index 26f2494ad..bb15bb155 100644
--- a/internal/activator/seedplace.go
+++ b/internal/activator/seedplace.go
@@ -180,6 +180,12 @@ func (b *ExecBackend) seededRestore(ctx context.Context, rt registry.Route, src
if err := b.settleSeedObligation(ctx, rt, paths.dbPath); err != nil {
return fail(err)
}
+ // The start rule (startrule.go): on a labelled row, a local copy not
+ // kept under the current assignment is set aside, never deleted,
+ // before it can be kept as this seed's or purged below.
+ if err := b.reconcileAssignment(rt, paths.dbPath); err != nil {
+ return fail(err)
+ }
// This seed, placed by an interrupted first wake: keep it. Replication
// starts in doWake, as generation one of the host's own lineage.
@@ -188,9 +194,33 @@ func (b *ExecBackend) seededRestore(ctx context.Context, rt registry.Route, src
return fail(seedPlaceFailed(host, err))
}
if placed {
+ if err := b.startAllowed(rt, true, false); err != nil {
+ return fail(err)
+ }
log.Printf("activator: %s: keeping seed %s placed by an earlier wake", host, src.ID)
return false, nil
}
+ // Placing the snapshot is a start from something other than the
+ // host's own copy: on a labelled row, the start rule decides it as it
+ // decides an empty start. Anything still at the path is a copy kept
+ // under the current assignment, which the purge below would delete,
+ // so it is set aside first (and the rule then refuses).
+ if rt.Assigned != "" {
+ present, data, err := localCopyNames(dir, base)
+ if err != nil {
+ return fail(seedPlaceFailed(host, err))
+ }
+ if data {
+ entry, err := b.supersede(host, dir, present)
+ if err != nil {
+ return fail(fmt.Errorf("%s: refusing to start: setting aside the local copy at %s before a seed placement: %w", host, paths.dbPath, err))
+ }
+ log.Printf("activator: %s: SET ASIDE the local copy at %s before placing seed %s: moved to %s, nothing deleted", host, paths.dbPath, src.ID, entry)
+ }
+ }
+ if err := b.startAllowed(rt, false, false); err != nil {
+ return fail(err)
+ }
if b.Seeds == nil {
return fail(seedUnread(host, errors.New("no seed reader on this box")))
}
diff --git a/internal/activator/startrule.go b/internal/activator/startrule.go
new file mode 100644
index 000000000..25bb56b5b
--- /dev/null
+++ b/internal/activator/startrule.go
@@ -0,0 +1,340 @@
+package activator
+
+// The start rule (managed fleets 1b, rule 6; amadan #470). On a fleet of
+// two or more boxes, the box that wins an instance's lease used to reuse
+// whatever local database it had, however stale: an instance that moved
+// to another box and back booted the copy it left behind. A labelled row
+// (registry.Route.Assigned set, the record's FleetBoxAt) now starts only
+// from:
+//
+// - a local copy kept under its current assignment: the marker
+// <db>.assigned beside the database names rt.Assigned;
+// - a replica restored from the fleet bucket; or
+// - empty, only when its record has never moved between boxes
+// (rt.Moved false) and no set-aside copy of it exists on this box.
+//
+// A local copy under any other assignment, or under none, is SET ASIDE,
+// NEVER DELETED: moved whole into <DataDir>/.superseded/<host>/<unix
+// nanos>/ (built as <unix nanos>.partial and renamed when complete). A
+// set-aside copy, complete or partial, stays on disk as the standing
+// reason to refuse an empty start, so a second wake and an agent restart
+// refuse again. Nothing in this package deletes from .superseded: that is
+// an operator's call.
+//
+// The check is local: no lock change and no extra bucket request. An
+// unlabelled row (Assigned "") keeps today's behaviour exactly: no marker
+// is read or written, nothing is set aside, nothing new is refused. An HA
+// host restores by the HA rules (hawake.go), unchanged.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "os"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/instancefs"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+const (
+ // AssignedMarkerSuffix names the marker beside a fleet row's database:
+ // the assignment (rt.Assigned) its local copy was kept under.
+ AssignedMarkerSuffix = ".assigned"
+ // assignedMarkerMax bounds the marker read: an RFC 3339 nanosecond
+ // time and a newline, in tenant-writable ground.
+ assignedMarkerMax = 128
+ // supersededDirName is the set-aside root under the box's DataDir.
+ supersededDirName = ".superseded"
+ // partialSuffix marks a set-aside entry whose move has not finished.
+ partialSuffix = ".partial"
+)
+
+// ErrNothingToRestore is the start rule's refusal: a labelled row with no
+// kept copy and no replica, whose record has moved or of which a copy was
+// set aside on this box. The wrapping error names the set-aside path or
+// says the instance moved.
+var ErrNothingToRestore = errors.New("nothing to restore")
+
+// setAsideRename is the one move the set-aside makes, a seam for the
+// interrupted-move test. It never replaces anything at the destination.
+var setAsideRename = instancefs.RenameBetweenNoReplace
+
+// supersededHostDir is <DataDir>/.superseded/<host>. The DataDir is the
+// agent's own root, never a tenant's instance directory, so a tenant
+// cannot plant or remove the set-aside evidence.
+func (b *ExecBackend) supersededHostDir(host string) (string, error) {
+ if b.DataDir == "" || !filepath.IsAbs(b.DataDir) {
+ return "", fmt.Errorf("%s: no absolute data directory to keep set-aside copies under (%q)", host, b.DataDir)
+ }
+ if host == "" || host == "." || host == ".." || strings.ContainsAny(host, `/\`) {
+ return "", fmt.Errorf("%q is not a host a set-aside copy can be filed under", host)
+ }
+ return filepath.Join(filepath.Clean(b.DataDir), supersededDirName, host), nil
+}
+
+// supersededEntries lists the host's set-aside entries, complete and
+// partial, oldest first (the names are unix nanoseconds). A host with no
+// directory has none; any other read failure is returned, never "none".
+func (b *ExecBackend) supersededEntries(host string) (string, []string, error) {
+ dir, err := b.supersededHostDir(host)
+ if err != nil {
+ return "", nil, err
+ }
+ ents, err := os.ReadDir(dir)
+ if errors.Is(err, os.ErrNotExist) {
+ return dir, nil, nil
+ }
+ if err != nil {
+ return dir, nil, err
+ }
+ names := make([]string, 0, len(ents))
+ for _, e := range ents {
+ names = append(names, e.Name())
+ }
+ sort.Strings(names)
+ return dir, names, nil
+}
+
+// readAssignedMarker reads the marker beside dir/base: "" with absent true
+// when there is none. Any other failure (a symlink, an oversized file, an
+// I/O error) is returned: the caller refuses rather than guess.
+func readAssignedMarker(dir, base string) (marker string, absent bool, err error) {
+ m, absent, err := instancefs.ReadBeneathLimitOrAbsent(dir, base+AssignedMarkerSuffix, assignedMarkerMax)
+ if err != nil || absent {
+ return "", absent, err
+ }
+ return strings.TrimSpace(string(m)), false, nil
+}
+
+// localCopyNames lists what of the local copy at dir/base is present, in
+// the order the set-aside moves it: the assignment marker first, so a move
+// interrupted after it leaves a copy no later wake can keep; then the
+// database and everything reconcileSeedMarker's purge would remove (WAL,
+// SHM, both litestream metadata directories, the seed marker, a seed
+// fetch's leftovers). data reports whether anything but the two markers is
+// there: markers alone are no copy, and set nothing aside.
+func localCopyNames(dir, base string) (present []string, data bool, err error) {
+ names := []string{base + AssignedMarkerSuffix, base, base + "-wal", base + "-shm",
+ base + "-litestream", ".activator-" + base + "-litestream", base + SeedMarkerSuffix}
+ ents, err := os.ReadDir(dir)
+ if err != nil {
+ return nil, false, err
+ }
+ for _, e := range ents {
+ if n := e.Name(); strings.HasPrefix(n, ".seed-sd_") && strings.Contains(n, ".tmp") {
+ names = append(names, n)
+ }
+ }
+ for _, n := range names {
+ if _, err := os.Lstat(filepath.Join(dir, n)); errors.Is(err, os.ErrNotExist) {
+ continue
+ } else if err != nil {
+ return nil, false, err
+ }
+ present = append(present, n)
+ if n != base+AssignedMarkerSuffix && n != base+SeedMarkerSuffix {
+ data = true
+ }
+ }
+ return present, data, nil
+}
+
+// reconcileAssignment runs on a labelled row before anything can count as
+// a warm cache, be purged or be restored over. The local copy at dbPath is
+// kept only when the marker beside it names rt.Assigned and the database
+// is a regular file there. Otherwise whatever of the copy is present is
+// moved into <DataDir>/.superseded/<host>/<unix nanos>.partial/, which is
+// then renamed to drop .partial. A move that fails part way leaves the
+// .partial directory (which counts as set aside) and fails the wake.
+// Nothing is ever removed. An unlabelled row is not touched.
+func (b *ExecBackend) reconcileAssignment(rt registry.Route, dbPath string) error {
+ if rt.Assigned == "" {
+ return nil
+ }
+ dir, base, err := splitDBPath(dbPath)
+ if err != nil {
+ return fmt.Errorf("%s: refusing to start: %w", rt.Host, err)
+ }
+ if _, err := os.Lstat(dir); errors.Is(err, os.ErrNotExist) {
+ return nil // nothing of it on this box
+ } else if err != nil {
+ return fmt.Errorf("%s: refusing to start: %w", rt.Host, err)
+ }
+ marker, absent, err := readAssignedMarker(dir, base)
+ if err != nil {
+ return fmt.Errorf("%s: refusing to start: the assignment marker beside %s cannot be read: %w", rt.Host, dbPath, err)
+ }
+ if !absent && marker == rt.Assigned {
+ fi, err := os.Lstat(dbPath)
+ if err == nil && fi.Mode().IsRegular() {
+ return nil // kept under the current assignment
+ }
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ return fmt.Errorf("%s: refusing to start: %w", rt.Host, err)
+ }
+ }
+ present, data, err := localCopyNames(dir, base)
+ if err != nil {
+ return fmt.Errorf("%s: refusing to start: cannot list the local copy at %s: %w", rt.Host, dbPath, err)
+ }
+ if !data {
+ return nil
+ }
+ why := fmt.Sprintf("kept under assignment %q, the record is now assigned %q", marker, rt.Assigned)
+ if absent {
+ why = fmt.Sprintf("no assignment marker, the record is assigned %q", rt.Assigned)
+ } else if marker == rt.Assigned {
+ why = "no database beside its marker"
+ }
+ entry, err := b.supersede(rt.Host, dir, present)
+ if err != nil {
+ return fmt.Errorf("%s: refusing to start: setting aside the local copy at %s (%s): %w", rt.Host, dbPath, why, err)
+ }
+ log.Printf("activator: %s: SET ASIDE the local copy at %s (%s): moved to %s, nothing deleted", rt.Host, dbPath, why, entry)
+ return nil
+}
+
+// supersede moves names from dir into a new set-aside entry for host and
+// returns the entry's final path. On a failure part way, what has moved
+// stays in the .partial directory, whose path the error names.
+func (b *ExecBackend) supersede(host, dir string, names []string) (string, error) {
+ hostDir, err := b.supersededHostDir(host)
+ if err != nil {
+ return "", err
+ }
+ root := filepath.Dir(hostDir)
+ if _, err := instancefs.EnsureDirBeneath(filepath.Dir(root), supersededDirName, 0o700); err != nil {
+ return "", err
+ }
+ if _, err := instancefs.EnsureDirBeneath(root, host, 0o700); err != nil {
+ return "", err
+ }
+ var stamp string
+ for i := 0; ; i++ {
+ stamp = strconv.FormatInt(time.Now().UnixNano(), 10)
+ err := os.Mkdir(filepath.Join(hostDir, stamp+partialSuffix), 0o700)
+ if err == nil {
+ break
+ }
+ if !errors.Is(err, os.ErrExist) || i >= 100 {
+ return "", err
+ }
+ // The same nanosecond as an earlier entry: take the next one.
+ time.Sleep(time.Microsecond)
+ }
+ partial := filepath.Join(hostDir, stamp+partialSuffix)
+ for _, n := range names {
+ if err := setAsideRename(dir, n, partial, n); err != nil {
+ return partial, fmt.Errorf("interrupted with part of it at %s: %w", partial, err)
+ }
+ }
+ // Durable before it is marked complete: a crash that loses a rename
+ // leaves the file where it was (rename is atomic), never nowhere.
+ for _, d := range []string{dir, partial} {
+ if err := syncDirIfThere(d); err != nil {
+ return partial, fmt.Errorf("moved to %s, which could not be synced: %w", partial, err)
+ }
+ }
+ if err := setAsideRename(hostDir, stamp+partialSuffix, hostDir, stamp); err != nil {
+ return partial, fmt.Errorf("moved to %s, which could not be marked complete: %w", partial, err)
+ }
+ if err := syncDirIfThere(hostDir); err != nil {
+ return filepath.Join(hostDir, stamp), fmt.Errorf("moved to %s, whose directory could not be synced: %w", filepath.Join(hostDir, stamp), err)
+ }
+ return filepath.Join(hostDir, stamp), nil
+}
+
+// startAllowed is the one start rule. haveLocal reports a local copy kept
+// under the current assignment (checked again here against its marker),
+// restored a replica restored from the bucket. Either allows the start.
+// For neither, an empty start is allowed only when the record has never
+// moved and no set-aside copy of the host exists on this box; otherwise
+// the answer wraps ErrNothingToRestore. A set-aside listing that cannot be
+// read refuses. An unlabelled row is always allowed (today's behaviour).
+// Every start path on a fleet box that would boot without a restored or
+// kept copy calls it (TestEveryFreshBootPathConsultsTheRule).
+func (b *ExecBackend) startAllowed(rt registry.Route, haveLocal, restored bool) error {
+ if rt.Assigned == "" || restored {
+ return nil
+ }
+ host := rt.Host
+ if haveLocal {
+ dbPath := b.pathsFor(rt).dbPath
+ dir, base, err := splitDBPath(dbPath)
+ if err != nil {
+ return fmt.Errorf("%s: refusing to start: %w", host, err)
+ }
+ marker, absent, err := readAssignedMarker(dir, base)
+ if err != nil {
+ return fmt.Errorf("%s: refusing to start: the assignment marker beside %s cannot be read: %w", host, dbPath, err)
+ }
+ if absent || marker != rt.Assigned {
+ return fmt.Errorf("%s: refusing to start: the local copy at %s is not kept under the current assignment %q (marker %q)", host, dbPath, rt.Assigned, marker)
+ }
+ return nil
+ }
+ dir, entries, err := b.supersededEntries(host)
+ if err != nil {
+ return fmt.Errorf("%s: refusing to start: cannot tell whether a copy of it was set aside on this box: %w", host, err)
+ }
+ if n := len(entries); n > 0 {
+ newest := filepath.Join(dir, entries[n-1])
+ more := ""
+ if n > 1 {
+ more = fmt.Sprintf(" (%d set-aside copies under %s)", n, dir)
+ }
+ return fmt.Errorf("%s: refusing to start empty: %w: no replica in the fleet bucket, and a copy of it was set aside on this box at %s%s", host, ErrNothingToRestore, newest, more)
+ }
+ if rt.Moved {
+ return fmt.Errorf("%s: refusing to start empty: %w: the instance has moved between boxes and no replica was found in the fleet bucket", host, ErrNothingToRestore)
+ }
+ return nil
+}
+
+// assignmentNoter is the optional Backend half that records, after a
+// start, the assignment a labelled row's local copy is now kept under.
+type assignmentNoter interface {
+ NoteAssignment(ctx context.Context, rt registry.Route) error
+}
+
+// NoteAssignment writes rt.Assigned to the marker beside the database,
+// through a temp file in the same directory, fsync and rename. doWake calls
+// it only after Restore (and so startAllowed) passed and the start
+// succeeded. An unlabelled row, or an HA host (the HA rules, unchanged),
+// writes nothing.
+func (b *ExecBackend) NoteAssignment(_ context.Context, rt registry.Route) error {
+ if rt.Assigned == "" {
+ return nil
+ }
+ if _, ha := b.haAcquired(rt.Host); ha {
+ return nil
+ }
+ dir, base, err := splitDBPath(b.pathsFor(rt).dbPath)
+ if err != nil {
+ return err
+ }
+ return instancefs.WriteAtomic(dir, base+AssignedMarkerSuffix, []byte(rt.Assigned+"\n"), 0o600)
+}
+
+// Both backends doWake can be handed carry the marker write: a production
+// agent runs a SplitBackend, and one that dropped it would set every
+// labelled copy aside on every wake.
+var (
+ _ assignmentNoter = (*ExecBackend)(nil)
+ _ assignmentNoter = (*SplitBackend)(nil)
+)
+
+// NoteAssignment dispatches like SeedPlaced: a unit-backed row has no
+// marker to write.
+func (b *SplitBackend) NoteAssignment(ctx context.Context, rt registry.Route) error {
+ if n, ok := b.pick(rt).(assignmentNoter); ok {
+ return n.NoteAssignment(ctx, rt)
+ }
+ return nil
+}
diff --git a/internal/activator/startrule_test.go b/internal/activator/startrule_test.go
new file mode 100644
index 000000000..ae0bdb046
--- /dev/null
+++ b/internal/activator/startrule_test.go
@@ -0,0 +1,790 @@
+//go:build linux
+
+package activator
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/seeds"
+)
+
+// The start rule (managed fleets 1b, rule 6, amadan #470): on a fleet box
+// an instance starts only from a local copy kept under its current
+// assignment, a replica restored from the fleet bucket, or empty when its
+// record has never moved and no set-aside copy of it exists on this box.
+// A stale local copy is set aside, never deleted.
+
+const (
+ ruleHost = "shop.example.com"
+ assignA = "2026-10-30T10:00:00.000000001Z"
+ assignB = "2026-10-30T11:00:00.000000002Z"
+)
+
+// fleetRoute is a flat fleet-placed row on b, labelled with assigned ("" =
+// unlabelled, today's behaviour).
+func fleetRoute(b *ExecBackend, assigned string, moved bool) registry.Route {
+ return registry.Route{Host: ruleHost, Kind: "instance", Hibernate: true,
+ Socket: "/tmp/nope.sock", DBPath: filepath.Join(b.DataDir, ruleHost+".db"),
+ Assigned: assigned, Moved: moved}
+}
+
+// localCopy lays down a database and the litestream sidecar state beside
+// it (the file set reconcileSeedMarker would remove), each with content of
+// its own, and an assignment marker naming marker ("" = none). It returns
+// what each name relative to the database's directory holds.
+func localCopy(t *testing.T, dbPath, marker string) map[string]string {
+ t.Helper()
+ dir, base := filepath.Dir(dbPath), filepath.Base(dbPath)
+ want := map[string]string{
+ base: "the database",
+ base + "-wal": "the unreplicated tail",
+ base + "-shm": "the shared memory index",
+ base + "-litestream/gen": "a box-wide replicator's metadata",
+ ".activator-" + base + "-litestream/generations/0/wal": "the lease's shadow WAL",
+ }
+ for name, body := range want {
+ p := filepath.Join(dir, name)
+ if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(p, []byte(body), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if marker != "" {
+ writeAssignedMarker(t, dbPath, marker)
+ want[base+AssignedMarkerSuffix] = marker + "\n"
+ }
+ return want
+}
+
+func writeAssignedMarker(t *testing.T, dbPath, marker string) {
+ t.Helper()
+ if err := os.WriteFile(dbPath+AssignedMarkerSuffix, []byte(marker+"\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func markerAt(t *testing.T, dbPath string) (string, bool) {
+ t.Helper()
+ b, err := os.ReadFile(dbPath + AssignedMarkerSuffix)
+ if errors.Is(err, os.ErrNotExist) {
+ return "", false
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ return strings.TrimSpace(string(b)), true
+}
+
+// supersededEntries lists the host's set-aside entries, complete and
+// partial, by name.
+func supersededEntries(t *testing.T, b *ExecBackend, host string) []string {
+ t.Helper()
+ ents, err := os.ReadDir(filepath.Join(b.DataDir, supersededDirName, host))
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ var names []string
+ for _, e := range ents {
+ names = append(names, e.Name())
+ }
+ sort.Strings(names)
+ return names
+}
+
+// assertSetAside checks that exactly one complete set-aside entry holds
+// every file of want, byte for byte, and returns its path.
+func assertSetAside(t *testing.T, b *ExecBackend, host string, want map[string]string) string {
+ t.Helper()
+ names := supersededEntries(t, b, host)
+ if len(names) != 1 || strings.HasSuffix(names[0], partialSuffix) {
+ t.Fatalf("set-aside entries %q; want exactly one complete entry", names)
+ }
+ entry := filepath.Join(b.DataDir, supersededDirName, host, names[0])
+ for name, body := range want {
+ got, err := os.ReadFile(filepath.Join(entry, name))
+ if err != nil {
+ t.Errorf("set-aside copy is missing %s: %v", name, err)
+ continue
+ }
+ if string(got) != body {
+ t.Errorf("set-aside %s = %q, want %q", name, got, body)
+ }
+ }
+ return entry
+}
+
+// assertGoneFromLive checks that none of want's names is left at the live
+// path (the copy moved, it was not copied).
+func assertGoneFromLive(t *testing.T, dbPath string, want map[string]string) {
+ t.Helper()
+ dir := filepath.Dir(dbPath)
+ for name := range want {
+ if strings.HasSuffix(name, AssignedMarkerSuffix) {
+ continue // the marker is rewritten after a start
+ }
+ top := strings.SplitN(name, "/", 2)[0]
+ if _, err := os.Lstat(filepath.Join(dir, top)); err == nil && top != filepath.Base(dbPath) {
+ t.Errorf("%s still at the live path after the set-aside", top)
+ }
+ }
+}
+
+// replicaCalls swaps the bucket restore: has reports whether a replica
+// exists (a usable database is written when it does); the count is the
+// number of restores asked.
+func replicaCalls(t *testing.T, has bool) *int {
+ t.Helper()
+ n := 0
+ swapRestoreReplica(t, func(_ context.Context, dbPath, _, _, _ string) (bool, error) {
+ n++
+ if has {
+ writeUsableDB(t, dbPath)
+ }
+ return has, nil
+ })
+ return &n
+}
+
+// ruleBackend runs a real ExecBackend's Restore and NoteAssignment under
+// the fake's start, lease and replication, so a test drives doWake's own
+// order: the rule in the restore, the marker after the start.
+type ruleBackend struct {
+ *fakeBackend
+ eb *ExecBackend
+ noted int
+ mu sync.Mutex
+}
+
+func (r *ruleBackend) Restore(ctx context.Context, rt registry.Route) (bool, error) {
+ _, _ = r.fakeBackend.Restore(ctx, rt) // counts it, in the order log
+ return r.eb.Restore(ctx, rt)
+}
+
+func (r *ruleBackend) NoteAssignment(ctx context.Context, rt registry.Route) error {
+ r.mu.Lock()
+ r.noted++
+ r.mu.Unlock()
+ return r.eb.NoteAssignment(ctx, rt)
+}
+
+// wakeOn wakes rt once through a Service over eb, and returns the wake's
+// error and the fake half (its start count).
+func wakeOn(t *testing.T, eb *ExecBackend, rt registry.Route, tweak func(*fakeBackend)) (*ruleBackend, error) {
+ t.Helper()
+ fb := &fakeBackend{}
+ if tweak != nil {
+ tweak(fb)
+ }
+ rb := &ruleBackend{fakeBackend: fb, eb: eb}
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ a := New(Config{Bucket: "test-bucket", Idle: time.Hour}, rb, reg)
+ release, err := a.beginRequest(context.Background(), rt)
+ if err == nil {
+ release()
+ }
+ return rb, err
+}
+
+func TestAssignmentChangeSetsTheCopyAside(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, assignB, true)
+ want := localCopy(t, rt.DBPath, assignA)
+ // A seed marker beside the stale copy goes with it, not to the purge.
+ base := filepath.Base(rt.DBPath)
+ if err := os.WriteFile(rt.DBPath+SeedMarkerSuffix, []byte("sd_other\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ want[base+SeedMarkerSuffix] = "sd_other\n"
+ restores := replicaCalls(t, true)
+
+ rb, err := wakeOn(t, b, rt, nil)
+ if err != nil {
+ t.Fatalf("wake: %v", err)
+ }
+ if *restores != 1 {
+ t.Fatalf("restores = %d; the stale copy must be replaced by the replica", *restores)
+ }
+ if rb.starts != 1 {
+ t.Fatalf("starts = %d", rb.starts)
+ }
+ assertSetAside(t, b, rt.Host, want)
+ assertGoneFromLive(t, rt.DBPath, want)
+ if got, ok := markerAt(t, rt.DBPath); !ok || got != assignB {
+ t.Fatalf("marker = %q (present %v); want the new assignment %q", got, ok, assignB)
+ }
+ // The live database is the restored replica, not the old file.
+ if body, _ := os.ReadFile(rt.DBPath); string(body) == want[filepath.Base(rt.DBPath)] {
+ t.Fatal("the stale database is still at the live path")
+ }
+}
+
+func TestSameAssignmentKeepsTheWarmCopy(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, assignA, true)
+ want := localCopy(t, rt.DBPath, assignA)
+ restores := replicaCalls(t, true)
+
+ rb, err := wakeOn(t, b, rt, nil)
+ if err != nil {
+ t.Fatalf("wake: %v", err)
+ }
+ if *restores != 0 {
+ t.Fatalf("restores = %d; an unchanged assignment keeps its warm copy", *restores)
+ }
+ if rb.starts != 1 {
+ t.Fatalf("starts = %d", rb.starts)
+ }
+ if names := supersededEntries(t, b, rt.Host); len(names) != 0 {
+ t.Fatalf("set aside %q under an unchanged assignment", names)
+ }
+ dir := filepath.Dir(rt.DBPath)
+ for name, body := range want {
+ got, err := os.ReadFile(filepath.Join(dir, name))
+ if err != nil || string(got) != body {
+ t.Errorf("%s = %q, %v; want it kept as %q", name, got, err, body)
+ }
+ }
+}
+
+func TestUnassignedRouteIgnoresTheRule(t *testing.T) {
+ t.Run("warm cache", func(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, "", true)
+ // A stray marker beside an unlabelled row is neither read nor
+ // rewritten.
+ want := localCopy(t, rt.DBPath, "stray")
+ restores := replicaCalls(t, true)
+ rb, err := wakeOn(t, b, rt, nil)
+ if err != nil {
+ t.Fatalf("wake: %v", err)
+ }
+ if *restores != 0 || rb.starts != 1 {
+ t.Fatalf("restores %d starts %d; want the warm cache, as on main", *restores, rb.starts)
+ }
+ if names := supersededEntries(t, b, rt.Host); len(names) != 0 {
+ t.Fatalf("an unlabelled row set aside %q", names)
+ }
+ if got, _ := markerAt(t, rt.DBPath); got != "stray" {
+ t.Fatalf("marker = %q; an unlabelled row never writes one", got)
+ }
+ if body, _ := os.ReadFile(rt.DBPath); string(body) != want[filepath.Base(rt.DBPath)] {
+ t.Fatal("the warm copy changed")
+ }
+ })
+ t.Run("fresh boot despite a set-aside copy", func(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, "", true)
+ if err := os.MkdirAll(filepath.Join(b.DataDir, supersededDirName, rt.Host, "1"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ restores := replicaCalls(t, false)
+ fresh, err := b.Restore(context.Background(), rt)
+ if err != nil || !fresh || *restores != 1 {
+ t.Fatalf("fresh %v err %v restores %d; want today's fresh boot", fresh, err, *restores)
+ }
+ _, err = wakeOn(t, b, rt, nil)
+ if err != nil {
+ t.Fatalf("wake: %v", err)
+ }
+ if _, ok := markerAt(t, rt.DBPath); ok {
+ t.Fatal("an unlabelled row wrote an assignment marker")
+ }
+ })
+}
+
+func TestMissingMarkerSetsAside(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, assignA, false)
+ want := localCopy(t, rt.DBPath, "")
+ restores := replicaCalls(t, true)
+
+ fresh, err := b.Restore(context.Background(), rt)
+ if err != nil || fresh {
+ t.Fatalf("fresh %v err %v; want a restore", fresh, err)
+ }
+ if *restores != 1 {
+ t.Fatalf("restores = %d; a copy with no marker is set aside and restored", *restores)
+ }
+ assertSetAside(t, b, rt.Host, want)
+ if _, ok := markerAt(t, rt.DBPath); ok {
+ t.Fatal("Restore wrote the marker; it is written only after the start")
+ }
+}
+
+func TestNothingToRestoreRefusesEveryTime(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, assignB, false)
+ want := localCopy(t, rt.DBPath, assignA)
+ restores := replicaCalls(t, false)
+
+ var entry string
+ for i, eb := range []*ExecBackend{
+ b, // the first wake sets the copy aside
+ b, // a second wake finds it set aside
+ {Cfg: b.Cfg, OptDir: b.OptDir, DataDir: b.DataDir}, // an agent restart
+ } {
+ rb, err := wakeOn(t, eb, rt, nil)
+ if !errors.Is(err, ErrNothingToRestore) {
+ t.Fatalf("wake %d: err %v; want ErrNothingToRestore", i+1, err)
+ }
+ if rb.starts != 0 || rb.seeds != 0 {
+ t.Fatalf("wake %d: starts %d seeds %d; nothing may boot", i+1, rb.starts, rb.seeds)
+ }
+ entry = assertSetAside(t, b, rt.Host, want)
+ if !strings.Contains(err.Error(), entry) {
+ t.Fatalf("wake %d: %q does not say where the copy is (%s)", i+1, err, entry)
+ }
+ if _, err := os.Lstat(rt.DBPath); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("wake %d: a database appeared at the live path: %v", i+1, err)
+ }
+ if _, ok := markerAt(t, rt.DBPath); ok {
+ t.Fatalf("wake %d: a refused wake wrote the marker", i+1)
+ }
+ }
+ if *restores != 3 {
+ t.Fatalf("restores = %d; every wake asks the bucket first", *restores)
+ }
+ // Direct, too: Restore never reports fresh.
+ if fresh, err := b.Restore(context.Background(), rt); fresh || !errors.Is(err, ErrNothingToRestore) {
+ t.Fatalf("Restore = fresh %v, %v", fresh, err)
+ }
+}
+
+func TestInterruptedSetAsideRefuses(t *testing.T) {
+ t.Run("partial directory left by a crash", func(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, assignA, false)
+ partial := filepath.Join(b.DataDir, supersededDirName, rt.Host, "1761818400000000000"+partialSuffix)
+ if err := os.MkdirAll(partial, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(partial, ruleHost+".db"), []byte("half moved"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ replicaCalls(t, false)
+ fresh, err := b.Restore(context.Background(), rt)
+ if fresh || !errors.Is(err, ErrNothingToRestore) || !strings.Contains(err.Error(), partial) {
+ t.Fatalf("fresh %v err %v; want a refusal naming %s", fresh, err, partial)
+ }
+ })
+ t.Run("crash in the middle of the move", func(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, assignB, false)
+ want := localCopy(t, rt.DBPath, assignA)
+ replicaCalls(t, false)
+ // Fault injection: the third rename fails, as a crash would stop
+ // the move there.
+ prev := setAsideRename
+ n := 0
+ setAsideRename = func(sd, sn, dd, dn string) error {
+ n++
+ if n == 3 {
+ return errors.New("injected: the box lost power")
+ }
+ return prev(sd, sn, dd, dn)
+ }
+ fresh, err := b.Restore(context.Background(), rt)
+ setAsideRename = prev
+ if err == nil || fresh {
+ t.Fatalf("fresh %v err %v; an interrupted set-aside fails the wake", fresh, err)
+ }
+ names := supersededEntries(t, b, rt.Host)
+ if len(names) != 1 || !strings.HasSuffix(names[0], partialSuffix) {
+ t.Fatalf("entries %q; want the .partial directory the crash left", names)
+ }
+ // The next wake (no fault) moves the rest aside and still refuses.
+ fresh, err = b.Restore(context.Background(), rt)
+ if fresh || !errors.Is(err, ErrNothingToRestore) {
+ t.Fatalf("fresh %v err %v; want ErrNothingToRestore", fresh, err)
+ }
+ // Nothing was lost: every file is in one of the entries.
+ found := map[string]string{}
+ for _, e := range supersededEntries(t, b, rt.Host) {
+ root := filepath.Join(b.DataDir, supersededDirName, rt.Host, e)
+ _ = filepath.Walk(root, func(p string, fi os.FileInfo, err error) error {
+ if err == nil && !fi.IsDir() {
+ rel, _ := filepath.Rel(root, p)
+ body, _ := os.ReadFile(p)
+ found[rel] = string(body)
+ }
+ return nil
+ })
+ }
+ for name, body := range want {
+ if found[name] != body {
+ t.Errorf("%s = %q across the set-aside entries, want %q", name, found[name], body)
+ }
+ }
+ })
+}
+
+func TestMovedInstanceOnACleanBoxRefusesWithoutReplica(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, assignB, true)
+ replicaCalls(t, false)
+ rb, err := wakeOn(t, b, rt, nil)
+ if !errors.Is(err, ErrNothingToRestore) || !strings.Contains(err.Error(), "moved") {
+ t.Fatalf("err %v; want ErrNothingToRestore saying the instance moved", err)
+ }
+ if rb.starts != 0 {
+ t.Fatalf("starts = %d", rb.starts)
+ }
+ if names := supersededEntries(t, b, rt.Host); len(names) != 0 {
+ t.Fatalf("nothing was there to set aside, but entries %q appeared", names)
+ }
+ // A restored replica is allowed on the same clean box.
+ replicaCalls(t, true)
+ if rb, err := wakeOn(t, b, rt, nil); err != nil || rb.starts != 1 {
+ t.Fatalf("with a replica: err %v starts %d", err, rb.starts)
+ }
+}
+
+func TestNewInstanceBootsFresh(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, assignA, false)
+ replicaCalls(t, false)
+ fresh, err := b.Restore(context.Background(), rt)
+ if err != nil || !fresh {
+ t.Fatalf("fresh %v err %v; a never-moved record with nothing set aside boots fresh", fresh, err)
+ }
+ rb, err := wakeOn(t, b, rt, nil)
+ if err != nil || rb.starts != 1 {
+ t.Fatalf("wake: err %v starts %d", err, rb.starts)
+ }
+ if got, ok := markerAt(t, rt.DBPath); !ok || got != assignA {
+ t.Fatalf("marker = %q (present %v); want %q after the start", got, ok, assignA)
+ }
+ // The marker went through a temp file and a rename: nothing else is
+ // left beside it.
+ ents, _ := os.ReadDir(filepath.Dir(rt.DBPath))
+ for _, e := range ents {
+ if strings.Contains(e.Name(), ".tmp") {
+ t.Errorf("%s left behind by the marker write", e.Name())
+ }
+ }
+}
+
+// The production agent's backend is a SplitBackend: it forwards the marker
+// write to the exec half, and a unit-backed row writes nothing.
+func TestSplitBackendNotesTheAssignment(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, assignA, false)
+ sb := &SplitBackend{Exec: b, Unit: &UnitBackend{OptDir: t.TempDir()}}
+ unit := rt
+ unit.Backing = registry.BackingUnit
+ if err := sb.NoteAssignment(context.Background(), unit); err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := markerAt(t, rt.DBPath); ok {
+ t.Fatal("a unit-backed row wrote a marker")
+ }
+ if err := sb.NoteAssignment(context.Background(), rt); err != nil {
+ t.Fatal(err)
+ }
+ if got, ok := markerAt(t, rt.DBPath); !ok || got != assignA {
+ t.Fatalf("marker = %q (present %v); want %q", got, ok, assignA)
+ }
+}
+
+func TestFailedRestoreLeavesNoMarker(t *testing.T) {
+ t.Run("bucket error", func(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, assignB, false)
+ localCopy(t, rt.DBPath, assignA)
+ swapRestoreReplica(t, func(context.Context, string, string, string, string) (bool, error) {
+ return false, errors.New("injected: bucket unreachable")
+ })
+ rb, err := wakeOn(t, b, rt, nil)
+ if err == nil || rb.starts != 0 {
+ t.Fatalf("err %v starts %d; want a failed wake", err, rb.starts)
+ }
+ if _, ok := markerAt(t, rt.DBPath); ok {
+ t.Fatal("a failed restore left a marker")
+ }
+ })
+ t.Run("corrupt replica", func(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, assignA, false)
+ swapRestoreReplica(t, func(_ context.Context, out, _, _, _ string) (bool, error) {
+ return true, os.WriteFile(out, []byte("not a database"), 0o600)
+ })
+ rb, err := wakeOn(t, b, rt, nil)
+ if err == nil || rb.starts != 0 {
+ t.Fatalf("err %v starts %d; want a failed wake", err, rb.starts)
+ }
+ if _, ok := markerAt(t, rt.DBPath); ok {
+ t.Fatal("a corrupt restore left a marker")
+ }
+ })
+ t.Run("start fails", func(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, assignA, false)
+ replicaCalls(t, true)
+ rb, err := wakeOn(t, b, rt, func(f *fakeBackend) { f.startErr = errors.New("injected: health probe timed out") })
+ if err == nil {
+ t.Fatal("the wake succeeded with a failing start")
+ }
+ if rb.noted != 0 {
+ t.Fatalf("NoteAssignment called %d times after a failed start", rb.noted)
+ }
+ if _, ok := markerAt(t, rt.DBPath); ok {
+ t.Fatal("a failed start left a marker")
+ }
+ })
+}
+
+// walCopy builds a WAL-mode database whose last rows live only in its
+// -wal (the tail litestream had not shipped), and copies the pair to
+// dbPath while the writer still holds them, so no checkpoint folds the
+// tail in.
+func walCopy(t *testing.T, dbPath string, rows int) {
+ t.Helper()
+ src := filepath.Join(t.TempDir(), "w.db")
+ db, err := sql.Open("sqlite", src)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ db.SetMaxOpenConns(1)
+ for _, q := range []string{"PRAGMA journal_mode=WAL", "PRAGMA wal_autocheckpoint=0",
+ "CREATE TABLE t (id INTEGER PRIMARY KEY)"} {
+ if _, err := db.Exec(q); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for i := 0; i < rows; i++ {
+ if _, err := db.Exec("INSERT INTO t VALUES (?)", i); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, suf := range []string{"", "-wal"} {
+ body, err := os.ReadFile(src + suf)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if suf == "-wal" && len(body) == 0 {
+ t.Fatal("the tail is not in the WAL")
+ }
+ if err := os.WriteFile(dbPath+suf, body, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func countRows(t *testing.T, dbPath string) int {
+ t.Helper()
+ db, err := sql.Open("sqlite", dbPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ var n int
+ if err := db.QueryRow("SELECT count(*) FROM t").Scan(&n); err != nil {
+ t.Fatalf("read %s: %v", dbPath, err)
+ }
+ return n
+}
+
+func TestUnreplicatedTailSurvives(t *testing.T) {
+ t.Run("set aside with its WAL", func(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, assignB, false)
+ walCopy(t, rt.DBPath, 7)
+ writeAssignedMarker(t, rt.DBPath, assignA)
+ replicaCalls(t, true) // the replica holds one row: the tail is newer
+ if _, err := b.Restore(context.Background(), rt); err != nil {
+ t.Fatalf("Restore: %v", err)
+ }
+ names := supersededEntries(t, b, rt.Host)
+ if len(names) != 1 {
+ t.Fatalf("entries %q", names)
+ }
+ aside := filepath.Join(b.DataDir, supersededDirName, rt.Host, names[0], ruleHost+".db")
+ if n := countRows(t, aside); n != 7 {
+ t.Fatalf("the set-aside copy holds %d rows, want 7: the WAL tail was lost", n)
+ }
+ if n := countRows(t, rt.DBPath); n != 1 {
+ t.Fatalf("live copy holds %d rows, want the replica's 1", n)
+ }
+ })
+ t.Run("kept with its WAL under the same assignment", func(t *testing.T) {
+ b := testExecBackend(t)
+ rt := fleetRoute(b, assignA, false)
+ walCopy(t, rt.DBPath, 7)
+ writeAssignedMarker(t, rt.DBPath, assignA)
+ restores := replicaCalls(t, true)
+ if fresh, err := b.Restore(context.Background(), rt); err != nil || fresh || *restores != 0 {
+ t.Fatalf("fresh %v err %v restores %d; want the warm copy", fresh, err, *restores)
+ }
+ if n := countRows(t, rt.DBPath); n != 7 {
+ t.Fatalf("warm copy holds %d rows, want 7", n)
+ }
+ })
+}
+
+// TestEveryFreshBootPathConsultsTheRule is the guard over the fresh-boot
+// call sites. Structurally: every function in the package that can put a
+// database in place without a kept copy (asks the bucket for the replica,
+// places a seed, or keeps a placed seed) also consults startAllowed and
+// runs reconcileAssignment, except the HA restore, which keeps the HA
+// rules unchanged (controller ruling). Behaviourally: each such path, on a
+// fleet row with a set-aside copy (or a moved record) and nothing to
+// restore, refuses with ErrNothingToRestore and places nothing.
+func TestEveryFreshBootPathConsultsTheRule(t *testing.T) {
+ sinks := map[string]bool{"restoreReplica": true, "placeSeed": true, "seedPlacedAt": true}
+ exempt := map[string]string{
+ "restoreHA": "an HA host restores by the HA rules (hawake.go), unchanged",
+ }
+ files, err := filepath.Glob("*.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fset := token.NewFileSet()
+ sinkFuncs := map[string][]string{}
+ for _, f := range files {
+ if strings.HasSuffix(f, "_test.go") {
+ continue
+ }
+ file, err := parser.ParseFile(fset, f, nil, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, d := range file.Decls {
+ fd, ok := d.(*ast.FuncDecl)
+ if !ok || fd.Body == nil {
+ continue
+ }
+ uses := map[string]bool{}
+ ast.Inspect(fd.Body, func(n ast.Node) bool {
+ switch x := n.(type) {
+ case *ast.Ident:
+ uses[x.Name] = true
+ case *ast.SelectorExpr:
+ uses[x.Sel.Name] = true
+ }
+ return true
+ })
+ var hit []string
+ for s := range sinks {
+ if uses[s] {
+ hit = append(hit, s)
+ }
+ }
+ if len(hit) == 0 || fd.Name.Name == "seedPlacedAt" {
+ continue
+ }
+ sort.Strings(hit)
+ sinkFuncs[fd.Name.Name] = hit
+ if _, ok := exempt[fd.Name.Name]; ok {
+ continue
+ }
+ if !uses["startAllowed"] {
+ t.Errorf("%s (%s) reaches %v without consulting startAllowed", fd.Name.Name, fset.Position(fd.Pos()), hit)
+ }
+ if !uses["reconcileAssignment"] && !uses["restorePlain"] {
+ t.Errorf("%s (%s) reaches %v without reconcileAssignment", fd.Name.Name, fset.Position(fd.Pos()), hit)
+ }
+ }
+ }
+ // The guard must be looking at the real call sites.
+ for _, name := range []string{"restorePlain", "seededRestore"} {
+ if _, ok := sinkFuncs[name]; !ok {
+ t.Fatalf("the guard found no fresh-boot sink in %s: the sink names moved (%v)", name, sinkFuncs)
+ }
+ }
+
+ // Behaviour: every fresh-boot path refuses.
+ setAside := func(b *ExecBackend, host string) {
+ if err := os.MkdirAll(filepath.Join(b.DataDir, supersededDirName, host, "1"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ type path struct {
+ name string
+ route func(t *testing.T) (*ExecBackend, registry.Route, *fakeSeedObjects)
+ }
+ plain := func(t *testing.T) (*ExecBackend, registry.Route, *fakeSeedObjects) {
+ b := testExecBackend(t)
+ return b, fleetRoute(b, assignA, false), nil
+ }
+ seeded := func(state string) func(t *testing.T) (*ExecBackend, registry.Route, *fakeSeedObjects) {
+ return func(t *testing.T) (*ExecBackend, registry.Route, *fakeSeedObjects) {
+ noOwnReplica(t)
+ b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{})
+ rt.Assigned = assignA
+ rt, objs, _ := seededRoute(t, b, rt, state)
+ return b, rt, objs
+ }
+ }
+ paths := []path{
+ {"plain restore, no replica", plain},
+ {"seed placement", seeded(seeds.StateReady)},
+ {"placed seed, own replica missing", seeded(seeds.StatePlaced)},
+ }
+ for _, p := range paths {
+ for _, why := range []string{"set aside", "moved"} {
+ t.Run(p.name+"/"+why, func(t *testing.T) {
+ b, rt, objs := p.route(t)
+ if why == "set aside" {
+ setAside(b, rt.Host)
+ } else {
+ rt.Moved = true
+ }
+ replicaCalls(t, false)
+ fresh, err := b.Restore(context.Background(), rt)
+ if fresh || !errors.Is(err, ErrNothingToRestore) {
+ t.Fatalf("fresh %v err %v; want ErrNothingToRestore", fresh, err)
+ }
+ if objs != nil && objs.opens != 0 {
+ t.Fatalf("the seed snapshot was opened %d times", objs.opens)
+ }
+ if _, err := os.Lstat(rt.DBPath); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("a database was placed: %v", err)
+ }
+ })
+ }
+ }
+ // A placed seed an earlier wake left under no marker is a stale copy
+ // too: set aside, then refused, never kept.
+ t.Run("placed seed kept by an interrupted wake", func(t *testing.T) {
+ b, rt, objs := seeded(seeds.StateReady)(t)
+ replicaCalls(t, false)
+ if fresh, err := b.Restore(context.Background(), fleetUnlabelled(rt)); err != nil || fresh {
+ t.Fatalf("placing the seed (unlabelled): fresh %v err %v", fresh, err)
+ }
+ fresh, err := b.Restore(context.Background(), rt)
+ if fresh || !errors.Is(err, ErrNothingToRestore) || objs.opens != 1 {
+ t.Fatalf("fresh %v err %v opens %d; want the placed copy set aside and a refusal", fresh, err, objs.opens)
+ }
+ if len(supersededEntries(t, b, rt.Host)) != 1 {
+ t.Fatal("the placed seed was not set aside")
+ }
+ })
+}
+
+func fleetUnlabelled(rt registry.Route) registry.Route {
+ rt.Assigned, rt.Moved = "", false
+ return rt
+}