carlos / platform Public

region HA P3b-2: retry group hairpin enable with backoff and alert

claude agent, operated by paul@keymail.dev 30489c1e0266821faa1d16fb813ad766c26a6891 parent a358712
3 files changed, +558 −14
  • internal/host/group_admission.go +25 −14
  • internal/host/group_hairpin_retry.go +139 −0
  • internal/host/group_hairpin_retry_test.go +394 −0
diff --git a/internal/host/group_admission.go b/internal/host/group_admission.go
index 149c11192..98b7bd22c 100644
--- a/internal/host/group_admission.go
+++ b/internal/host/group_admission.go
@@ -23,6 +23,7 @@ import (
var armedFixedAdmission atomic.Pointer[fixedAdmission]
type fixedAdmission struct {
+ hairpinRetryState
hairpin func(bool) error
hairpinMu sync.Mutex
hairpinReady atomic.Bool
@@ -145,7 +146,11 @@ func (a *fixedAdmission) tick(ctx context.Context) {
}
}
if a.state.Admitted() {
+ retry := a.hairpin != nil && !a.hairpinReady.Load()
a.mu.Unlock()
+ if retry {
+ a.enableGroupHairpin()
+ }
return
}
if !a.state.Ready() || !a.known || (a.group && (a.launch == nil || a.completer == nil || a.role != boxroles.Serve)) {
@@ -153,30 +158,25 @@ func (a *fixedAdmission) tick(ctx context.Context) {
a.mu.Unlock()
return
}
- a.health.SetHosting(true)
+ if a.hairpin == nil {
+ a.health.SetHosting(true)
+ }
launch, complete := a.launch, a.completer
a.mu.Unlock()
// No orchestration lock spans the provider call. Close can win immediately.
if err := a.state.Admit(ctx, launch, complete, a.initialHealthy); err == nil {
- a.hairpinMu.Lock()
- a.mu.Lock()
- closed, change := a.closed, a.hairpin
- a.mu.Unlock()
- var hairpinErr error
- if !closed && change != nil {
- hairpinErr = change(true)
+ if a.hairpin != nil {
+ a.enableGroupHairpin()
+ return
}
+ a.hairpinMu.Lock()
a.mu.Lock()
- if !a.closed && hairpinErr == nil {
+ if !a.closed {
a.hairpinReady.Store(true)
a.openOnce.Do(func() { close(a.opened); log.Print("tenant admission is open. accepting tenant work") })
}
a.mu.Unlock()
a.hairpinMu.Unlock()
- if hairpinErr != nil {
- log.Printf("group hairpin activation failed: %v", hairpinErr)
- a.Close()
- }
} else {
a.mu.Lock()
if a.group && !errors.Is(err, groupadmission.ErrNotReady) {
@@ -191,7 +191,18 @@ func (a *fixedAdmission) tick(ctx context.Context) {
}
}
func (a *fixedAdmission) initialHealthy() bool {
- return a.allowed.Load() && a.groupReadersReady(time.Now()) && len(a.health.Failing(time.Now())) == 0
+ now := a.admissionNow()
+ if !a.allowed.Load() || !a.groupReadersReady(now) {
+ return false
+ }
+ for _, failure := range a.health.Failing(now) {
+ // Hosting stays false until root enables hairpin. It is the result
+ // of this check, not a prerequisite for the first enable or a retry.
+ if failure != lbhealth.CondHosting || a.hairpin == nil {
+ return false
+ }
+ }
+ return true
}
func (a *fixedAdmission) Close() {
if a == nil {
diff --git a/internal/host/group_hairpin_retry.go b/internal/host/group_hairpin_retry.go
new file mode 100644
index 000000000..7516a9222
--- /dev/null
+++ b/internal/host/group_hairpin_retry.go
@@ -0,0 +1,139 @@
+package host
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "time"
+
+ "github.com/carlosframework/platform/internal/alerting"
+ "github.com/carlosframework/platform/internal/boxroles"
+ "github.com/carlosframework/platform/internal/instancectl"
+)
+
+const (
+ groupHairpinRetryFirst = 10 * time.Second
+ groupHairpinRetryCap = 5 * time.Minute
+ groupHairpinAlertAfter = 15 * time.Minute
+)
+
+// Operator text stays together for the controller's copy pass.
+const (
+ groupHairpinRetryFailureText = "group hairpin activation failed: code=%s; retry in %s"
+ groupHairpinAlertSubjectText = "Group hairpin enable needs attention"
+ groupHairpinAlertBodyText = "Box %s cannot enable hairpin. Failure code: %s. Admission has stayed closed for 15 minutes. Local retries continue."
+ groupHairpinClearSubjectText = "Group hairpin enable recovered"
+ groupHairpinClearBodyText = "Box %s enabled hairpin and opened admission. Previous failure code: %s."
+ groupHairpinPageFailureText = "group hairpin alert delivery failed: %v"
+)
+
+// Retry and alert fields are protected by fixedAdmission.mu. The clock is
+// installed before ticks start; production uses time.Now.
+type hairpinRetryState struct {
+ clock func() time.Time
+ hairpinNext time.Time
+ hairpinDelay time.Duration
+ hairpinFailedAt time.Time
+ hairpinCode string
+ hairpinAlerted bool
+ hairpinAlertDone chan struct{}
+}
+
+func (a *fixedAdmission) admissionNow() time.Time {
+ if a.clock != nil {
+ return a.clock()
+ }
+ return time.Now()
+}
+
+func (a *fixedAdmission) enableGroupHairpin() {
+ a.hairpinMu.Lock()
+ defer a.hairpinMu.Unlock()
+ a.mu.Lock()
+ if a.closed || a.refusal != "" || !a.state.Admitted() || a.hairpinReady.Load() {
+ a.mu.Unlock()
+ return
+ }
+ a.health.SetHosting(false)
+ now := a.admissionNow()
+ if !a.hairpinFailedAt.IsZero() && !a.hairpinAlerted && now.Sub(a.hairpinFailedAt) >= groupHairpinAlertAfter {
+ a.hairpinAlerted = true
+ a.pageHairpinLocked(false)
+ }
+ if now.Before(a.hairpinNext) || !a.known || a.role != boxroles.Serve || !a.initialHealthy() {
+ a.mu.Unlock()
+ return
+ }
+ change := a.hairpin
+ a.mu.Unlock()
+ err := change(true)
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ // Close publishes its refusal before waiting for hairpinMu, then calls
+ // change(false). A completed enable must never reopen that gate.
+ if a.closed {
+ return
+ }
+ if err != nil {
+ now = a.admissionNow()
+ if a.hairpinFailedAt.IsZero() {
+ a.hairpinFailedAt = now
+ }
+ a.hairpinCode = groupHairpinFailureCode(err)
+ if a.hairpinDelay == 0 {
+ a.hairpinDelay = groupHairpinRetryFirst
+ } else {
+ a.hairpinDelay = min(a.hairpinDelay*2, groupHairpinRetryCap)
+ }
+ a.hairpinNext = now.Add(a.hairpinDelay)
+ log.Printf(groupHairpinRetryFailureText, a.hairpinCode, a.hairpinDelay)
+ return
+ }
+ a.hairpinReady.Store(true)
+ a.health.SetHosting(true)
+ a.openOnce.Do(func() { close(a.opened); log.Print("tenant admission is open. accepting tenant work") })
+ if a.hairpinAlerted {
+ a.pageHairpinLocked(true)
+ }
+ a.hairpinNext = time.Time{}
+ a.hairpinDelay = 0
+ a.hairpinFailedAt = time.Time{}
+ a.hairpinCode = ""
+ a.hairpinAlerted = false
+}
+
+func groupHairpinFailureCode(err error) string {
+ var refusal *instancectl.GroupHairpinError
+ if errors.As(err, &refusal) {
+ switch refusal.Code {
+ case "group_hairpin_closed", "group_hairpin_peer", "group_hairpin_request", "group_hairpin_unavailable":
+ return refusal.Code
+ }
+ }
+ return "group_hairpin_unavailable"
+}
+
+// Like metrics alerts, send only a firing or clearing transition. PageOperator
+// has no resolve API, so recovery is a second page. Preserve their order even
+// when a sink is slow, without blocking admission or adding a polling loop.
+func (a *fixedAdmission) pageHairpinLocked(clear bool) {
+ subject, body := groupHairpinAlertSubjectText, groupHairpinAlertBodyText
+ if clear {
+ subject, body = groupHairpinClearSubjectText, groupHairpinClearBodyText
+ }
+ body = fmt.Sprintf(body, a.readerSelf, a.hairpinCode)
+ previous, done := a.hairpinAlertDone, make(chan struct{})
+ a.hairpinAlertDone = done
+ go func() {
+ defer close(done)
+ if previous != nil {
+ <-previous
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ if err := PageOperator(ctx, alerting.LevelWarning, subject, body); err != nil {
+ log.Printf(groupHairpinPageFailureText, err)
+ }
+ }()
+}
diff --git a/internal/host/group_hairpin_retry_test.go b/internal/host/group_hairpin_retry_test.go
new file mode 100644
index 000000000..87ed0187d
--- /dev/null
+++ b/internal/host/group_hairpin_retry_test.go
@@ -0,0 +1,394 @@
+package host
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log"
+ "slices"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/boxroles"
+ "github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/groupadmission"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/lbhealth"
+)
+
+func TestGroupHairpinAdmissionFailureDoesNotClose(t *testing.T) {
+ a := readyGroupAdmission(t)
+ a.observe(groupadmission.Facts{TerminationStarted: true})
+ work, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ a.workCtx, a.workCancel = work, cancel
+ var disables int
+ a.hairpin = func(on bool) error {
+ if !on {
+ disables++
+ }
+ return &instancectl.GroupHairpinError{StatusCode: 503, Code: "group_hairpin_unavailable"}
+ }
+ a.tick(t.Context())
+ if a.closed || !a.state.Admitted() {
+ t.Fatal("hairpin failure latched shutdown instead of retaining launch completion for retry")
+ }
+ if a.TenantAdmitted() || a.startAllowed() || a.health.Hosting() {
+ t.Fatal("hairpin failure opened admission or reported hosting")
+ }
+ if disables != 0 || work.Err() != nil {
+ t.Fatal("hairpin failure disabled root hairpin or cancelled work")
+ }
+}
+
+type hairpinRetryFixture struct {
+ a *fixedAdmission
+ base time.Time
+ stamp atomic.Int64
+ readers atomic.Bool
+}
+
+func newHairpinRetryFixture(t *testing.T) *hairpinRetryFixture {
+ t.Helper()
+ f := &hairpinRetryFixture{a: readyGroupAdmission(t), base: time.Unix(1800000000, 0)}
+ f.readers.Store(true)
+ f.a.clock = func() time.Time { return time.Unix(0, f.stamp.Load()) }
+ f.a.readers = func() edgesfile.ReaderSnapshot {
+ return edgesfile.ReaderSnapshot{Complete: f.readers.Load(), CheckedAt: f.a.clock().Add(-time.Second), Self: "self", KnownReaders: []string{}}
+ }
+ f.a.observe(groupadmission.Facts{TerminationStarted: true})
+ f.at(0)
+ t.Cleanup(func() {
+ f.a.mu.Lock()
+ done := f.a.hairpinAlertDone
+ f.a.mu.Unlock()
+ if done != nil {
+ <-done
+ }
+ })
+ return f
+}
+
+func (f *hairpinRetryFixture) at(elapsed time.Duration) {
+ now := f.base.Add(elapsed)
+ f.stamp.Store(now.UnixNano())
+ f.a.health.EdgeBeat(now)
+ f.a.health.RefreshAttempted(now)
+ f.a.health.SetActivator(f.a.clock)
+}
+
+func assertHairpinWaiting(t *testing.T, a *fixedAdmission) {
+ t.Helper()
+ if a.TenantAdmitted() || a.startAllowed() || a.health.Hosting() || a.hairpinReady.Load() {
+ t.Fatal("tenant admission, starts or health opened before hairpin")
+ }
+ if role, admitted, _ := a.EdgesRole(); role != boxroles.Booting || admitted {
+ t.Fatal("waiting member advertised as serving")
+ }
+ select {
+ case <-a.opened:
+ t.Fatal("open notification sent before hairpin")
+ default:
+ }
+}
+
+func TestGroupHairpinAdmissionRetrySuccess(t *testing.T) {
+ f := newHairpinRetryFixture(t)
+ a := f.a
+ var output bytes.Buffer
+ old := log.Writer()
+ log.SetOutput(&output)
+ defer log.SetOutput(old)
+ completions, attempts := 0, 0
+ a.completer = groupCompleteFunc(func(context.Context, groupadmission.Launch) error {
+ completions++
+ assertHairpinWaiting(t, a)
+ return nil
+ })
+ a.hairpin = func(on bool) error {
+ if !on || completions != 1 {
+ t.Fatal("hairpin called before launch completion, or disabled on failure")
+ }
+ assertHairpinWaiting(t, a)
+ attempts++
+ if attempts == 1 {
+ return fmt.Errorf("control: %w", &instancectl.GroupHairpinError{StatusCode: 403, Code: "group_hairpin_peer"})
+ }
+ return nil
+ }
+ for _, step := range []struct {
+ at time.Duration
+ attempts int
+ open bool
+ }{{0, 1, false}, {9 * time.Second, 1, false}, {10 * time.Second, 2, true}, {time.Hour, 2, true}} {
+ f.at(step.at)
+ a.tick(t.Context())
+ if attempts != step.attempts || completions != 1 {
+ t.Fatalf("at %s: attempts=%d completions=%d", step.at, attempts, completions)
+ }
+ if !step.open {
+ assertHairpinWaiting(t, a)
+ continue
+ }
+ if !a.TenantAdmitted() || !a.startAllowed() || len(a.health.Failing(a.clock())) != 0 {
+ t.Fatal("successful retry did not restore admission and health")
+ }
+ select {
+ case <-a.opened:
+ default:
+ t.Fatal("successful retry did not notify workers")
+ }
+ }
+ if strings.Count(output.String(), "tenant admission is open.") != 1 || strings.Contains(output.String(), "closed for shutdown") || !strings.Contains(output.String(), "code=group_hairpin_peer") {
+ t.Fatalf("wrong transition log: %s", output.String())
+ }
+}
+
+func TestGroupHairpinAdmissionRetryBackoff(t *testing.T) {
+ for _, failure := range []struct {
+ name string
+ err error
+ }{
+ {"unavailable", &instancectl.GroupHairpinError{StatusCode: 503, Code: "group_hairpin_unavailable"}},
+ {"closed tombstone", &instancectl.GroupHairpinError{StatusCode: 409, Code: "group_hairpin_closed"}},
+ } {
+ t.Run(failure.name, func(t *testing.T) {
+ f := newHairpinRetryFixture(t)
+ a := f.a
+ attempts := 0
+ a.hairpin = func(on bool) error {
+ if !on {
+ t.Fatal("retry disabled hairpin")
+ }
+ assertHairpinWaiting(t, a)
+ attempts++
+ return failure.err
+ }
+ a.tick(t.Context())
+ elapsed := time.Duration(0)
+ for i, delay := range []time.Duration{10, 20, 40, 80, 160, 300, 300, 300, 300} {
+ delay *= time.Second
+ elapsed += delay
+ f.at(elapsed - time.Nanosecond)
+ a.tick(t.Context())
+ if attempts != i+1 {
+ t.Fatalf("retry before %s: %d attempts", elapsed, attempts)
+ }
+ f.at(elapsed)
+ a.tick(t.Context())
+ if attempts != i+2 || a.closed || !a.state.Admitted() {
+ t.Fatalf("retry at %s: attempts=%d closed=%v", elapsed, attempts, a.closed)
+ }
+ assertHairpinWaiting(t, a)
+ }
+ })
+ }
+}
+
+func TestGroupHairpinAdmissionRetryPredicate(t *testing.T) {
+ for _, missing := range []string{"allowed", "known", "role", "readers", "forwarding", "certificates", "edge", "activator", "refresh"} {
+ t.Run(missing, func(t *testing.T) {
+ f := newHairpinRetryFixture(t)
+ a := f.a
+ attempts := 0
+ a.hairpin = func(bool) error {
+ attempts++
+ return errors.New("local failure")
+ }
+ a.tick(t.Context())
+ f.at(10 * time.Second)
+ switch missing {
+ case "allowed":
+ a.allowed.Store(false)
+ case "known":
+ a.known = false
+ case "role":
+ a.role = boxroles.Drain
+ case "readers":
+ f.readers.Store(false)
+ default:
+ h := &lbhealth.State{}
+ if missing != "forwarding" {
+ h.MapLoaded()
+ h.KeyLoaded()
+ }
+ if missing != "certificates" {
+ h.CertsLoaded()
+ }
+ if missing != "edge" {
+ h.EdgeBeat(a.clock())
+ }
+ if missing != "activator" {
+ h.SetActivator(a.clock)
+ }
+ if missing != "refresh" {
+ h.RefreshAttempted(a.clock())
+ }
+ a.health = h
+ }
+ a.tick(t.Context())
+ if attempts != 1 {
+ t.Fatal("retry ignored opening predicate")
+ }
+ assertHairpinWaiting(t, a)
+ // Recovery of the local predicate permits the pending attempt.
+ a.health = admissionHealth()
+ f.at(11 * time.Second)
+ f.readers.Store(true)
+ _ = a.applyRole(boxroles.Serve, true)
+ a.tick(t.Context())
+ if attempts != 2 {
+ t.Fatal("recovered predicate left retry stuck")
+ }
+ })
+ }
+}
+
+func TestGroupHairpinAdmissionAlertTransitions(t *testing.T) {
+ for _, blocked := range []bool{false, true} {
+ t.Run(fmt.Sprintf("blocked sink %v", blocked), func(t *testing.T) {
+ var pages []struct{ Kind, Level, Subject, Body string }
+ entered, release := make(chan struct{}), make(chan struct{})
+ armPaging(newAlertSinks("http://example.test/hook", func(_ string, raw []byte) error {
+ var p struct{ Kind, Level, Subject, Body string }
+ if err := json.Unmarshal(raw, &p); err != nil {
+ return err
+ }
+ pages = append(pages, p)
+ if len(pages) == 1 {
+ close(entered)
+ <-release
+ }
+ return nil
+ }, "", nil, nil))
+ t.Cleanup(func() { armPaging(nil) })
+ if !blocked {
+ close(release)
+ }
+ f := newHairpinRetryFixture(t)
+ a := f.a
+ fail := true
+ a.hairpin = func(bool) error {
+ if fail {
+ return &instancectl.GroupHairpinError{StatusCode: 409, Code: "group_hairpin_closed"}
+ }
+ return nil
+ }
+ for _, seconds := range []int{0, 10, 30, 70, 150, 310, 610, 899} {
+ f.at(time.Duration(seconds) * time.Second)
+ a.tick(t.Context())
+ if a.hairpinAlerted || a.hairpinAlertDone != nil {
+ t.Fatal("alert before 15 minutes")
+ }
+ }
+ f.at(15 * time.Minute)
+ a.tick(t.Context())
+ <-entered
+ fired := a.hairpinAlertDone
+ for _, seconds := range []int{901, 910, 1210} {
+ f.at(time.Duration(seconds) * time.Second)
+ a.tick(t.Context())
+ if a.hairpinAlertDone != fired {
+ t.Fatal("repeated firing page")
+ }
+ }
+ fail = false
+ f.at(1510 * time.Second)
+ a.tick(t.Context())
+ if !a.TenantAdmitted() || a.hairpinAlerted || !a.hairpinFailedAt.IsZero() {
+ t.Fatal("success did not clear failure state")
+ }
+ if blocked {
+ close(release)
+ }
+ <-a.hairpinAlertDone
+ if len(pages) != 2 || pages[0].Subject != groupHairpinAlertSubjectText || pages[1].Subject != groupHairpinClearSubjectText {
+ t.Fatalf("unordered or missing transitions: %+v", pages)
+ }
+ for _, p := range pages {
+ if p.Kind != "page" || p.Level != "warning" || !strings.Contains(p.Body, "self") || !strings.Contains(p.Body, "group_hairpin_closed") {
+ t.Fatalf("missing box or failure code: %+v", p)
+ }
+ }
+ f.at(time.Hour)
+ a.tick(t.Context())
+ <-a.hairpinAlertDone
+ if len(pages) != 2 {
+ t.Fatal("duplicate recovery page")
+ }
+ })
+ }
+}
+
+func TestGroupHairpinAdmissionRetryClose(t *testing.T) {
+ for _, phase := range []string{"backoff", "in flight"} {
+ t.Run(phase, func(t *testing.T) {
+ f := newHairpinRetryFixture(t)
+ a := f.a
+ entered, release := make(chan struct{}), make(chan struct{})
+ work, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ a.workCtx, a.workCancel = work, cancel
+ var calls []bool
+ a.hairpin = func(on bool) error {
+ calls = append(calls, on)
+ if len(calls) == 1 {
+ return errors.New("local failure")
+ }
+ if on {
+ close(entered)
+ <-release
+ }
+ return nil
+ }
+ a.tick(t.Context())
+ want := []bool{true, false}
+ if phase == "in flight" {
+ want = []bool{true, true, false}
+ f.at(10 * time.Second)
+ ticked := make(chan struct{})
+ go func() { a.tick(t.Context()); close(ticked) }()
+ <-entered
+ closed := make(chan struct{})
+ go func() { a.Close(); close(closed) }()
+ <-work.Done()
+ assertHairpinWaiting(t, a)
+ close(release)
+ <-ticked
+ <-closed
+ } else {
+ a.Close()
+ }
+ f.at(time.Hour)
+ a.tick(t.Context())
+ assertHairpinWaiting(t, a)
+ if !a.closed || a.state.Admitted() || !slices.Equal(calls, want) {
+ t.Fatalf("close lost: closed=%v calls=%v", a.closed, calls)
+ }
+ })
+ }
+}
+
+func TestGroupHairpinAdmissionFixedUnchanged(t *testing.T) {
+ for _, role := range []boxroles.Role{boxroles.Serve, boxroles.Drain, boxroles.Platform} {
+ t.Run(string(role), func(t *testing.T) {
+ a := newFixedAdmission(admissionEnv, admissionHealth())
+ _ = a.applyRole(role, true)
+ a.observe(groupadmission.Facts{EnvLoaded: true, Reconciled: true, RolePublished: true, TerminationStarted: true})
+ a.tick(t.Context())
+ a.tick(t.Context())
+ if !a.TenantAdmitted() || !a.health.Hosting() || a.startAllowed() != (role == boxroles.Serve) || a.hairpinAlertDone != nil {
+ t.Fatal("fixed admission changed")
+ }
+ a.Close()
+ a.tick(t.Context())
+ if a.TenantAdmitted() || a.health.Hosting() {
+ t.Fatal("fixed box reopened after close")
+ }
+ })
+ }
+}