ha: revalidate silent holders without replaying requests
Co-Authored-By: GPT-6 Astra <noreply@openai.com>
internal/activator/hacache.go+1 −1internal/activator/haforward.go+6 −2internal/activator/hasuspect_test.go+170 −0internal/edge/forwardha.go+75 −9internal/edge/forwardha_service_test.go+227 −0internal/edge/forwardha_test.go+260 −5
Intent
<task-notification> <task-id>a0891111dad85f92d</task-id> <tool-use-id>toolu_01EN9pfTUfzCsE1uuY8bWaBn</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/5555438b-7fa2-408d-b2c4-9fa87ea89332/tasks/a0891111dad85f92d.output</output-file> <status>completed</status> <summary>Agent "F-B re-review R3 (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.** I didn't run any tests; this verdict comes from reading the code at bf234169. - **P1-1 residual (regional names): ADDRESSED.** `regional.go:163-165` now checks for an eligible local holder before the zero-route 503 at :170-172, in the same order as `haingress.go:76`. Witness: `TestHAIngressRegionalReceiver` (`haingress_internal_test.go:213`), across 6 projection states, each run on an eligible and an ineligible box. - **Ineligible box with a stale local row:** it can't serve a regional name locally. `regionalHALocal` checks `localPoolEligible(up.route)` first (`regional.go:188`). A zero projection gets a 503. An unknown one is refused by `regionalRefuse` on a hop, or by `routeHAIngress` and the activator gate on a direct request. - **P3 (unopened obligation store): ADDRESSED.** `lease.ObligationStoreReady` (`owed.go:176`) is checked at `poolwithdrawal.go:155-157`, ahead of both withdrawal completion paths. Witness: fresh-process modes `store-unopened` and `never-held-store-unopened`. - **New P1/P2:** none. Review: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-g2-fixes/.superpowers/sdd/2026-11-06-region-ha-g2-fixes/fb-review-r3.md</result> <usage><subagent_tokens>61078</subagent_tokens><tool_uses>7</tool_uses><duration_ms>81823</duration_ms></usage> </task-notification>
diff --git a/internal/activator/hacache.go b/internal/activator/hacache.go| index 64144017f..81a9d4c61 100644 |
| --- a/internal/activator/hacache.go |
| +++ b/internal/activator/hacache.go |
| @@ -436,7 +436,7 @@ func (c *holderCache) holderResult(host, self string, res edge.ForwardResult, ac |
| switch { |
| case res.Outcome == edge.ForwardNotInView: |
| drop() |
| - case res.Outcome == edge.ForwardUnreachable: |
| + case res.Outcome == edge.ForwardUnreachable || res.Outcome == edge.ForwardSilent: |
| if el != nil && res.Gen != 0 { |
| e := el.Value.(*holderEntry) |
| if e.ref != "" && !e.suspect { |
diff --git a/internal/activator/haforward.go b/internal/activator/haforward.go| index e06771c01..b4bb2209a 100644 |
| --- a/internal/activator/haforward.go |
| +++ b/internal/activator/haforward.go |
| @@ -254,19 +254,23 @@ func otherHolder(v hafresh.View, self hafresh.Self, now time.Time) string { |
| // NoteForward follows a forward's outcome for host: a named box out of |
| // view, an answer of "none", and a 503 that names nobody drop the entry; an |
| // answer naming a box sets it, unless the box is this one, which drops it |
| -// (this box is never forwarded to). A box that could not be connected to |
| +// (this box is never forwarded to). An unreachable or silent holder |
| // is suspect for holderSuspectTTL, unless the forward's generation is |
| // older than the entry's; any other answer from a box clears a suspect |
| // entry: that box is the holder. |
| func (a *Service) NoteForward(host string, res edge.ForwardResult) { |
| + if res.Outcome == edge.ForwardCanceled { |
| + return |
| + } |
| self, _ := boxSelfRef(a.backend) |
| accepted := false |
| note := func() { |
| peerResult := res |
| - if res.Kind == edge.Holder && res.Outcome == edge.ForwardUnreachable { |
| + if res.Kind == edge.Holder && (res.Outcome == edge.ForwardUnreachable || res.Outcome == edge.ForwardSilent) { |
| // N-HA15: a release found by the suspect re-read must not send |
| // placement back to this failed box. Reuse N-HA12's classifier. |
| peerResult.Kind = edge.Placement |
| + peerResult.Outcome = edge.ForwardUnreachable |
| } |
| a.peers.note(peerResult, a.holders.clock()) |
| accepted = true |
diff --git a/internal/activator/hasuspect_test.go b/internal/activator/hasuspect_test.go| index 87abd3c98..b82a8d145 100644 |
| --- a/internal/activator/hasuspect_test.go |
| +++ b/internal/activator/hasuspect_test.go |
| @@ -2,12 +2,14 @@ package activator |
| import ( |
| "context" |
| + "fmt" |
| "net/http" |
| "net/http/httptest" |
| "sync/atomic" |
| "testing" |
| "time" |
| + "github.com/carlosframework/platform/internal/boxchoice" |
| "github.com/carlosframework/platform/internal/edge" |
| "github.com/carlosframework/platform/internal/hafresh" |
| ) |
| @@ -636,3 +638,171 @@ func TestSuspectWindowRevalidationTimeout(t *testing.T) { |
| t.Fatalf("after timeout: %+v, reads=%d, local wake=%v", d, reads.Load(), s.wokeHere()) |
| } |
| } |
| + |
| +func TestCanceledHolderDoesNotConfirm(t *testing.T) { |
| + s := haHeldByB(t) |
| + d := s.decide() |
| + s.note(d, edge.ForwardResult{Outcome: edge.ForwardUnreachable}) |
| + s.a.holders.mu.Lock() |
| + before := *s.a.holders.holders[s.rt.Host].Value.(*holderEntry) |
| + s.a.holders.mu.Unlock() |
| + var departures atomic.Int32 |
| + s.a.OnDepartureSuspect = func(string) { departures.Add(1) } |
| + for _, gen := range []uint64{d.Gen, before.gen} { |
| + for _, result := range []edge.ForwardResult{ |
| + {Outcome: edge.ForwardCanceled, Ref: d.Ref, Gen: gen}, |
| + {Outcome: edge.ForwardCanceled, Ref: d.Ref, Gen: gen, Status: 200, Holder: d.Ref}, |
| + } { |
| + s.a.NoteForward(s.rt.Host, result) |
| + } |
| + } |
| + s.a.holders.mu.Lock() |
| + after := *s.a.holders.holders[s.rt.Host].Value.(*holderEntry) |
| + s.a.holders.mu.Unlock() |
| + if before != after || departures.Load() != 0 || s.wokeHere() { |
| + t.Fatalf("cancellation changed suspect: before=%+v after=%+v departures=%d", before, after, departures.Load()) |
| + } |
| + s.a.holders.set(s.rt.Host, "c") |
| + s.note(d, edge.ForwardResult{Outcome: edge.ForwardCanceled}) |
| + if ref, positive, _ := s.a.holders.get(s.rt.Host); ref != "c" || !positive { |
| + t.Fatal("cancellation replaced newer holder") |
| + } |
| +} |
| + |
| +func TestSilentHolderRevalidatesOnce(t *testing.T) { |
| + for _, answer := range []string{"held", "absent", "released", "expired", "error"} { |
| + t.Run(answer, func(t *testing.T) { |
| + s := haHeldByB(t) |
| + d := s.decide() |
| + var departures atomic.Int32 |
| + s.a.OnDepartureSuspect = func(string) { departures.Add(1) } |
| + s.a.NoteForward(s.rt.Host, edge.ForwardResult{Outcome: edge.ForwardSilent, Ref: d.Ref, Gen: d.Gen, PeerGen: d.PeerGen}) |
| + if got, hit := s.a.holders.peek(s.rt.Host); !hit || !got.Refuse { |
| + t.Fatalf("silent holder not suspect: %+v", got) |
| + } |
| + if !s.a.peers.snapshot(time.Now()).Suspect[d.Ref] || departures.Load() != 0 { |
| + t.Fatal("silence must exclude placement without departure evidence") |
| + } |
| + old := readHolderLock |
| + var reads atomic.Int32 |
| + readHolderLock = func(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) { |
| + reads.Add(1) |
| + if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > holderReadTimeout { |
| + t.Error("unbounded suspect read") |
| + } |
| + switch answer { |
| + case "absent": |
| + return hafresh.View{Absent: true}, nil |
| + case "released": |
| + return hafresh.DecodeLock(markerBody(t, "b", "i-b", haFixOf(s.b).lifetime, 5, true), "released") |
| + case "expired": |
| + return hafresh.DecodeLock(leaseBody(t, heldByB, time.Now().Add(-time.Minute)), "expired") |
| + case "error": |
| + <-ctx.Done() |
| + return hafresh.View{}, ctx.Err() |
| + default: |
| + return old(ctx, bucket, prefix, region) |
| + } |
| + } |
| + t.Cleanup(func() { readHolderLock = old }) |
| + out := s.concurrently(50) |
| + free := answer == "absent" || answer == "released" |
| + for range 50 { |
| + got := recv(t, out) |
| + if got.Refuse == free || got.Ref != "" { |
| + t.Fatalf("after silence: %+v, free=%v", got, free) |
| + } |
| + } |
| + if reads.Load() != 1 || s.wokeHere() { |
| + t.Fatalf("reads=%d local wake=%v", reads.Load(), s.wokeHere()) |
| + } |
| + if free { |
| + got := s.a.ForwardTarget(t.Context(), s.rt, func() boxchoice.WakeSnapshot { return placementSnapshot(time.Now()) }) |
| + if got.Ref != "" || got.Refuse || got.Unavailable { |
| + t.Fatalf("eligible local placement not available: %+v", got) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestSlowHolderResponseIsNotAbortedCacheGeneration(t *testing.T) { |
| + for _, change := range []string{"same holder", "new holder", "acquire", "revalidation"} { |
| + t.Run(change, func(t *testing.T) { |
| + s := haHeldByB(t) |
| + d := s.decide() |
| + s.note(d, edge.ForwardResult{Outcome: edge.ForwardSilent}) |
| + if change == "new holder" { |
| + s.a.holders.set(s.rt.Host, "c") |
| + } |
| + if change == "acquire" { |
| + s.a.holders.drop(s.rt.Host) |
| + } |
| + if change == "revalidation" { |
| + s.a.holders.mu.Lock() |
| + s.a.holders.removeLocked(s.a.holders.holders[s.rt.Host]) |
| + s.a.holders.flights[s.rt.Host] = &holderFlight{suspect: d.Ref} |
| + s.a.holders.mu.Unlock() |
| + } |
| + s.note(d, edge.ForwardResult{Outcome: edge.ForwardDone, Status: 201}) |
| + ref, positive, found := s.a.holders.get(s.rt.Host) |
| + switch change { |
| + case "same holder", "revalidation": |
| + if !positive || ref != d.Ref { |
| + t.Fatalf("valid headers did not clear own suspicion: %q", ref) |
| + } |
| + case "new holder": |
| + if !positive || ref != "c" { |
| + t.Fatal("old response replaced new holder") |
| + } |
| + case "acquire": |
| + if found { |
| + t.Fatal("old response resurrected acquired host") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestSilentHolderExpiredLeaseStillRequiresProof(t *testing.T) { |
| + for _, terminated := range []bool{false, true} { |
| + t.Run(fmt.Sprint(terminated), func(t *testing.T) { |
| + s := haHeldByB(t) |
| + clk := &fakeClock{t: time.Now()} |
| + s.a.holders.now = clk.now |
| + d := s.decide() |
| + s.note(d, edge.ForwardResult{Outcome: edge.ForwardSilent}) |
| + oracle := &terminatedOracle{yes: map[string]bool{"i-b": terminated}} |
| + s.b.OwnerTerminated = oracle.terminated |
| + putLockFor(t, s.b, s.rt, leaseBody(t, heldByB, time.Now().Add(-time.Minute))) |
| + if d := s.decide(); !d.Refuse || s.wokeHere() || len(oracle.calls()) != 0 { |
| + t.Fatal("silence granted takeover") |
| + } |
| + clk.advance(holderSuspectTTL + time.Millisecond) |
| + if d := s.decide(); d.Refuse || d.Ref != "" { |
| + t.Fatalf("expired window: %+v", d) |
| + } |
| + served := false |
| + rec := httptest.NewRecorder() |
| + s.a.ServeHTTP(rec, httptest.NewRequest("GET", "http://"+s.rt.Host+"/", nil), s.rt, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { served = true; w.WriteHeader(http.StatusOK) })) |
| + if served != terminated || (!terminated && rec.Code != http.StatusServiceUnavailable) { |
| + t.Fatalf("terminated=%v served=%v status=%d", terminated, served, rec.Code) |
| + } |
| + if got := oracle.calls(); len(got) != 1 || got[0] != "i-b" { |
| + t.Fatalf("termination proof calls: %v", got) |
| + } |
| + v, err := hafresh.DecodeLock(lockBodyOf(s.b, s.rt), "x") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + owner, ok := hafresh.ParseOwner(v.Lock.Owner) |
| + want := "b" |
| + if terminated { |
| + want = "a" |
| + } |
| + if !ok || owner.Ref != want { |
| + t.Fatalf("lock owner %q, want %s", owner.Ref, want) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/edge/forwardha.go b/internal/edge/forwardha.go| index 6a2671bf2..d959b91c4 100644 |
| --- a/internal/edge/forwardha.go |
| +++ b/internal/edge/forwardha.go |
| @@ -22,6 +22,7 @@ import ( |
| "fmt" |
| "net" |
| "net/http" |
| + "net/http/httptrace" |
| "sync" |
| "time" |
| @@ -77,7 +78,7 @@ type ForwardDecision struct { |
| Gen uint64 |
| } |
| -// ForwardOutcome is how one forward ended. |
| +// ForwardOutcome describes a forward's result or an in-flight observation. |
| type ForwardOutcome int |
| const ( |
| @@ -89,13 +90,14 @@ const ( |
| // (answerHolderUnreachable). |
| ForwardUnreachable |
| // ForwardDone: the request went to the named box and its answer, whatever |
| - // it was, was relayed, or this box refused the hop itself (Status 0), or |
| - // a Holder request was cancelled or waited out its dial queue (Status 0). |
| + // it was, was relayed, or this box refused the hop itself (Status 0). |
| ForwardDone |
| - // ForwardCanceled: a Placement or Recovery request's client left, or its |
| - // dial timed out in the queue without reaching the target. Neither is |
| - // evidence of target reachability. Holder keeps P1b-2's ForwardDone. |
| + // ForwardCanceled: the client left before final headers, or the dial |
| + // timed out in the queue. Neither is evidence of target reachability. |
| ForwardCanceled |
| + // ForwardSilent: a connected holder sent no final headers within |
| + // holderHeaderSuspectAfter. The original request is still running. |
| + ForwardSilent |
| ) |
| // ForwardResult is what NoteForward is told. Ref and Gen are the decision's: |
| @@ -243,8 +245,12 @@ func (e *Edge) forwardHAAndNote(w http.ResponseWriter, r *http.Request, host str |
| }} |
| r = r.WithContext(context.WithValue(r.Context(), forwardDialObservationKey{}, observation)) |
| } |
| - res := e.forwardHA(w, r, host, d) |
| - fw.NoteForward(rt.Host, res) |
| + res := e.forwardHAObserved(w, r, host, d, func(res ForwardResult) { |
| + fw.NoteForward(rt.Host, res) |
| + }) |
| + if d.Kind != Holder || res.Status == 0 { |
| + fw.NoteForward(rt.Host, res) |
| + } |
| if observation != nil { |
| observation.update(false, res.Outcome == ForwardCanceled) |
| } |
| @@ -261,6 +267,10 @@ func (e *Edge) forwardHAAndNote(w http.ResponseWriter, r *http.Request, host str |
| // It repeats the arrived-hop guard: a verified hop is never forwarded, so a |
| // forwarding loop needs this line and frontForwardHA's to be wrong at once. |
| func (e *Edge) forwardHA(w http.ResponseWriter, r *http.Request, host string, d ForwardDecision) ForwardResult { |
| + return e.forwardHAObserved(w, r, host, d, nil) |
| +} |
| + |
| +func (e *Edge) forwardHAObserved(w http.ResponseWriter, r *http.Request, host string, d ForwardDecision, note func(ForwardResult)) ForwardResult { |
| ref := d.Ref |
| res := ForwardResult{Outcome: ForwardNotInView, Ref: ref, Gen: d.Gen, Kind: d.Kind, PeerGen: d.PeerGen} |
| m := e.homes.Load() |
| @@ -277,8 +287,17 @@ func (e *Edge) forwardHA(w http.ResponseWriter, r *http.Request, host string, d |
| return res |
| } |
| res.Outcome = ForwardDone |
| + stopObservation := func() {} |
| + if d.Kind == Holder && note != nil { |
| + silent := res |
| + silent.Outcome = ForwardSilent |
| + var ctx context.Context |
| + ctx, stopObservation = observeHolderHeaders(r.Context(), func() { note(silent) }) |
| + r = r.WithContext(ctx) |
| + defer stopObservation() |
| + } |
| onError := func(w http.ResponseWriter, r *http.Request, err error) { |
| - if res.Kind != Holder && (r.Context().Err() != nil || errors.Is(err, errForwardDialQueued)) { |
| + if res.Status == 0 && (r.Context().Err() != nil || errors.Is(err, errForwardDialQueued)) { |
| res.Outcome = ForwardCanceled |
| } |
| var connect *forwardConnectError |
| @@ -298,13 +317,60 @@ func (e *Edge) forwardHA(w http.ResponseWriter, r *http.Request, host string, d |
| w.WriteHeader(http.StatusBadGateway) |
| } |
| onResponse := func(resp *http.Response) { |
| + // ModifyResponse sees final headers, including 101; 100/103 bypass it. |
| + stopObservation() |
| res.Status = resp.StatusCode |
| res.Holder = resp.Header.Get(holderHeader) |
| + if d.Kind == Holder && note != nil { |
| + note(res) |
| + } |
| } |
| e.hopTo(w, r, host, dial, ref, key, "forward", e.forwardTransport(dial), onError, onResponse) |
| return res |
| } |
| +const holderHeaderSuspectAfter = 3 * time.Second |
| + |
| +// Observation never cancels the transport. Joining at final headers orders |
| +// their confirmation after any suspicion already being reported. Joining on |
| +// completion also covers proxy panics when a streaming client disconnects. |
| +func observeHolderHeaders(ctx context.Context, report func()) (context.Context, func()) { |
| + connected := make(chan struct{}) |
| + var connectedOnce sync.Once |
| + ctx = httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{GotConn: func(httptrace.GotConnInfo) { |
| + connectedOnce.Do(func() { close(connected) }) |
| + }}) |
| + stop, done := make(chan struct{}), make(chan struct{}) |
| + timer := time.NewTimer(holderHeaderSuspectAfter) |
| + go func() { |
| + defer close(done) |
| + defer timer.Stop() |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-stop: |
| + return |
| + case <-timer.C: |
| + } |
| + // Time spent waiting for a connection says nothing about the target. |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-stop: |
| + return |
| + case <-connected: |
| + } |
| + if ctx.Err() == nil { |
| + report() |
| + } |
| + }() |
| + var stopOnce sync.Once |
| + return ctx, func() { |
| + stopOnce.Do(func() { close(stop) }) |
| + <-done |
| + } |
| +} |
| + |
| // answerHolderUnreachable is the answer to a request whose holder could not |
| // be connected to, now or moments ago: 503, Retry-After: 10. |
| func answerHolderUnreachable(w http.ResponseWriter, r *http.Request) { |
diff --git a/internal/edge/forwardha_service_test.go b/internal/edge/forwardha_service_test.go| new file mode 100644 |
| index 000000000..610da62ce |
| --- /dev/null |
| +++ b/internal/edge/forwardha_service_test.go |
| @@ -0,0 +1,227 @@ |
| +package edge_test |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/lease/locktest" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +func holderService(t *testing.T) (*activator.Service, registry.Route, *locktest.LockFixture) { |
| + t.Helper() |
| + fx := locktest.NewLockFixture(t) |
| + cfg := activator.Config{Bucket: fx.Bucket, Region: "eu-west-1", Self: func() hafresh.Self { return hafresh.Self{Ref: "annie", IID: "i-a"} }} |
| + a := activator.New(cfg, &activator.ExecBackend{Cfg: cfg}, nil) |
| + t.Cleanup(func() { a.Shutdown(context.Background()) }) |
| + rt := registry.Route{Host: "ha.forward.test", HA: true, Kind: "instance", Hibernate: true} |
| + body, err := json.Marshal(hafresh.Lock{Owner: hafresh.OwnerFor(hafresh.Self{Ref: "betty", IID: "i-b"}, 1, true), ExpiresAt: time.Now().Add(time.Hour)}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.PutLock(activator.HibernatePrefix("", rt.Host), body) |
| + return a, rt, fx |
| +} |
| + |
| +func TestSilentHolderRevalidatesOnceThroughEdge(t *testing.T) { |
| + a, rt, fx := holderService(t) |
| + d := a.ForwardTarget(t.Context(), rt, nil) |
| + if d.Ref != "betty" { |
| + t.Fatalf("discovery: %+v", d) |
| + } |
| + var writes, departures atomic.Int32 |
| + a.OnDepartureSuspect = func(string) { departures.Add(1) } |
| + started := make(chan struct{}) |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + defer cancel() |
| + forward := edge.ForwardHolderForTest(t, a, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + writes.Add(1) |
| + close(started) |
| + <-r.Context().Done() |
| + })) |
| + done := make(chan edge.ForwardResult, 1) |
| + go func() { done <- forward(ctx, d) }() |
| + select { |
| + case <-started: |
| + case got := <-done: |
| + t.Fatalf("forward failed: %+v", got) |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("no request") |
| + } |
| + deadline := time.Now().Add(4 * time.Second) |
| + for { |
| + got, hit := a.ForwardTargetFromMemory(rt, nil) |
| + if hit && got.Refuse { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + cancel() |
| + <-done |
| + t.Fatal("connected silent holder not suspect before client timeout") |
| + } |
| + time.Sleep(time.Millisecond) |
| + } |
| + results := make(chan edge.ForwardDecision, 50) |
| + for range 50 { |
| + go func() { results <- a.ForwardTarget(t.Context(), rt, nil) }() |
| + } |
| + for range 50 { |
| + if got := <-results; !got.Refuse { |
| + t.Fatalf("silence granted local service: %+v", got) |
| + } |
| + } |
| + reads := 0 |
| + for _, request := range fx.Requests() { |
| + if request == "GET "+activator.HibernatePrefix("", rt.Host)+"/lock.json" { |
| + reads++ |
| + } |
| + if len(request) >= 4 && request[:4] == "PUT " { |
| + t.Fatalf("silence caused acquire: %s", request) |
| + } |
| + } |
| + if reads != 2 || writes.Load() != 1 || departures.Load() != 0 { |
| + t.Fatalf("reads=%d writes=%d departures=%d", reads, writes.Load(), departures.Load()) |
| + } |
| + cancel() |
| + if got := <-done; got.Outcome != edge.ForwardCanceled { |
| + t.Fatalf("canceled original POST: %+v", got) |
| + } |
| + if got, hit := a.ForwardTargetFromMemory(rt, nil); !hit || !got.Refuse { |
| + t.Fatal("cancel resurrected holder") |
| + } |
| +} |
| + |
| +func TestSlowHolderResponseIsNotAbortedThroughEdge(t *testing.T) { |
| + for _, holder := range []string{"", "none"} { |
| + t.Run("503/"+holder, func(t *testing.T) { |
| + a, rt, _ := holderService(t) |
| + d := a.ForwardTarget(t.Context(), rt, nil) |
| + forward := edge.ForwardHolderForTest(t, a, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| + w.Header().Set("X-Carlos-Holder", holder) |
| + w.WriteHeader(http.StatusServiceUnavailable) |
| + })) |
| + if got := forward(t.Context(), d); got.Status != 503 { |
| + t.Fatalf("forward: %+v", got) |
| + } |
| + if got, hit := a.ForwardTargetFromMemory(rt, nil); hit { |
| + t.Fatalf("503 did not drop holder: %+v", got) |
| + } |
| + }) |
| + } |
| + for _, newer := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "same holder", true: "new holder"}[newer], func(t *testing.T) { |
| + a, rt, _ := holderService(t) |
| + d := a.ForwardTarget(t.Context(), rt, nil) |
| + headers, body := make(chan struct{}), make(chan struct{}) |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + defer cancel() |
| + forward := edge.ForwardHolderForTest(t, a, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(http.StatusEarlyHints) |
| + select { |
| + case <-headers: |
| + case <-r.Context().Done(): |
| + return |
| + } |
| + w.WriteHeader(http.StatusCreated) |
| + w.(http.Flusher).Flush() |
| + select { |
| + case <-body: |
| + case <-r.Context().Done(): |
| + return |
| + } |
| + io.WriteString(w, "one response") |
| + })) |
| + done := make(chan edge.ForwardResult, 1) |
| + go func() { done <- forward(ctx, d) }() |
| + time.Sleep(3200 * time.Millisecond) |
| + if got, hit := a.ForwardTargetFromMemory(rt, nil); !hit || !got.Refuse { |
| + cancel() |
| + <-done |
| + t.Fatalf("103 confirmed holder: %+v", got) |
| + } |
| + want := "betty" |
| + if newer { |
| + want = "carol" |
| + a.NoteForward(rt.Host, edge.ForwardResult{Outcome: edge.ForwardDone, Holder: want}) |
| + } |
| + close(headers) |
| + deadline := time.Now().Add(time.Second) |
| + for { |
| + got, hit := a.ForwardTargetFromMemory(rt, nil) |
| + if hit && got.Ref == want && !got.Refuse { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + cancel() |
| + <-done |
| + t.Fatalf("final headers: %+v, want %s", got, want) |
| + } |
| + time.Sleep(time.Millisecond) |
| + } |
| + close(body) |
| + if got := <-done; got.Status != 201 { |
| + t.Fatalf("stream: %+v", got) |
| + } |
| + if got, hit := a.ForwardTargetFromMemory(rt, nil); !hit || got.Ref != want { |
| + t.Fatalf("old completion overwrote holder: %+v", got) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type pausedSilentForwarder struct { |
| + *activator.Service |
| + started, release chan struct{} |
| +} |
| + |
| +func (f *pausedSilentForwarder) NoteForward(host string, res edge.ForwardResult) { |
| + if res.Outcome == edge.ForwardSilent { |
| + close(f.started) |
| + <-f.release |
| + } |
| + f.Service.NoteForward(host, res) |
| +} |
| + |
| +func TestSilentHolderNewOwnershipDuringTimer(t *testing.T) { |
| + for _, owner := range []string{"carol", "annie"} { |
| + t.Run(owner, func(t *testing.T) { |
| + a, rt, _ := holderService(t) |
| + d := a.ForwardTarget(t.Context(), rt, nil) |
| + fw := &pausedSilentForwarder{Service: a, started: make(chan struct{}), release: make(chan struct{})} |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + defer cancel() |
| + forward := edge.ForwardHolderForTest(t, fw, http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { <-r.Context().Done() })) |
| + done := make(chan edge.ForwardResult, 1) |
| + go func() { done <- forward(ctx, d) }() |
| + select { |
| + case <-fw.started: |
| + case <-time.After(4 * time.Second): |
| + close(fw.release) |
| + cancel() |
| + <-done |
| + t.Fatal("timer did not fire") |
| + } |
| + // A new remote owner replaces the hint; local ownership drops it. |
| + a.NoteForward(rt.Host, edge.ForwardResult{Outcome: edge.ForwardDone, Ref: d.Ref, Gen: d.Gen, Holder: owner}) |
| + close(fw.release) |
| + cancel() |
| + <-done |
| + got, hit := a.ForwardTargetFromMemory(rt, nil) |
| + if owner == "annie" { |
| + if hit { |
| + t.Fatalf("timer resurrected local acquire's dropped hint: %+v", got) |
| + } |
| + } else if !hit || got.Ref != owner || got.Refuse { |
| + t.Fatalf("timer replaced newer owner: %+v", got) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/edge/forwardha_test.go b/internal/edge/forwardha_test.go| index a1d7c3445..b7e3420ea 100644 |
| --- a/internal/edge/forwardha_test.go |
| +++ b/internal/edge/forwardha_test.go |
| @@ -22,6 +22,7 @@ import ( |
| "net" |
| "net/http" |
| "net/http/httptest" |
| + "net/http/httptrace" |
| "path/filepath" |
| "strings" |
| "sync" |
| @@ -1187,8 +1188,8 @@ func TestForwardHAQueuedPastTheDeadlineIsNotUnreachable(t *testing.T) { |
| t.Fatalf("GET = %d Retry-After %q %q, want the unreachable 503", resp.StatusCode, resp.Header.Get("Retry-After"), body) |
| } |
| notes := x.aAct.noted() |
| - if len(notes) == 0 || notes[len(notes)-1] != (fwNote{fwHost, ForwardResult{Outcome: ForwardDone, Ref: "betty"}}) { |
| - t.Fatalf("notes = %+v, want ForwardDone with no status last (not ForwardUnreachable)", notes) |
| + if len(notes) == 0 || notes[len(notes)-1] != (fwNote{fwHost, ForwardResult{Outcome: ForwardCanceled, Ref: "betty"}}) { |
| + t.Fatalf("notes = %+v, want ForwardCanceled with no status last (not ForwardUnreachable)", notes) |
| } |
| if n := x.bApp.n.Load(); n != 0 { |
| t.Fatalf("betty's app saw %d requests", n) |
| @@ -1369,9 +1370,7 @@ func TestForwardHAClientCanceledOutcome(t *testing.T) { |
| if mode == "connect failure" { |
| want, wantStatus = ForwardUnreachable, http.StatusServiceUnavailable |
| } else if mode != "target hang" { |
| - if kind != Holder { |
| - want = ForwardCanceled |
| - } |
| + want = ForwardCanceled |
| if mode == "queued" { |
| wantStatus = http.StatusServiceUnavailable |
| } |
| @@ -1405,3 +1404,259 @@ func TestForwardDialObservationCompletionOrder(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +// ResponseRecorder treats the first 1xx as final; a real HTTP server does not. |
| +type fwFinalRecorder struct{ *httptest.ResponseRecorder } |
| + |
| +func (w fwFinalRecorder) WriteHeader(status int) { |
| + if status >= 100 && status < 200 && status != http.StatusSwitchingProtocols { |
| + return |
| + } |
| + w.ResponseRecorder.WriteHeader(status) |
| +} |
| + |
| +// ForwardHolderForTest keeps the real signed-hop proxy and callback path while |
| +// redirecting its TLS transport to a loopback test server. The external-package |
| +// witness uses this to connect the edge to the real activator without a cycle. |
| +func ForwardHolderForTest(t *testing.T, fw HAForwarder, handler http.Handler, checks ...func(*httptest.ResponseRecorder)) func(context.Context, ForwardDecision) ForwardResult { |
| + t.Helper() |
| + x := newFwScene(t, fwOpts{}) |
| + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if _, err := io.Copy(io.Discard, r.Body); err != nil { |
| + return |
| + } |
| + handler.ServeHTTP(w, r) |
| + })) |
| + t.Cleanup(srv.Close) |
| + tr := srv.Client().Transport.(*http.Transport).Clone() |
| + tr.TLSClientConfig.ServerName = "example.com" |
| + tr.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) { |
| + return (&net.Dialer{}).DialContext(ctx, network, srv.Listener.Addr().String()) |
| + } |
| + t.Cleanup(tr.CloseIdleConnections) |
| + dial, ok := x.a.homes.boxInView("betty", time.Now()) |
| + if !ok { |
| + t.Fatal("betty out of view") |
| + } |
| + x.a.edge.forwardTransports.Store(dial, tr) |
| + return func(ctx context.Context, d ForwardDecision) ForwardResult { |
| + r := httptest.NewRequest(http.MethodPost, "https://"+fwHost+"/write", strings.NewReader("one write")).WithContext(ctx) |
| + rec := httptest.NewRecorder() |
| + result := x.a.edge.forwardHAAndNote(fwFinalRecorder{rec}, r, fwHost, registry.Route{Host: fwHost}, fw, d) |
| + if ctx.Err() == nil { |
| + for _, check := range checks { |
| + check(rec) |
| + } |
| + } |
| + return result |
| + } |
| +} |
| + |
| +func TestCanceledHolderDoesNotConfirm(t *testing.T) { |
| + x := newFwScene(t, fwOpts{}) |
| + dial, _ := x.a.homes.boxInView("betty", time.Now()) |
| + for _, mode := range []string{"before dial", "queue", "queue deadline", "after connect"} { |
| + t.Run(mode, func(t *testing.T) { |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + defer cancel() |
| + if mode == "before dial" { |
| + cancel() |
| + } |
| + tr := &http.Transport{} |
| + tr.RegisterProtocol("https", fwRoundTripFunc(func(*http.Request) (*http.Response, error) { |
| + if mode == "queue deadline" { |
| + return nil, &forwardConnectError{errForwardDialQueued} |
| + } |
| + cancel() |
| + if mode == "queue" { |
| + return nil, &forwardConnectError{fmt.Errorf("%w: %w", errForwardDialQueued, ctx.Err())} |
| + } |
| + return nil, ctx.Err() |
| + })) |
| + x.a.edge.forwardTransports.Store(dial, tr) |
| + fw := &fwAct{} |
| + r := httptest.NewRequest(http.MethodPost, "https://"+fwHost+"/write", strings.NewReader("one write")).WithContext(ctx) |
| + d := ForwardDecision{Ref: "betty", Gen: 7, PeerGen: 11} |
| + got := x.a.edge.forwardHAAndNote(httptest.NewRecorder(), r, fwHost, registry.Route{Host: fwHost}, fw, d) |
| + if got.Outcome != ForwardCanceled || got.Status != 0 { |
| + t.Fatalf("canceled holder result: %+v", got) |
| + } |
| + if notes := fw.noted(); len(notes) != 1 || notes[0].res != got { |
| + t.Fatalf("synthetic reachability evidence: %+v", notes) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestSlowHolderResponseIsNotAborted(t *testing.T) { |
| + for _, informational := range []bool{false, true} { |
| + t.Run(fmt.Sprint(informational), func(t *testing.T) { |
| + fw := &fwAct{} |
| + started, headers, body := make(chan struct{}), make(chan struct{}), make(chan struct{}) |
| + var writes atomic.Int32 |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + defer cancel() |
| + forward := ForwardHolderForTest(t, fw, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + writes.Add(1) |
| + if informational { |
| + w.WriteHeader(http.StatusEarlyHints) |
| + } |
| + close(started) |
| + select { |
| + case <-headers: |
| + case <-r.Context().Done(): |
| + return |
| + } |
| + w.WriteHeader(http.StatusCreated) |
| + w.(http.Flusher).Flush() |
| + select { |
| + case <-body: |
| + case <-r.Context().Done(): |
| + return |
| + } |
| + io.WriteString(w, "original response") |
| + }), func(rec *httptest.ResponseRecorder) { |
| + if rec.Code != http.StatusCreated || rec.Body.String() != "original response" { |
| + t.Errorf("original response not delivered: %d %q", rec.Code, rec.Body.String()) |
| + } |
| + }) |
| + done := make(chan ForwardResult, 1) |
| + go func() { done <- forward(ctx, ForwardDecision{Ref: "betty", Gen: 7, PeerGen: 11}) }() |
| + select { |
| + case <-started: |
| + case got := <-done: |
| + t.Fatalf("request ended before reaching server: %+v", got) |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("server never received request") |
| + } |
| + time.Sleep(3200 * time.Millisecond) |
| + notes := fw.noted() |
| + if len(notes) != 1 || notes[0].res.Outcome != ForwardSilent || notes[0].res.Gen != 7 || notes[0].res.Ref != "betty" || notes[0].host != fwHost { |
| + cancel() |
| + <-done |
| + t.Fatalf("no final headers must report silence once: %+v", notes) |
| + } |
| + select { |
| + case got := <-done: |
| + t.Fatalf("slow request aborted: %+v", got) |
| + default: |
| + } |
| + if !informational { |
| + // The three-second observation must still allow a twenty-second app. |
| + time.Sleep(17 * time.Second) |
| + } |
| + close(headers) |
| + deadline := time.Now().Add(time.Second) |
| + for len(fw.noted()) < 2 && time.Now().Before(deadline) { |
| + time.Sleep(time.Millisecond) |
| + } |
| + notes = fw.noted() |
| + if len(notes) != 2 || notes[1].res.Status != http.StatusCreated || notes[1].res.Outcome != ForwardDone { |
| + cancel() |
| + <-done |
| + t.Fatalf("final headers not observed before body: %+v", notes) |
| + } |
| + select { |
| + case got := <-done: |
| + t.Fatalf("stream interrupted: %+v", got) |
| + default: |
| + } |
| + close(body) |
| + if got := <-done; got.Status != http.StatusCreated || got.Outcome != ForwardDone || writes.Load() != 1 { |
| + t.Fatalf("original POST: %+v, writes=%d", got, writes.Load()) |
| + } |
| + if len(fw.noted()) != 2 { |
| + t.Fatalf("duplicate observation: %+v", fw.noted()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestCanceledHolderDoesNotConfirmNearThreshold(t *testing.T) { |
| + fw := &fwAct{} |
| + started := make(chan struct{}) |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + defer cancel() |
| + forward := ForwardHolderForTest(t, fw, http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { |
| + close(started) |
| + <-r.Context().Done() |
| + })) |
| + done := make(chan ForwardResult, 1) |
| + go func() { done <- forward(ctx, ForwardDecision{Ref: "betty", Gen: 7}) }() |
| + select { |
| + case <-started: |
| + case got := <-done: |
| + t.Fatalf("forward failed: %+v", got) |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("no request") |
| + } |
| + time.Sleep(holderHeaderSuspectAfter - 200*time.Millisecond) |
| + cancel() |
| + if got := <-done; got.Outcome != ForwardCanceled { |
| + t.Fatalf("canceled: %+v", got) |
| + } |
| + time.Sleep(300 * time.Millisecond) |
| + if notes := fw.noted(); len(notes) != 1 || notes[0].res.Outcome != ForwardCanceled { |
| + t.Fatalf("callback after cancellation: %+v", notes) |
| + } |
| +} |
| + |
| +func TestSlowHolderResponseIsNotAbortedAfterHeaderDisconnect(t *testing.T) { |
| + fw := &fwAct{} |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + defer cancel() |
| + forward := ForwardHolderForTest(t, fw, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(http.StatusCreated) |
| + w.(http.Flusher).Flush() |
| + <-r.Context().Done() |
| + })) |
| + done := make(chan ForwardResult, 1) |
| + go func() { done <- forward(ctx, ForwardDecision{Ref: "betty", Gen: 7}) }() |
| + deadline := time.Now().Add(2 * time.Second) |
| + for len(fw.noted()) == 0 && time.Now().Before(deadline) { |
| + time.Sleep(time.Millisecond) |
| + } |
| + cancel() |
| + if got := <-done; got.Status != 201 || got.Outcome != ForwardDone { |
| + t.Fatalf("disconnect lost observed headers: %+v", got) |
| + } |
| + if notes := fw.noted(); len(notes) != 1 || notes[0].res.Status != 201 { |
| + t.Fatalf("synthetic status-zero note: %+v", notes) |
| + } |
| +} |
| + |
| +func TestSilentHolderObservationJoinsCallback(t *testing.T) { |
| + started, release := make(chan struct{}), make(chan struct{}) |
| + var calls atomic.Int32 |
| + ctx, stop := observeHolderHeaders(t.Context(), func() { |
| + calls.Add(1) |
| + close(started) |
| + <-release |
| + }) |
| + httptrace.ContextClientTrace(ctx).GotConn(httptrace.GotConnInfo{}) |
| + select { |
| + case <-started: |
| + case <-time.After(4 * time.Second): |
| + close(release) |
| + stop() |
| + t.Fatal("no silent callback") |
| + } |
| + joined := make(chan struct{}) |
| + go func() { stop(); close(joined) }() |
| + select { |
| + case <-joined: |
| + close(release) |
| + t.Fatal("disposed an active callback") |
| + case <-time.After(20 * time.Millisecond): |
| + } |
| + close(release) |
| + select { |
| + case <-joined: |
| + case <-time.After(time.Second): |
| + t.Fatal("callback not joined") |
| + } |
| + stop() |
| + if calls.Load() != 1 { |
| + t.Fatal("duplicate silent callback") |
| + } |
| +} |