carlos / platform Public

ha: report when EC2 confirms an owner is still running

Co-Authored-By: GPT-6 Astra <noreply@openai.com>
claude agent, operated by paul@keymail.dev 717a8af9175df6991462ff6d2b5f1d35edcfb16e parent 662e4de
6 files changed, +251 −15
  • internal/activator/hatakeover.go +12 −7
  • internal/activator/hatakeover_test.go +92 −0
  • internal/lease/termination_proof_test.go +60 −4
  • internal/termfence/confirm.go +1 −1
  • internal/termfence/termination_proof.go +24 −3
  • internal/termfence/termination_proof_test.go +62 −0
diff --git a/internal/activator/hatakeover.go b/internal/activator/hatakeover.go
index 2077e3197..cf7ecfacf 100644
--- a/internal/activator/hatakeover.go
+++ b/internal/activator/hatakeover.go
@@ -2,6 +2,7 @@ package activator
import (
"context"
+ "errors"
"fmt"
"log"
"sync"
@@ -26,7 +27,7 @@ import (
// ownerTerminated is the takeover proof for rt's acquire: nil (no
// takeover) when OwnerTerminated is not wired. A confirmed termination is
-// logged; a failed describe is logged at most once a minute per host.
+// logged; a refused proof is logged at most once a minute per host.
func (b *ExecBackend) ownerTerminated(ctx context.Context, rt registry.Route) func(iid string) (bool, error) {
if b.OwnerTerminated == nil {
return nil
@@ -45,9 +46,6 @@ func (b *ExecBackend) reportTakeover(ctx context.Context, rt registry.Route, iid
cause = "departure-finalize"
}
if !gone || err != nil {
- if err == nil {
- err = termfence.ErrTerminationProof
- }
b.takeover.alarm(rt.Host, iid, cause, err)
if cause == "visitor" {
b.note(rt.Host, iid, false, b.suspectHolders.clock())
@@ -86,7 +84,7 @@ type takeoverState struct {
paged map[string]time.Time
}
-// alarm logs a takeover refused because EC2 could not be asked, at most
+// alarm logs a takeover whose termination proof was refused, at most
// once a minute per host (the twin of sameBoxState.alarm).
func (s *takeoverState) alarm(host, iid, cause string, why error) {
s.mu.Lock()
@@ -101,8 +99,15 @@ func (s *takeoverState) alarm(host, iid, cause string, why error) {
}
s.alarmed[host] = now
s.mu.Unlock()
- 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)
+ diagnostic := fmt.Sprintf("termination could not be proven: %v", why)
+ switch {
+ case why == nil:
+ diagnostic = fmt.Sprintf("owner %s is not terminated", iid)
+ case errors.Is(why, termfence.ErrOwnerNotTerminated):
+ diagnostic = why.Error()
+ }
+ log.Printf("ha_takeover host=%s iid=%s cause=%s confirmed=false error=%t", host, iid, cause, why != nil)
+ log.Printf("activator: ALERT %s: the takeover of %s's expired HA lock is refused: %s (the host stays down until EC2 confirms the holder terminated)", host, iid, diagnostic)
}
// Operator page copy (approved by delegation, one Luna pass, 2026-11-03).
diff --git a/internal/activator/hatakeover_test.go b/internal/activator/hatakeover_test.go
index c6e7649bc..7a14bfc11 100644
--- a/internal/activator/hatakeover_test.go
+++ b/internal/activator/hatakeover_test.go
@@ -4,13 +4,22 @@ import (
"bytes"
"context"
"errors"
+ "net/http"
+ "net/http/httptest"
"strings"
"sync"
"testing"
"time"
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/ec2"
+ ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
+ "github.com/carlosframework/platform/internal/boxid"
+ "github.com/carlosframework/platform/internal/boxid/boxidtest"
"github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/termfence"
)
// Region HA P1b-1: a born-HA host whose holder box is terminated, and
@@ -168,3 +177,86 @@ func TestNoTakeoverWithoutTheOracle(t *testing.T) {
t.Fatal("the refused wake wrote the lock")
}
}
+
+type takeoverDiagnosticEC2 struct {
+ calls int
+ state ec2types.InstanceStateName
+}
+
+func (a *takeoverDiagnosticEC2) DescribeInstances(_ context.Context, in *ec2.DescribeInstancesInput, _ ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) {
+ a.calls++
+ return &ec2.DescribeInstancesOutput{Reservations: []ec2types.Reservation{{OwnerId: aws.String("111122223333"), Instances: []ec2types.Instance{{InstanceId: aws.String(in.InstanceIds[0]), State: &ec2types.InstanceState{Name: a.state}}}}}}, nil
+}
+
+func TestTakeoverLiveOwnerDiagnostic(t *testing.T) {
+ t.Run("legacy boolean", func(t *testing.T) {
+ logs := captureLog(t)
+ b, rt, body := takeoverBackend(t, time.Now().Add(-time.Minute), &terminatedOracle{})
+ for range 3 {
+ held, err := b.Acquire(t.Context(), rt)
+ if held != nil || err == nil {
+ t.Fatalf("held=%v err=%v", held, err)
+ }
+ }
+ if !strings.Contains(logs.String(), "not terminated") || strings.Contains(logs.String(), "still running") || strings.Contains(logs.String(), "EC2 did not answer") {
+ t.Fatalf("legacy diagnostic: %s", logs)
+ }
+ if strings.Count(logs.String(), "activator: ALERT") != 1 || lockWrites(t, b, rt) != 0 || !bytes.Equal(lockBodyOf(b, rt), body) {
+ t.Fatalf("refusal/throttle: %s", logs)
+ }
+ })
+ t.Run("proof cache", func(t *testing.T) {
+ logs := captureLog(t)
+ b, rt := haBackend(t, "shop.example.com")
+ me := hafresh.Self{Ref: "a", IID: "i-0123456789abcdef0", Account: "111122223333", Region: "eu-west-1"}
+ lease.SetSelf(me)
+ b.Cfg.Region = me.Region
+ iid := "i-1123456789abcdef0"
+ signer := boxidtest.NewSigner(t)
+ _, raw := signer.Record(t, "b", me.Account, me.Region, iid)
+ binding, err := termfence.VerifyProofIdentity(boxid.Verifier{Account: me.Account, Certs: signer.Certs()}, raw, boxid.Expect{Box: "b", AWSRegion: me.Region, TofuInstanceID: iid}, b.Cfg.Bucket)
+ if err != nil {
+ t.Fatal(err)
+ }
+ at := time.Now()
+ now := func() time.Time { return at }
+ api := &takeoverDiagnosticEC2{state: ec2types.InstanceStateNameRunning}
+ confirmer := &termfence.Confirmer{Now: now, Self: func() boxid.Cloud {
+ return boxid.Cloud{Provider: "aws", Account: me.Account, Region: me.Region, InstanceID: me.IID}
+ }, API: func(context.Context, string) (termfence.EC2, error) { return api, nil }, Logf: func(string, ...any) {}}
+ b.TerminationProofs = &lease.TerminationProofAdapter{Cache: &termfence.ProofCache{Now: now}, Confirmer: confirmer, Resolve: func(context.Context, string, string) (termfence.ProofIdentity, error) { return binding, nil }, Lifetime: func(context.Context, string, string, string) (string, error) { return haFixOf(b).lifetime, nil }}
+ body := leaseBody(t, hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: iid}, 7, true), at.Add(-time.Minute))
+ putLockFor(t, b, rt, body)
+ for range 3 {
+ held, err := b.Acquire(t.Context(), rt)
+ if held != nil || err == nil {
+ t.Fatalf("held=%v err=%v", held, err)
+ }
+ }
+ if api.calls != 1 || strings.Count(logs.String(), "EC2 says "+iid+" is still running") != 1 || !strings.Contains(logs.String(), "ha_owner_not_terminated") || strings.Contains(logs.String(), "EC2 did not answer") {
+ t.Fatalf("calls=%d logs=%s", api.calls, logs)
+ }
+ at = at.Add(termfence.ConfirmNegativeTTL)
+ api.state = ec2types.InstanceStateNameStopped
+ b.takeover.mu.Lock()
+ b.takeover.alarmed[rt.Host] = time.Now().Add(-takeoverAlarmEvery)
+ b.takeover.mu.Unlock()
+ held, err := b.Acquire(t.Context(), rt)
+ if held != nil || err == nil || api.calls != 2 || !strings.Contains(logs.String(), "stopped") || strings.Count(logs.String(), "activator: ALERT") != 2 {
+ t.Fatalf("re-observation: held=%v err=%v calls=%d logs=%s", held, err, api.calls, logs)
+ }
+ if !bytes.Equal(lockBodyOf(b, rt), body) {
+ t.Fatal("refusal changed lease")
+ }
+ w := httptest.NewRecorder()
+ (&Service{}).serveWakeError(w, httptest.NewRequest("GET", "/", nil), rt, err)
+ if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") != "10" || strings.Contains(w.Body.String(), "ha_owner_not_terminated") || strings.Contains(w.Body.String(), "EC2") {
+ t.Fatalf("HTTP refusal exposed diagnostic: status=%d body=%s", w.Code, w.Body.String())
+ }
+ for _, request := range haFixOf(b).fx.Requests() {
+ if strings.HasPrefix(request, "PUT ") {
+ t.Fatal("refusal wrote proof or lease:", request)
+ }
+ }
+ })
+}
diff --git a/internal/lease/termination_proof_test.go b/internal/lease/termination_proof_test.go
index 230b33028..8a96d7344 100644
--- a/internal/lease/termination_proof_test.go
+++ b/internal/lease/termination_proof_test.go
@@ -24,18 +24,35 @@ import (
type proofEC2 struct {
calls int
running bool
+ state ec2types.InstanceStateName
+ account string
+ missing bool
+ err error
}
func (p *proofEC2) DescribeInstances(ctx context.Context, in *ec2.DescribeInstancesInput, opts ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) {
p.calls++
+ if p.err != nil {
+ return nil, p.err
+ }
+ if p.missing {
+ return &ec2.DescribeInstancesOutput{}, nil
+ }
state := ec2types.InstanceStateNameTerminated
if p.running {
state = ec2types.InstanceStateNameRunning
}
- return &ec2.DescribeInstancesOutput{Reservations: []ec2types.Reservation{{OwnerId: aws.String("111122223333"), Instances: []ec2types.Instance{{InstanceId: aws.String(in.InstanceIds[0]), State: &ec2types.InstanceState{Name: state}}}}}}, nil
+ if p.state != "" {
+ state = p.state
+ }
+ account := p.account
+ if account == "" {
+ account = "111122223333"
+ }
+ return &ec2.DescribeInstancesOutput{Reservations: []ec2types.Reservation{{OwnerId: aws.String(account), Instances: []ec2types.Instance{{InstanceId: aws.String(in.InstanceIds[0]), State: &ec2types.InstanceState{Name: state}}}}}}, nil
}
func TestTerminationProofAcquireOnly(t *testing.T) {
- for _, mode := range []string{"expired", "unexpired", "equality", "unbound", "unbound equality", "same box", "malformed", "wrong lifetime", "lifetime changes during proof", "owner CAS", "bucket", "region", "restart"} {
+ for _, mode := range []string{"expired", "unexpired", "equality", "unbound", "unbound equality", "same box", "malformed", "wrong lifetime", "lifetime changes during proof", "owner CAS", "bucket", "region", "restart", "running", "stopped", "shutting-down", "unknown", "account mismatch", "missing instance", "API error", "malformed proof with live owner"} {
t.Run(mode, func(t *testing.T) {
ResetForTest()
t.Cleanup(ResetForTest)
@@ -59,11 +76,37 @@ func TestTerminationProofAcquireOnly(t *testing.T) {
t.Fatal(err)
}
api := &proofEC2{}
+ liveState := ""
+ switch mode {
+ case "running", "stopped", "shutting-down", "unknown":
+ liveState = mode
+ api.state = ec2types.InstanceStateName(mode)
+ case "account mismatch":
+ api.account = "999999999999"
+ case "missing instance":
+ api.missing = true
+ case "API error":
+ api.err = errors.New("RequestLimitExceeded")
+ case "malformed proof with live owner":
+ liveState = "running"
+ api.running = true
+ fx.PutObject(binding.Key(), []byte("{}"))
+ }
confirm := &termfence.Confirmer{Self: func() boxid.Cloud {
return boxid.Cloud{Provider: "aws", Account: me.Account, Region: me.Region, InstanceID: me.IID}
}, API: func(context.Context, string) (termfence.EC2, error) { return api, nil }, Logf: func(string, ...any) {}}
lifetimeReads := 0
- adapter := &TerminationProofAdapter{Cache: &termfence.ProofCache{}, Confirmer: confirm, Resolve: func(ctx context.Context, ref, iid string) (termfence.ProofIdentity, error) {
+ adapter := &TerminationProofAdapter{Observe: func(_ string, gone bool, err error) {
+ if liveState != "" {
+ var live *termfence.OwnerNotTerminatedError
+ if gone || !errors.Is(err, termfence.ErrOwnerNotTerminated) || !errors.As(err, &live) || live.State != liveState {
+ t.Errorf("live refusal lost: gone=%v err=%v", gone, err)
+ }
+ if mode == "malformed proof with live owner" && !errors.Is(err, termfence.ErrTerminationProof) {
+ t.Errorf("malformed proof error lost: %v", err)
+ }
+ }
+ }, Cache: &termfence.ProofCache{}, Confirmer: confirm, Resolve: func(ctx context.Context, ref, iid string) (termfence.ProofIdentity, error) {
if strings.HasPrefix(mode, "unbound") || ref != "departed" || iid != "i-1123456789abcdef0" {
return termfence.ProofIdentity{}, termfence.ErrProofUnbound
}
@@ -143,6 +186,14 @@ func TestTerminationProofAcquireOnly(t *testing.T) {
if mode == "expired" || mode == "owner CAS" || mode == "restart" || mode == "lifetime changes during proof" {
wantDescribe = 1
}
+ if liveState != "" || mode == "account mismatch" || mode == "missing instance" || mode == "API error" {
+ wantDescribe = 1
+ for _, request := range fx.Requests() {
+ if strings.HasPrefix(request, "PUT ") {
+ t.Fatal("refusal wrote proof or lease:", request)
+ }
+ }
+ }
if api.calls != wantDescribe {
t.Fatalf("describes %d want %d", api.calls, wantDescribe)
}
@@ -179,7 +230,12 @@ func TestTerminationProofRequestBudget(t *testing.T) {
return boxid.Cloud{Provider: "aws", Account: me.Account, Region: me.Region, InstanceID: me.IID}
}
confirmer := &termfence.Confirmer{Self: self, Now: now, API: func(context.Context, string) (termfence.EC2, error) { return api, nil }, Logf: func(string, ...any) {}}
- adapter := &TerminationProofAdapter{Cache: &termfence.ProofCache{Now: now}, Confirmer: confirmer, Resolve: func(context.Context, string, string) (termfence.ProofIdentity, error) { return binding, nil }, Lifetime: func(context.Context, string, string, string) (string, error) { return "life", nil }}
+ adapter := &TerminationProofAdapter{Observe: func(_ string, gone bool, err error) {
+ var live *termfence.OwnerNotTerminatedError
+ if !gone && (!errors.Is(err, termfence.ErrOwnerNotTerminated) || !errors.As(err, &live) || live.State != "running") {
+ t.Errorf("joined diagnostic lost: gone=%v err=%v", gone, err)
+ }
+ }, Cache: &termfence.ProofCache{Now: now}, Confirmer: confirmer, Resolve: func(context.Context, string, string) (termfence.ProofIdentity, error) { return binding, nil }, Lifetime: func(context.Context, string, string, string) (string, error) { return "life", nil }}
ctx := WithTerminationProof(context.Background(), adapter)
for i := 0; i < 20; i++ {
body, _ := json.Marshal(hafresh.Lock{Generation: 1, Owner: hafresh.OwnerFor(hafresh.Self{Ref: "departed", IID: binding.Evidence().Cloud.InstanceID}, 1, true), ExpiresAt: time.Now().Add(-time.Hour)})
diff --git a/internal/termfence/confirm.go b/internal/termfence/confirm.go
index ddeeaf2c7..0f4a16d3a 100644
--- a/internal/termfence/confirm.go
+++ b/internal/termfence/confirm.go
@@ -237,7 +237,7 @@ func (c *Confirmer) ask(ctx context.Context, self boxid.Cloud, iid string) confi
}
return confirmed{yes: true, observation: o, observedAt: c.now()}
case errors.Is(err, ErrNotEvidence):
- return confirmed{}
+ return confirmed{observation: o, observedAt: c.now()}
default:
return confirmed{err: err}
}
diff --git a/internal/termfence/termination_proof.go b/internal/termfence/termination_proof.go
index c0e3a5f82..561fe402e 100644
--- a/internal/termfence/termination_proof.go
+++ b/internal/termfence/termination_proof.go
@@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"errors"
+ "fmt"
"io"
"regexp"
"strings"
@@ -23,6 +24,22 @@ const MaxTerminationProofBytes = 2048
var ErrProofUnbound = errors.New("ha_termination_proof_unbound")
var ErrTerminationProof = errors.New("ha_termination_proof_invalid")
+var ErrOwnerNotTerminated = errors.New("ha_owner_not_terminated")
+
+type OwnerNotTerminatedError struct {
+ IID string
+ State string
+}
+
+func (e *OwnerNotTerminatedError) Error() string {
+ if e.State == "running" {
+ return fmt.Sprintf("%s: EC2 says %s is still running", ErrOwnerNotTerminated, e.IID)
+ }
+ return fmt.Sprintf("%s: EC2 says %s is %q", ErrOwnerNotTerminated, e.IID, e.State)
+}
+
+func (e *OwnerNotTerminatedError) Unwrap() error { return ErrOwnerNotTerminated }
+
var proofIID = regexp.MustCompile(`^i-([0-9a-f]{8}|[0-9a-f]{17})$`)
var proofAccount = regexp.MustCompile(`^[0-9]{12}$`)
var proofRegion = regexp.MustCompile(`^[a-z]{2}(-[a-z]+)+-[0-9]+$`)
@@ -318,12 +335,16 @@ func (c *Confirmer) persistTermination(ctx context.Context, api ProofStore, b Pr
if err != nil {
return TerminationProof{}, err
}
- if !yes {
- return TerminationProof{}, ErrTerminationProof
- }
c.mu.Lock()
observation := c.cache[e.Cloud.InstanceID]
c.mu.Unlock()
+ if !yes {
+ o := observation.observation
+ if !observation.observedAt.IsZero() && o.Via == ViaDescribe && o.Found && o.InstanceID == e.Cloud.InstanceID && o.Account == self.Account && o.Region == self.Region && o.State != "" && o.State != stateTerminated {
+ return TerminationProof{}, &OwnerNotTerminatedError{IID: o.InstanceID, State: o.State}
+ }
+ return TerminationProof{}, ErrTerminationProof
+ }
if !observation.yes || observation.observedAt.IsZero() || SameAccountTerminated(self, e.Cloud.InstanceID, observation.observation) != nil {
return TerminationProof{}, ErrTerminationProof
}
diff --git a/internal/termfence/termination_proof_test.go b/internal/termfence/termination_proof_test.go
index 054d4f500..55c7121a0 100644
--- a/internal/termfence/termination_proof_test.go
+++ b/internal/termfence/termination_proof_test.go
@@ -16,6 +16,7 @@ import (
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials"
+ "github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/service/ec2/types"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/carlosframework/platform/internal/boxid"
@@ -370,3 +371,64 @@ func TestDepartureProofInternalTimeoutCached(t *testing.T) {
t.Fatalf("proof calls = %d, want 1", api.calls)
}
}
+
+func TestTerminationProofDistinguishesLiveOwner(t *testing.T) {
+ b := proofIdentity(t)
+ apiErr := errors.New("RequestLimitExceeded")
+ for _, tc := range []struct {
+ name string
+ out *ec2.DescribeInstancesOutput
+ apiErr error
+ state string
+ terminated bool
+ }{
+ {name: "running", out: describe("111122223333", b.Evidence().Cloud.InstanceID, types.InstanceStateNameRunning), state: "running"},
+ {name: "stopped", out: describe("111122223333", b.Evidence().Cloud.InstanceID, types.InstanceStateNameStopped), state: "stopped"},
+ {name: "shutting-down", out: describe("111122223333", b.Evidence().Cloud.InstanceID, types.InstanceStateNameShuttingDown), state: "shutting-down"},
+ {name: "unknown state", out: describe("111122223333", b.Evidence().Cloud.InstanceID, "unknown"), state: "unknown"},
+ {name: "missing state", out: describe("111122223333", b.Evidence().Cloud.InstanceID, "")},
+ {name: "account mismatch", out: describe("999999999999", b.Evidence().Cloud.InstanceID, types.InstanceStateNameRunning)},
+ {name: "instance mismatch", out: describe("111122223333", "i-2123456789abcdef0", types.InstanceStateNameRunning)},
+ {name: "missing instance", out: &ec2.DescribeInstancesOutput{}},
+ {name: "API error", apiErr: apiErr},
+ {name: "terminated", out: describe("111122223333", b.Evidence().Cloud.InstanceID, types.InstanceStateNameTerminated), terminated: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ r := proofConfirmer()
+ r.f.out, r.f.err = tc.out, tc.apiErr
+ store := &proofTransport{}
+ cache := &ProofCache{Now: func() time.Time { return r.at }}
+ for range 2 {
+ proof, err := r.c.PersistTermination(t.Context(), store.client(), b, "survivor", cache)
+ if tc.terminated {
+ if err != nil || proof.State != "terminated" || store.puts != 1 {
+ t.Fatalf("proof=%+v err=%v puts=%d", proof, err, store.puts)
+ }
+ continue
+ }
+ if err == nil || store.puts != 0 {
+ t.Fatalf("refusal err=%v puts=%d", err, store.puts)
+ }
+ if tc.state != "" {
+ var live *OwnerNotTerminatedError
+ joined := errors.Join(errors.New("proof read failed"), err)
+ if !errors.Is(joined, ErrOwnerNotTerminated) || !errors.As(joined, &live) || live.IID != b.Evidence().Cloud.InstanceID || live.State != tc.state || errors.Is(err, ErrTerminationProof) {
+ t.Errorf("live owner classified as %v", err)
+ }
+ } else if tc.apiErr != nil {
+ if errors.Is(err, ErrOwnerNotTerminated) {
+ t.Errorf("API failure classified as live: %v", err)
+ }
+ if !errors.Is(err, apiErr) {
+ t.Errorf("API error lost: %v", err)
+ }
+ } else if !errors.Is(err, ErrTerminationProof) || errors.Is(err, ErrOwnerNotTerminated) {
+ t.Errorf("invalid observation classified as %v", err)
+ }
+ }
+ if len(r.f.ids) != 1 {
+ t.Fatalf("describes=%d", len(r.f.ids))
+ }
+ })
+ }
+}