carlos / platform Public

ha: verify departure replay and counted adoption pages

Exercise two receivers, pool correction, scanner loss, completion commit failures, and the production importer across 33 hosts. Reuse the scanner staging read while preserving acquire CAS and replay validation; resume unfinished local authority before accepting a self marker. Persist bounded retry backoff and expose one counted identity summary per hour.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev c06d16695321e17c0bba581ee9d70af37c3e4324 parent 83900c0
11 files changed, +485 −22
  • internal/activator/haadopt.go +9 −3
  • internal/activator/haadopt_test.go +2 −1
  • internal/host/hadepartures.go +6 −1
  • internal/host/hadepartures_scan.go +26 −2
  • internal/host/hadepartures_scan_test.go +317 −1
  • internal/host/hadepartures_wiring.go +6 −1
  • internal/lease/ha_test.go +26 −0
  • internal/registry/ha_journal.go +37 −0
  • internal/registry/ha_journal_test.go +49 −0
  • internal/registry/ha_scan.go +6 −12
  • internal/registry/remote.go +1 −1
diff --git a/internal/activator/haadopt.go b/internal/activator/haadopt.go
index 20ce3680e..272895d8e 100644
--- a/internal/activator/haadopt.go
+++ b/internal/activator/haadopt.go
@@ -25,6 +25,7 @@ type Adoption struct {
Pair registry.Pair
Observed hafresh.View
Revision uint64
+ ScanObservation bool
}
func adoptionBackend(b Backend, rt registry.Route) *ExecBackend {
@@ -175,9 +176,14 @@ func (a *Service) AdoptHost(ctx context.Context, rt registry.Route, req Adoption
read := func() (hafresh.View, error) {
return lease.ReadLock(ctx, b.Cfg.Bucket, b.Cfg.hibernatePrefix(rt.Host), b.Cfg.Region)
}
- view, err := read()
- if err != nil {
- return Deferred, err
+ view := req.Observed
+ // A scanner already paid for this staging observation. Acquire still reads
+ // and compares its exact revision before any write; replay needs a fresh read.
+ if !req.ScanObservation || exists {
+ view, err = read()
+ if err != nil {
+ return Deferred, err
+ }
}
self := b.self()
selfMarker := func(v hafresh.View) bool {
diff --git a/internal/activator/haadopt_test.go b/internal/activator/haadopt_test.go
index 09dbdbbb2..54bde7cfd 100644
--- a/internal/activator/haadopt_test.go
+++ b/internal/activator/haadopt_test.go
@@ -397,6 +397,7 @@ func haAdoptMarker(t *testing.T, ref, iid, life string, generation int64, clean
func TestHAAdoptRequestBudget(t *testing.T) {
s, req := haAdoptionFixture(t)
ctx := context.Background()
+ req.ScanObservation = true
publishManifest(t, s.b, s.rt, map[string]string{"private.txt": "file tree"}, "PRIVATE=secret")
m, _, err := hostfiles.Load(ctx, s.b.FilesStore, s.b.filesPrefix(s.rt.Host))
if err != nil {
@@ -423,7 +424,7 @@ func TestHAAdoptRequestBudget(t *testing.T) {
t.Fatalf("unexpected request: %s", r)
}
}
- if wakes != 1 || manifests != 2 || locks != 3 || puts != 2 {
+ if wakes != 1 || manifests != 2 || locks != 2 || puts != 2 {
t.Fatalf("wake=%d manifest=%d lock=%d put=%d", wakes, manifests, locks, puts)
}
}
diff --git a/internal/host/hadepartures.go b/internal/host/hadepartures.go
index 0c1a7bb30..f265702dc 100644
--- a/internal/host/hadepartures.go
+++ b/internal/host/hadepartures.go
@@ -400,7 +400,12 @@ func (c *Controller) step(ctx context.Context) error {
return e
}
if page {
- c.logf("ha_departure_pending code=%s iid=%s", code, h.IID)
+ count, e := c.cfg.Registry.PendingTerminationCount(ctx)
+ if e != nil {
+ return e
+ }
+ code = fmt.Sprintf("%s count=%d", code, count)
+ c.logf("ha_departure_pending code=%s sample_iid=%s", code, h.IID)
if c.cfg.PageIdentity != nil {
if e = c.cfg.PageIdentity(ctx, h, code); e != nil {
c.logf("ha_departure_page code=failed")
diff --git a/internal/host/hadepartures_scan.go b/internal/host/hadepartures_scan.go
index ce1e8d630..fb40368bc 100644
--- a/internal/host/hadepartures_scan.go
+++ b/internal/host/hadepartures_scan.go
@@ -52,7 +52,7 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
}
d := rows[0]
// Reserve the next slot before I/O so one failing departure cannot starve peers.
- if _, err = c.cfg.Registry.RetryDeparture(ctx, d.ID, c.now(), c.now().Add(30*time.Second), "scan", false); err != nil {
+ if _, err = c.cfg.Registry.RetryDeparture(ctx, d.ID, c.now(), c.now().Add(30*time.Second), "reserve", false); err != nil {
return false, err
}
if d.Phase == "edges_deleted_or_absent" || d.Phase == "indexed" {
@@ -151,6 +151,26 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
}
match := MatchesDeparture(v, d.Box.Ref, d.Box.InstanceID, h.Lifetime)
if !match {
+ if seen && ref == c.cfg.Self.Ref && iid == c.cfg.Self.InstanceID {
+ receipt, present, e := c.cfg.Registry.HAAdoption(ctx, h.Host, h.Lifetime, d.ID)
+ if e != nil {
+ s.Unresolved++
+ continue
+ }
+ if present && receipt.Phase != "adopted" {
+ // Our marker cannot discharge our unfinished local commit.
+ // Resume the one importer using its original departure view.
+ if s.Rescan || c.cfg.Adopt == nil {
+ s.Unresolved++
+ continue
+ }
+ result, e := c.cfg.Adopt(ctx, h, d, old.Observed)
+ if e != nil || result == activator.Deferred {
+ s.Unresolved++
+ continue
+ }
+ }
+ }
if seen && v.Lock.Generation <= old.Observed.Lock.Generation {
s.Unresolved++
continue
@@ -227,6 +247,7 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
s.Rescan = false
s.Unresolved++
}
+ blocked := s.Unresolved > 0
phase := "scanning"
if s.Cursor == len(inv.Records) && s.Generation == generation {
if s.Rescan && CanCompleteDeparture(RescanResult{Inventory: inv, EvidenceAt: d.ObservedAt, Finished: true, Unresolved: s.Unresolved}) {
@@ -244,9 +265,12 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
if phase == "authority_complete" {
return true, c.complete(ctx, d.ID)
}
- return true, c.retryScan(ctx, d, blockers, "scan", len(blockers) > 0 || s.Unresolved > 0)
+ return true, c.retryScan(ctx, d, blockers, "scan", len(blockers) > 0 || blocked)
}
func (c *Controller) retryScan(ctx context.Context, d registry.HADeparture, hosts []provision.DepartureHost, code string, page bool) error {
+ if code == "scan" && page {
+ code = "blocked"
+ }
claimed, err := c.cfg.Registry.RetryDeparture(ctx, d.ID, c.now(), c.now().Add(30*time.Second), code, page)
if err != nil {
return err
diff --git a/internal/host/hadepartures_scan_test.go b/internal/host/hadepartures_scan_test.go
index a7c5e163a..92cd40fa3 100644
--- a/internal/host/hadepartures_scan_test.go
+++ b/internal/host/hadepartures_scan_test.go
@@ -2,10 +2,19 @@ package host
import (
"context"
+ "database/sql"
+ "encoding/json"
"errors"
"fmt"
"github.com/aws/smithy-go"
+ "github.com/carlosframework/platform/internal/hostfiles"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/lease/locktest"
+ "github.com/carlosframework/platform/internal/termfence"
"path/filepath"
+ "strings"
+ "sync/atomic"
"testing"
"time"
@@ -92,7 +101,7 @@ func (x *scanRig) pass(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- x.now = x.now.Add(31 * time.Second)
+ x.now = x.now.Add(301 * time.Second)
}
func TestDepartureCompletionRescan(t *testing.T) {
x := newScanRig(t, 33)
@@ -354,3 +363,310 @@ func TestDepartureFairScheduling(t *testing.T) {
t.Fatal(a.Cursor, b.Cursor)
}
}
+
+type scanQueue struct {
+ received atomic.Int32
+ deleted atomic.Int32
+ receipt string
+}
+
+func (q *scanQueue) Receive(ctx context.Context, _ time.Duration) ([]hadeparture.Message, error) {
+ if q.received.Add(1) == 1 {
+ return []hadeparture.Message{{ID: "event", Receipt: q.receipt, Body: []byte(`{"version":"0","id":"event","source":"aws.ec2","detail-type":"EC2 Instance State-change Notification","account":"111122223333","region":"eu-west-1","detail":{"instance-id":"i-1123456789abcdef0","state":"terminated"}}`)}}, nil
+ }
+ <-ctx.Done()
+ return nil, ctx.Err()
+}
+func (q *scanQueue) Delete(_ context.Context, receipt string) error {
+ if receipt != q.receipt {
+ return errors.New("stale_receipt")
+ }
+ q.deleted.Add(1)
+ return nil
+}
+func (x *scanRig) start(t *testing.T, receipt string) *scanQueue {
+ t.Helper()
+ q := &scanQueue{receipt: receipt}
+ x.c.cfg.Self.Account = x.d.Box.Account
+ x.c.cfg.Self.InstanceID = "i-0123456789abcdef0"
+ x.c.consumer = hadeparture.NewConsumer(func(context.Context) error { return nil }, x.c.record, nil)
+ life, err := x.c.Start(t.Context(), func(context.Context) (hadeparture.Queue, error) { return q, nil })
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = life.Stop(context.Background()) })
+ select {
+ case <-life.Started():
+ case <-time.After(time.Second):
+ t.Fatal("consumer failed to start")
+ }
+ return q
+}
+func TestDeparturePoolCoverage(t *testing.T) {
+ b := newScanRig(t, 2)
+ c := newScanRig(t, 2)
+ b.inv.Records[1].Pool = "hapair"
+ c.inv = b.inv
+ c.locks = b.locks
+ c.store = b.store
+ c.c.cfg.Policy = func() LocalPolicy { return LocalPolicy{Scope: c.d.Box.Scope, Pools: []string{"", "hapair"}} }
+ qb := b.start(t, "queue-b-current")
+ qc := c.start(t, "queue-c-current")
+ b.pass(t)
+ if b.imports != 1 || qb.deleted.Load() != 0 {
+ t.Fatal(b.imports, qb.deleted.Load())
+ }
+ c.pass(t)
+ if c.imports != 1 {
+ t.Fatal(c.imports)
+ }
+ c.pass(t)
+ b.pass(t)
+ b.pass(t)
+ if qb.deleted.Load() != 1 || qc.deleted.Load() != 1 {
+ t.Fatal(qb.deleted.Load(), qc.deleted.Load())
+ }
+ if qb.received.Load() == 0 || qc.received.Load() == 0 {
+ t.Fatal("coverage gated receive")
+ }
+}
+func TestDepartureCoverageIsolationIntegrated(t *testing.T) {
+ x := newScanRig(t, 2)
+ x.inv.Records[1].Pool = "hapair"
+ q := x.start(t, "current")
+ x.pass(t)
+ if x.imports != 1 {
+ t.Fatal(x.imports)
+ }
+ // Both asleep and awake legacy sidecars remain in the pre-filter census.
+ for _, state := range []string{"asleep", "awake"} {
+ h := provision.DepartureHost{Host: "worker.example.com", Kind: "sidecar", Lifetime: "side-life", Revision: state}
+ x.inv.Records = append(x.inv.Records[:2], h)
+ x.pass(t)
+ d, e := x.r.Departure(t.Context(), x.d.ID)
+ if e != nil || d.Phase == "complete" || q.deleted.Load() != 0 {
+ t.Fatal(d, e, q.deleted.Load())
+ }
+ }
+ x.c.cfg.Policy = func() LocalPolicy { return LocalPolicy{Scope: x.d.Box.Scope, Pools: []string{"", "hapair"}} }
+ x.pass(t)
+ if x.imports != 2 {
+ t.Fatal("policy correction required restart", x.imports)
+ }
+ x.inv.Records = x.inv.Records[:2]
+ x.inv.Generation = "retired-sidecar"
+ x.pass(t)
+ x.pass(t)
+ if q.deleted.Load() != 1 {
+ t.Fatal("did not finish after authoritative retirement")
+ }
+}
+func TestDepartureScannerDeath(t *testing.T) {
+ x := newScanRig(t, 2)
+ ctx, cancel := context.WithCancel(t.Context())
+ adopt := x.c.cfg.Adopt
+ x.c.cfg.Adopt = func(ctx context.Context, h provision.DepartureHost, d registry.HADeparture, v hafresh.View) (activator.AdoptResult, error) {
+ result, err := adopt(ctx, h, d, v)
+ cancel()
+ return result, err
+ }
+ _, _ = x.c.ScanPass(ctx)
+ if x.imports != 1 {
+ t.Fatal(x.imports)
+ }
+ y := newScanRig(t, 2)
+ y.locks = x.locks
+ y.store = x.store
+ y.inv = x.inv
+ y.pass(t)
+ y.pass(t)
+ if y.imports != 1 {
+ t.Fatal("successor reimported or remaining lost", y.imports)
+ }
+ d, err := y.r.Departure(t.Context(), y.d.ID)
+ if err != nil || d.Phase != "complete" {
+ t.Fatal(d, err)
+ }
+}
+
+func TestDepartureNoEarlyDeleteCommitFailure(t *testing.T) {
+ for _, phase := range []string{"authority_complete", "edges_deleted_or_absent", "indexed", "complete"} {
+ t.Run(phase, func(t *testing.T) {
+ x := newScanRig(t, 1)
+ x.pass(t)
+ db, err := sql.Open("sqlite", x.r.Path())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ _, err = db.Exec(`CREATE TRIGGER fail_departure_phase BEFORE UPDATE OF phase ON ha_departures WHEN NEW.phase='` + phase + `' BEGIN SELECT RAISE(ABORT,'injected_commit'); END`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = x.c.ScanPass(t.Context())
+ if err == nil {
+ t.Fatal("commit failure ignored")
+ }
+ d, err := x.r.Departure(t.Context(), x.d.ID)
+ if err != nil || d.Phase == "complete" {
+ t.Fatal(d, err)
+ }
+ if phase == "authority_complete" {
+ if _, _, err = x.store.Get(t.Context(), x.d.EdgesKey); err != nil {
+ t.Fatal("early delete", err)
+ }
+ }
+ if _, err = db.Exec(`DROP TRIGGER fail_departure_phase`); err != nil {
+ t.Fatal(err)
+ }
+ for range 3 {
+ x.pass(t)
+ }
+ d, err = x.r.Departure(t.Context(), x.d.ID)
+ if err != nil || d.Phase != "complete" {
+ t.Fatal(d, err)
+ }
+ if x.imports != 1 {
+ t.Fatal("commit replay imported again", x.imports)
+ }
+ })
+ }
+}
+func TestDepartureProductionImporter(t *testing.T) {
+ old := lease.CurrentSelf()
+ t.Cleanup(func() { lease.SetSelf(old) })
+ fx := locktest.NewLockFixture(t)
+ a, _, _ := departureArmFixture(t)
+ a.Self.Scope.DataBucket = fx.Bucket
+ a.ProofStore = nil
+ a.Backend.Cfg.Bucket = fx.Bucket
+ a.Backend.Registry = a.Registry
+ a.Backend.DataDir = filepath.Join(t.TempDir(), "data")
+ a.Backend.RunDirOverride = filepath.Join(t.TempDir(), "run")
+ a.Backend.Control = instancectl.NewClient("/unused/control.sock")
+ a.Backend.Cfg.Record = func(context.Context, registry.Route) (activator.RecordFacts, error) {
+ return activator.RecordFacts{LifetimeEntry: provision.LifetimeEntry{ID: "life", HA: true}}, nil
+ }
+ files, err := lease.NewFilesStore(t.Context(), fx.Bucket, "eu-west-1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ a.Backend.FilesStore = files
+ rt := registry.Route{Host: "shop.example.com", Kind: "instance", Account: "bab", App: "shop", Status: "ready", HA: true, Provisioned: true, Hibernate: true, DBPath: provision.NestedDBPath(a.Backend.DataDir, "shop.example.com"), Socket: filepath.Join(a.Backend.RunDirOverride, "instances", provision.InstanceID("shop.example.com"), "app.sock")}
+ if err := a.Registry.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ a.Service = activator.New(a.Backend.Cfg, a.Backend, a.Registry)
+ a.Service.DutyStore = a.Registry
+ lease.SetSelf(hafresh.Self{Ref: a.Self.Ref, IID: a.Self.InstanceID, Account: a.Self.Account, Region: a.Self.Scope.CloudRegion})
+ if err := lease.SetObligationDir(t.TempDir()); err != nil {
+ t.Fatal(err)
+ }
+ p, err := hostfiles.Open(t.Context(), a.Backend.FilesStore, "instances/shop.example.com/files/0/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = hostfiles.StageWake(t.Context(), p, hostfiles.WakeState{V: 1, Host: rt.Host, NextDue: 9999999999, Timers: []hostfiles.WakeTimer{{Name: "reminder", Kind: "once", Spec: "at 9999999999", Path: "/remind", NextAt: 9999999999, Registration: "original"}}}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = p.Commit(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ body, _ := hafresh.MarkerBody(5, hafresh.Marker{V: 1, Box: "dead", IID: "i-1123456789abcdef0", Lifetime: "life"})
+ fx.PutLock("instances/shop.example.com", body)
+ records := []provision.DepartureHost{{Host: rt.Host, Account: rt.Account, App: rt.App, Kind: "instance", HA: true, Lifetime: "life", Revision: "one"}}
+ for i := 1; i < 33; i++ {
+ other := rt
+ other.Host = fmt.Sprintf("shop%d.example.com", i)
+ other.DBPath = provision.NestedDBPath(a.Backend.DataDir, other.Host)
+ other.Socket = filepath.Join(a.Backend.RunDirOverride, "instances", provision.InstanceID(other.Host), "app.sock")
+ if err = a.Registry.Upsert(other); err != nil {
+ t.Fatal(err)
+ }
+ pub, e := hostfiles.Open(t.Context(), files, "instances/"+other.Host+"/files/0/")
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = hostfiles.StageWake(t.Context(), pub, hostfiles.WakeState{V: 1, Host: other.Host, NextDue: 9999999999}); e != nil {
+ t.Fatal(e)
+ }
+ if _, e = pub.Commit(t.Context()); e != nil {
+ t.Fatal(e)
+ }
+ fx.PutLock("instances/"+other.Host, body)
+ records = append(records, provision.DepartureHost{Host: other.Host, Account: other.Account, App: other.App, Kind: "instance", HA: true, Lifetime: "life", Revision: "one"})
+ }
+
+ c, life, err := armHADepartures(t.Context(), a)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = life.Stop(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ obs, err := c.cfg.Identities.Observe(t.Context(), hadeparture.BoxObservation{Known: true, Box: hadeparture.Box{Ref: "dead", Scope: a.Self.Scope}, EdgesKey: "control/edges/dead.json", EdgesETag: "exact"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = c.Enqueue(t.Context(), obs); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ inv := provision.InventorySnapshot{Generation: "fresh", Complete: true, WalkStartedAt: now.Add(time.Second), SourceReadStartedAt: now.Add(time.Second), Records: records}
+ c.cfg.Now = func() time.Time { return now }
+ c.cfg.Inventory = func() provision.InventorySnapshot { return inv }
+ // The adopter's own cloud binding is already established at arm time.
+ c.cfg.ValidateSuccessor = func(ctx context.Context, ref, iid string) (bool, error) {
+ return ref == a.Self.Ref && iid == a.Self.InstanceID, nil
+ }
+
+ c.cfg.Cache = &termfence.ProofCache{}
+ a.Backend.TerminationProofs.Cache = c.cfg.Cache
+ constructors := 0
+ reader := c.cfg.NewReader
+ c.cfg.NewReader = func(ctx context.Context, region string) (DepartureLockReader, error) {
+ constructors++
+ return reader(ctx, region)
+ }
+ for page, want := range []struct{ gets, puts int }{{193, 64}, {6, 2}, {32, 0}, {1, 0}} {
+ before := len(fx.Requests())
+ if _, err = c.ScanPass(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ gets, puts := 0, 0
+ for _, request := range fx.Requests()[before:] {
+ if strings.HasPrefix(request, "GET ") {
+ gets++
+ } else if strings.HasPrefix(request, "PUT ") {
+ puts++
+ } else {
+ t.Fatal("unexpected request", request)
+ }
+ }
+ if gets != want.gets || puts != want.puts {
+ t.Fatalf("page %d: GET=%d PUT=%d want %+v", page, gets, puts, want)
+ }
+ now = now.Add(31 * time.Second)
+ }
+ if constructors != 4 {
+ t.Fatal("scan reader clients", constructors)
+ }
+
+ duty, ok, err := a.Registry.HADuty(rt.Host, "life")
+ if err != nil || !ok || duty.Basis != "adopted" {
+ t.Fatal(duty, ok, err)
+ }
+ timers, err := a.Registry.TimersFor(rt.Host)
+ if err != nil || len(timers) != 1 || timers[0].Registration != "original" {
+ t.Fatal(timers, err)
+ }
+ var lock hafresh.Lock
+ if err = json.Unmarshal(fx.LockBody("instances/shop.example.com"), &lock); err != nil || lock.Release == nil || lock.Release.Box != a.Self.Ref || lock.Release.Clean {
+ t.Fatal(lock, err)
+ }
+
+ d, err := a.Registry.Departure(t.Context(), departureID(c.cfg.DeploymentBucket, obs.Box))
+ if err != nil || d.Phase != "complete" {
+ t.Fatal(d, err)
+ }
+}
diff --git a/internal/host/hadepartures_wiring.go b/internal/host/hadepartures_wiring.go
index c70256d9d..8e871e47f 100644
--- a/internal/host/hadepartures_wiring.go
+++ b/internal/host/hadepartures_wiring.go
@@ -113,6 +113,11 @@ func armHADepartures(ctx context.Context, a departureArm) (*Controller, hadepart
messages := []string{fmt.Sprintf("Duties from box %s have not been recovered. The scan will retry automatically. Check the box's wake state before removing its records.", d.Box.Ref)}
for _, h := range hosts {
if h.Kind != "sidecar" {
+ policy := LocalPolicy{Scope: a.Self.Scope, Pools: provision.ParseBoxPools(a.Getenv("CARLOS_POOLS"))}
+ if CanAdopt(h, policy) {
+ messages = append(messages, fmt.Sprintf("host=%s code=unsupported_wake", h.Host))
+ continue
+ }
pool := h.Pool
if pool == "" {
pool = "shared"
@@ -194,7 +199,7 @@ func armHADepartures(ctx context.Context, a departureArm) (*Controller, hadepart
return activator.Deferred, err
}
}
- return a.Service.AdoptHost(ctx, *rt, activator.Adoption{Departure: d.ID, Ref: d.Box.Ref, IID: d.Box.InstanceID, Lifetime: h.Lifetime, Pair: pair, Revision: duty.Revision, Observed: v})
+ return a.Service.AdoptHost(ctx, *rt, activator.Adoption{Departure: d.ID, Ref: d.Box.Ref, IID: d.Box.InstanceID, Lifetime: h.Lifetime, Pair: pair, Revision: duty.Revision, Observed: v, ScanObservation: true})
}
a.Service.OnDepartureSuspect = c.Suspect
life, err := c.Start(ctx, queue)
diff --git a/internal/lease/ha_test.go b/internal/lease/ha_test.go
index fff0dde8a..4d145146f 100644
--- a/internal/lease/ha_test.go
+++ b/internal/lease/ha_test.go
@@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"errors"
+ "fmt"
"log"
"net/http"
"os"
@@ -490,3 +491,28 @@ func TestAcquireHALogsTheWinningRule(t *testing.T) {
})
}
}
+
+func TestDepartureSharedLockReader(t *testing.T) {
+ fx := leasetest.NewLockFixture(t)
+ reader, err := lease.NewLockReader(ctx, "eu-west-1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 32; i++ {
+ prefix := fmt.Sprintf("instances/shop%d", i)
+ fx.PutLock(prefix, leaseBody("legacy:1", time.Now().Add(time.Hour)))
+ if _, err = reader.ReadLock(ctx, fx.Bucket, prefix); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if len(fx.Requests()) != 32 {
+ t.Fatal(fx.Requests())
+ }
+ before := len(fx.Requests())
+ if _, err = reader.ReadLock(ctx, fx.Bucket, "../escape"); err == nil {
+ t.Fatal("unsafe key accepted")
+ }
+ if len(fx.Requests()) != before {
+ t.Fatal("invalid key made request")
+ }
+}
diff --git a/internal/registry/ha_journal.go b/internal/registry/ha_journal.go
index 58cf2f03b..6511ede2c 100644
--- a/internal/registry/ha_journal.go
+++ b/internal/registry/ha_journal.go
@@ -26,6 +26,7 @@ type HAPendingTermination struct {
LastError string
}
type HADeparture struct {
+ RetryCount int
hadeparture.Departure
ProofKey, ProofDigest, Phase, InventoryGeneration, LastError string
NextAttempt, LastPage time.Time
@@ -57,6 +58,7 @@ type haJournalRequest struct {
Scan HADepartureScan
}
type haJournalResponse struct {
+ Count int
Scan HADepartureScan
Inbox []HATerminationInbox
Hints []HAPendingTermination
@@ -167,6 +169,9 @@ func (r *Registry) haJournal(ctx context.Context, q haJournalRequest) (out haJou
return resp.HAJournal, e
}
switch q.Op {
+ case "hint_count":
+ err = r.sql.QueryRowContext(ctx, `SELECT count(*) FROM ha_pending_terminations`).Scan(&out.Count)
+ return out, err
case "departure", "scan", "scan_save":
return r.departureScanJournal(ctx, q)
case "park":
@@ -410,6 +415,33 @@ func (r *Registry) haJournal(ctx context.Context, q haJournalRequest) (out haJou
return out, e
}
defer tx.Rollback()
+ var body []byte
+ if e = tx.QueryRowContext(ctx, `SELECT body FROM ha_departures WHERE id=?`, q.ID).Scan(&body); e != nil {
+ return out, e
+ }
+ var d HADeparture
+ if e = json.Unmarshal(body, &d); e != nil {
+ return out, e
+ }
+ if q.Code != "reserve" {
+ if q.Code == "scan" || q.Code == "pending" {
+ d.RetryCount = 0
+ } else {
+ waits := []time.Duration{30 * time.Second, time.Minute, 2 * time.Minute, 5 * time.Minute}
+ next := q.At.Add(waits[min(d.RetryCount, 3)])
+ if next.After(q.Next) {
+ q.Next = next
+ }
+ d.RetryCount = min(d.RetryCount+1, 3)
+ }
+ body, e = json.Marshal(d)
+ if e != nil {
+ return out, e
+ }
+ if _, e = tx.ExecContext(ctx, `UPDATE ha_departures SET body=? WHERE id=?`, body, q.ID); e != nil {
+ return out, e
+ }
+ }
if q.Page {
res, e := tx.ExecContext(ctx, `UPDATE ha_departures SET last_page=? WHERE id=? AND phase<>'complete' AND (last_page=0 OR last_page<=?)`, journalTime(q.At), q.ID, journalTime(q.At.Add(-time.Hour)))
if e != nil {
@@ -481,3 +513,8 @@ func (r *Registry) haJournal(ctx context.Context, q haJournalRequest) (out haJou
}
return out, err
}
+
+func (r *Registry) PendingTerminationCount(ctx context.Context) (int, error) {
+ out, err := r.haJournal(ctx, haJournalRequest{Op: "hint_count"})
+ return out.Count, err
+}
diff --git a/internal/registry/ha_journal_test.go b/internal/registry/ha_journal_test.go
index 45ee15e64..ab1999222 100644
--- a/internal/registry/ha_journal_test.go
+++ b/internal/registry/ha_journal_test.go
@@ -3,6 +3,7 @@ package registry
import (
"context"
"crypto/sha256"
+ "errors"
"fmt"
"testing"
"time"
@@ -260,3 +261,51 @@ func TestDeparturePendingPagesGloballyBounded(t *testing.T) {
t.Fatal(page, err)
}
}
+
+func TestDepartureScanPhasesAndReplay(t *testing.T) {
+ for _, remote := range []bool{false, true} {
+ t.Run(fmt.Sprint(remote), func(t *testing.T) {
+ var r *Registry
+ var path string
+ if remote {
+ r, path = remoteTestRegistry(t)
+ } else {
+ r, path = adoptRegistry(t)
+ }
+ d := HADeparture{Departure: hadeparture.Departure{ID: "dead", Box: hadeparture.Box{Ref: "dead", InstanceID: "i-dead"}, ObservedAt: time.Now()}, ProofKey: "proof", ProofDigest: "digest"}
+ if err := r.EnrollDeparture(t.Context(), d, ""); err != nil {
+ t.Fatal(err)
+ }
+ s := HADepartureScan{Generation: "full", Rescan: true, Hosts: map[string]HADepartureHostScan{"shop.example.com": {Lifetime: "life", Result: "adopted"}}}
+ if err := r.SaveDepartureScan(t.Context(), d.ID, "complete", s); !errors.Is(err, ErrHAJournal) {
+ t.Fatal("phase skip", err)
+ }
+ for _, phase := range []string{"scanning", "authority_complete", "edges_deleted_or_absent", "indexed", "complete"} {
+ if err := r.SaveDepartureScan(t.Context(), d.ID, phase, s); err != nil {
+ t.Fatal(phase, err)
+ }
+ if phase == "scanning" {
+ if err := r.SaveDepartureScan(t.Context(), d.ID, phase, s); !errors.Is(err, ErrHAChanged) {
+ t.Fatal("stale checkpoint", err)
+ }
+ }
+ s.Version++
+ r.Close()
+ var err error
+ r, err = Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, e := r.DepartureScan(t.Context(), d.ID)
+ if e != nil || got.Version != s.Version || got.Hosts["shop.example.com"].Result != "adopted" {
+ t.Fatal(got, e)
+ }
+ gotd, e := r.Departure(t.Context(), d.ID)
+ if e != nil || gotd.Phase != phase {
+ t.Fatal(gotd, e)
+ }
+ }
+ r.Close()
+ })
+ }
+}
diff --git a/internal/registry/ha_scan.go b/internal/registry/ha_scan.go
index 707ef98af..d9cd0fa5f 100644
--- a/internal/registry/ha_scan.go
+++ b/internal/registry/ha_scan.go
@@ -100,8 +100,12 @@ func (r *Registry) departureScanJournal(ctx context.Context, q haJournalRequest)
if err != nil {
return out, err
}
- res, err := tx.ExecContext(ctx, `INSERT INTO ha_departure_scans(id,body,version) SELECT ?,?,? WHERE ?=0 ON CONFLICT(id) DO UPDATE SET body=excluded.body,version=excluded.version WHERE version=?`, q.ID, body, s.Version, q.Scan.Version, q.Scan.Version)
- // Existing rows need an UPDATE; INSERT SELECT's guard deliberately excludes them.
+ var res sql.Result
+ if q.Scan.Version == 0 {
+ res, err = tx.ExecContext(ctx, `INSERT OR IGNORE INTO ha_departure_scans(id,body,version) VALUES(?,?,?)`, q.ID, body, s.Version)
+ } else {
+ res, err = tx.ExecContext(ctx, `UPDATE ha_departure_scans SET body=?,version=? WHERE id=? AND version=?`, body, s.Version, q.ID, q.Scan.Version)
+ }
if err != nil {
return out, err
}
@@ -109,16 +113,6 @@ func (r *Registry) departureScanJournal(ctx context.Context, q haJournalRequest)
if err != nil {
return out, err
}
- if n == 0 && q.Scan.Version > 0 {
- res, err = tx.ExecContext(ctx, `UPDATE ha_departure_scans SET body=?,version=? WHERE id=? AND version=?`, body, s.Version, q.ID, q.Scan.Version)
- if err != nil {
- return out, err
- }
- n, err = res.RowsAffected()
- if err != nil {
- return out, err
- }
- }
if n != 1 {
return out, ErrHAChanged
}
diff --git a/internal/registry/remote.go b/internal/registry/remote.go
index e073f5156..7093f81d6 100644
--- a/internal/registry/remote.go
+++ b/internal/registry/remote.go
@@ -14,7 +14,7 @@ import (
var errRemoteMethod = errors.New("registry: unsupported remote operation")
-var remoteErrors = []error{os.ErrNotExist, os.ErrPermission, sql.ErrNoRows, ErrClaimOwnership, ErrTimerChanged, ErrTimerKind, ErrPathsChanged, ErrFleetBoxActive, context.Canceled, context.DeadlineExceeded, ErrGoodBuildChanged, ErrRuntimeFixed, ErrRootfsRow, ErrRuntimePlacement, ErrFleetKeyInUse, ErrForwardRow, ErrHostHeld, ErrNotForward, ErrHAChanged, ErrHAWake}
+var remoteErrors = []error{os.ErrNotExist, os.ErrPermission, sql.ErrNoRows, ErrClaimOwnership, ErrTimerChanged, ErrTimerKind, ErrPathsChanged, ErrFleetBoxActive, context.Canceled, context.DeadlineExceeded, ErrGoodBuildChanged, ErrRuntimeFixed, ErrRootfsRow, ErrRuntimePlacement, ErrFleetKeyInUse, ErrForwardRow, ErrHostHeld, ErrNotForward, ErrHAChanged, ErrHAWake, ErrHAJournal}
func responseError(out remoteResponse) error {
if !out.Failed {