carlos / platform Public

region HA P1a Task 9: fix round 1 (staged starts gated; litestream state removed checked; the restored replication class governs the wake)

I1: StartStaged and StartSidecarGen ask the HA containment gate before any
preparation, so a planned, pinned or swap start of a host acquired HA and
since moved out of the nested layout starts nothing.
I2: setAside removes both litestream metadata directories first, checked
and beneath their directory (no PurgeLocalDBArtifacts, which drops its
errors): a failure fails the wake with nothing moved, restored or
replicated.
The class an HA restore imports from the published wake state is recorded
for that wake (restoredReplication, dispatched by SplitBackend), and doWake
replicates at it and puts it on the entry's route.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 2d44a2d670762d7d41ab7a4eef674641d444e433 parent 126e34a
5 files changed, +221 −5
  • internal/activator/activator.go +14 −0
  • internal/activator/backend_unit.go +8 −0
  • internal/activator/genbackend.go +6 −0
  • internal/activator/hawake.go +45 −5
  • internal/activator/hawake_test.go +148 −0

CI failed — run details

diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 68c208fa5..22ce0d155 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -2359,6 +2359,20 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro
return w, fmt.Errorf("restore %s: %w", host, err)
}
w.steps.mark(a.now(), "restore")
+ // An HA restore may have imported the host's published wake state,
+ // replication class included (region HA P1a): this wake replicates at
+ // that class, not the one the row carried before the restore.
+ if rr, ok := a.backend.(restoredReplicator); ok {
+ if class, ok := rr.restoredReplication(rt); ok && class != rt.Replication {
+ log.Printf("activator: %s: replication class %q from the restored wake state (the row had %q)", host, class, rt.Replication)
+ rt.Replication = class
+ a.mu.Lock()
+ if e := a.entries[host]; e != nil {
+ e.route.Replication = class
+ }
+ a.mu.Unlock()
+ }
+ }
if ctx.Err() != nil || !a.wakeAllowed(host) {
w.stopOutcome.leaseReleased = a.giveBack(ctx, host, lease)
return w, ErrFenced
diff --git a/internal/activator/backend_unit.go b/internal/activator/backend_unit.go
index 9a73d9240..ef1128995 100644
--- a/internal/activator/backend_unit.go
+++ b/internal/activator/backend_unit.go
@@ -334,6 +334,14 @@ func (b *SplitBackend) SeedPlaced(ctx context.Context, rt registry.Route, rep Re
func (b *SplitBackend) Restore(ctx context.Context, rt registry.Route) (bool, error) {
return b.pick(rt).Restore(ctx, rt)
}
+
+// restoredReplication dispatches like Restore (hawake.go).
+func (b *SplitBackend) restoredReplication(rt registry.Route) (string, bool) {
+ if r, ok := b.pick(rt).(restoredReplicator); ok {
+ return r.restoredReplication(rt)
+ }
+ return "", false
+}
func (b *SplitBackend) Seed(ctx context.Context, rt registry.Route) error {
return b.pick(rt).Seed(ctx, rt)
}
diff --git a/internal/activator/genbackend.go b/internal/activator/genbackend.go
index d58e6da00..572664900 100644
--- a/internal/activator/genbackend.go
+++ b/internal/activator/genbackend.go
@@ -228,6 +228,9 @@ func (a *Service) SetLiveExecGate(gate func(rt registry.Route, build string) err
// whose generation path would not fit a unix socket path is handled the
// same way (genLayout, rev 19 rule 4).
func (b *ExecBackend) StartStaged(ctx context.Context, rt registry.Route, g Gen) (Gen, Proc, error) {
+ if err := b.haSpawnGate(rt); err != nil {
+ return g, nil, err
+ }
if g.Tier == (cgroup.Limit{}) {
g.Tier = b.GenTier(rt, g.Build)
}
@@ -432,6 +435,9 @@ type SidecarGenStarter interface {
// the start, and after a fallback the live link names a build the instance
// is not serving. The supervisor retries with its backoff.
func (b *ExecBackend) StartSidecarGen(ctx context.Context, rt registry.Route, g Gen) (Proc, error) {
+ if err := b.haSpawnGate(rt); err != nil {
+ return nil, err
+ }
p := b.pathsFor(rt)
switch p.layout {
case LayoutNested:
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go
index b958fb572..8ab07219e 100644
--- a/internal/activator/hawake.go
+++ b/internal/activator/hawake.go
@@ -148,10 +148,13 @@ type haWake struct {
entry provision.LifetimeEntry
}
-// haWakes holds each host's last Acquire classification.
+// haWakes holds each host's last Acquire classification, and the
+// replication class an HA restore imported from the host's published wake
+// state, if it imported one, for the wake that restore belongs to.
type haWakes struct {
- mu sync.Mutex
- m map[string]haWake
+ mu sync.Mutex
+ m map[string]haWake
+ classes map[string]string
}
func (w *haWakes) set(host string, s haWake) {
@@ -174,6 +177,35 @@ func (w *haWakes) forget(host string) {
w.mu.Lock()
defer w.mu.Unlock()
delete(w.m, host)
+ delete(w.classes, host)
+}
+
+func (w *haWakes) setClass(host, class string) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ if w.classes == nil {
+ w.classes = map[string]string{}
+ }
+ w.classes[host] = class
+}
+
+func (w *haWakes) class(host string) (string, bool) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ c, ok := w.classes[host]
+ return c, ok
+}
+
+// restoredReplicator is the optional Backend capability doWake asks after
+// a successful Restore: the replication class the restore imported for
+// rt's host (an HA restore's published wake state, ImportWake), so this
+// wake replicates at the class it restored, not the row's older one.
+type restoredReplicator interface {
+ restoredReplication(rt registry.Route) (class string, ok bool)
+}
+
+func (b *ExecBackend) restoredReplication(rt registry.Route) (string, bool) {
+ return b.haWakes.class(rt.Host)
}
// SetSameBoxProof installs the same-box emptiness proof the HA acquire
@@ -434,6 +466,14 @@ const staleSuffix = ".stale"
func (b *ExecBackend) setAside(p instancePaths, host string) error {
dbDir, dbName := filepath.Dir(p.dbPath), filepath.Base(p.dbPath)
steps := []func() error{
+ // litestream's local state first, before anything is moved: it
+ // describes the copy being set aside, and a directory of it that
+ // survived would let replication resume from the discarded
+ // history's position. Both are removed checked, beneath their
+ // directory: a failure fails the wake with nothing else touched.
+ // (PurgeLocalDBArtifacts discards its errors, so it is not used.)
+ func() error { return removeAllIfThere(dbDir, dbName+"-litestream") },
+ func() error { return removeAllIfThere(dbDir, ".activator-"+dbName+"-litestream") },
func() error { return removeIfThere(dbDir, dbName+staleSuffix) },
func() error { return removeIfThere(dbDir, dbName+staleSuffix+"-wal") },
func() error { return renameIfThere(dbDir, dbName, dbName+staleSuffix) },
@@ -450,8 +490,6 @@ func (b *ExecBackend) setAside(p instancePaths, host string) error {
return err
}
}
- // litestream's own local state describes the database set aside.
- PurgeLocalDBArtifacts(p.dbPath, false)
for _, dir := range uniqueDirs(dbDir, p.dataDir, filepath.Dir(p.envFile)) {
if err := syncDirIfThere(dir); err != nil {
return err
@@ -579,6 +617,8 @@ func (b *ExecBackend) restoreFilesClean(ctx context.Context, rt registry.Route)
if err := hostfiles.ImportWake(b.Registry, host, ws); err != nil {
return err
}
+ // This wake replicates at the imported class (restoredReplication).
+ b.haWakes.setClass(host, ws.Replication)
}
return nil
}
diff --git a/internal/activator/hawake_test.go b/internal/activator/hawake_test.go
index 65a98e72b..929d65c02 100644
--- a/internal/activator/hawake_test.go
+++ b/internal/activator/hawake_test.go
@@ -713,11 +713,159 @@ func TestHASpawnRefusedAfterLayoutChange(t *testing.T) {
if err := b.Seed(ctx, rt); !errors.As(err, &refused) {
t.Fatalf("Seed: %v", err)
}
+ // The staged starts that planned wakes, pinned starts and swaps use
+ // (fix round 1, I1): refused before any preparation or dispatch.
+ staged := Gen{N: 2, StagedPath: filepath.Join(b.OptDir, "versions", "v1", "app"), Build: "v1"}
+ if _, proc, err := b.StartStaged(ctx, rt, staged); !errors.As(err, &refused) || proc != nil {
+ t.Fatalf("StartStaged: %v, proc %v", err, proc)
+ }
+ if exists(b.flatGenSocket(rt.Host, staged.N)) || exists(filepath.Dir(b.flatGenSocket(rt.Host, staged.N))) {
+ t.Fatal("StartStaged prepared a generation socket")
+ }
+ if _, err := b.StartSidecarGen(ctx, rt, staged); !errors.As(err, &refused) {
+ t.Fatalf("StartSidecarGen: %v", err)
+ }
if spawns(b) != 0 {
t.Fatal("something was started")
}
}
+// litestream's local state for the copy being set aside must go, checked
+// (fix round 1, I2): state that survived would let replication resume from
+// the discarded history. A metadata directory that cannot be removed fails
+// the wake before anything is moved, restored or replicated.
+func TestSetAsideFailsWhenLitestreamStateCannotBeRemoved(t *testing.T) {
+ ctx := context.Background()
+ for _, meta := range []func(db string) string{
+ func(db string) string {
+ return filepath.Join(filepath.Dir(db), ".activator-"+filepath.Base(db)+"-litestream")
+ },
+ func(db string) string { return db + "-litestream" },
+ } {
+ b, rt := haBackend(t, "shop.example.com")
+ l1 := haFixOf(b).lifetime
+ writeDBAndRecord(t, b, rt, hafresh.Marker{V: 1, Box: "a", IID: "i-a", Lifetime: l1, TXID: 5, Clean: true})
+ dir := meta(dbPathOf(b, rt))
+ // Deeper than the checked removal descends (64): it refuses, as
+ // a directory it cannot write would, for any user, root included.
+ deep := dir
+ for range 66 {
+ deep = filepath.Join(deep, "d")
+ }
+ if err := os.MkdirAll(deep, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ putLockFor(t, b, rt, markerBody(t, "b", "i-b", l1, 6, true))
+ l, err := b.Acquire(ctx, rt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ releaseHALease(t, l)
+ if _, err := b.Restore(ctx, rt); err == nil {
+ t.Fatalf("%s: the wake went on over litestream state it could not remove", filepath.Base(dir))
+ }
+ if restoreCalls(b) != 0 || !exists(dbPathOf(b, rt)) || exists(dbPathOf(b, rt)+".stale") {
+ t.Fatalf("%s: the copy was moved or restored over (%d restores)", filepath.Base(dir), restoreCalls(b))
+ }
+ }
+ // Removable state goes with the set-aside copy.
+ b, rt := haBackend(t, "shop.example.com")
+ db := dbPathOf(b, rt)
+ writeDBAndRecord(t, b, rt, hafresh.Marker{V: 1, Box: "a", IID: "i-a", Lifetime: haFixOf(b).lifetime, TXID: 5, Clean: true})
+ for _, d := range []string{db + "-litestream", filepath.Join(filepath.Dir(db), ".activator-"+filepath.Base(db)+"-litestream")} {
+ if err := os.MkdirAll(filepath.Join(d, "ltx", "0"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err := b.restoreHA(ctx, rt, markerView("b", "i-b", haFixOf(b).lifetime, 5, true), false); err != nil {
+ t.Fatal(err)
+ }
+ if exists(db+"-litestream") || exists(filepath.Join(filepath.Dir(db), ".activator-"+filepath.Base(db)+"-litestream")) {
+ t.Fatal("litestream state of the set-aside copy survived")
+ }
+}
+
+// An HA restore that imports the host's wake state records its replication
+// class for the wake (fix round 1): the backend half.
+func TestHARestoreRecordsImportedReplicationClass(t *testing.T) {
+ ctx := context.Background()
+ b, rt := haBackend(t, "shop.example.com")
+ pub, err := hostfiles.Open(ctx, b.FilesStore, b.filesPrefix(rt.Host))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := hostfiles.StageWake(ctx, pub, hostfiles.WakeState{V: 1, Host: rt.Host, Replication: replicationStream}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := pub.Commit(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if err := b.Registry.SetReplication(rt.Host, replicationDaily); err != nil {
+ t.Fatal(err)
+ }
+ putLockFor(t, b, rt, markerBody(t, "b", "i-b", haFixOf(b).lifetime, 6, true))
+ l, err := b.Acquire(ctx, rt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ releaseHALease(t, l)
+ split := &SplitBackend{Exec: b, Unit: &UnitBackend{OptDir: b.OptDir}}
+ if _, err := split.Restore(ctx, rt); err != nil {
+ t.Fatal(err)
+ }
+ if c, ok := split.restoredReplication(rt); !ok || c != replicationStream {
+ t.Fatalf("restored class %q %v, want %q", c, ok, replicationStream)
+ }
+ // The next Acquire starts a new wake: nothing carried over.
+ if _, err := b.Acquire(ctx, rt); err == nil {
+ t.Fatal("fixture: the lock should be held")
+ }
+ if _, ok := b.restoredReplication(rt); ok {
+ t.Fatal("a restored class outlived its wake")
+ }
+}
+
+// restoredClassBackend is the fake backend whose Restore imported class.
+type restoredClassBackend struct {
+ *fakeBackend
+ class string
+}
+
+func (b *restoredClassBackend) restoredReplication(registry.Route) (string, bool) {
+ return b.class, true
+}
+
+// The service half (fix round 1): the class the restore imported, not the
+// row's older one, is the interval handed to Replicate, and the entry's
+// route carries it.
+func TestWakeReplicatesAtTheRestoredClass(t *testing.T) {
+ fb := &fakeBackend{}
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ a := New(Config{Bucket: "test-bucket", Idle: time.Minute}, &restoredClassBackend{fakeBackend: fb, class: replicationStream}, reg)
+ rt := testRoute("shop.example.com")
+ rt.Replication = replicationDaily
+ release, err := a.beginRequest(context.Background(), rt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ release()
+ fb.mu.Lock()
+ got := fb.syncIntervals[len(fb.syncIntervals)-1]
+ fb.mu.Unlock()
+ if got != replicationSyncInterval(replicationStream) {
+ t.Fatalf("replicated every %v, want the restored stream class's %v", got, replicationSyncInterval(replicationStream))
+ }
+ a.mu.Lock()
+ e := a.entries[rt.Host]
+ a.mu.Unlock()
+ if e == nil || e.route.Replication != replicationStream {
+ t.Fatalf("the entry's route kept the old class")
+ }
+}
+
func TestLeaseRefusedAnswers503RetryAfter10(t *testing.T) {
a := &Service{}
w := httptest.NewRecorder()