edge: keep the serving copy while a copies raise converts the route (#511 R23)
Drill 3's copies 1 to 2 gave 9 s of hub 503s after the hub rewrote the host's single-box forward row into the replica set's route, while the copy kept running. Every copy of a new set starts unhealthy and needs two passing probes, and a copy's probe passes only once its own box has reloaded the set's row: until then the set had no live copy, and the hub answered "no healthy copy" with the serving copy still up. The old forward row now stays authoritative until the set has a healthy copy (R23's second option; the forward row has no health of its own to inherit). Reload keeps the map it replaces, and a set row whose host was a fleet forward row of the same account, app and fleet, whose box the set keeps, gets a replicaHandoff: while no live copy exists and no copy of the set's incarnation has ever passed (replicaProber.Risen, a latch on the job), the replica transport sends the request to that box only, as the authoritative forward row would. Reload carries the handoff from map to map and drops it once a copy has risen, so a set that has served never falls back to the replaced row. TestReplicaCopiesRaiseKeepsServingCopy is the witness through PutForward and Reload: zero 503s across the conversion (11 without the fix).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+338
−2
internal/edge/edge.go+16 −2internal/edge/replica_handoff_test.go+232 −0internal/edge/replicaprober.go+25 −0internal/edge/replicaproxy.go+65 −0
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 4dc8cfe12..7cefe0e93 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -572,6 +572,10 @@ type upstream struct { |
| // the app carries the same fleet placement on its row and serves it from |
| // the socket, and must file what it sees (emitEdgeError). |
| viaTunnel bool |
| + // handoff is an ArmReplica entry's replaced forward row, while it is |
| + // still authoritative (replicaHandoff, R23); nil otherwise. Reload |
| + // reads it from the map it replaces to carry it to the next. |
| + handoff *replicaHandoff |
| // alias marks an entry mapped in from route_aliases: it shares the |
| // primary's proxy/route/hibernating verbatim (so hibernation wakes the |
| // primary's actEntry and #152's per-primary prober state applies), and |
| @@ -962,6 +966,10 @@ func (e *Edge) Reload() error { |
| return err |
| } |
| m := make(map[string]upstream, len(routes)) |
| + // prevMap is the map this reload replaces: only Reload publishes, under |
| + // reloadMu, so it is the one requests are being served from. A replica |
| + // set's handoff (R23) is judged against the host's entry in it. |
| + prevMap := e.current() |
| // The hosts the activator should manage after this reload — feeds both the |
| // per-upstream gate and the retire pass below. |
| managed := make(map[string]bool) |
| @@ -1080,6 +1088,8 @@ func (e *Edge) Reload() error { |
| // ten: the tenancy of a host served through a tunnel (upgrades.go), |
| // from the same value that picks the arm's destination below. |
| var ten tenancy |
| + // handoff: an ArmReplica entry's replaced forward row (R23). |
| + var handoff *replicaHandoff |
| // served is the fleet arm's answer for this row (FleetArmVerdict's |
| // Arm): the fleet cases below take their fleet from it, and nothing |
| // else reaches a fleet's tunnel. The arm itself is DispatchArm, the |
| @@ -1092,7 +1102,11 @@ func (e *Edge) Reload() error { |
| switch arm { |
| // Sets select only live assigned copies, before legacy fleet fallback. |
| case ArmReplica: |
| - p := replicaProxy(t.Host, served.Fleet, e.replicaProberForRouting(), e.tunnels) |
| + prober := e.replicaProberForRouting() |
| + prevUp, had := prevMap[t.Host] |
| + handoff = replicaHandoffFor(t, served, prevUp, had, prober) |
| + p := replicaProxy(t.Host, served.Fleet, prober, e.tunnels) |
| + p.Transport.(*replicaTransport).handoff = handoff |
| p.ModifyResponse = classifyMoveStreams(e.responseModifier(t)) |
| proxy, viaTunnel = p, true |
| ten = tenancy{Arm: ArmReplica, Account: served.Account, App: served.App, Fleet: served.Fleet} |
| @@ -1394,7 +1408,7 @@ func (e *Edge) Reload() error { |
| "route %s is a hibernating instance but this box has no activator, so nothing here will create %s or start its process. If this box runs `carlos agent`, set CARLOS_HIBERNATE_BUCKET in /etc/carlos/host.env and restart carlos-edge; `carlos edge` on its own never runs instances.", |
| t.Host, t.Socket)) |
| } |
| - m[t.Host] = upstream{demoAPIProxy: demoAPIProxy, proxy: proxy, route: t, hibernating: hib, viaTunnel: viaTunnel, genManaged: genManaged, |
| + m[t.Host] = upstream{demoAPIProxy: demoAPIProxy, proxy: proxy, route: t, hibernating: hib, viaTunnel: viaTunnel, genManaged: genManaged, handoff: handoff, |
| rate: e.parseRateSettings(t), tenancy: ten, localBackend: !viaTunnel && (arm == ArmSocket || hib)} |
| } |
| // Path routes, folded BEFORE aliases so an alias of a prefix-routed |
diff --git a/internal/edge/replica_handoff_test.go b/internal/edge/replica_handoff_test.go| new file mode 100644 |
| index 000000000..373091109 |
| --- /dev/null |
| +++ b/internal/edge/replica_handoff_test.go |
| @@ -0,0 +1,232 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/replicas" |
| +) |
| + |
| +// handoffFixture is a hub with two connected fleet boxes, box-00 and |
| +// box-01, each answering with its own name, and a replica prober whose |
| +// probe of a box passes only once that box has the set's row (ready), as a |
| +// real box's replica-probe endpoint does only after its own registry |
| +// reload. |
| +type handoffFixture struct { |
| + e *Edge |
| + clock *replicaTestClock |
| + mu sync.Mutex |
| + ready map[string]bool |
| +} |
| + |
| +func (f *handoffFixture) setReady(box string, ready bool) { |
| + f.mu.Lock() |
| + f.ready[box] = ready |
| + f.mu.Unlock() |
| +} |
| + |
| +func newHandoffFixture(t *testing.T) *handoffFixture { |
| + t.Helper() |
| + answer := func(box string) http.HandlerFunc { |
| + return func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, box) } |
| + } |
| + hub, _, _ := replicaProxyFixture(t, answer("box-00"), answer("box-01")) |
| + reg := openReg(t) |
| + if err := reg.UpsertFleet(registry.Fleet{Name: "pi", Account: "bab", Bucket: "pi-data"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + e, err := New(reg, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Setenv("CARLOS_TUNNEL_HOST", "tunnel.example.com") |
| + t.Setenv("CARLOS_FLEET", "") |
| + e.EnableTunnels(hub) |
| + f := &handoffFixture{e: e, clock: newReplicaTestClock(), ready: map[string]bool{}} |
| + e.replicaProbes = newReplicaProber(hub, func(_ context.Context, channel, host string) (replicas.Copy, error) { |
| + box := strings.TrimPrefix(channel, "pi/") |
| + f.mu.Lock() |
| + ok := f.ready[box] |
| + f.mu.Unlock() |
| + if !ok { |
| + return replicas.Copy{}, errors.New(replicaFailed) |
| + } |
| + row, err := reg.Get(host) |
| + if err != nil { |
| + return replicas.Copy{}, err |
| + } |
| + return replicaTestCopy(*row, box), nil |
| + }, f.clock) |
| + t.Cleanup(e.stopReplicaProbes) |
| + t.Cleanup(e.probers.Stop) |
| + return f |
| +} |
| + |
| +// get sends one GET through the hub's front door and returns the status and |
| +// which box answered. |
| +func (f *handoffFixture) get(t *testing.T) (int, string) { |
| + t.Helper() |
| + w := replicaRoutingGet(f.e, "shop.example.com") |
| + return w.Code, w.Body.String() |
| +} |
| + |
| +// TestReplicaCopiesRaiseKeepsServingCopy is R23's witness: copies 1 -> 2 |
| +// through the hub's real route rewrite (PutForward, the registry writer the |
| +// provision pass's "forward ...: rewritten" calls, then Reload), with zero |
| +// 503s across the conversion. Drill 3 saw 9 s of hub 503s here: the new |
| +// set's copies start unhealthy, and box-1's probe passes only once box-1 |
| +// has reloaded its own registry, while the copy itself never stopped. |
| +// |
| +// The old forward row stays authoritative until a copy of the set has |
| +// passed its health check; from then on the set is, even when every copy |
| +// later fails (no fallback back to the old row). |
| +func TestReplicaCopiesRaiseKeepsServingCopy(t *testing.T) { |
| + f := newHandoffFixture(t) |
| + single := registry.Route{Host: "shop.example.com", Kind: registry.KindForward, Region: "fleet/pi", Account: "bab", App: "shop", FleetLabel: "box-00", Stateless: true} |
| + if err := f.e.reg.PutForward(single); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if code, box := f.get(t); code != 200 || box != "box-00" { |
| + t.Fatalf("copies 1: %d %q", code, box) |
| + } |
| + |
| + // The raise: the hub's row becomes the set. Neither box has the set's |
| + // row yet, so no copy's probe passes. |
| + set := single |
| + set.FleetLabel = "" |
| + set.FleetBoxes, set.Copies, set.ReplicaRevision, set.ReplicaIncarnation = `["box-00","box-01"]`, 2, 1, "life" |
| + if err := f.e.reg.PutForward(set); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + var fives int |
| + check := func(when string) { |
| + t.Helper() |
| + code, box := f.get(t) |
| + if code == http.StatusServiceUnavailable { |
| + fives++ |
| + } |
| + if code != 200 || box != "box-00" { |
| + t.Errorf("%s: %d %q, want the serving copy on box-00", when, code, box) |
| + } |
| + } |
| + check("right after the rewrite") |
| + replicaSettled(t, f.clock, 2) |
| + // About drill 3's 9 s of failing probes, with an unrelated reload in |
| + // the middle: the handoff is carried from map to map. |
| + for i := 0; i < 9; i++ { |
| + f.clock.advance(time.Second) |
| + replicaSettled(t, f.clock, 4+2*i) |
| + check("while the set's probes fail") |
| + if i == 4 { |
| + if err := f.e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + // box-00 reloads its registry: its copy passes twice and the set takes |
| + // over. |
| + f.setReady("box-00", true) |
| + f.clock.advance(time.Second) |
| + replicaSettled(t, f.clock, 22) |
| + check("one passing probe") |
| + f.clock.advance(time.Second) |
| + replicaSettled(t, f.clock, 24) |
| + check("the set's first healthy copy") |
| + // TestReplicaCopiesRaiseKeepsServingCopy |
| + if fives != 0 { |
| + t.Fatalf("%d hub 503s across the conversion", fives) |
| + } |
| + if up, _ := f.e.lookupUpstream("shop.example.com"); up.tenancy.Arm != ArmReplica || !f.e.replicaProbes.Risen("shop.example.com", "life") { |
| + t.Fatalf("the set is not authoritative: %+v", up.tenancy) |
| + } |
| + |
| + // box-01 joins: both copies serve. |
| + f.setReady("box-01", true) |
| + f.clock.advance(time.Second) |
| + replicaSettled(t, f.clock, 26) |
| + f.clock.advance(time.Second) |
| + replicaSettled(t, f.clock, 28) |
| + seen := map[string]bool{} |
| + for i := 0; i < 4; i++ { |
| + code, box := f.get(t) |
| + if code != 200 { |
| + t.Fatalf("2 of 2: %d %q", code, box) |
| + } |
| + seen[box] = true |
| + } |
| + if !seen["box-00"] || !seen["box-01"] { |
| + t.Fatalf("both copies did not serve: %v", seen) |
| + } |
| + |
| + // Every copy fails: the set answers, not the replaced row, and a reload |
| + // does not bring the row back. |
| + f.setReady("box-00", false) |
| + f.setReady("box-01", false) |
| + for n := 30; n <= 32; n += 2 { |
| + f.clock.advance(time.Second) |
| + replicaSettled(t, f.clock, n) |
| + } |
| + if err := f.e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + w := replicaRoutingGet(f.e, "shop.example.com") |
| + if w.Code != http.StatusServiceUnavailable || w.Body.String() != replicaUnavailable+"\n" { |
| + t.Fatalf("the replaced forward row came back after the set had risen: %d %q", w.Code, w.Body) |
| + } |
| +} |
| + |
| +// TestReplicaHandoffOnlyForTheServingBox: the replaced row hands off only |
| +// to its own box, and only when the set keeps that box; a set without it, |
| +// a set in another lifetime, or a host whose previous entry was not a |
| +// fleet forward row gets no handoff (the set answers from the start). |
| +func TestReplicaHandoffOnlyForTheServingBox(t *testing.T) { |
| + served := FleetServed{Account: "bab", App: "shop", Fleet: "pi"} |
| + set := registry.Route{Host: "shop.example.com", Kind: registry.KindForward, Region: "fleet/pi", Account: "bab", App: "shop", Stateless: true, |
| + FleetBoxes: `["box-00","box-01"]`, Copies: 2, ReplicaRevision: 1, ReplicaIncarnation: "life"} |
| + forward := upstream{route: registry.Route{Host: set.Host, Kind: registry.KindForward, FleetLabel: "box-00", FleetBox: "box-00"}, tenancy: tenancy{Arm: ArmForward, Account: "bab", App: "shop", Fleet: "pi"}} |
| + p := newReplicaProber(nil, nil, newReplicaTestClock()) |
| + if h := replicaHandoffFor(set, served, forward, true, p); h == nil || h.box != "box-00" || h.fleet != "pi" || h.incarnation != "life" { |
| + t.Fatalf("forward row to set: %+v", h) |
| + } |
| + other := forward |
| + other.route.FleetLabel, other.route.FleetBox = "box-09", "box-09" |
| + wrongApp := forward |
| + wrongApp.tenancy.App = "another" |
| + alias := forward |
| + alias.route.Host = "elsewhere.example.com" |
| + local := forward |
| + local.tenancy = tenancy{} |
| + carried := upstream{route: set, tenancy: tenancy{Arm: ArmReplica, Account: "bab", App: "shop", Fleet: "pi"}, handoff: &replicaHandoff{fleet: "pi", box: "box-00", incarnation: "old-life"}} |
| + for name, prev := range map[string]upstream{"box not in the set": other, "another app": wrongApp, "an alias entry": alias, "not a fleet row": local, "another lifetime": carried} { |
| + if h := replicaHandoffFor(set, served, prev, true, p); h != nil { |
| + t.Fatalf("%s: handed off to %+v", name, h) |
| + } |
| + } |
| + if h := replicaHandoffFor(set, served, forward, false, p); h != nil { |
| + t.Fatal("no previous entry handed off") |
| + } |
| + carried.handoff.incarnation = "life" |
| + if h := replicaHandoffFor(set, served, carried, true, p); h == nil || h.box != "box-00" { |
| + t.Fatalf("handoff not carried: %+v", h) |
| + } |
| + // A channel the handoff names that is not connected answers as an |
| + // empty set does. |
| + tr := &replicaTransport{host: set.Host, fleet: "pi", p: p, hub: NewTunnelHub("tunnel.example.com", nil), handoff: &replicaHandoff{fleet: "pi", box: "box-00", incarnation: "life"}} |
| + if _, err := tr.RoundTrip(httptest.NewRequest("GET", "https://shop.example.com/", nil)); err != errReplicaUnavailable { |
| + t.Fatalf("disconnected handoff box: %v", err) |
| + } |
| +} |
diff --git a/internal/edge/replicaprober.go b/internal/edge/replicaprober.go| index a94efc066..9d7e6d60d 100644 |
| --- a/internal/edge/replicaprober.go |
| +++ b/internal/edge/replicaprober.go |
| @@ -71,6 +71,10 @@ type replicaJob struct { |
| count upstreamState |
| sample replicas.Copy |
| evidence replicas.Copy |
| + // risen: this job's copy has passed its health check at least once |
| + // (count.up). It survives ejection and reconnection, and goes with |
| + // the job when Sync replaces it (Risen, R23). |
| + risen bool |
| } |
| type replicaProber struct { |
| mu sync.Mutex |
| @@ -269,6 +273,7 @@ func (p *replicaProber) record(j *replicaJob, conn *tunnelConn, c replicas.Copy, |
| failure = errors.New(reason) |
| } |
| current.count.recordProbe(failure, replicaProbeFail, replicaProbeRise, p.clock.Now()) |
| + current.risen = current.risen || current.count.up |
| current.sample.Healthy = current.count.up |
| current.sample.ObservedAt = p.clock.Now() |
| if current.count.up { |
| @@ -343,6 +348,26 @@ func (p *replicaProber) Live(host string) []replicas.Copy { |
| return live |
| } |
| +// Risen reports whether any copy of host's current set, in incarnation, has |
| +// passed its health check since its job began: the moment a replaced |
| +// forward row stops being authoritative (replicaHandoff, R23). |
| +func (p *replicaProber) Risen(host, incarnation string) bool { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + rt, ok := p.routes[host] |
| + if !ok { |
| + return false |
| + } |
| + var boxes []string |
| + _ = json.Unmarshal([]byte(rt.FleetBoxes), &boxes) |
| + for _, box := range boxes { |
| + if j := p.jobs[replicaSlot{host, box}]; j != nil && j.key.incarnation == incarnation && j.risen { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| // Eject is for a copy whose connection is gone or refusing new streams |
| // (TunnelHub.replicaChannelLost), found on a request's failure (R22). An |
| // ordinary request error must be left to the health probes. |
diff --git a/internal/edge/replicaproxy.go b/internal/edge/replicaproxy.go| index 30a6b831c..4b6360a34 100644 |
| --- a/internal/edge/replicaproxy.go |
| +++ b/internal/edge/replicaproxy.go |
| @@ -13,6 +13,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/apperr" |
| + "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/replicas" |
| ) |
| @@ -35,6 +36,9 @@ type replicaTransport struct { |
| p *replicaProber |
| hub *TunnelHub |
| cursor atomic.Uint64 |
| + // handoff, when set, is the forward row this set replaced on this hub |
| + // (R23, replicaHandoff). Reload sets it once, before the proxy serves. |
| + handoff *replicaHandoff |
| // Test seam for the interval between transport completion and timer stop. |
| afterRoundTrip func(context.Context) |
| // Test seam for the interval between selecting a copy and dispatching |
| @@ -69,6 +73,9 @@ func replicaProxy(host, fleet string, p *replicaProber, hub *TunnelHub) *httputi |
| func (t *replicaTransport) RoundTrip(req *http.Request) (*http.Response, error) { |
| // Capture once: a request never cycles around or expands its retry budget. |
| live := t.p.Live(t.host) |
| + if len(live) == 0 && t.handoff != nil && !t.p.Risen(t.host, t.handoff.incarnation) { |
| + return t.handoffRoundTrip(req) |
| + } |
| body := replicaBody(req.Body) |
| owned := false |
| defer func() { |
| @@ -239,6 +246,64 @@ func (t *replicaTransport) RoundTrip(req *http.Request) (*http.Response, error) |
| return nil, last |
| } |
| +// handoffRoundTrip serves a request through the forward row the set |
| +// replaced (R23): to that row's own box only, as an authoritative forward |
| +// row would, with no other copy to retry on. The box keeps the copy that was |
| +// serving the host running, so the conversion drops nothing while the set's |
| +// copies wait for their first passing health check. |
| +func (t *replicaTransport) handoffRoundTrip(req *http.Request) (*http.Response, error) { |
| + h := t.handoff |
| + channel := h.fleet + "/" + h.box |
| + if t.hub.channel(channel) == nil { |
| + return nil, errReplicaUnavailable |
| + } |
| + if o := outcomeFrom(req); o != nil { |
| + o.replicaBox = h.box |
| + o.replicaAttempts = 1 |
| + } |
| + return t.hub.transportFor(channel).RoundTrip(req) |
| +} |
| + |
| +// replicaHandoff is the forward row a replica set replaced on this hub |
| +// (R23). A copies raise rewrites the hub's single-box forward row into the |
| +// set's route, and every copy of the new set starts unhealthy until it |
| +// passes two probes; a copy's probe passes only once its own box has the |
| +// set's row, which can take several seconds. Until some copy of the set has |
| +// passed its health check, the old row stays authoritative: its box (the |
| +// one already serving the host, which the set keeps) serves every request. |
| +// Once a copy has passed, the set is authoritative for good, even if every |
| +// copy later fails. Reload carries the handoff from map to map, for the |
| +// same host, tenancy, incarnation and box, and drops it once a copy has |
| +// risen. |
| +type replicaHandoff struct { |
| + fleet, box, incarnation string |
| +} |
| + |
| +// replicaHandoffFor is the handoff for set route t, whose fleet arm is |
| +// served, given the host's entry in the map being replaced (prev, had). |
| +// Only the host's own entry counts, never an alias of another host. |
| +func replicaHandoffFor(t registry.Route, served FleetServed, prev upstream, had bool, p *replicaProber) *replicaHandoff { |
| + if !had || prev.route.Host != t.Host || prev.tenancy.Account != served.Account || prev.tenancy.App != served.App || prev.tenancy.Fleet != served.Fleet { |
| + return nil |
| + } |
| + var box string |
| + switch prev.tenancy.Arm { |
| + case ArmForward, ArmFleet: |
| + box, _ = fleetBoxOf(prev.route) |
| + case ArmReplica: |
| + if prev.handoff == nil || prev.handoff.incarnation != t.ReplicaIncarnation { |
| + return nil |
| + } |
| + box = prev.handoff.box |
| + default: |
| + return nil |
| + } |
| + if box == "" || !t.ReplicaContains(box) || p.Risen(t.Host, t.ReplicaIncarnation) { |
| + return nil |
| + } |
| + return &replicaHandoff{fleet: served.Fleet, box: box, incarnation: t.ReplicaIncarnation} |
| +} |
| + |
| // replicaAttemptBody is one attempt's view of the request body. Close is |
| // passed on only once the attempt has started reading: a ClientConn closes |
| // the body on every exit, and on a stream refused before its headers were |