ha: refuse promptly while lost lease cleanup is pending
Keep lost ownership refused across stop and entry removal. Recover through the normal gated acquire with bounded, joined background workers.
Co-Authored-By: GPT-6 Astra <noreply@openai.com>
internal/activator/activator.go+62 −1internal/activator/haforward.go+24 −7internal/activator/haleaseloss.go+218 −0internal/activator/haleaseloss_test.go+471 −0internal/activator/harelease.go+7 −0internal/activator/rootfs_service.go+3 −0
Intent
<task-notification> <task-id>a7b71da7ff615cbcc</task-id> <tool-use-id>toolu_011F3zBm2PPczrBc9SUygcWB</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/5555438b-7fa2-408d-b2c4-9fa87ea89332/tasks/a7b71da7ff615cbcc.output</output-file> <status>completed</status> <summary>Agent "F-B re-review R2 (Opus)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Verdict: READY AFTER FIXES.** P1-1 is only half fixed: exact names now serve on the holder, but regional names still don't. **Per finding:** - P1-1: NOT ADDRESSED (regional names only) - P2-1: ADDRESSED - P2-2: ADDRESSED - P3-1: ADDRESSED - P3-2: ADDRESSED - P3-3: no code expected, and none was written **Remaining P1:** `internal/edge/regional.go:163-169` (`regionalHAIngress`) answers 503 when the regional projection holds a known name with a zero route. It does this before the check at :177 that lets the local holder serve. Several things zero every regional name: an incomplete alias pass (`host/agent.go:1397,1403`, for example when any box's edges file is unusable), any alias-pass error, or a whole refresh failure. When that happens, every regional domain in the region returns a 503 on every box, the awake holder included. Regional domains shipped in v0.31.0. The fix is the same eligible-holder shortcut that `haingress.go:76` now uses, plus a regional witness test. **New P1/P2 in the fix diff:** none. There is one new P3: the owed-obligation check reads an empty list if the obligation store failed to open at startup. Today the lock-owner check still stops an unsafe delete, so this is a missing second guard. The controller's successor-present ruling held up: I checked it against the release order and found no unsound case. The two CI-repair production hunks (`cmd.go`, the registry delete guard) are fine. The shared worktree has uncommitted edits from another session (`activator.go`, `haforward.go`, `rootfs_service.go`, new `haleaseloss*.go`). I cited line numbers from f4945a2c and left those edits alone. Review: `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-g2-fixes/.superpowers/sdd/2026-11-06-region-ha-g2-fixes/fb-review-r2.md`</result> <usage><subagent_tokens>110761</subagent_tokens><tool_uses>33</tool_uses><duration_ms>351983</duration_ms></usage> </task-notification>
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index e4830201b..6fb5bafdf 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -488,6 +488,9 @@ const ( |
| ) |
| type actEntry struct { |
| + haRecovery *haLeaseLoss |
| + haReleasing bool |
| + haAcquireUntil time.Time |
| duty bool |
| statelessPrepared *statelessPreparation |
| claimResult *wokenInstance |
| @@ -1366,6 +1369,7 @@ type Service struct { |
| // markers is the sweep's retry of owed region HA release markers |
| // (retryOwedMarkers). |
| markers markerRetry |
| + haLoss haLossState |
| mu sync.Mutex |
| entries map[string]*actEntry |
| @@ -1638,6 +1642,7 @@ func New(cfg Config, backend Backend, due DueStore) *Service { |
| entries: make(map[string]*actEntry), |
| gens: GenerationsEnabled(), |
| } |
| + a.initHALosses() |
| a.wakeSlots = make(chan struct{}, wakeSlotCount(cfg.WakeSlots)) |
| // The resident listing (Plan 3 Task 8): the registry in production. A |
| // DueStore without it (a test double) has no residents. |
| @@ -1751,6 +1756,11 @@ func (a *Service) begin(ctx context.Context, rt registry.Route, stamp bool, req |
| return nil, &errLeaseRefused{reason: hafresh.ReasonPoolIneligible} |
| } |
| a.mu.Lock() |
| + if err := a.haLeaseRefusalLocked(rt); err != nil { |
| + a.mu.Unlock() |
| + a.retryHALostHost(rt) |
| + return nil, err |
| + } |
| if a.fences[rt.Host] != 0 { |
| a.mu.Unlock() |
| return nil, ErrFenced |
| @@ -2014,6 +2024,11 @@ func (a *Service) consumeDueTime(e *actEntry) { |
| // agent shutting down, the entry retired, or its route turned off. wake asks |
| // at its start and again once it holds a wake slot. |
| func (a *Service) refuseWakeLocked(e *actEntry, cancel context.CancelFunc) { |
| + _ = a.haLeaseRefusalLocked(e.route) |
| + if l := a.haLoss.hosts[e.host]; l != nil && (e.haRecovery != l || l.recovery != e) { |
| + cancel() |
| + } |
| + |
| // A wake that starts after Shutdown began is cancelled before its |
| // lease, whatever CARLOS_SWAP says (#292): with swaps off it used to run |
| // on, and take a lease the exiting agent never gave back. |
| @@ -2037,6 +2052,9 @@ func (a *Service) wake(e *actEntry) { |
| defer a.wakeEnded(e.host) |
| } |
| parent := context.Background() |
| + if e.haRecovery != nil { |
| + parent = a.life() |
| + } |
| if e.probe != nil && e.probe.parent != nil { |
| // A probe's wake ends with its caller (ProbeWake). |
| parent = e.probe.parent |
| @@ -2804,7 +2822,13 @@ func (a *Service) doWakeOnce(ctx context.Context, e *actEntry) (*wokenInstance, |
| return w, err |
| } |
| *w.stopOutcome = stopObservation{} |
| - lease, err := a.backend.Acquire(ctx, rt) |
| + acquireCtx := ctx |
| + cancelAcquire := func() {} |
| + if !e.haAcquireUntil.IsZero() { |
| + acquireCtx, cancelAcquire = context.WithDeadline(ctx, e.haAcquireUntil) |
| + } |
| + lease, err := a.backend.Acquire(acquireCtx, rt) |
| + cancelAcquire() |
| if err == nil { |
| // This box holds the host now: no holder elsewhere to forward to. |
| a.holders.drop(host) |
| @@ -3366,6 +3390,10 @@ const actStopTimeout = 20 * time.Second |
| // why (the Stop* reasons in cmd.go): a run the stop interrupts tells the |
| // member (run spec §5.3). |
| func (a *Service) beginStopLocked(e *actEntry, why string) { |
| + if why == StopLeaseLost || (e.state == actAwake && servingError(e) != nil) { |
| + a.latchHALossLocked(e) |
| + } |
| + |
| // Held legs end with the stop, in this critical section, before the |
| // stop goroutine starts (edge-held streams spec §3.2): a leg is either |
| // registered now and cancelled here, or admitted later and refused. |
| @@ -3997,6 +4025,11 @@ func (a *Service) WakeWorker(rt registry.Route) error { |
| extended := false |
| for { |
| a.mu.Lock() |
| + if err := a.haLeaseRefusalLocked(rt); err != nil { |
| + a.mu.Unlock() |
| + a.retryHALostHost(rt) |
| + return err |
| + } |
| // Refused once a shutdown has announced itself. Shutdown sets the flag |
| // BEFORE it snapshots the entry map, so a wake dispatched after that |
| // point — a sidecar-wake leg tick, a boot pass, an operator command |
| @@ -5161,6 +5194,13 @@ func (a *Service) retryPendingStop(e *actEntry) { |
| // ErrStillRunning and returned, plus whatever finishPendingStop's own |
| // retried proc.Stop just added. |
| func (a *Service) finishStop(e *actEntry, outcome *stopObservation) { |
| + a.mu.Lock() |
| + current := a.entries[e.host] == e |
| + a.mu.Unlock() |
| + if !current { |
| + return |
| + } |
| + |
| // A run attached to this instance is stopped and settled before |
| // replication closes (run spec §5.3, codex 1): everything it committed |
| // is in the final checkpoint, and nothing writes the database after. |
| @@ -5238,6 +5278,10 @@ func (a *Service) finishStop(e *actEntry, outcome *stopObservation) { |
| log.Printf("activator: final checkpoint %s: %v", e.host, repErr) |
| } |
| a.mu.Lock() |
| + var owed *lease.ObligationError |
| + if errors.As(repErr, &owed) { |
| + a.latchHALossLocked(e) |
| + } |
| outcome.uncertain = !outcome.complete() |
| e.stopOutcome = outcome |
| a.rememberStopLocked(e.host, outcome) |
| @@ -5389,6 +5433,7 @@ func (a *Service) sweepOnce() { |
| // Owed release markers (region HA P1a): lease retries each on its own |
| // spacing; one retry pass at a time, off a.mu. |
| a.retryOwedMarkers() |
| + a.retryHALostHosts() |
| // The due query runs before the lock — it's a registry read, and nothing |
| // under a.mu should wait on SQLite. |
| dueRoutes, err := a.due.DueInstances(now.Unix()) |
| @@ -6111,6 +6156,7 @@ func (a *Service) Shutdown(ctx context.Context) { |
| if a.lifeStop != nil { |
| a.lifeStop() |
| } |
| + a.haLoss.joined.Wait() |
| if sweepStop != nil { |
| close(sweepStop) |
| <-sweepDone |
| @@ -6342,6 +6388,16 @@ func (a *Service) ServeScheduled(w http.ResponseWriter, r *http.Request, rt regi |
| } |
| func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Route, proxy http.Handler, stamp bool) bool { |
| + if rt.ActivatorOwned() { |
| + a.mu.Lock() |
| + refusal := a.haLeaseRefusalLocked(rt) |
| + a.mu.Unlock() |
| + if refusal != nil { |
| + a.retryHALostHost(rt) |
| + return a.serveWakeError(w, r, rt, refusal) |
| + } |
| + } |
| + |
| if rt.ActivatorOwned() && a.Startup != nil { |
| deadline := time.NewTimer(wakeWaitBound) |
| err := a.awaitStartup(r.Context(), deadline.C) |
| @@ -6431,6 +6487,11 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout |
| } |
| func (a *Service) serveWakeError(w http.ResponseWriter, r *http.Request, rt registry.Route, err error) bool { |
| + if errors.Is(err, ErrHALeaseUnavailable) { |
| + edge.HAUnavailableResponse(w, r) |
| + return true |
| + } |
| + |
| var poolRefusal *errLeaseRefused |
| if errors.As(err, &poolRefusal) && poolRefusal.reason == hafresh.ReasonPoolIneligible { |
| edge.HAUnavailableResponse(w, r) |
diff --git a/internal/activator/haforward.go b/internal/activator/haforward.go| index f484dcf6a..e06771c01 100644 |
| --- a/internal/activator/haforward.go |
| +++ b/internal/activator/haforward.go |
| @@ -124,18 +124,35 @@ var _ edge.HAForwarderFromMemory = (*Service)(nil) |
| // forwardTarget is ForwardTarget; with memoryOnly, a holder-cache miss |
| // answers ok false instead of reading the lock. |
| func (a *Service) forwardTarget(ctx context.Context, rt registry.Route, snapshot func() boxchoice.WakeSnapshot, memoryOnly bool) (edge.ForwardDecision, bool) { |
| - if !rt.HA { |
| - return edge.ForwardDecision{Unavailable: !a.LocalEligible(rt)}, true |
| - } |
| - r := holderReaderFor(a.backend, rt) |
| - if r == nil { |
| - return edge.ForwardDecision{Unavailable: !a.LocalEligible(rt)}, true |
| - } |
| eligible := a.LocalEligible(rt) |
| a.mu.Lock() |
| + refusal := a.haLeaseRefusalLocked(rt) |
| e := a.entries[rt.Host] |
| here := eligible && samePoolRoute(e, rt) && !e.retired && !e.probeHeld && e.err == nil && a.fences[rt.Host] == 0 && !a.shuttingDown && (e.state == actWaking || (e.state == actAwake && e.proc != nil && !e.proc.Exited() && servingError(e) == nil)) |
| + // Health can fail between the first check and the shortcut's own read. |
| + if !here && refusal == nil { |
| + refusal = a.haLeaseRefusalLocked(rt) |
| + } |
| + l := a.haLoss.hosts[rt.Host] |
| + foreign := l != nil && l.foreign |
| a.mu.Unlock() |
| + if refusal != nil { |
| + a.retryHALostHost(rt) |
| + if foreign { |
| + if resolved, ok := a.holders.peek(rt.Host); ok && resolved.Ref != "" && !resolved.Refuse { |
| + token, _ := a.peers.holderToken(resolved.Ref, a.holders.clock()) |
| + return edge.ForwardDecision{Ref: resolved.Ref, Gen: resolved.Gen, PeerGen: token}, true |
| + } |
| + } |
| + return edge.ForwardDecision{Unavailable: true}, true |
| + } |
| + if !rt.HA { |
| + return edge.ForwardDecision{Unavailable: !eligible}, true |
| + } |
| + r := holderReaderFor(a.backend, rt) |
| + if r == nil { |
| + return edge.ForwardDecision{Unavailable: !eligible}, true |
| + } |
| if here { |
| return edge.ForwardDecision{}, true |
| } |
diff --git a/internal/activator/haleaseloss.go b/internal/activator/haleaseloss.go| new file mode 100644 |
| index 000000000..91bb1544c |
| --- /dev/null |
| +++ b/internal/activator/haleaseloss.go |
| @@ -0,0 +1,218 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "path" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +var ErrHALeaseUnavailable = errors.New("ha_lease_unavailable") |
| + |
| +const haLossRetryInterval = 10 * time.Second |
| +const haLossAttemptBudget = 2 * time.Second |
| +const haLossWorkers = 4 |
| + |
| +// A loss belongs to the entry that lost ownership, including its record |
| +// lifetime and generation. Entry removal cannot discharge it. Only the |
| +// recovery entry's healthy, newly acquired replica can do that. |
| +type haLeaseLoss struct { |
| + old *actEntry |
| + route registry.Route |
| + running bool |
| + next time.Time |
| + recovery *actEntry |
| + foreign bool |
| +} |
| + |
| +type haLossState struct { |
| + hosts map[string]*haLeaseLoss |
| + startup []lease.Obligation |
| + workers int |
| + joined sync.WaitGroup |
| +} |
| + |
| +// Startup reads the durable obligations once, before requests. The request |
| +// path never waits on the obligation store's disk-write mutex. |
| +func (a *Service) initHALosses() { a.haLoss.startup = lease.PendingObligations() } |
| + |
| +func haOwedKey(b Backend, rt registry.Route) (string, string) { |
| + switch b := b.(type) { |
| + case *SplitBackend: |
| + return haOwedKey(b.pick(rt), rt) |
| + case *ExecBackend: |
| + return b.Cfg.Bucket, path.Join(b.Cfg.hibernatePrefix(rt.Host), "lock.json") |
| + } |
| + return "", "" |
| +} |
| + |
| +func (a *Service) latchHALossLocked(e *actEntry) { |
| + if a.entries[e.host] != e || e.gen.Stateless { |
| + return |
| + } |
| + if _, ok := haEntryRep(e); !ok && !e.route.HA { |
| + return |
| + } |
| + if a.haLoss.hosts == nil { |
| + a.haLoss.hosts = make(map[string]*haLeaseLoss) |
| + } |
| + if l := a.haLoss.hosts[e.host]; l != nil { |
| + // A failed recovery must itself finish stopping before another try. |
| + if l.recovery == e { |
| + l.old = e |
| + l.foreign = false |
| + } |
| + return |
| + } |
| + a.haLoss.hosts[e.host] = &haLeaseLoss{old: e, route: e.route} |
| + a.holders.drop(e.host) |
| +} |
| + |
| +func haUnexpectedLoss(e *actEntry, err error) bool { |
| + return err != nil && (!e.haReleasing || !errors.Is(err, lease.ErrSpent)) |
| +} |
| + |
| +// haLeaseRefusalLocked is entirely local. Call before any healthy-entry |
| +// shortcut, stop wait or request accounting. Ordinary intentional stops |
| +// may spend their handles during release; that alone is not a loss. |
| +func (a *Service) haLeaseRefusalLocked(rt registry.Route) error { |
| + e := a.entries[rt.Host] |
| + if e != nil && (e.route.HA || haHeld(nil, e.rep)) && !e.gen.Stateless { |
| + health := servingError(e) |
| + if e.state == actAwake && health != nil { |
| + a.beginStopLocked(e, StopLeaseLost) |
| + } else if e.state == actStopping && (e.stopWhy == StopLeaseLost || haUnexpectedLoss(e, health)) { |
| + a.latchHALossLocked(e) |
| + } |
| + } |
| + if a.haLoss.hosts[rt.Host] != nil { |
| + return ErrHALeaseUnavailable |
| + } |
| + bucket, key := haOwedKey(a.backend, rt) |
| + for _, o := range a.haLoss.startup { |
| + if bucket != "" && o.Bucket == bucket && o.Key == key { |
| + if a.haLoss.hosts == nil { |
| + a.haLoss.hosts = make(map[string]*haLeaseLoss) |
| + } |
| + a.haLoss.hosts[rt.Host] = &haLeaseLoss{route: rt} |
| + return ErrHALeaseUnavailable |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// retryHALostHost reserves bounded work without doing I/O on the caller. |
| +// The ordinary acquire settles owed markers and applies pool, lifetime, |
| +// same-box-empty and foreign-termination checks. It never reuses a Held. |
| +func (a *Service) retryHALostHost(rt registry.Route) { |
| + if !a.LocalEligible(rt) { |
| + return |
| + } |
| + if a.Startup != nil { |
| + select { |
| + case <-a.Startup: |
| + default: |
| + return |
| + } |
| + } |
| + a.mu.Lock() |
| + l := a.haLoss.hosts[rt.Host] |
| + if l == nil || l.running || a.haLoss.workers >= haLossWorkers || a.shuttingDown || a.life().Err() != nil || a.now().Before(l.next) || a.entries[rt.Host] != nil || a.fences[rt.Host] != 0 || a.unprovenWakes[rt.Host] != nil || a.releaseOps[rt.Host] != nil || len(a.straySidecars[rt.Host]) != 0 { |
| + a.mu.Unlock() |
| + return |
| + } |
| + if l.old != nil { |
| + select { |
| + case <-l.old.stopped: |
| + default: |
| + a.mu.Unlock() |
| + return |
| + } |
| + } |
| + l.running = true |
| + l.route = rt |
| + l.next = a.now().Add(haLossRetryInterval) |
| + a.haLoss.workers++ |
| + a.haLoss.joined.Add(1) |
| + a.mu.Unlock() |
| + go a.recoverHALostHost(rt, l) |
| +} |
| + |
| +func (a *Service) recoverHALostHost(rt registry.Route, l *haLeaseLoss) { |
| + defer func() { |
| + a.mu.Lock() |
| + l.running = false |
| + a.haLoss.workers-- |
| + a.mu.Unlock() |
| + a.haLoss.joined.Done() |
| + }() |
| + attempt, cancel := context.WithTimeout(a.life(), haLossAttemptBudget) |
| + defer cancel() |
| + // Discovery and acquisition share one deadline. No helper goroutine is |
| + // abandoned when it expires: the worker owns and joins all its work. |
| + if r := holderReaderFor(a.backend, rt); r != nil { |
| + v, err := r.readHolderView(attempt, rt) |
| + if err != nil { |
| + return |
| + } |
| + if ref := otherHolder(v, r.self(), a.holders.clock()); ref != "" { |
| + a.mu.Lock() |
| + if a.haLoss.hosts[rt.Host] == l { |
| + a.holders.set(rt.Host, ref) |
| + l.foreign = true |
| + } |
| + a.mu.Unlock() |
| + return |
| + } |
| + } |
| + a.mu.Lock() |
| + if a.haLoss.hosts[rt.Host] != l || a.shuttingDown || a.entries[rt.Host] != nil || a.fences[rt.Host] != 0 || attempt.Err() != nil { |
| + a.mu.Unlock() |
| + return |
| + } |
| + e := &actEntry{host: rt.Host, route: rt, state: actWaking, ready: make(chan struct{})} |
| + if rt.IsSidecar() { |
| + e = a.newWorkerEntry(rt) |
| + } |
| + e.haRecovery = l |
| + e.haAcquireUntil, _ = attempt.Deadline() |
| + l.recovery = e |
| + l.foreign = false |
| + a.putEntryLocked(rt.Host, e) |
| + a.mu.Unlock() |
| + a.wake(e) |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + if a.haLoss.hosts[rt.Host] != l || a.entries[rt.Host] != e || e.state != actAwake || e.err != nil || e.proc == nil || e.proc.Exited() || servingError(e) != nil || !a.LocalEligible(e.route) { |
| + return |
| + } |
| + if _, ha := haEntryRep(e); !ha { |
| + return |
| + } |
| + delete(a.haLoss.hosts, rt.Host) |
| + e.haRecovery = nil |
| + bucket, key := haOwedKey(a.backend, rt) |
| + kept := a.haLoss.startup[:0] |
| + for _, o := range a.haLoss.startup { |
| + if o.Bucket != bucket || o.Key != key { |
| + kept = append(kept, o) |
| + } |
| + } |
| + a.haLoss.startup = kept |
| +} |
| + |
| +func (a *Service) retryHALostHosts() { |
| + a.mu.Lock() |
| + routes := make([]registry.Route, 0, len(a.haLoss.hosts)) |
| + for _, l := range a.haLoss.hosts { |
| + routes = append(routes, l.route) |
| + } |
| + a.mu.Unlock() |
| + for _, rt := range routes { |
| + a.retryHALostHost(rt) |
| + } |
| +} |
diff --git a/internal/activator/haleaseloss_test.go b/internal/activator/haleaseloss_test.go| new file mode 100644 |
| index 000000000..b2858574d |
| --- /dev/null |
| +++ b/internal/activator/haleaseloss_test.go |
| @@ -0,0 +1,471 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +type lossTestRep struct { |
| + Rep |
| + haRep |
| + lost atomic.Bool |
| + entered chan struct{} |
| + unblock chan struct{} |
| +} |
| + |
| +func (r *lossTestRep) Err() error { |
| + if r.lost.Load() { |
| + return lease.ErrSpent |
| + } |
| + return r.Rep.Err() |
| +} |
| +func (r *lossTestRep) Finish(ctx context.Context) (uint64, error) { |
| + close(r.entered) |
| + <-r.unblock |
| + return r.haRep.Finish(ctx) |
| +} |
| +func (r *lossTestRep) Abandon(ctx context.Context) { |
| + r.Rep.(interface{ Abandon(context.Context) }).Abandon(ctx) |
| +} |
| + |
| +func lostTestEntry(t *testing.T) (*haSvc, *actEntry, *lossTestRep) { |
| + t.Helper() |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + s.rt.HA = true |
| + r := &lossTestRep{Rep: e.rep, haRep: e.rep.(haRep), entered: make(chan struct{}), unblock: make(chan struct{})} |
| + s.a.mu.Lock() |
| + e.route.HA = true |
| + e.rep = r |
| + s.a.mu.Unlock() |
| + r.lost.Store(true) |
| + t.Cleanup(func() { |
| + select { |
| + case <-r.unblock: |
| + default: |
| + close(r.unblock) |
| + } |
| + s.a.lifeStop() |
| + s.a.haLoss.joined.Wait() |
| + s.a.mu.Lock() |
| + stopped := e.stopped |
| + s.a.mu.Unlock() |
| + if stopped != nil { |
| + select { |
| + case <-stopped: |
| + case <-time.After(10 * time.Second): |
| + t.Error("stop did not finish") |
| + } |
| + } |
| + }) |
| + return s, e, r |
| +} |
| + |
| +func assertLostResponse(t *testing.T, s *haSvc) { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(context.Background(), time.Second) |
| + defer cancel() |
| + req := httptest.NewRequest("GET", "http://shop.example.com/", nil).WithContext(ctx) |
| + w := httptest.NewRecorder() |
| + var proxied atomic.Bool |
| + start := time.Now() |
| + s.a.ServeHTTP(w, req, s.rt, http.HandlerFunc(func(http.ResponseWriter, *http.Request) { proxied.Store(true) })) |
| + if time.Since(start) >= time.Second || w.Code != 503 || w.Header().Get("Retry-After") != "10" || w.Header().Get("X-Carlos-Holder") != "none" || w.Body.String() != edge.HAUnavailableMessage+"\n" || proxied.Load() { |
| + t.Errorf("loss answer after %s: status=%d headers=%v body=%q proxy=%v", time.Since(start), w.Code, w.Header(), w.Body.String(), proxied.Load()) |
| + } |
| +} |
| + |
| +func TestHALostLeaseAnswersImmediately(t *testing.T) { |
| + for _, stopping := range []bool{false, true} { |
| + for _, hop := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "awake", true: "stopping"}[stopping]+map[bool]string{false: "/ordinary", true: "/hop"}[hop], func(t *testing.T) { |
| + if hop { |
| + asForwarded(t) |
| + } |
| + s, e, r := lostTestEntry(t) |
| + if stopping { |
| + s.a.mu.Lock() |
| + s.a.beginStopLocked(e, StopLeaseLost) |
| + s.a.mu.Unlock() |
| + select { |
| + case <-r.entered: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("stop did not enter Finish") |
| + } |
| + } |
| + before := lockGets(s.b, s.rt) |
| + assertLostResponse(t, s) |
| + s.a.mu.Lock() |
| + inflight := e.inflight |
| + current := s.a.entries[s.rt.Host] |
| + s.a.mu.Unlock() |
| + if inflight != 0 || current != e || lockGets(s.b, s.rt) != before { |
| + t.Fatal("refusal entered accounting or re-woke") |
| + } |
| + if d, ok := s.a.ForwardTargetFromMemory(s.rt, nil); !ok || !d.Unavailable { |
| + t.Errorf("memory forward: %+v %v", d, ok) |
| + } |
| + if d := s.a.ForwardTarget(context.Background(), s.rt, nil); !d.Unavailable { |
| + t.Errorf("forward: %+v", d) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +func TestHALostLatchSurvivesEntryRemoval(t *testing.T) { |
| + s, e, r := lostTestEntry(t) |
| + s.failMarkerPuts(100) |
| + s.a.mu.Lock() |
| + s.a.beginStopLocked(e, StopLeaseLost) |
| + s.a.mu.Unlock() |
| + close(r.unblock) |
| + select { |
| + case <-e.stopped: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("stop did not finish") |
| + } |
| + if len(lease.PendingObligations()) != 1 { |
| + t.Fatal("missing owed marker") |
| + } |
| + assertLostResponse(t, s) |
| +} |
| + |
| +func TestHALostLeaseRecoversOnlyAfterFreshAcquire(t *testing.T) { |
| + s, e, r := lostTestEntry(t) |
| + s.a.mu.Lock() |
| + s.a.beginStopLocked(e, StopLeaseLost) |
| + s.a.mu.Unlock() |
| + assertLostResponse(t, s) |
| + r.lost.Store(false) // a late healthy observation cannot clear the loss |
| + assertLostResponse(t, s) |
| + close(r.unblock) |
| + select { |
| + case <-e.stopped: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("stop did not finish") |
| + } |
| + // The first recovery must use the conditional acquire after the release. |
| + assertLostResponse(t, s) |
| + deadline := time.Now().Add(10 * time.Second) |
| + for time.Now().Before(deadline) { |
| + s.a.mu.Lock() |
| + n := s.a.entries[s.rt.Host] |
| + recovered := n != nil && n != e && n.state == actAwake && servingError(n) == nil |
| + s.a.mu.Unlock() |
| + if recovered { |
| + writes := lockWriteLogOf(s) |
| + if len(writes) < 3 || !isMarker(writes[len(writes)-2]) || !isHAHeld(writes[len(writes)-1], s.b.self()) { |
| + t.Fatalf("recovery did not acquire after marker: %v", writes) |
| + } |
| + done, err := s.a.beginRequest(context.Background(), s.rt) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + done() |
| + return |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| + t.Fatal("fresh healthy acquisition did not recover") |
| +} |
| + |
| +func finishLostTestEntry(t *testing.T, s *haSvc, e *actEntry, r *lossTestRep) { |
| + t.Helper() |
| + s.a.mu.Lock() |
| + s.a.beginStopLocked(e, StopLeaseLost) |
| + s.a.mu.Unlock() |
| + close(r.unblock) |
| + select { |
| + case <-e.stopped: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("stop did not finish") |
| + } |
| +} |
| + |
| +func assertLossLatched(t *testing.T, s *haSvc) { |
| + t.Helper() |
| + s.a.mu.Lock() |
| + err := s.a.haLeaseRefusalLocked(s.rt) |
| + s.a.mu.Unlock() |
| + if !errors.Is(err, ErrHALeaseUnavailable) { |
| + t.Fatalf("loss gate = %v", err) |
| + } |
| +} |
| + |
| +func recoverLostTestHost(t *testing.T, s *haSvc) *actEntry { |
| + t.Helper() |
| + s.a.retryHALostHost(s.rt) |
| + s.a.haLoss.joined.Wait() |
| + s.a.mu.Lock() |
| + defer s.a.mu.Unlock() |
| + e := s.a.entries[s.rt.Host] |
| + if e == nil || e.state != actAwake || servingError(e) != nil || s.a.haLeaseRefusalLocked(s.rt) != nil { |
| + t.Fatal("fresh acquisition did not recover the host") |
| + } |
| + return e |
| +} |
| + |
| +func TestHALostLeaseRecoversOnlyAfterFreshAcquireTemporaryS3Failure(t *testing.T) { |
| + s, e, r := lostTestEntry(t) |
| + s.failMarkerPuts(2) // the release, then the first recovery's settlement |
| + finishLostTestEntry(t, s, e, r) |
| + clk := &fakeClock{t: time.Now()} |
| + s.a.now = clk.now |
| + s.a.retryHALostHost(s.rt) |
| + s.a.haLoss.joined.Wait() |
| + assertLossLatched(t, s) |
| + if len(lease.PendingObligations()) != 1 { |
| + t.Fatal("failed settlement discarded the obligation") |
| + } |
| + before := len(s.fx.Requests()) |
| + s.a.retryHALostHost(s.rt) |
| + s.a.haLoss.joined.Wait() |
| + if len(s.fx.Requests()) != before { |
| + t.Fatal("retried before 10 seconds") |
| + } |
| + clk.advance(10 * time.Second) |
| + n := recoverLostTestHost(t, s) |
| + if n == e { |
| + t.Fatal("reused lost entry") |
| + } |
| + writes := lockWriteLogOf(s) |
| + if len(writes) < 3 || !isMarker(writes[len(writes)-2]) || !isHAHeld(writes[len(writes)-1], s.b.self()) { |
| + t.Fatal("recovery skipped the marker or acquire") |
| + } |
| + // A delayed old callback must neither poison nor delete the successor. |
| + s.a.mu.Lock() |
| + s.a.latchHALossLocked(e) |
| + s.a.mu.Unlock() |
| + s.a.finishStop(e, &stopObservation{}) |
| + s.a.mu.Lock() |
| + current := s.a.entries[s.rt.Host] |
| + refusal := s.a.haLeaseRefusalLocked(s.rt) |
| + s.a.mu.Unlock() |
| + if current != n || refusal != nil { |
| + t.Fatal("old stop changed the successor") |
| + } |
| +} |
| + |
| +func TestHALostLeaseRecoversOnlyAfterFreshAcquireRestart(t *testing.T) { |
| + s, e, r := lostTestEntry(t) |
| + s.failMarkerPuts(2) |
| + finishLostTestEntry(t, s, e, r) |
| + s2 := s.restart(t) |
| + // Loaded obligations close the fast gate even though no entry survived. |
| + assertLostResponse(t, s2) |
| + s2.a.haLoss.joined.Wait() |
| + assertLossLatched(t, s2) |
| + if len(lease.PendingObligations()) != 1 { |
| + t.Fatal("restart lost the owed marker") |
| + } |
| + clk := &fakeClock{t: time.Now().Add(11 * time.Second)} |
| + s2.a.now = clk.now |
| + recoverLostTestHost(t, s2) |
| +} |
| + |
| +func TestHALostLeaseRecoversOnlyAfterFreshAcquireForeignLease(t *testing.T) { |
| + s, e, r := lostTestEntry(t) |
| + finishLostTestEntry(t, s, e, r) |
| + putLockFor(t, s.b, s.rt, leaseBody(t, heldByB, time.Now().Add(-time.Minute))) |
| + before := len(lockWriteLogOf(s)) |
| + s.a.retryHALostHost(s.rt) |
| + s.a.haLoss.joined.Wait() |
| + assertLossLatched(t, s) |
| + if len(lockWriteLogOf(s)) != before { |
| + t.Fatal("foreign expiry authorized an acquire") |
| + } |
| + // A live foreign holder permits forwarding, without opening local service. |
| + clk := &fakeClock{t: time.Now().Add(11 * time.Second)} |
| + s.a.now = clk.now |
| + putLockFor(t, s.b, s.rt, leaseBody(t, heldByB, time.Now().Add(time.Minute))) |
| + s.a.retryHALostHost(s.rt) |
| + s.a.haLoss.joined.Wait() |
| + assertLossLatched(t, s) |
| + if d, ok := s.a.ForwardTargetFromMemory(s.rt, nil); !ok || d.Ref != "b" || d.Unavailable { |
| + t.Fatalf("foreign forward=%+v, %v", d, ok) |
| + } |
| + assertLostResponse(t, s) |
| +} |
| + |
| +func TestHALostLeaseRecoversOnlyAfterFreshAcquirePoolWithdrawal(t *testing.T) { |
| + s, e, r := lostTestEntry(t) |
| + finishLostTestEntry(t, s, e, r) |
| + original := s.b.ServedPools |
| + s.b.ServedPools = func() edgesfile.PoolEvidence { return edgesfile.PoolEvidence(`["another-pool"]`) } |
| + before := len(s.fx.Requests()) |
| + s.a.retryHALostHost(s.rt) |
| + s.a.haLoss.joined.Wait() |
| + assertLossLatched(t, s) |
| + assertLostResponse(t, s) |
| + if len(s.fx.Requests()) != before { |
| + t.Fatal("pool withdrawal attempted recovery") |
| + } |
| + s.b.ServedPools = original |
| + recoverLostTestHost(t, s) |
| +} |
| + |
| +func TestHALostLeaseRecoversOnlyAfterFreshAcquireNewLifetime(t *testing.T) { |
| + s, e, r := lostTestEntry(t) |
| + finishLostTestEntry(t, s, e, r) |
| + h := haFixOf(s.b) |
| + h.mu.Lock() |
| + rec := h.records[s.rt.Host] |
| + rec.CreatedAt = rec.CreatedAt.Add(time.Hour) |
| + h.records[s.rt.Host] = rec |
| + h.mu.Unlock() |
| + s.b.Lifetimes.Merge(map[string]provision.Record{s.rt.Host: rec}) |
| + assertLossLatched(t, s) |
| + n := recoverLostTestHost(t, s) |
| + acquired, ok := s.b.haAcquired(s.rt.Host) |
| + if !ok || acquired.entry.ID == h.lifetime || n == e { |
| + t.Fatal("recovery used the old record lifetime") |
| + } |
| +} |
| + |
| +func TestHALostLeaseRecoveryAttemptAndShutdown(t *testing.T) { |
| + s, e, r := lostTestEntry(t) |
| + finishLostTestEntry(t, s, e, r) |
| + old := readHolderLock |
| + entered := make(chan struct{}) |
| + finished := make(chan struct{}) |
| + readHolderLock = func(ctx context.Context, _, _, _ string) (hafresh.View, error) { |
| + defer close(finished) |
| + deadline, ok := ctx.Deadline() |
| + if !ok || time.Until(deadline) > 2*time.Second { |
| + t.Error("discovery missing the 2-second attempt bound") |
| + } |
| + close(entered) |
| + <-ctx.Done() |
| + return hafresh.View{}, ctx.Err() |
| + } |
| + t.Cleanup(func() { readHolderLock = old }) |
| + s.a.retryHALostHost(s.rt) |
| + <-entered |
| + for i := 0; i < 20; i++ { |
| + s.a.retryHALostHost(s.rt) |
| + } |
| + s.a.mu.Lock() |
| + workers := s.a.haLoss.workers |
| + s.a.mu.Unlock() |
| + if workers != 1 { |
| + t.Fatalf("%d concurrent workers for one host", workers) |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), time.Second) |
| + defer cancel() |
| + s.a.Shutdown(ctx) |
| + select { |
| + case <-finished: |
| + default: |
| + t.Fatal("Shutdown did not join the recovery") |
| + } |
| + assertLossLatched(t, s) |
| +} |
| + |
| +func TestHALostLatchPrecedesHealthyShortcut(t *testing.T) { |
| + s, e, r := lostTestEntry(t) |
| + r.lost.Store(false) |
| + s.a.mu.Lock() |
| + s.a.latchHALossLocked(e) |
| + s.a.mu.Unlock() |
| + assertLostResponse(t, s) |
| + if d, ok := s.a.ForwardTargetFromMemory(s.rt, nil); !ok || !d.Unavailable { |
| + t.Fatalf("healthy shortcut bypassed loss: %+v %v", d, ok) |
| + } |
| +} |
| + |
| +func TestHALostOrdinaryStopStillWaits(t *testing.T) { |
| + s, e, r := lostTestEntry(t) |
| + r.lost.Store(false) |
| + s.a.mu.Lock() |
| + s.a.beginStopLocked(e, StopIdle) |
| + s.a.mu.Unlock() |
| + <-r.entered |
| + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) |
| + defer cancel() |
| + _, err := s.a.beginRequest(ctx, s.rt) |
| + if !errors.Is(err, context.DeadlineExceeded) { |
| + t.Fatalf("ordinary idle stop = %v", err) |
| + } |
| + s.a.mu.Lock() |
| + latched := s.a.haLoss.hosts[s.rt.Host] != nil |
| + s.a.mu.Unlock() |
| + if latched { |
| + t.Fatal("ordinary idle stop latched a loss") |
| + } |
| +} |
| + |
| +func TestHALostLeaseRecoveryAcquireBudget(t *testing.T) { |
| + s, e, r := lostTestEntry(t) |
| + finishLostTestEntry(t, s, e, r) |
| + old := acquireHALease |
| + called := false |
| + acquireHALease = func(ctx context.Context, bucket, prefix, region string, base hafresh.Marker, p hafresh.Proofs) (*lease.Held, error) { |
| + called = true |
| + deadline, ok := ctx.Deadline() |
| + if !ok || time.Until(deadline) > 2*time.Second { |
| + t.Error("acquire missing the shared 2-second budget") |
| + } |
| + <-ctx.Done() |
| + return nil, ctx.Err() |
| + } |
| + t.Cleanup(func() { acquireHALease = old }) |
| + s.a.retryHALostHost(s.rt) |
| + s.a.haLoss.joined.Wait() |
| + if !called { |
| + t.Fatal("did not use the normal HA acquire path") |
| + } |
| + assertLossLatched(t, s) |
| +} |
| + |
| +type lostDiscoveryBackend struct{ Backend } |
| + |
| +func (lostDiscoveryBackend) self() hafresh.Self { return hafresh.Self{Ref: "a", IID: "i-a"} } |
| +func (lostDiscoveryBackend) readHolderView(ctx context.Context, _ registry.Route) (hafresh.View, error) { |
| + <-ctx.Done() |
| + return hafresh.View{}, ctx.Err() |
| +} |
| + |
| +func TestHALostLeaseRecoveryWorkersBounded(t *testing.T) { |
| + a := New(Config{}, lostDiscoveryBackend{}, nil) |
| + a.haLoss.hosts = make(map[string]*haLeaseLoss) |
| + for i := 0; i < haLossWorkers+1; i++ { |
| + rt := registry.Route{Host: fmt.Sprintf("host%d.example.com", i), HA: true} |
| + a.mu.Lock() |
| + a.haLoss.hosts[rt.Host] = &haLeaseLoss{route: rt} |
| + a.mu.Unlock() |
| + a.retryHALostHost(rt) |
| + } |
| + a.mu.Lock() |
| + workers := a.haLoss.workers |
| + pending := len(a.haLoss.hosts) |
| + a.mu.Unlock() |
| + a.lifeStop() |
| + a.haLoss.joined.Wait() |
| + if workers != haLossWorkers || pending != haLossWorkers+1 { |
| + t.Fatalf("workers=%d pending=%d; bounded workers must not evict safety state", workers, pending) |
| + } |
| +} |
| + |
| +func TestHALostLeaseDuringOrdinaryStop(t *testing.T) { |
| + s, e, r := lostTestEntry(t) |
| + r.lost.Store(false) |
| + s.a.mu.Lock() |
| + s.a.beginStopLocked(e, StopIdle) |
| + s.a.mu.Unlock() |
| + <-r.entered |
| + r.lost.Store(true) |
| + assertLostResponse(t, s) |
| +} |
diff --git a/internal/activator/harelease.go b/internal/activator/harelease.go| index 89d87d419..bebf4ecc5 100644 |
| --- a/internal/activator/harelease.go |
| +++ b/internal/activator/harelease.go |
| @@ -210,6 +210,13 @@ func (a *Service) releaseHAClean(ctx context.Context, e *actEntry) error { |
| // The marker's PUT gets its own budget too, as Close's release does: |
| // a final sync that ran long must not leave it a dead context. |
| mctx, mcancel := context.WithTimeout(context.WithoutCancel(ctx), haMarkerBudget) |
| + a.mu.Lock() |
| + if haUnexpectedLoss(e, servingError(e)) { |
| + a.latchHALossLocked(e) |
| + } |
| + // After this point ErrSpent is the normal marker release's own result. |
| + e.haReleasing = true |
| + a.mu.Unlock() |
| merr := hr.ReleaseMarker(mctx, m) |
| mcancel() |
| if merr == nil { |
diff --git a/internal/activator/rootfs_service.go b/internal/activator/rootfs_service.go| index 0566bbd9c..a95ed36ac 100644 |
| --- a/internal/activator/rootfs_service.go |
| +++ b/internal/activator/rootfs_service.go |
| @@ -999,6 +999,9 @@ func (a *Service) residentLeaseLostLocked(e *actEntry, err error) (gens []uint64 |
| if a.entries[e.host] != e { |
| return nil, nil |
| } |
| + if haUnexpectedLoss(e, err) { |
| + a.latchHALossLocked(e) |
| + } |
| oneShots = a.stopOneShotsAtLeaseLocked(e, e.route, true) |
| if !e.route.Resident() { |
| if len(oneShots) > 0 { |