carlos / platform Public

region HA: page on refused departure finalizers

Enforce the invariant that termination-proof refusals page a departure finalizer at most once per hour per host. Inject the existing host paging path at warning level, keep visitor refusals log-only, and isolate paging from the log throttle. Operator wording is draft copy for the follow-up copy pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 8b48ef770b43e4fb5a3332d3a71e8480a191feab parent 93f01b5
6 files changed, +228 −2
  • internal/activator/backend_exec.go +2 −0
  • internal/activator/haadopt.go +1 −1
  • internal/activator/hatakeover.go +28 −1
  • internal/activator/hatakeover_page_test.go +35 −0
  • internal/host/hadepartures_page_followups_test.go +161 −0
  • internal/host/hadepartures_wiring.go +1 −0
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index 48e6a264b..5913c2c1a 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -391,6 +391,8 @@ type ExecBackend struct {
// TerminationProofs replaces live-only takeover when the departure controller
// installs its verified identity resolver and shared durable proof cache.
TerminationProofs *lease.TerminationProofAdapter
+ // Page sends finalizer proof refusals through the host paging sinks. Nil disables paging.
+ Page func(ctx context.Context, level, subject, body string) error
// takeover is the takeover proof's log throttle (hatakeover.go).
takeover takeoverState
// sameBox is the same-box recovery's state (hasamebox.go): the hosts
diff --git a/internal/activator/haadopt.go b/internal/activator/haadopt.go
index 0afc8e2cc..a0311d723 100644
--- a/internal/activator/haadopt.go
+++ b/internal/activator/haadopt.go
@@ -296,7 +296,7 @@ func (a *Service) AdoptHost(ctx context.Context, rt registry.Route, req Adoption
if err = phase("acquiring", expected, nil); err != nil {
return Deferred, err
}
- ctx = context.WithValue(ctx, adoptionCauseKey{}, true)
+ ctx = context.WithValue(ctx, adoptionCauseKey{}, req.Ref)
proofs := hafresh.Proofs{SameBoxEmpty: b.sameBoxEmpty(ctx, rt), OwnerTerminated: b.ownerTerminated(ctx, rt)}
if b.TerminationProofs != nil {
adapter := *b.TerminationProofs
diff --git a/internal/activator/hatakeover.go b/internal/activator/hatakeover.go
index 82d2653eb..b5b9e96d0 100644
--- a/internal/activator/hatakeover.go
+++ b/internal/activator/hatakeover.go
@@ -2,10 +2,12 @@ package activator
import (
"context"
+ "fmt"
"log"
"sync"
"time"
+ "github.com/carlosframework/platform/internal/alerting"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/termfence"
)
@@ -38,7 +40,8 @@ func (b *ExecBackend) ownerTerminated(ctx context.Context, rt registry.Route) fu
func (b *ExecBackend) reportTakeover(ctx context.Context, rt registry.Route, iid string, gone bool, err error) {
cause := "visitor"
- if ctx.Value(adoptionCauseKey{}) == true {
+ ref, finalizer := ctx.Value(adoptionCauseKey{}).(string)
+ if finalizer {
cause = "departure-finalize"
}
if !gone || err != nil {
@@ -46,6 +49,12 @@ func (b *ExecBackend) reportTakeover(ctx context.Context, rt registry.Route, iid
err = termfence.ErrTerminationProof
}
b.takeover.alarm(rt.Host, iid, cause, err)
+ if finalizer && b.Page != nil && b.takeover.claimPage(rt.Host, time.Now()) {
+ if ref == "" {
+ ref = iid
+ }
+ _ = b.Page(ctx, alerting.LevelWarning, fmt.Sprintf(takeoverPageSubject, ref), fmt.Sprintf(takeoverPageBody, ref, rt.Host, "termination_unproven"))
+ }
return
}
if cause == "departure-finalize" {
@@ -63,6 +72,7 @@ const takeoverAlarmEvery = sameBoxAlarmEvery
type takeoverState struct {
mu sync.Mutex
alarmed map[string]time.Time
+ paged map[string]time.Time
}
// alarm logs a takeover refused because EC2 could not be asked, at most
@@ -83,3 +93,20 @@ func (s *takeoverState) alarm(host, iid, cause string, why error) {
log.Printf("ha_takeover host=%s iid=%s cause=%s confirmed=false error=true", host, iid, cause)
log.Printf("activator: ALERT %s: the takeover of %s's expired HA lock is refused: EC2 did not answer whether it is terminated: %v (the host stays down until EC2 confirms the holder terminated)", host, iid, why)
}
+
+// Draft operator copy; the follow-up copy pass replaces these constants.
+const takeoverPageSubject = "Box %s's duties cannot be recovered"
+const takeoverPageBody = "The departed box %s still holds the lock for %s. This box could not prove it was terminated: %s. The host stays on that box until the proof can be read or the box comes back."
+
+func (s *takeoverState) claimPage(host string, now time.Time) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if last, seen := s.paged[host]; seen && now.Sub(last) < time.Hour {
+ return false
+ }
+ if s.paged == nil {
+ s.paged = map[string]time.Time{}
+ }
+ s.paged[host] = now
+ return true
+}
diff --git a/internal/activator/hatakeover_page_test.go b/internal/activator/hatakeover_page_test.go
new file mode 100644
index 000000000..c6e61540e
--- /dev/null
+++ b/internal/activator/hatakeover_page_test.go
@@ -0,0 +1,35 @@
+package activator
+
+import (
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestTakeoverPageHourlyPerHost(t *testing.T) {
+ var state takeoverState
+ now := time.Now()
+ var claims atomic.Int32
+ var wg sync.WaitGroup
+ for range 20 {
+ wg.Go(func() {
+ if state.claimPage("shop.example.com", now) {
+ claims.Add(1)
+ }
+ })
+ }
+ wg.Wait()
+ if claims.Load() != 1 {
+ t.Fatalf("concurrent pages=%d", claims.Load())
+ }
+ if state.claimPage("shop.example.com", now.Add(time.Hour-time.Nanosecond)) {
+ t.Fatal("paged within the hour")
+ }
+ if !state.claimPage("shop.example.com", now.Add(time.Hour)) {
+ t.Fatal("hourly retry suppressed")
+ }
+ if !state.claimPage("other.example.com", now) {
+ t.Fatal("another host suppressed")
+ }
+}
diff --git a/internal/host/hadepartures_page_followups_test.go b/internal/host/hadepartures_page_followups_test.go
new file mode 100644
index 000000000..f6d1b87ab
--- /dev/null
+++ b/internal/host/hadepartures_page_followups_test.go
@@ -0,0 +1,161 @@
+package host
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/service/ec2"
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/hadeparture"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "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/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/termfence"
+)
+
+func TestTerminationFinalizerPagesThroughWiring(t *testing.T) {
+ for _, mode := range []string{"identity", "missing-proof", "invalid-proof", "ec2"} {
+ t.Run(mode, func(t *testing.T) {
+ t.Cleanup(lease.ProcessStateForTest())
+ fx := locktest.NewLockFixture(t)
+ a, _, _ := departureArmFixtureBucket(t, 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, a.Self.Scope.CloudRegion)
+ 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)
+ }
+ stored, err := a.Registry.Get(rt.Host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rt = *stored
+ a.Service = activator.New(a.Backend.Cfg, a.Backend, a.Registry)
+ t.Cleanup(func() { a.Service.Shutdown(context.Background()) })
+ 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)
+ }
+ pub, err := hostfiles.Open(t.Context(), files, "instances/"+rt.Host+"/files/0/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = hostfiles.StageWake(t.Context(), pub, hostfiles.WakeState{V: 1, Host: rt.Host, NextDue: 9999999999}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = pub.Commit(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ c, lifecycle, err := armHADepartures(t.Context(), a)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = lifecycle.Stop(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if mode != "ec2" {
+ if _, 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"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ switch mode {
+ case "identity":
+ db, err := sql.Open("sqlite", a.Registry.Path())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ if _, err = db.Exec(`UPDATE ha_box_identities SET body=json_set(body,'$.Digest','bad')`); err != nil {
+ t.Fatal(err)
+ }
+ case "invalid-proof":
+ binding, err := a.Backend.TerminationProofs.Resolve(t.Context(), "dead", "i-1123456789abcdef0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = files.Put(t.Context(), binding.Key(), []byte(`{}`), ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ a.Confirmer.API = func(context.Context, string) (termfence.EC2, error) {
+ if mode == "ec2" {
+ return describeInstances(func(context.Context, *ec2.DescribeInstancesInput, ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) {
+ return &ec2.DescribeInstancesOutput{}, nil
+ }), nil
+ }
+ return nil, errors.New("unavailable")
+ }
+ a.Backend.OwnerTerminated = a.Confirmer.Terminated
+ body, _ := json.Marshal(hafresh.Lock{Generation: 5, Owner: hafresh.OwnerFor(hafresh.Self{Ref: "dead", IID: "i-1123456789abcdef0"}, 1, true), ExpiresAt: time.Now().Add(-time.Hour)})
+ fx.PutLock("instances/"+rt.Host, body)
+ type page struct{ Level, Subject, Body string }
+ var pages []page
+ armPaging(newAlertSinks("http://example.test/hook", func(_ string, raw []byte) error {
+ var p page
+ if err := json.Unmarshal(raw, &p); err != nil {
+ return err
+ }
+ pages = append(pages, p)
+ return nil
+ }, "", nil, &alertCounters{}))
+ t.Cleanup(func() { armPaging(nil) })
+ held, err := a.Backend.Acquire(t.Context(), rt)
+ if held != nil {
+ _ = held.Release(t.Context())
+ }
+ if err == nil {
+ t.Fatal("visitor acquired")
+ }
+ if len(pages) != 0 {
+ t.Fatal("visitor paged", pages)
+ }
+ observed, err := lease.ReadLock(t.Context(), fx.Bucket, "instances/"+rt.Host, a.Self.Scope.CloudRegion)
+ if err != nil {
+ t.Fatal(err)
+ }
+ duty, err := a.Registry.LoadDuty(t.Context(), rt.Host, "life")
+ if err != nil {
+ t.Fatal(err)
+ }
+ req := activator.Adoption{Departure: "departure-dead", Ref: "dead", IID: "i-1123456789abcdef0", Lifetime: "life", Pair: registry.Pair{Incarnation: rt.Incarnation, ServingSeq: rt.ServingSeq}, Revision: duty.Revision, Observed: observed}
+ for range 2 {
+ result, err := a.Service.AdoptHost(t.Context(), rt, req)
+ if result != activator.Deferred || err == nil {
+ t.Fatalf("adoption=%v err=%v", result, err)
+ }
+ }
+ if len(pages) != 1 {
+ t.Fatalf("pages=%+v, want one finalizer warning", pages)
+ }
+ if pages[0].Level != "warning" || !strings.Contains(pages[0].Body, rt.Host) || !strings.Contains(pages[0].Subject, "dead") {
+ t.Fatalf("page=%+v", pages[0])
+ }
+ for _, request := range fx.Requests() {
+ if request == "PUT instances/"+rt.Host+"/lock.json" {
+ t.Fatal("refused finalizer wrote lock")
+ }
+ }
+ })
+ }
+}
diff --git a/internal/host/hadepartures_wiring.go b/internal/host/hadepartures_wiring.go
index 69d5926b9..1ccfa3ec4 100644
--- a/internal/host/hadepartures_wiring.go
+++ b/internal/host/hadepartures_wiring.go
@@ -161,6 +161,7 @@ func armHADepartures(ctx context.Context, a departureArm) (*Controller, hadepart
}
return makeQueue(ctx)
}
+ a.Backend.Page = PageOperator
a.Confirmer.OnConfirmed = c.confirmed
a.Backend.TerminationProofs = &lease.TerminationProofAdapter{Cache: cache, Confirmer: a.Confirmer, Resolve: repo.Proof, Lifetime: func(ctx context.Context, bucket, prefix, region string) (string, error) {
if bucket != a.Backend.Cfg.Bucket || region != a.Backend.Cfg.Region {