carlos / platform Public

edge-roll-blip: D10b, probed local upstreams wait for readmission

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 53bce5ef810de2d34b01c17c7f170d219da47917 parent 0a9793c
6 files changed, +613 −86
  • internal/edge/edge.go +106 −43
  • internal/edge/edge_test.go +6 −4
  • internal/edge/localhold_probed_test.go +367 −0
  • internal/edge/localhold_witness_test.go +62 −23
  • internal/edge/prober.go +61 −5
  • internal/edge/prober_test.go +11 −11
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 9a11f73b8..ff5fd1d63 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -464,7 +464,7 @@ func New(reg *registry.Registry, act Activator) (*Edge, error) {
// newEdge is New with the local-upstream hold settings given, so a test can
// shorten or turn off a hold on its own Edge without touching a global.
func newEdge(reg *registry.Registry, act Activator, hold localHold) (*Edge, error) {
- e := &Edge{reg: reg, act: act, hold: hold, gate: gate.New(), probers: newProberSet(), gzipOn: gzipEnabled(), guard: guardModeFromEnv(os.Getenv), steeringHost: steeringProbeHostFromEnv(), appsDomain: appsDomainFromEnv(),
+ e := &Edge{reg: reg, act: act, hold: hold, gate: gate.New(), probers: newProberSet(hold), gzipOn: gzipEnabled(), guard: guardModeFromEnv(os.Getenv), steeringHost: steeringProbeHostFromEnv(), appsDomain: appsDomainFromEnv(),
lbHealth: lbHealthFromEnv(os.Getenv, act), rateMode: rateModeFromEnv(), rateLimiter: ratelimit.NewLimiter(time.Now, 100_000),
planLimiter: ratelimit.NewLimiter(time.Now, 100_000)}
e.geo = geo.NewSwappable()
@@ -877,7 +877,7 @@ func (e *Edge) Reload() error {
// through Health.WithDefaults itself, and normalizing here too
// would just be a second place to keep in step with it.
probeSpecs[t.Host] = probeSpec{Host: t.Host, Addrs: addrs, Health: h}
- p = multiProxy(t.Host, e.probers)
+ p = multiProxy(t.Host, e.probers, e.hold)
}
p.ModifyResponse = e.responseModifier(t)
proxy = p
@@ -2780,7 +2780,8 @@ func tcpProxy(addr string, hold localHold) *httputil.ReverseProxy {
// errNoLiveUpstream is the sentinel multiProxy's dialer returns when a probed
// route has nothing left to try — an empty live set, or every live upstream
-// refusing the dial inside this one request. multiProxy's ErrorHandler turns
+// refusing the dial inside this one request — or, for a route with a local
+// upstream, when its D10b hold ends first. multiProxy's ErrorHandler turns
// it into 503 + Retry-After: 2, the same "nobody is home right now, come back
// shortly" answer errFleetDark gets, rather than the ReverseProxy default's
// 502 (which reads as "your backend is broken" and is what an UNPROBED addr
@@ -2841,7 +2842,7 @@ const multiDialTimeout = 3 * time.Second
// handshake per request to a backend that is, in every deployment this exists
// for, on the same network. The unprobed tcpProxy path keeps its pool
// untouched.
-func multiProxy(host string, p *proberSet) *httputil.ReverseProxy {
+func multiProxy(host string, p *proberSet, hold localHold) *httputil.ReverseProxy {
// Per-ROUTE cursor: closed over by this proxy alone, so two routes cannot
// interleave their rotations (a global counter would make a two-upstream
// route's balance depend on the request rate of every other route on the
@@ -2849,7 +2850,10 @@ func multiProxy(host string, p *proberSet) *httputil.ReverseProxy {
// upstream set — which is what you want, since the set it was counting
// over no longer exists.
var cursor atomic.Uint64
- dialer := &net.Dialer{Timeout: multiDialTimeout}
+ dial := hold.dialer
+ if dial == nil {
+ dial = (&net.Dialer{}).DialContext
+ }
return &httputil.ReverseProxy{
Rewrite: func(pr *httputil.ProxyRequest) {
setForwarded(pr)
@@ -2860,50 +2864,109 @@ func multiProxy(host string, p *proberSet) *httputil.ReverseProxy {
scrubInboundPurgeHeader(pr)
},
Transport: &http.Transport{
+ // The dialer works in passes (D10b, spec §3). A pass walks a fresh
+ // Live snapshot once; a host with no local upstream gets one pass,
+ // as before. A host with a local upstream, when a pass connects
+ // nothing, waits 100ms and passes again until its hold ends: the
+ // local upstream is restarting, and the prober will readmit it.
+ // Only the live set is ever dialed, so a held request waits for
+ // readmission; it never dials an ejected upstream itself.
DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
- live := p.Live(host)
- if len(live) == 0 {
- return nil, errNoLiveUpstream
+ holdFor, local := p.Hold(host)
+ // One deadline, fixed on entry, bounds every attempt and
+ // every wait between passes.
+ var deadline time.Time
+ if local {
+ deadline = time.Now().Add(holdFor)
+ }
+ var (
+ lastErr error
+ tried int
+ )
+ noLive := func() error {
+ if tried == 0 {
+ if local {
+ return fmt.Errorf("%w for %s within its %v hold", errNoLiveUpstream, host, holdFor)
+ }
+ return errNoLiveUpstream
+ }
+ return fmt.Errorf("%w for %s: %d dial(s) refused, last: %v",
+ errNoLiveUpstream, host, tried, lastErr)
}
- // Start where the last request left off, then walk the whole
- // snapshot once. Snapshot rather than re-reading Live per
- // attempt: each Eject below shrinks the live set, and re-reading
- // would skip untried upstreams as the list moved under us.
- //
- // The index arithmetic stays in uint64 all the way to the
- // modulo. Converting the counter to int first would wrap
- // NEGATIVE once it passed 2^31 on a 32-bit box (the Pi fleet),
- // and Go's modulo keeps the sign — so the very next request
- // after that wrap would index out of range and panic the edge.
- start := cursor.Add(1) - 1
- n := uint64(len(live))
- var lastErr error
- for i := range live {
- if err := ctx.Err(); err != nil {
- // The client went away (or the request deadline
- // expired) mid-loop. Stop, and do NOT eject: a dial we
- // abandoned says nothing about the upstream's health,
- // and marking it down here would take a healthy box out
- // of rotation because one user hit stop.
- return nil, err
+ for {
+ live := p.Live(host)
+ if len(live) > 0 {
+ // Start where the last pass left off, then walk the
+ // whole snapshot once. Snapshot rather than re-reading
+ // Live per attempt: each Eject below shrinks the live
+ // set, and re-reading would skip untried upstreams as
+ // the list moved under us.
+ //
+ // The index arithmetic stays in uint64 all the way to
+ // the modulo. Converting the counter to int first would
+ // wrap NEGATIVE once it passed 2^31 on a 32-bit box
+ // (the Pi fleet), and Go's modulo keeps the sign — so
+ // the very next request after that wrap would index out
+ // of range and panic the edge.
+ start := cursor.Add(1) - 1
+ n := uint64(len(live))
+ for i := range live {
+ if err := ctx.Err(); err != nil {
+ // The client went away (or the request deadline
+ // expired) mid-loop. Stop, and do NOT eject: a
+ // dial we abandoned says nothing about the
+ // upstream's health, and marking it down here
+ // would take a healthy box out of rotation
+ // because one user hit stop.
+ return nil, err
+ }
+ addr := live[(start+uint64(i))%n]
+ // Each attempt ends at the earlier of
+ // multiDialTimeout and the hold's deadline.
+ until := time.Now().Add(multiDialTimeout)
+ if local && deadline.Before(until) {
+ until = deadline
+ }
+ actx, cancel := context.WithDeadline(ctx, until)
+ conn, err := dial(actx, network, addr)
+ cancel()
+ if err == nil {
+ return conn, nil
+ }
+ lastErr = err
+ tried++
+ if ctx.Err() != nil {
+ return nil, err // as above: our own cancellation, not the upstream's fault
+ }
+ if local && !time.Now().Before(deadline) {
+ // The hold ran out mid-attempt: the budget is
+ // spent, not the upstream. No Eject.
+ return nil, noLive()
+ }
+ // The fast path the probe cadence cannot match: a
+ // box that died since the last tick is out of
+ // rotation now, for every other in-flight request
+ // too, instead of collecting failures until
+ // fail_after.
+ p.Eject(host, addr)
+ }
+ }
+ if !local {
+ return nil, noLive()
+ }
+ left := time.Until(deadline)
+ if left <= 0 {
+ return nil, noLive()
}
- addr := live[(start+uint64(i))%n]
- conn, err := dialer.DialContext(ctx, network, addr)
- if err == nil {
- return conn, nil
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-time.After(min(localDialStep, left)):
}
- lastErr = err
- if ctx.Err() != nil {
- return nil, err // as above: our own cancellation, not the upstream's fault
+ if !time.Now().Before(deadline) {
+ return nil, noLive()
}
- // The fast path the probe cadence cannot match: a box that
- // died since the last tick is out of rotation now, for
- // every other in-flight request too, instead of collecting
- // failures until fail_after.
- p.Eject(host, addr)
}
- return nil, fmt.Errorf("%w for %s: %d upstream(s) refused, last: %v",
- errNoLiveUpstream, host, len(live), lastErr)
},
// No MaxIdleConns/IdleConnTimeout twin of tcpProxy's: with
// keep-alives off nothing is ever pooled, so the idle bounds that
diff --git a/internal/edge/edge_test.go b/internal/edge/edge_test.go
index 5e1b50b8f..4e61314ec 100644
--- a/internal/edge/edge_test.go
+++ b/internal/edge/edge_test.go
@@ -1776,9 +1776,10 @@ func TestAllUpstreamsDownAnswers503WithRetryAfter(t *testing.T) {
t.Fatalf("upsert: %v", err)
}
- e, err := New(reg, nil)
+ // noHold: the point here is the 503 itself, not the D10b wait.
+ e, err := newEdge(reg, nil, noHold())
if err != nil {
- t.Fatalf("New: %v", err)
+ t.Fatalf("newEdge: %v", err)
}
defer e.probers.Stop()
srv := httptest.NewServer(e)
@@ -1818,9 +1819,10 @@ func TestSingleAddrWithHealthGets503Semantics(t *testing.T) {
t.Fatalf("upsert: %v", err)
}
- e, err := New(reg, nil)
+ // noHold: the point here is the 503 itself, not the D10b wait.
+ e, err := newEdge(reg, nil, noHold())
if err != nil {
- t.Fatalf("New: %v", err)
+ t.Fatalf("newEdge: %v", err)
}
defer e.probers.Stop()
srv := httptest.NewServer(e)
diff --git a/internal/edge/localhold_probed_test.go b/internal/edge/localhold_probed_test.go
new file mode 100644
index 000000000..293c1ce96
--- /dev/null
+++ b/internal/edge/localhold_probed_test.go
@@ -0,0 +1,367 @@
+package edge
+
+import (
+ "context"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "slices"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/apperr"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// readmitBound is spec §3's R, computed here independently of prober.go:
+// n upstreams probed every interval, rise passes to rejoin, probe timeout T.
+func readmitBound(n int, interval time.Duration, rise int, probe time.Duration) time.Duration {
+ g := max(interval, probe) + time.Duration(n-1)*probe
+ return time.Duration(rise)*g + probe
+}
+
+func TestHoldMatchesFormula(t *testing.T) {
+ local := "127.0.0.1:8080"
+ others := []string{"10.0.0.1:80", "10.0.0.2:80", "10.0.0.3:80"}
+ def := provision.Health{}.WithDefaults()
+ off := defaultLocalHold()
+ off.dial = 0
+ for _, tc := range []struct {
+ name string
+ addrs []string
+ health provision.Health
+ hold localHold
+ want time.Duration
+ ok bool
+ }{
+ {"one local", []string{local}, def, defaultLocalHold(), 19 * time.Second, true},
+ {"local plus 1", []string{local, others[0]}, def, defaultLocalHold(), 23 * time.Second, true},
+ {"local plus 2", []string{local, others[0], others[1]}, def, defaultLocalHold(), 27 * time.Second, true},
+ {"local plus 3 capped", append([]string{local}, others...), def, defaultLocalHold(), 30 * time.Second, true},
+ {"remote only", others, def, defaultLocalHold(), 0, false},
+ {"raw Health{}", []string{local}, provision.Health{}, defaultLocalHold(), 19 * time.Second, true},
+ {"negative interval", []string{local}, provision.Health{IntervalMS: -1}, defaultLocalHold(), 19 * time.Second, true},
+ {"negative rise", []string{local}, provision.Health{RiseAfter: -1}, defaultLocalHold(), 19 * time.Second, true},
+ {"dial 0", []string{local}, def, off, 0, false},
+ {"cap 0", []string{local}, def, localHold{dial: localDialHold, probe: probeTimeout}, 0, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ p := newProberSet(tc.hold)
+ hp := newHostProber(probeSpec{Host: "shop.example.com", Addrs: tc.addrs, Health: tc.health}, p.client, tc.hold)
+ p.mu.Lock()
+ p.hosts["shop.example.com"] = hp // not started: Hold reads only what newHostProber fixed
+ p.mu.Unlock()
+ got, ok := p.Hold("shop.example.com")
+ if got != tc.want || ok != tc.ok {
+ t.Fatalf("Hold = (%v, %v), want (%v, %v)", got, ok, tc.want, tc.ok)
+ }
+ })
+ }
+ if d, ok := newProberSet(defaultLocalHold()).Hold("unknown.example.com"); d != 0 || ok {
+ t.Fatalf("Hold(unknown) = (%v, %v), want (0, false)", d, ok)
+ }
+}
+
+// probedHold is the shortened hold the D10b behaviour tests run on unless
+// they say otherwise: one upstream gets min(300ms + 250ms, 5s) = 550ms.
+func probedHold() localHold {
+ return localHold{dial: 300 * time.Millisecond, cap: 5 * time.Second, probe: 50 * time.Millisecond}
+}
+
+// fastHealth probes every 100ms, fails on one miss and rejoins on two passes.
+func fastHealth() provision.Health {
+ return provision.Health{Path: testProbePath, IntervalMS: 100, FailAfter: 1, RiseAfter: 2}
+}
+
+// probedEdge is an Edge over one probed service route at addrs.
+func probedEdge(t *testing.T, addrs []string, h provision.Health, hold localHold) (*Edge, *httptest.Server) {
+ t.Helper()
+ reg := openReg(t)
+ csv := ""
+ for i, a := range addrs {
+ if i > 0 {
+ csv += ","
+ }
+ csv += a
+ }
+ if err := reg.Upsert(registry.Route{
+ Host: "shop.example.com", Kind: "service", Status: "ready",
+ Addrs: csv, Health: healthJSON(t, h),
+ }); err != nil {
+ t.Fatalf("upsert: %v", err)
+ }
+ e, err := newEdge(reg, nil, hold)
+ if err != nil {
+ t.Fatalf("newEdge: %v", err)
+ }
+ t.Cleanup(e.probers.Stop)
+ srv := httptest.NewServer(e)
+ t.Cleanup(srv.Close)
+ return e, srv
+}
+
+// countingHandler counts proxied requests and answers "ok"; probes are
+// answered but never counted.
+func countingHandler(hits *atomic.Int64) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == testProbePath {
+ return
+ }
+ hits.Add(1)
+ io.WriteString(w, "ok")
+ })
+}
+
+// probedGet sends one GET for shop.example.com and returns the response
+// (body drained) and how long it took.
+func probedGet(t *testing.T, url string) (*http.Response, time.Duration) {
+ t.Helper()
+ start := time.Now()
+ resp := getHostHeader(t, url, "shop.example.com")
+ return resp, time.Since(start)
+}
+
+func TestProbedLocalUpstreamWaitsForReadmission(t *testing.T) {
+ a := deadAddr(t)
+ var hits atomic.Int64
+ e, srv := probedEdge(t, []string{a}, fastHealth(), probedHold())
+ listenLater(t, a, 200*time.Millisecond, countingHandler(&hits))
+ resp, el := probedGet(t, srv.URL)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("status = %d after %v (hold %v), want 200 once readmitted", resp.StatusCode, el, mustHold(t, e))
+ }
+ if n := hits.Load(); n != 1 {
+ t.Fatalf("proxied requests = %d, want exactly 1 (nothing reaches an ejected upstream)", n)
+ }
+}
+
+func TestProbedEmptyLiveSetOnArrivalWaits(t *testing.T) {
+ a := deadAddr(t)
+ var hits atomic.Int64
+ e, srv := probedEdge(t, []string{a}, fastHealth(), probedHold())
+ waitFor(t, 2*time.Second, "the probe to empty the live set", func() bool {
+ return len(e.probers.Live("shop.example.com")) == 0
+ })
+ listenLater(t, a, 200*time.Millisecond, countingHandler(&hits))
+ resp, el := probedGet(t, srv.URL)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("status = %d after %v, want 200 once readmitted", resp.StatusCode, el)
+ }
+ if n := hits.Load(); n != 1 {
+ t.Fatalf("proxied requests = %d, want exactly 1", n)
+ }
+}
+
+func mustHold(t *testing.T, e *Edge) time.Duration {
+ t.Helper()
+ d, ok := e.probers.Hold("shop.example.com")
+ if !ok {
+ t.Fatalf("Hold(shop.example.com) = (%v, false), want a local hold", d)
+ }
+ return d
+}
+
+// want503At checks a held request's 503: Retry-After 2, cause
+// CauseNoUpstream, and elapsed in [at, at+150ms).
+func want503At(t *testing.T, resp *http.Response, el, at time.Duration, sink *memErrSink) {
+ t.Helper()
+ if resp.StatusCode != http.StatusServiceUnavailable {
+ t.Fatalf("status = %d after %v, want 503", resp.StatusCode, el)
+ }
+ if got := resp.Header.Get("Retry-After"); got != "2" {
+ t.Fatalf("Retry-After = %q, want 2", got)
+ }
+ if el < at || el >= at+150*time.Millisecond {
+ t.Fatalf("503 after %v, want within 150ms of %v", el, at)
+ }
+ waitFor(t, time.Second, "the edge error record", func() bool { return len(sink.snap()) > 0 })
+ recs := sink.snap()
+ if len(recs) != 1 || recs[0].Cause != apperr.CauseNoUpstream {
+ t.Fatalf("records = %+v, want one with cause %q", recs, apperr.CauseNoUpstream)
+ }
+}
+
+func TestProbedLocalStillDownPastHold(t *testing.T) {
+ e, srv := probedEdge(t, []string{deadAddr(t)}, fastHealth(), probedHold())
+ sink := &memErrSink{}
+ e.EnableErrors(sink)
+ hold := mustHold(t, e)
+ if want := 300*time.Millisecond + readmitBound(1, 100*time.Millisecond, 2, 50*time.Millisecond); hold != want {
+ t.Fatalf("Hold = %v, want %v", hold, want)
+ }
+ resp, el := probedGet(t, srv.URL)
+ want503At(t, resp, el, hold, sink)
+}
+
+func TestProbedPastCapAnswersAtCap(t *testing.T) {
+ hold := probedHold()
+ hold.cap = 400 * time.Millisecond
+ e, srv := probedEdge(t, []string{deadAddr(t)}, fastHealth(), hold)
+ sink := &memErrSink{}
+ e.EnableErrors(sink)
+ if got := mustHold(t, e); got != hold.cap {
+ t.Fatalf("Hold = %v, want the cap %v", got, hold.cap)
+ }
+ resp, el := probedGet(t, srv.URL)
+ want503At(t, resp, el, hold.cap, sink)
+}
+
+func TestProbedRemoteOnlyAnswersAtOnce(t *testing.T) {
+ hold := probedHold()
+ hold.dialer = func(context.Context, string, string) (net.Conn, error) { return nil, refusedErr() }
+ e, srv := probedEdge(t, []string{"10.0.0.5:80"}, fastHealth(), hold)
+ if d, ok := e.probers.Hold("shop.example.com"); ok {
+ t.Fatalf("Hold = (%v, true), want no hold for a remote-only route", d)
+ }
+ resp, el := probedGet(t, srv.URL)
+ if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") != "2" {
+ t.Fatalf("status = %d Retry-After %q, want 503 and 2", resp.StatusCode, resp.Header.Get("Retry-After"))
+ }
+ if el > 100*time.Millisecond {
+ t.Fatalf("503 after %v, want within 100ms", el)
+ }
+}
+
+func TestProbedMixedSetWithLiveUpstreamServesAtOnce(t *testing.T) {
+ live, hits := countingBackend(t, "A")
+ _, srv := probedEdge(t, []string{deadAddr(t), live}, fastHealth(), probedHold())
+ resp, el := probedGet(t, srv.URL)
+ if resp.StatusCode != http.StatusOK || hits.Load() != 1 {
+ t.Fatalf("status = %d, live upstream hits = %d, want 200 from it", resp.StatusCode, hits.Load())
+ }
+ if el > 100*time.Millisecond {
+ t.Fatalf("200 after %v, want within 100ms", el)
+ }
+}
+
+// TestProbedDelayedProbeServedWithinR is spec §10 "Delayed probe": three
+// upstreams whose health check blocks past the probe timeout are probed
+// before the restarting one, so its readmission takes the longest the
+// formula allows for. It must still come within R, and the held request is
+// served then.
+func TestProbedDelayedProbeServedWithinR(t *testing.T) {
+ release := make(chan struct{})
+ var slowHits atomic.Int64
+ var slow []string
+ for i := 0; i < 3; i++ {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == testProbePath {
+ select {
+ case <-r.Context().Done():
+ case <-release:
+ }
+ return
+ }
+ slowHits.Add(1)
+ io.WriteString(w, "slow")
+ }))
+ t.Cleanup(ts.Close)
+ slow = append(slow, ts.Listener.Addr().String())
+ }
+ t.Cleanup(func() { close(release) }) // runs before the servers close
+ a := deadAddr(t)
+ hold := probedHold()
+ e, srv := probedEdge(t, append(slow, a), fastHealth(), hold)
+ r := readmitBound(4, 100*time.Millisecond, 2, hold.probe)
+ if got := mustHold(t, e); got != hold.dial+r {
+ t.Fatalf("Hold = %v, want dial + R = %v", got, hold.dial+r)
+ }
+ waitFor(t, 2*time.Second, "every upstream to leave the live set", func() bool {
+ return len(e.probers.Live("shop.example.com")) == 0
+ })
+
+ // The upstream comes back 100ms into the request's hold; a watcher
+ // stamps the moment the prober readmits it.
+ var hits atomic.Int64
+ back := make(chan time.Time, 1)
+ readmitted := make(chan time.Time, 1)
+ go func() {
+ time.Sleep(100 * time.Millisecond)
+ ln, err := net.Listen("tcp", a)
+ if err != nil {
+ t.Errorf("listen %s: %v", a, err)
+ close(back)
+ close(readmitted)
+ return
+ }
+ s := httptest.NewUnstartedServer(countingHandler(&hits))
+ s.Listener.Close()
+ s.Listener = ln
+ s.Start()
+ t.Cleanup(s.Close)
+ back <- time.Now()
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) {
+ if slices.Contains(e.probers.Live("shop.example.com"), a) {
+ readmitted <- time.Now()
+ return
+ }
+ time.Sleep(2 * time.Millisecond)
+ }
+ close(readmitted)
+ }()
+ resp, el := probedGet(t, srv.URL)
+ if resp.StatusCode != http.StatusOK || hits.Load() != 1 {
+ t.Fatalf("status = %d after %v, hits = %d, want 200 from the readmitted upstream", resp.StatusCode, el, hits.Load())
+ }
+ if n := slowHits.Load(); n != 0 {
+ t.Fatalf("ejected slow upstreams served %d requests, want 0", n)
+ }
+ upAt, ok1 := <-back
+ inAt, ok2 := <-readmitted
+ if !ok1 || !ok2 {
+ t.Fatalf("upstream never came back or was never readmitted")
+ }
+ if took := inAt.Sub(upAt); took > r {
+ t.Fatalf("readmission took %v, want at most R = %v", took, r)
+ } else {
+ t.Logf("readmission %v (R %v), served after %v (hold %v)", took, r, el, hold.dial+r)
+ }
+}
+
+func TestProbedDeadlineMidPassDoesNotEject(t *testing.T) {
+ const remote = "10.0.0.9:80"
+ hold := probedHold()
+ hold.cap = 400 * time.Millisecond
+ var plain net.Dialer
+ hold.dialer = func(ctx context.Context, network, addr string) (net.Conn, error) {
+ if addr == remote {
+ <-ctx.Done()
+ return nil, ctx.Err()
+ }
+ return plain.DialContext(ctx, network, addr)
+ }
+ e, srv := probedEdge(t, []string{deadAddr(t), remote}, frozenHealth(), hold)
+ sink := &memErrSink{}
+ e.EnableErrors(sink)
+ if got := mustHold(t, e); got != hold.cap {
+ t.Fatalf("Hold = %v, want the cap %v", got, hold.cap)
+ }
+ resp, el := probedGet(t, srv.URL)
+ want503At(t, resp, el, hold.cap, sink)
+ if live := e.probers.Live("shop.example.com"); !slices.Contains(live, remote) {
+ t.Fatalf("live set = %v, want %s still live: the hold ran out, the upstream did not fail", live, remote)
+ }
+}
+
+func TestProbedHoldSurvivesReload(t *testing.T) {
+ a := deadAddr(t)
+ var hits atomic.Int64
+ e, srv := probedEdge(t, []string{a}, fastHealth(), probedHold())
+ listenLater(t, a, 200*time.Millisecond, countingHandler(&hits))
+ reloaded := make(chan error, 1)
+ go func() {
+ time.Sleep(100 * time.Millisecond)
+ reloaded <- e.Reload()
+ }()
+ resp, el := probedGet(t, srv.URL)
+ if err := <-reloaded; err != nil {
+ t.Fatalf("Reload: %v", err)
+ }
+ if resp.StatusCode != http.StatusOK || hits.Load() != 1 {
+ t.Fatalf("status = %d after %v, hits = %d, want 200 across the reload", resp.StatusCode, el, hits.Load())
+ }
+}
diff --git a/internal/edge/localhold_witness_test.go b/internal/edge/localhold_witness_test.go
index 2e2480df7..3bd40fdd7 100644
--- a/internal/edge/localhold_witness_test.go
+++ b/internal/edge/localhold_witness_test.go
@@ -13,6 +13,7 @@ import (
"testing"
"time"
+ "github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
)
@@ -25,6 +26,8 @@ type witnessStats struct {
// gap is how long the upstream refused, from the start of its Shutdown
// until the new server was listening.
gap time.Duration
+ // held counts requests whose added wait exceeded witnessHeldOver.
+ held int
}
const (
@@ -36,6 +39,8 @@ const (
witnessBaseline = time.Second
witnessGap = 1500 * time.Millisecond
witnessAfter = time.Second
+ // witnessHeldOver is the added wait past which a request counts as held.
+ witnessHeldOver = 100 * time.Millisecond
)
type witnessSample struct {
@@ -178,6 +183,9 @@ func runRestartWitness(t *testing.T, e *Edge, listen func() (net.Listener, error
if w < 0 {
w = 0
}
+ if w > witnessHeldOver {
+ st.held++
+ }
added = append(added, w)
}
sortDurations(added)
@@ -201,8 +209,37 @@ func percentile(d []time.Duration, q float64) time.Duration {
func logWitness(t *testing.T, route string, st witnessStats) {
t.Helper()
- t.Logf("local-hold witness: route=%s gap=%v requests=%d ok=%d 502=%d 503=%d other=%d added_wait p50=%v p99=%v max=%v",
- route, st.gap.Round(time.Millisecond), st.requests, st.ok, st.s502, st.s503, st.other, st.p50, st.p99, st.max)
+ t.Logf("local-hold witness: route=%s gap=%v requests=%d ok=%d 502=%d 503=%d other=%d added_wait p50=%v p99=%v max=%v held=%d",
+ route, st.gap.Round(time.Millisecond), st.requests, st.ok, st.s502, st.s503, st.other, st.p50, st.p99, st.max, st.held)
+}
+
+// checkWitness is the pass rule for a held route: no failures, a max added
+// wait under gap+extra, and at least gap/2 of it, so a run in which nothing
+// was actually held (the restart missed the load) cannot pass.
+func checkWitness(t *testing.T, st witnessStats, extra time.Duration) {
+ t.Helper()
+ if st.s502 != 0 || st.s503 != 0 || st.other != 0 {
+ t.Errorf("failures during restart: 502=%d 503=%d other=%d, want none", st.s502, st.s503, st.other)
+ }
+ if st.max >= st.gap+extra {
+ t.Errorf("max added wait %v, want under gap+%v = %v", st.max, extra, st.gap+extra)
+ }
+ if st.max < st.gap/2 {
+ t.Errorf("max added wait %v, want at least gap/2 = %v: no request was held through the restart", st.max, st.gap/2)
+ }
+}
+
+// witnessEdge builds the witness's Edge with the rate limiter off on that
+// Edge alone, so the eight workers measure the hold and nothing else.
+func witnessEdge(t *testing.T, reg *registry.Registry, hold localHold) *Edge {
+ t.Helper()
+ e, err := newEdge(reg, nil, hold)
+ if err != nil {
+ t.Fatalf("newEdge: %v", err)
+ }
+ e.rateMode = RateOff
+ t.Cleanup(e.probers.Stop)
+ return e
}
// reserveLoopbackAddr picks a free 127.0.0.1 port and releases it, so the
@@ -242,12 +279,7 @@ func witnessTCPEdge(t *testing.T, hold localHold) (*Edge, func() (net.Listener,
if err := reg.Upsert(registry.Route{Host: witnessHost, Kind: "service", Addr: addr, Status: "ready"}); err != nil {
t.Fatalf("upsert: %v", err)
}
- e, err := newEdge(reg, nil, hold)
- if err != nil {
- t.Fatalf("newEdge: %v", err)
- }
- t.Cleanup(e.probers.Stop)
- return e, listenTCPFixed(addr)
+ return witnessEdge(t, reg, hold), listenTCPFixed(addr)
}
// TestLocalUpstreamRestartWitness restarts a local upstream under load and
@@ -263,12 +295,7 @@ func TestLocalUpstreamRestartWitness(t *testing.T) {
e, listen := witnessTCPEdge(t, defaultLocalHold())
st := runRestartWitness(t, e, listen)
logWitness(t, "tcp", st)
- if st.s502 != 0 || st.s503 != 0 || st.other != 0 {
- t.Errorf("failures during restart: 502=%d 503=%d other=%d, want none", st.s502, st.s503, st.other)
- }
- if st.max >= st.gap+time.Second {
- t.Errorf("max added wait %v, want under gap+1s = %v", st.max, st.gap+time.Second)
- }
+ checkWitness(t, st, time.Second)
})
t.Run("unix", func(t *testing.T) {
@@ -281,19 +308,31 @@ func TestLocalUpstreamRestartWitness(t *testing.T) {
if err := reg.Upsert(registry.Route{Host: witnessHost, Kind: "instance", Socket: sock, Status: "ready"}); err != nil {
t.Fatalf("upsert: %v", err)
}
- e, err := newEdge(reg, nil, defaultLocalHold())
- if err != nil {
- t.Fatalf("newEdge: %v", err)
- }
- t.Cleanup(e.probers.Stop)
+ e := witnessEdge(t, reg, defaultLocalHold())
st := runRestartWitness(t, e, func() (net.Listener, error) { return net.Listen("unix", sock) })
logWitness(t, "unix", st)
- if st.s502 != 0 || st.s503 != 0 || st.other != 0 {
- t.Errorf("failures during restart: 502=%d 503=%d other=%d, want none", st.s502, st.s503, st.other)
+ checkWitness(t, st, time.Second)
+ })
+
+ // A probed route: the probe ejects the upstream when it goes, the
+ // requests wait for its readmission, and readmission takes up to R.
+ t.Run("probed", func(t *testing.T) {
+ t.Parallel()
+ addr := reserveLoopbackAddr(t)
+ h := provision.Health{Path: "/healthz", IntervalMS: 100, FailAfter: 1, RiseAfter: 2}
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: witnessHost, Kind: "service", Addrs: addr, Health: healthJSON(t, h), Status: "ready"}); err != nil {
+ t.Fatalf("upsert: %v", err)
}
- if st.max >= st.gap+time.Second {
- t.Errorf("max added wait %v, want under gap+1s = %v", st.max, st.gap+time.Second)
+ hold := defaultLocalHold()
+ e := witnessEdge(t, reg, hold)
+ r := readmitBound(1, 100*time.Millisecond, 2, hold.probe)
+ if got, ok := e.probers.Hold(witnessHost); !ok || got != min(hold.dial+r, hold.cap) {
+ t.Fatalf("Hold = (%v, %v), want (%v, true)", got, ok, min(hold.dial+r, hold.cap))
}
+ st := runRestartWitness(t, e, listenTCPFixed(addr))
+ logWitness(t, "probed", st)
+ checkWitness(t, st, r)
})
// Negative control: with the dial hold off the same restart must 502,
diff --git a/internal/edge/prober.go b/internal/edge/prober.go
index 5ebc6d21b..030e65ab3 100644
--- a/internal/edge/prober.go
+++ b/internal/edge/prober.go
@@ -121,13 +121,25 @@ type proberSet struct {
mu sync.Mutex
hosts map[string]*hostProber
client *http.Client
+ // hold is the Edge's local-upstream hold (localhold.go), which Sync
+ // hands to every hostProber so each can work out its own D10b hold.
+ hold localHold
}
-func newProberSet() *proberSet {
+// newProberSet builds the set with hold.probe as the probe timeout (T in
+// the readmission formula, spec §3), and hold.dialer, when set, as the
+// probes' dialer, so a test's instrumented dialer sees the probes too. A
+// non-positive probe falls back to probeTimeout: an unbounded probe would
+// stall every tick behind one black-holed upstream.
+func newProberSet(hold localHold) *proberSet {
+ if hold.probe <= 0 {
+ hold.probe = probeTimeout
+ }
return &proberSet{
hosts: make(map[string]*hostProber),
+ hold: hold,
client: &http.Client{
- Timeout: probeTimeout,
+ Timeout: hold.probe,
// A redirect is not health: an upstream answering 302 has not
// served the configured status, and following the hop would
// probe something the operator never named.
@@ -140,7 +152,8 @@ func newProberSet() *proberSet {
// bounded tightly, since every probed upstream holds one.
MaxIdleConnsPerHost: 1,
IdleConnTimeout: 90 * time.Second,
- ResponseHeaderTimeout: probeTimeout,
+ ResponseHeaderTimeout: hold.probe,
+ DialContext: hold.dialer, // nil: the default dialer
},
},
}
@@ -170,6 +183,12 @@ type hostProber struct {
ctx context.Context
done chan struct{}
+ // local and hold are D10b's (spec §3), fixed here and never changed:
+ // local when any addr is this box's loopback, and hold how long a
+ // request may wait for the live set to readmit one.
+ local bool
+ hold time.Duration
+
mu sync.Mutex
order []string // addrs in spec order — Live/State iterate this, not the map
state map[string]*upstreamState
@@ -185,7 +204,7 @@ type upstreamState struct {
lastError string
}
-func newHostProber(spec probeSpec, client *http.Client) *hostProber {
+func newHostProber(spec probeSpec, client *http.Client, hold localHold) *hostProber {
h := spec.Health
hp := &hostProber{
spec: spec,
@@ -231,10 +250,34 @@ func newHostProber(spec probeSpec, client *http.Client) *hostProber {
// Rule 1: everything starts live.
hp.state[addr] = &upstreamState{up: true, since: now}
}
+ hp.hold, hp.local = readmitHold(hp.order, hp.interval, hp.riseAt, hold)
hp.ctx, hp.cancel = context.WithCancel(context.Background())
return hp
}
+// readmitHold is D10b's hold for a probed host (spec §3), from the clamped
+// cadence the prober actually runs. One probe of an addr starts at most
+//
+// G = max(I, T) + (N-1)*T
+//
+// after the one before it (I the interval, T the probe timeout, N the
+// addrs), so an upstream that is back rejoins within R = r*G + T (r the
+// rise count). The hold is min(dial + R, cap). ok is false when no addr is
+// local, or when the dial hold or cap is off: such a host answers at once.
+func readmitHold(order []string, interval time.Duration, rise int, hold localHold) (time.Duration, bool) {
+ if hold.dial <= 0 || hold.cap <= 0 || !slices.ContainsFunc(order, isLocalUpstream) {
+ return 0, false
+ }
+ t := hold.probe
+ g := max(interval, t) + time.Duration(len(order)-1)*t
+ r := time.Duration(rise)
+ // Saturate rather than overflow: a hand-written rise_after can be huge.
+ if g > 0 && r > hold.cap/g {
+ return hold.cap, true
+ }
+ return min(hold.dial+r*g+t, hold.cap), true
+}
+
// stop cancels the goroutine's context — aborting any in-flight probe at once,
// so this does not wait out the 2s client timeout — and blocks until it has
// exited.
@@ -289,7 +332,7 @@ func (p *proberSet) Sync(want map[string]probeSpec) {
// that removed the outgoing prober, so a concurrent Live never
// observes a replaced host as having no upstreams — a gap there
// would be a 503 for a route that is perfectly healthy.
- hp := newHostProber(w, p.client)
+ hp := newHostProber(w, p.client, p.hold)
p.hosts[host] = hp
started = append(started, hp)
}
@@ -329,6 +372,19 @@ func (p *proberSet) Live(host string) []string {
return out
}
+// Hold reports host's D10b hold: how long multiProxy may wait for the live
+// set to readmit an upstream, and whether the host has a local upstream at
+// all. An unknown host, or one with no local addr, is (0, false).
+func (p *proberSet) Hold(host string) (time.Duration, bool) {
+ p.mu.Lock()
+ hp := p.hosts[host]
+ p.mu.Unlock()
+ if hp == nil || !hp.local {
+ return 0, false
+ }
+ return hp.hold, true
+}
+
// Eject drops addr from host's live set immediately — the in-request
// dial-failure fast path, so a box that died between probe ticks costs one
// retry rather than up to fail_after × interval of 502s. Fails is set to
diff --git a/internal/edge/prober_test.go b/internal/edge/prober_test.go
index 381e99e67..2876466f8 100644
--- a/internal/edge/prober_test.go
+++ b/internal/edge/prober_test.go
@@ -71,7 +71,7 @@ func TestProberFailsAwayAndBack(t *testing.T) {
}.WithDefaults(),
}
- p := newProberSet()
+ p := newProberSet(defaultLocalHold())
defer p.Stop()
// Optimism: a fresh Sync must not 503 a healthy fleet while the first
// probes run, so both upstreams are live before any probe has landed.
@@ -132,7 +132,7 @@ func TestProberSendsConfiguredHostHeader(t *testing.T) {
// HostHeader set: it wins over the route host, so a shared upstream that
// vhosts on Host can be probed on the name it actually answers to.
- p := newProberSet()
+ p := newProberSet(defaultLocalHold())
p.Sync(map[string]probeSpec{"m.example.com": {
Host: "m.example.com",
Addrs: []string{ts.Listener.Addr().String()},
@@ -155,7 +155,7 @@ func TestProberSendsConfiguredHostHeader(t *testing.T) {
// HostHeader unset: the route host is substituted — WithDefaults
// deliberately leaves HostHeader empty so the prober can see "unset".
- p2 := newProberSet()
+ p2 := newProberSet(defaultLocalHold())
defer p2.Stop()
p2.Sync(map[string]probeSpec{"m.example.com": {
Host: "m.example.com",
@@ -175,7 +175,7 @@ func TestSyncStopsVanishedHosts(t *testing.T) {
backend, ok, hits := switchableBackend(t, http.StatusInternalServerError)
ok.Store(true)
- p := newProberSet()
+ p := newProberSet(defaultLocalHold())
defer p.Stop()
spec := probeSpec{
Host: "m.example.com",
@@ -249,7 +249,7 @@ func TestSyncReplacesChangedSpecWithoutAGap(t *testing.T) {
}
}
- p := newProberSet()
+ p := newProberSet(defaultLocalHold())
defer p.Stop()
p.Sync(map[string]probeSpec{host: spec(aAddr, bAddr)})
waitFor(t, 2*time.Second, "the outgoing addr set to be probed", func() bool {
@@ -321,7 +321,7 @@ func TestSyncNormalizesHealthBeforeComparing(t *testing.T) {
backend, ok, _ := switchableBackend(t, http.StatusInternalServerError)
ok.Store(true)
- p := newProberSet()
+ p := newProberSet(defaultLocalHold())
defer p.Stop()
proberFor := func() *hostProber {
p.mu.Lock()
@@ -367,7 +367,7 @@ func TestEjectIsImmediateAndProbeRejoins(t *testing.T) {
t.Cleanup(b.Close)
aAddr, bAddr := a.Listener.Addr().String(), b.Listener.Addr().String()
- p := newProberSet()
+ p := newProberSet(defaultLocalHold())
defer p.Stop()
p.Sync(map[string]probeSpec{"m.example.com": {
Host: "m.example.com",
@@ -438,7 +438,7 @@ func TestProberClampsNonPositiveInterval(t *testing.T) {
Host: "m.example.com",
Addrs: []string{"10.0.0.1:80"},
Health: provision.Health{IntervalMS: ms},
- }, nil)
+ }, nil, defaultLocalHold())
if hp.interval != fallbackProbeInterval {
t.Errorf("interval_ms %d clamped to %v, want the %v fallback", ms, hp.interval, fallbackProbeInterval)
}
@@ -449,7 +449,7 @@ func TestProberClampsNonPositiveInterval(t *testing.T) {
// panic.
backend, ok, hits := switchableBackend(t, http.StatusInternalServerError)
ok.Store(true)
- p := newProberSet()
+ p := newProberSet(defaultLocalHold())
defer p.Stop()
p.Sync(map[string]probeSpec{"m.example.com": {
Host: "m.example.com",
@@ -482,7 +482,7 @@ func TestProberClampsNonPositiveFailAndRiseCounts(t *testing.T) {
Host: "m.example.com",
Addrs: []string{addr},
Health: provision.Health{Path: "/", Status: 200, IntervalMS: 20, FailAfter: -1, RiseAfter: 0},
- }, nil)
+ }, nil, defaultLocalHold())
if hp.failAt != fallbackFailAfter || hp.riseAt != fallbackRiseAfter {
t.Fatalf("clamped counts = fail %d rise %d, want %d/%d", hp.failAt, hp.riseAt, fallbackFailAfter, fallbackRiseAfter)
}
@@ -528,7 +528,7 @@ func TestProberStateReturnsCopies(t *testing.T) {
backend, ok, _ := switchableBackend(t, http.StatusInternalServerError)
ok.Store(true)
- p := newProberSet()
+ p := newProberSet(defaultLocalHold())
defer p.Stop()
addr := backend.Listener.Addr().String()
p.Sync(map[string]probeSpec{"m.example.com": {