box: refuse a retired replica copy's late requests (#511 R28)
Drill 4 scaled copies 2 to 1 and got 14 POST 404s: box-2's provision pass dropped its row (reconcile.go DeleteReplicaAssignment, "removed retired instance route ... (record gone)"), its edge reloaded with no entry for the host, and requests the hub still sent it fell to the lookup miss and unknownHost's 404. Reload now notes, before it publishes, every name the map it replaces served for this box's copy of a set with more than one copy (an instance row, ManyCopies) that the new map lacks along with the copy's own host. For retiredCopyGrace (60 s, two hubSetReloadBound of 30 s), a lookup miss on such a name over a fleet tunnel is refused with REFUSED_STREAM, so the hub retries it on a surviving copy whatever its method (R26). After the probe branch, so the hub's probe still fails and keeps the copy out. Any other host, and the same host after the grace, gets the unknown-host answer as before. Witness through the real hub and box wiring: TestReplicaRetiredCopyServedBySurvivor (scale-down under GET and POST load, late requests to box-00 served by box-01, the hub's rewrite to one copy, zero failures). TestRetiredCopyGraceEnds and TestRetiredCopyNeverServedHost404 are the negatives; TestRetiredCopiesNote pins the scope.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/edge/edge.go+14 −0internal/edge/replica_drain_e2e_test.go+18 −11internal/edge/replica_retire_e2e_test.go+347 −0internal/edge/retiredcopy.go+126 −0internal/edge/retiredcopy_test.go+82 −0
Intent
<task-notification> <task-id>a41c5fc02dcfea0c5</task-id> <tool-use-id>toolu_01V4Ef5SHJf4qDBiXPPjGatd</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/a41c5fc02dcfea0c5.output</output-file> <status>completed</status> <summary>Agent "Fix drill-3 hub routing gaps" 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>- **Status: DONE.** Tip 561beefc, not pushed. - **Commits:** - d68aad3d: an outside stop now ends the dial hold, or refuses a request, only on a replica-set row with more than one copy (`edge.ManyCopies`: the box's own row has FleetBoxes, Copies above 1 and a valid replica projection). Single-copy rows hold up to 13 s for a restart and are not refused. The drain still applies to every row. - 561beefc: census re-proposed (new unit `ManyCopies`, seal 7103c9b7, `make census-card` clean). `Edge.Reload` changed, so it is re-pinned in `TestGroupNameClassCensus`. - **Tests:** - New `TestSingleCopyDialHoldWaitsForRestart`: on a single-copy row the app is stopped from outside, a POST waits in the real dial hold, the app restarts, and box-00 serves the POST (200, no 503). Without the copies check, the hold ends and box-01 serves it, so the test fails. - The replica-row witnesses, now on a real two-copy box row, pass 3 runs together with the earlier witnesses and `TestTwoBoxFleetEndToEnd`. - The activator test now covers one copy and two. - A targeted race run, the HA guards, grouproll, the three cross-compiles and the census tests all pass. - **Concerns:** the copy count is read from the box's own row, so a copies change on the box takes effect when the box next reloads its registry. Astra's census review is still owed. - **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/stateless-replicas-4/.superpowers/sdd/2026-11-01-stateless-replicas-4-deploy-and-drill/task-drill3-report.md</result> <usage><subagent_tokens>756576</subagent_tokens><tool_uses>36</tool_uses><duration_ms>2956013</duration_ms></usage> </task-notification>
<paseo-system version="1" kind="agent-message" source-agent-id="8a3d302a-eac7-407c-b61c-f5ccc66b5544" message-id="56dc81cb-f41b-41e4-b768-f3f1a6d3fcb6"> Agent manager 8a3d302: drill 4 window: dev is free now. Tonight is preferred: start any time after the re-reviews, census and CI are clean and Paul's B2 go is recorded, with a hard end 01:30Z (dev must be quiet before the 03:00Z restore drill, whose results get checked in the morning). If you can't start by 23:00Z, take tomorrow from 05:00Z instead, but then ask me first: the v0.34.49 flagship roll may need the window slot then (one live window at a time). Same rules as before; end state dev console on v0.34.49 by promote; delete drill-sr4 boxes before 01:30Z so they don't run tonight's drill. </paseo-system>
<task-notification> <task-id>bynnpukp2</task-id> <tool-use-id>toolu_01Ds7htzvZWJzitkHfzdSpey</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/bynnpukp2.output</output-file> <status>completed</status> <summary>Background command "Astra final re-review of drill-3 rounds 2-3" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>b0g9vbawo</task-id> <tool-use-id>toolu_01G9EdvsxKUJ6d1czLHoTq1A</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/b0g9vbawo.output</output-file> <status>completed</status> <summary>Background command "Astra census review of rounds 2-3" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>bkmyh9r14</task-id> <tool-use-id>toolu_01DhxmAes4t8sTxXUuPvhYLp</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/bkmyh9r14.output</output-file> <status>completed</status> <summary>Background command "Fable final re-review of drill-3 rounds 2-3" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>bvwchnr5a</task-id> <tool-use-id>toolu_016M7QHYcCrVTSthQJim398j</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/bvwchnr5a.output</output-file> <status>completed</status> <summary>Background command "Wait for CI on 561beefc" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a3c9bf7fefa2920e1</task-id> <tool-use-id>toolu_014momJoB6xcevKByT8bRo9F</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/a3c9bf7fefa2920e1.output</output-file> <status>completed</status> <summary>Agent "Run stateless replicas dev drill 4" 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>**FAIL.** Drill 4 ran from start to finish, but it could not test most of the fixes. The hub that routes the drill traffic is sophie's carlos-edge, which the drill rules keep on v0.34.49. So the hub-side fixes R22, R23, R25 and R26 were never in play. Only the box-side R24 and R27 ran on v0.35.902. - **Copies 1 to 2 (5 GET + 5 POST a second):** 70 hub 503s (35 GET, 35 POST) over 7 s (17:33:39-46Z), right after the hub rewrote its route for the app. That is drill 3's 503 gap again, from the v0.34.49 hub. The serving copy stayed up, box-2 joined without running the release, and the view showed 2 of 2. That took 5 min, against about 2 min in drill 3. - **Graceful stop of box-2 (10 GET + 10 POST a second):** 0 failed GETs, 2 failed POSTs, 2 cut streams. - **The gap:** box-2's app stopped at 17:40:14.703Z and its edge got SIGTERM at 14.937 (234 ms). - **What the gap requests got:** the one GET was held by box-2, then retried by the hub on box-1 (200). Both gap POSTs got 502 from the hub at 14.928 and no app processed them. That fits box-2 refusing them as the drain started (R27); the v0.34.49 hub then answered 502 instead of retrying them on box-1. - **Return:** 50/50 split with 0 failures. **Good deploy:** the release ran once, the swaps were ordered, 0 failed reads, 2 cut streams. - **Extra phases:** the failing release passed. Scale-down to 1 copy had 54 failures: 14 were 404s because box-2 dropped its route while the hub still sent to it, and 40 were hub 503s. - Every one of the 8,541 successful POSTs ran exactly once, on the box that answered. - **B2 window (on v0.34.49):** passed in one go, with 54 s of console downtime, and the HA rows were unchanged. **Cleanup:** complete by 18:02Z, well inside 01:15Z. The dev console is back on v0.34.49 by promote (exe 4fe296d2). The v0.35.902 console release files are deleted. The drill-sr4 boxes were terminated at 17:59:40Z and detached, and their bucket, security group and IAM user are deleted. srdrill4 is in the trash. Canary and stable were not touched, and the #421 lock is released. **For you:** 1. Testing R22, R23, R25 and R26 needs a hub running the candidate. That means either a ruling from Paul and 8a3d302 to put it on sophie's carlos-edge for a window, or a live test once v0.35.0 reaches dev. 2. The scale-down 404s come from box-2 dropping its route before the hub stopped sending to it. That ordering is on the console and box side, not the hub. 3. Still on dev: - the drill-sr4 fleet row (the next hostname-history refresh needs `-close-fleet drill-sr4`); - srdrill4 in the hostname history; - backups on sophie in `/root/console-db-backups/*drill4` and `/root/hu-sr44`. 4. The next candidate name is v0.35.903. 5. My GET/POST alternation meant only 2 POSTs reached box-2 during the stop. The next drill should pick the method at random; `sr4load -random` in the evidence scripts does that. Files are in /home/paulca/.cache/tmp/claude-1001/sr4-drill4/: - drill-report.md - progress.log - evidence/</result> <usage><subagent_tokens>329849</subagent_tokens><tool_uses>158</tool_uses><duration_ms>3294434</duration_ms></usage> </task-notification>
<paseo-system version="1" kind="agent-message" source-agent-id="8a3d302a-eac7-407c-b61c-f5ccc66b5544" message-id="b1038500-6054-4445-8810-79d99acfafc9"> Agent manager 8a3d302: understood, Paul's ruling noted. Tell me when Plan 4 is merged (SHA, CI green). I'll then have v0.35.0 cut and rolled to dev only; it queues behind the v0.34.49 flagship roll (tomorrow after the member-backups morning check), one window at a time. Drill 5 window after the dev roll. </paseo-system>
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 30362fe26..7f30d079c 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -123,6 +123,9 @@ type Edge struct { |
| ReplicaProbe func(context.Context, string, string) (replicas.Copy, error) |
| replicaMu sync.Mutex |
| replicaProbes *replicaProber |
| + // retired: the hosts whose replica copy this box retired within the |
| + // grace (#511 R28, retiredcopy.go). Reload writes it; ServeHTTP reads it. |
| + retired retiredCopies |
| demoTraffic *demoTrafficState |
| demoTrafficOnce sync.Once |
| @@ -1573,6 +1576,9 @@ func (e *Edge) Reload() error { |
| } |
| e.haIngressBlocked.Store(&blockedIngress) |
| e.demoNames.Store(&demoNames) |
| + // Before the publication: a request that misses a retiring copy's host |
| + // in m must already find it retiring (R28). |
| + e.noteRetiredCopies(prevMap, m) |
| e.upstreams.Store(&m) |
| if h := e.hooks; h != nil && h.afterPublish != nil { |
| _ = h.afterPublish(id) |
| @@ -2424,6 +2430,14 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| e.serveReplicaProbe(w, r, host, up.route, replicaProbe) |
| return |
| } |
| + // A host this box no longer serves because its replica copy just |
| + // retired (#511 R28): the hub may still send it requests until it |
| + // drops the copy, so they are refused unprocessed for the hub to serve |
| + // from another copy, never answered as an unknown host. After the |
| + // probe's branch, so the hub's probe still fails and keeps the copy out. |
| + if !ok && !pinned && e.refuseRetiredCopy(r, host) { |
| + return |
| + } |
| // GeoIP steps 3-4 (geoip spec §8.1, §8.2): decide once, keep it on the |
| // context for setGeo and analytics, and expose the app-visible headers on |
| // r.Header so the cache's Vary matching sees exactly what the app will |
diff --git a/internal/edge/replica_drain_e2e_test.go b/internal/edge/replica_drain_e2e_test.go| index f04d62db4..bbf024ab4 100644 |
| --- a/internal/edge/replica_drain_e2e_test.go |
| +++ b/internal/edge/replica_drain_e2e_test.go |
| @@ -34,16 +34,17 @@ func (a *replicaDrainAdmission) CloseTenantAdmission() { a.closed.Store( |
| // local backend, behind the production tunnel loop with its drain wired |
| // to the edge's shutdown start, as the agent wires it. |
| type replicaDrainBox struct { |
| - label string |
| - edge *Edge |
| - admission *replicaDrainAdmission |
| - reached atomic.Int32 // requests that reached the box's edge over the tunnel |
| - backend atomic.Int32 // requests that reached the app |
| - cancel context.CancelFunc |
| - done chan struct{} |
| - finish chan struct{} // releases /slow?id=finish |
| - release sync.Once |
| - inflight chan string // /slow ids that reached the app |
| + label string |
| + edge *Edge |
| + admission *replicaDrainAdmission |
| + reached atomic.Int32 // requests that reached the box's edge over the tunnel |
| + reachedPost atomic.Int32 // the POSTs among them |
| + backend atomic.Int32 // requests that reached the app |
| + cancel context.CancelFunc |
| + done chan struct{} |
| + finish chan struct{} // releases /slow?id=finish |
| + release sync.Once |
| + inflight chan string // /slow ids that reached the app |
| } |
| func newReplicaDrainBox(t *testing.T, hubURL, label, token string, drains bool, act *replicaGapActivator, genAct *replicaGenActivator) *replicaDrainBox { |
| @@ -140,7 +141,13 @@ func newReplicaDrainBox(t *testing.T, hubURL, label, token string, drains bool, |
| if drains { |
| loopDrain = drain |
| } |
| - handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { b.reached.Add(1); e.ServeHTTP(w, r) }) |
| + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + b.reached.Add(1) |
| + if r.Method == http.MethodPost { |
| + b.reachedPost.Add(1) |
| + } |
| + e.ServeHTTP(w, r) |
| + }) |
| ctx, cancel := context.WithCancel(context.Background()) |
| b.cancel = cancel |
| go func() { |
diff --git a/internal/edge/replica_retire_e2e_test.go b/internal/edge/replica_retire_e2e_test.go| new file mode 100644 |
| index 000000000..4d0434dfd |
| --- /dev/null |
| +++ b/internal/edge/replica_retire_e2e_test.go |
| @@ -0,0 +1,347 @@ |
| +package edge |
| + |
| +import ( |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// retireDo sends method with body for host to the hub. No t.Fatal: it may |
| +// run off the test's goroutine, so a failed request is a result with code |
| +// 0 and the error as its text. |
| +func retireDo(srvURL, host, method, body string) drainResult { |
| + var rd io.Reader |
| + if body != "" { |
| + rd = strings.NewReader(body) |
| + } |
| + req, err := http.NewRequest(method, srvURL+"/", rd) |
| + if err != nil { |
| + return drainResult{method, body, 0, err.Error()} |
| + } |
| + req.Host = host |
| + resp, err := (&http.Client{Timeout: 10 * time.Second}).Do(req) |
| + if err != nil { |
| + return drainResult{method, body, 0, err.Error()} |
| + } |
| + b, _ := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + return drainResult{method, body, resp.StatusCode, string(b)} |
| +} |
| + |
| +// retireLoad is GET and POST load on shop.example.com through the hub: |
| +// workers each alternate the method, every POST with its own body. |
| +type retireLoad struct { |
| + stop chan struct{} |
| + wg sync.WaitGroup |
| + mu sync.Mutex |
| + res []drainResult |
| +} |
| + |
| +func startRetireLoad(srvURL string, workers int) *retireLoad { |
| + l := &retireLoad{stop: make(chan struct{})} |
| + for w := 0; w < workers; w++ { |
| + l.wg.Add(1) |
| + go func(w int) { |
| + defer l.wg.Done() |
| + for i := 0; ; i++ { |
| + select { |
| + case <-l.stop: |
| + return |
| + default: |
| + } |
| + method, body := "GET", "" |
| + if (w+i)%2 == 0 { |
| + method, body = "POST", fmt.Sprintf("w%d-%d", w, i) |
| + } |
| + res := retireDo(srvURL, "shop.example.com", method, body) |
| + l.mu.Lock() |
| + l.res = append(l.res, res) |
| + l.mu.Unlock() |
| + time.Sleep(2 * time.Millisecond) |
| + } |
| + }(w) |
| + } |
| + return l |
| +} |
| + |
| +func (l *retireLoad) end() []drainResult { |
| + close(l.stop) |
| + l.wg.Wait() |
| + return l.res |
| +} |
| + |
| +// checkServed fails t for every result that is not a 200 with the |
| +// echoing copy's answer from one of boxes. |
| +func checkServed(t *testing.T, phase string, res []drainResult, boxes ...string) (posts, gets int) { |
| + t.Helper() |
| + for _, r := range res { |
| + ok := r.code == http.StatusOK |
| + if ok { |
| + ok = false |
| + for _, b := range boxes { |
| + if r.got == b+" "+r.method+" "+r.body { |
| + ok = true |
| + } |
| + } |
| + } |
| + if !ok { |
| + t.Errorf("%s: %s %q: %d %q, want 200 from %v", phase, r.method, r.body, r.code, r.got, boxes) |
| + } |
| + if r.method == "POST" { |
| + posts++ |
| + } else { |
| + gets++ |
| + } |
| + } |
| + return posts, gets |
| +} |
| + |
| +// retireBox00 makes box-00's two-copy row the one provisioning holds |
| +// (Provisioned) and returns it; retire then drops it the way the box's |
| +// provisioning pass does when its copy retires (reconcile.go: |
| +// DeleteReplicaAssignment, "removed retired instance route ... (record |
| +// gone)"), and the box's registry poll reloads its edge. |
| +func retireBox00(t *testing.T, b0 *replicaDrainBox) (retire func()) { |
| + t.Helper() |
| + reg := b0.edge.reg |
| + row, err := reg.Get("shop.example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + row.Provisioned = true |
| + if err := reg.Upsert(*row); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := b0.edge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !ManyCopies(*row) { |
| + t.Fatalf("box-00's row is not a two-copy set: %+v", *row) |
| + } |
| + held := *row |
| + return func() { |
| + t.Helper() |
| + deleted, err := reg.DeleteReplicaAssignment(held) |
| + if err != nil || !deleted { |
| + t.Fatalf("retire box-00's copy: deleted %v, %v", deleted, err) |
| + } |
| + if err := b0.edge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok := b0.edge.current()["shop.example.com"]; ok { |
| + t.Fatal("box-00 still serves shop.example.com after its copy retired") |
| + } |
| + } |
| +} |
| + |
| +// tickUntil steps the hub's probe clock a second at a time until cond |
| +// holds, letting the probes each tick starts finish before the next tick |
| +// could time them out (relive's three back-to-back ticks can, under -race). |
| +func tickUntil(t *testing.T, r *drainRig, what string, cond func() bool) { |
| + t.Helper() |
| + deadline := time.Now().Add(10 * time.Second) |
| + for !cond() { |
| + if time.Now().After(deadline) { |
| + t.Fatal("timed out: " + what) |
| + } |
| + r.clock.advance(time.Second) |
| + time.Sleep(5 * time.Millisecond) |
| + for settle := time.Now().Add(time.Second); time.Now().Before(settle); time.Sleep(time.Millisecond) { |
| + r.clock.mu.Lock() |
| + idle := r.clock.started == r.clock.completed |
| + r.clock.mu.Unlock() |
| + if idle { |
| + break |
| + } |
| + } |
| + } |
| +} |
| + |
| +// reliveSteady brings box-00's copy back into the hub's live set after a |
| +// refusal ejected it, as relive does. |
| +func reliveSteady(t *testing.T, r *drainRig) { |
| + t.Helper() |
| + tickUntil(t, r, "both copies live again", func() bool { return len(r.edge.replicaProbes.Live("shop.example.com")) == 2 }) |
| +} |
| + |
| +// TestReplicaRetiredCopyServedBySurvivor is #511 R28's witness, drill 4's |
| +// scale-down from two copies to one through the real hub and box wiring |
| +// (a hub Edge and TunnelHub, fleet credentials from the registry, the |
| +// production tunnel loop, box Edges, box-00's instance through the real |
| +// appSocketProxy): under GET and POST load, box-00 drops its row the way |
| +// its provisioning pass does when its copy retires, while the hub still |
| +// lists box-00 in the set (its prober still finds the copy healthy: the |
| +// worst case, longer than a real probe of a host the box no longer |
| +// serves). Every late request the hub sends box-00, GETs and POSTs, is |
| +// refused unprocessed and served by box-01; then the hub rewrites the set |
| +// to box-01 alone under the same load. Zero failures throughout, and |
| +// box-00's app sees none of the late requests. |
| +// |
| +// Without the refusal box-00 answers them 404 "unknown host", as drill |
| +// 4's 14 POSTs got. |
| +func TestReplicaRetiredCopyServedBySurvivor(t *testing.T) { |
| + genAct := newReplicaGenActivator() |
| + r := newReplicaDrainRig(t, drainRigOpts{drains: true, genAct: genAct}) |
| + b0, b1 := r.boxes[0], r.boxes[1] |
| + retire := retireBox00(t, b0) |
| + |
| + // Load on both copies, then box-00's copy retires under it. |
| + load := startRetireLoad(r.url, 4) |
| + replicaAwait(t, "both copies serving the load", func() bool { return b0.backend.Load() > 0 && b1.backend.Load() > 0 }) |
| + retire() |
| + if !b0.edge.retired.retiring("shop.example.com") { |
| + t.Fatal("box-00 did not record its copy as retiring") |
| + } |
| + time.Sleep(300 * time.Millisecond) |
| + across := load.end() |
| + // Requests box-00 took before its row went may finish there. |
| + checkServed(t, "load across the retirement", across, "box-00", "box-01") |
| + // The activator retires the instance (RetireExcept): its app stops. |
| + genAct.app.stop() |
| + appAfter := b0.backend.Load() |
| + |
| + // The hub keeps sending box-00 requests: every time its copy comes |
| + // back into the live set (two passing probes), the next request of a |
| + // pair goes to it. Each is refused, and box-01 serves it. |
| + for wave := 0; wave < 3; wave++ { |
| + for _, method := range []string{"POST", "GET"} { |
| + reliveSteady(t, r) |
| + reached, posts := b0.reached.Load(), b0.reachedPost.Load() |
| + var pair []drainResult |
| + for k := 0; k < 2; k++ { |
| + body := "" |
| + if method == "POST" { |
| + body = fmt.Sprintf("late-%d-%d", wave, k) |
| + } |
| + pair = append(pair, retireDo(r.url, "shop.example.com", method, body)) |
| + } |
| + // TestReplicaRetiredCopyServedBySurvivor |
| + checkServed(t, "a late request", pair, "box-01") |
| + if got := b0.reached.Load() - reached; got != 1 { |
| + t.Fatalf("wave %d %s: %d of the pair reached box-00, want 1 (the hub picks copies in turn)", wave, method, got) |
| + } |
| + if method == "POST" && b0.reachedPost.Load()-posts != 1 { |
| + t.Fatalf("wave %d: the POST did not reach box-00", wave) |
| + } |
| + } |
| + // A burst while box-00 is live again. |
| + reliveSteady(t, r) |
| + var burst []<-chan drainResult |
| + for k := 0; k < 10; k++ { |
| + method, body := "GET", "" |
| + if k%2 == 0 { |
| + method, body = "POST", fmt.Sprintf("burst-%d-%d", wave, k) |
| + } |
| + ch := make(chan drainResult, 1) |
| + go func() { ch <- retireDo(r.url, "shop.example.com", method, body) }() |
| + burst = append(burst, ch) |
| + } |
| + var got []drainResult |
| + for _, ch := range burst { |
| + got = append(got, <-ch) |
| + } |
| + checkServed(t, "a burst", got, "box-01") |
| + } |
| + |
| + // The hub's own reload: its provision pass rewrites the set to box-01 |
| + // alone, under load. |
| + load = startRetireLoad(r.url, 4) |
| + time.Sleep(100 * time.Millisecond) |
| + one := registry.Route{Host: "shop.example.com", Kind: registry.KindForward, Region: "fleet/pi", Account: "bab", App: "shop", Stateless: true, |
| + FleetBoxes: `["box-01"]`, Copies: 1, ReplicaRevision: 2, ReplicaIncarnation: "life"} |
| + if err := r.edge.reg.PutForward(one); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := r.edge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + time.Sleep(300 * time.Millisecond) |
| + posts, gets := checkServed(t, "load across the hub's rewrite", load.end(), "box-01") |
| + if posts == 0 || gets == 0 { |
| + t.Fatalf("the load across the hub's rewrite sent %d POSTs and %d GETs", posts, gets) |
| + } |
| + if b0.backend.Load() != appAfter { |
| + t.Fatalf("box-00's app saw %d requests after its copy retired", b0.backend.Load()-appAfter) |
| + } |
| +} |
| + |
| +// TestRetiredCopyGraceEnds: R28's refusal lasts retiredCopyGrace. After it |
| +// box-00 answers a request for the retired host as an unknown host again |
| +// (404), the normal behaviour. |
| +func TestRetiredCopyGraceEnds(t *testing.T) { |
| + genAct := newReplicaGenActivator() |
| + r := newReplicaDrainRig(t, drainRigOpts{drains: true, genAct: genAct}) |
| + b0 := r.boxes[0] |
| + retireBox00(t, b0)() |
| + genAct.app.stop() |
| + |
| + pair := func() (res []drainResult) { |
| + reliveSteady(t, r) |
| + reached := b0.reached.Load() |
| + for k := 0; k < 2; k++ { |
| + res = append(res, retireDo(r.url, "shop.example.com", "GET", "")) |
| + } |
| + if got := b0.reached.Load() - reached; got != 1 { |
| + t.Fatalf("%d of the pair reached box-00, want 1", got) |
| + } |
| + return res |
| + } |
| + checkServed(t, "within the grace", pair(), "box-01") |
| + |
| + b0.edge.retired.mu.Lock() |
| + b0.edge.retired.now = func() time.Time { return time.Now().Add(retiredCopyGrace) } |
| + b0.edge.retired.mu.Unlock() |
| + var notFound, survivor int |
| + for _, res := range pair() { |
| + switch { |
| + case res.code == http.StatusNotFound && strings.Contains(res.got, "unknown host"): |
| + notFound++ |
| + case res.code == http.StatusOK && res.got == "box-01 GET ": |
| + survivor++ |
| + default: |
| + t.Errorf("after the grace: %d %q", res.code, res.got) |
| + } |
| + } |
| + // TestRetiredCopyGraceEnds |
| + if notFound != 1 || survivor != 1 { |
| + t.Fatalf("after the grace: %d answered 404 by box-00 and %d by box-01, want 1 and 1", notFound, survivor) |
| + } |
| +} |
| + |
| +// TestRetiredCopyNeverServedHost404: the refusal is only for a host whose |
| +// copy this box retired. Inside box-00's grace for shop.example.com, a |
| +// host box-00 never served, which the hub sends to box-00 alone, still |
| +// gets box-00's 404 (a refusal would leave the hub no copy: 503). |
| +func TestRetiredCopyNeverServedHost404(t *testing.T) { |
| + genAct := newReplicaGenActivator() |
| + r := newReplicaDrainRig(t, drainRigOpts{drains: true, genAct: genAct}) |
| + b0 := r.boxes[0] |
| + retireBox00(t, b0)() |
| + if !b0.edge.retired.retiring("shop.example.com") { |
| + t.Fatal("box-00 did not record its copy as retiring") |
| + } |
| + never := registry.Route{Host: "never.example.com", Kind: registry.KindForward, Region: "fleet/pi", Account: "bab", App: "never", Stateless: true, |
| + FleetBoxes: `["box-00"]`, Copies: 1, ReplicaRevision: 1, ReplicaIncarnation: "never-life"} |
| + if err := r.edge.reg.PutForward(never); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := r.edge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Its probing job starts with the reload: tick until it has passed. |
| + tickUntil(t, r, "box-00's copy of never.example.com live at the hub", func() bool { return len(r.edge.replicaProbes.Live("never.example.com")) == 1 }) |
| + for _, method := range []string{"GET", "POST"} { |
| + reached := b0.reached.Load() |
| + res := retireDo(r.url, "never.example.com", method, "x") |
| + // TestRetiredCopyNeverServedHost404 |
| + if res.code != http.StatusNotFound || !strings.Contains(res.got, "unknown host") || b0.reached.Load()-reached != 1 { |
| + t.Fatalf("a %s for a host box-00 never served: %d %q (reached box-00: %d), want box-00's 404", method, res.code, res.got, b0.reached.Load()-reached) |
| + } |
| + } |
| +} |
diff --git a/internal/edge/retiredcopy.go b/internal/edge/retiredcopy.go| new file mode 100644 |
| index 000000000..2c22c8bfe |
| --- /dev/null |
| +++ b/internal/edge/retiredcopy.go |
| @@ -0,0 +1,126 @@ |
| +package edge |
| + |
| +import ( |
| + "fmt" |
| + "log" |
| + "net/http" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/tunnelclient" |
| +) |
| + |
| +// hubSetReloadBound bounds one hub reload of a replica set: how long the |
| +// hub takes, after a box's copy retires, to rewrite the set's row in its |
| +// provision pass and load it through its registry poll (2 s). Drill 4 |
| +// (#511) saw the dev hub rewrite the set 2 s after box-2 dropped its row, |
| +// and its passes about 15 s apart (17:53:40.7Z, 17:53:55.6Z). A refusal |
| +// ejects the copy at the hub sooner than that (R26), and the box's replica |
| +// probe for a host it no longer serves fails, which keeps it out. |
| +const hubSetReloadBound = 30 * time.Second |
| + |
| +// retiredCopyGrace is #511 R28's grace window: two hub reload intervals. |
| +// For this long after this box drops a replica set's row because its copy |
| +// is retiring (the copies lowered, or the box removed as a member), a |
| +// request for the host that still arrives over the fleet tunnel is refused |
| +// unprocessed (RST_STREAM REFUSED_STREAM) instead of answered 404, and the |
| +// hub serves it from a surviving copy whatever its method (R26). After it, |
| +// the host gets the normal unknown-host answer. |
| +const retiredCopyGrace = 2 * hubSetReloadBound |
| + |
| +// retiredCopies is the hosts whose replica copy this box retired within |
| +// retiredCopyGrace, each with the time its grace ends. Only Reload writes |
| +// it, from the map it replaces and the one it publishes (note); the |
| +// request path reads it (retiring). The zero value is ready. |
| +type retiredCopies struct { |
| + mu sync.Mutex |
| + until map[string]time.Time |
| + // now is a test seam, set and read under mu; nil is time.Now. |
| + now func() time.Time |
| +} |
| + |
| +// clock is called with mu held. |
| +func (c *retiredCopies) clock() time.Time { |
| + if c.now != nil { |
| + return c.now() |
| + } |
| + return time.Now() |
| +} |
| + |
| +// note records, before Reload publishes next, every name that prev served |
| +// for a replica copy on this box (an instance row of a set with more than |
| +// one copy, ManyCopies, as this box held it) whose row next no longer |
| +// holds: the copy is retiring. Any name next serves leaves the set, so a |
| +// copy raised again is served as usual, and a lapsed grace is dropped. |
| +// It returns the names it added. |
| +// |
| +// The row this box held decides, never the request: a host this box never |
| +// served as a copy, or served as a single copy, or a hub's forward row, is |
| +// never recorded, and keeps today's answer. |
| +func (c *retiredCopies) note(prev, next map[string]upstream) []string { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + now := c.clock() |
| + for host, end := range c.until { |
| + if _, served := next[host]; served || !now.Before(end) { |
| + delete(c.until, host) |
| + } |
| + } |
| + var added []string |
| + for host, up := range prev { |
| + if _, served := next[host]; served { |
| + continue |
| + } |
| + // The copy itself retired: its own host is gone too. A name |
| + // dropped while the copy's row stays (an alias detached) is not a |
| + // retiring copy. |
| + if _, stays := next[up.route.Host]; stays { |
| + continue |
| + } |
| + if up.route.Kind != "instance" || !ManyCopies(up.route) { |
| + continue |
| + } |
| + if c.until == nil { |
| + c.until = make(map[string]time.Time) |
| + } |
| + c.until[host] = now.Add(retiredCopyGrace) |
| + added = append(added, host) |
| + } |
| + return added |
| +} |
| + |
| +// retiring reports whether host's copy retired on this box within the |
| +// grace. |
| +func (c *retiredCopies) retiring(host string) bool { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + now := c.clock() |
| + end, ok := c.until[host] |
| + return ok && now.Before(end) |
| +} |
| + |
| +// noteRetiredCopies is Reload's call, right before it publishes next. |
| +func (e *Edge) noteRetiredCopies(prev, next map[string]upstream) { |
| + for _, host := range e.retired.note(prev, next) { |
| + log.Printf("edge: %s: this box's replica copy retired; its tunnel requests are refused for %s so the hub serves them from another copy", host, retiredCopyGrace) |
| + } |
| +} |
| + |
| +// refuseRetiredCopy is #511 R28's refusal, for a request whose host this |
| +// box's route table no longer holds. When the host's replica copy retired |
| +// here within the grace, r's fleet tunnel stream is refused unprocessed |
| +// (tunnelclient.Refuse: REFUSED_STREAM, nothing written) and it answers |
| +// true; the caller writes nothing and returns. It answers false, and the |
| +// caller answers the unknown host as before, for any other host, for a |
| +// client that has gone, off a fleet tunnel stream, or once the grace ends. |
| +// No app, activator or proxy has seen the request: the host has no entry. |
| +func (e *Edge) refuseRetiredCopy(r *http.Request, host string) bool { |
| + if r.Context().Err() != nil || !e.retired.retiring(host) { |
| + return false |
| + } |
| + if !tunnelclient.Refuse(r) { |
| + return false |
| + } |
| + e.logThrottled("retired-copy "+host, fmt.Sprintf("refused a tunnel request for %s: this box's replica copy retired", host)) |
| + return true |
| +} |
diff --git a/internal/edge/retiredcopy_test.go b/internal/edge/retiredcopy_test.go| new file mode 100644 |
| index 000000000..06f659b5a |
| --- /dev/null |
| +++ b/internal/edge/retiredcopy_test.go |
| @@ -0,0 +1,82 @@ |
| +package edge |
| + |
| +import ( |
| + "slices" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +func retiredCopyRow(host string, copies int) registry.Route { |
| + rt := registry.Route{Host: host, Kind: "instance", Status: "ready", Account: "bab", App: "shop", Stateless: true} |
| + if copies > 0 { |
| + boxes := `["box-00"]` |
| + if copies > 1 { |
| + boxes = `["box-00","box-01"]` |
| + } |
| + rt.Region, rt.FleetBoxes, rt.Copies, rt.ReplicaRevision, rt.ReplicaIncarnation = "fleet/pi", boxes, copies, 1, "life" |
| + } |
| + return rt |
| +} |
| + |
| +// TestRetiredCopiesNote: only a name this box served for a replica copy |
| +// of a set with more than one copy, gone from the new table along with |
| +// the copy's own row, is recorded (#511 R28); the grace ends. |
| +func TestRetiredCopiesNote(t *testing.T) { |
| + set := retiredCopyRow("shop.example.com", 2) |
| + if !ManyCopies(set) { |
| + t.Fatal("fixture: not a two-copy set") |
| + } |
| + stays := retiredCopyRow("stays.example.com", 2) |
| + single := retiredCopyRow("single.example.com", 1) |
| + plain := retiredCopyRow("plain.example.com", 0) |
| + fwd := set |
| + fwd.Host, fwd.Kind = "forward.example.com", registry.KindForward |
| + prev := map[string]upstream{ |
| + "shop.example.com": {route: set}, |
| + "www.shop.example.com": {route: set, alias: true}, |
| + "stays.example.com": {route: stays}, |
| + "www.stays.example": {route: stays, alias: true}, |
| + "single.example.com": {route: single}, |
| + "plain.example.com": {route: plain}, |
| + "forward.example.com": {route: fwd}, |
| + } |
| + next := map[string]upstream{"stays.example.com": {route: stays}} |
| + now := time.Now() |
| + c := &retiredCopies{now: func() time.Time { return now }} |
| + added := c.note(prev, next) |
| + slices.Sort(added) |
| + if want := []string{"shop.example.com", "www.shop.example.com"}; !slices.Equal(added, want) { |
| + t.Fatalf("recorded %v, want %v", added, want) |
| + } |
| + for _, host := range []string{"stays.example.com", "www.stays.example", "single.example.com", "plain.example.com", "forward.example.com", "never.example.com"} { |
| + if c.retiring(host) { |
| + t.Errorf("%s recorded as a retiring copy", host) |
| + } |
| + } |
| + |
| + // The copy raised again: served, so no longer retiring. |
| + back := map[string]upstream{"stays.example.com": {route: stays}, "shop.example.com": {route: set}} |
| + c.note(next, back) |
| + if c.retiring("shop.example.com") || !c.retiring("www.shop.example.com") { |
| + t.Fatal("a copy served again is still retiring, or its alias stopped") |
| + } |
| + |
| + // The grace ends. |
| + now = now.Add(retiredCopyGrace - time.Millisecond) |
| + if !c.retiring("www.shop.example.com") { |
| + t.Fatal("the grace ended early") |
| + } |
| + now = now.Add(time.Millisecond) |
| + if c.retiring("www.shop.example.com") { |
| + t.Fatal("the grace did not end") |
| + } |
| + c.note(back, back) |
| + if len(c.until) != 0 { |
| + t.Fatalf("a lapsed grace was kept: %v", c.until) |
| + } |
| + if retiredCopyGrace < 2*hubSetReloadBound { |
| + t.Fatal("the grace is under two hub reload intervals") |
| + } |
| +} |