| 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 |
| +} |