activator: refuse a retiring copy's request before the app (#511 R28)
Review round 2, Astra: a request that chose a replica row before the edge dropped it and waited in the activator's begin across RetireExcept came round to a fresh wake that found the row gone, and got the wake-failed 503, which the hub forwards. serveWakeErrorBeforeApp now also refuses with REFUSED_STREAM when the copy is retiring on this box, so the hub serves it from a survivor (R26). "Retiring" is the edge's retired-copy set: edge.New hands its check to the activator (SetRetiringCopy), so no new import. It covers an asleep copy too, which RetireExcept's own entries would not. Still only for a route with more than one copy (edge.ManyCopies) and only through RefuseBeforeApp (a fleet tunnel stream with nothing written); single-copy rows are unchanged. Witness through the real activator, behind a real box edge, hub and tunnel loops: TestRetiringCopyRefusedInBegin. A POST and a GET wait in begin on a wake; the copy retires; the wake fails on the deleted row; both are refused and served by the survivor, with no 503. Without the condition both get 503. TestServeRefusesBeforeAppRead gains the retiring cases, one copy and two.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/activator/activator.go+28 −3internal/activator/retire_refuse_e2e_test.go+291 −0internal/activator/tunnel_refuse_test.go+10 −5internal/edge/edge.go+6 −0
Intent
<task-notification> <task-id>a882c6cc125e29e60</task-id> <tool-use-id>toolu_01YAdrGrRKXovzr5i9PGJhYR</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/a882c6cc125e29e60.output</output-file> <status>completed</status> <summary>Agent "Implement R28 scale-down fix" 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_WITH_CONCERNS - **Commits:** 2a167602 (Astra's P1: a request picked before the switch and dialing after the stop is now refused), 51ead0a1 (grace and catch-alls), d068b069 (census re-proposed under the same NAME, seal e324eba4, card clean; `Edge.Reload` re-pinned). Tip d068b069, not pushed. - **The four ruling items:** 1. **Astra's P1:** `holdEnded` and `refuseUnreachedApp` now also end the dial hold and refuse (REFUSED_STREAM) when this box's copy is retiring. This applies to replicated rows only. The proof that no app bytes were written is unchanged, and single-copy rows still wait for a restart. 2. **Grace:** 120 s. The comment now names the probe eject (`replicaProbeInterval` × `replicaProbeFail`) as the real protection, with the hub's reload as a backstop and not a proven bound. 3. **Catch-alls:** `*` keys are skipped, with a comment that replica rows are exact hosts. 4. **Test timing:** the fixed sleeps are replaced by waits on request counts. - **New witness:** `TestReplicaRetiringDialHoldRefused` goes through the real `genRoundTripper`. A POST and a GET are held after the route was picked; the copy then retires and its app stops; then they dial. box-01 serves both within 2 s, and box-00's app sees neither. Without the fix they wait out the 13 s hold. - **Tests:** the R28 and dial-hold tests pass at `-count=10 -cpu=1,2,8` and under `-race`. The edge regression set, TestGroupNameClassCensus, TestRegionHA (12), grouproll/grouprollaws, the provision census tests and all three cross-compiles pass. - **Concern (needs a ruling):** an older problem outside this ruling. If a request picked before the switch reaches the activator's `begin` after `RetireExcept`, `begin` waits for the stop and then wakes the retired copy again. The client gets an answer, but the retired copy runs until it idles. One option is that `begin` refuses to wake a host the edge no longer maps. - **Other concerns:** - Round 0's instance-delete 503 and mixed-version POST 502 still stand. - The census review is owed again for the re-proposal. - **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/stateless-replicas-4/.superpowers/sdd/2026-11-01-stateless-replicas-4-deploy-and-drill/task-r28-report.md (new "Review round 1" section)</result> <usage><subagent_tokens>314506</subagent_tokens><tool_uses>25</tool_uses><duration_ms>1048172</duration_ms></usage> </task-notification>
<task-notification> <task-id>b44ewqmd4</task-id> <tool-use-id>toolu_01D3HAPqATE2bZZRChPDo594</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/b44ewqmd4.output</output-file> <status>completed</status> <summary>Background command "Astra scoped re-check of R28 round 1" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>b87oulcit</task-id> <tool-use-id>toolu_01GhvZcb5rJEBSSzH3Pqqrut</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/b87oulcit.output</output-file> <status>completed</status> <summary>Background command "Wait for CI on d068b069" completed (exit code 0)</summary> </task-notification>
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index 5aabc1319..b41f81105 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -1379,6 +1379,9 @@ type Service struct { |
| // test that doesn't wire it, and any caller that doesn't set it) keeps |
| // today's behaviour: the wake runs on the route it was handed. |
| Routes RouteLookup |
| + // retiringCopy is the edge's retired-copy check (#511 R28 review round |
| + // 2), handed over by edge.New through SetRetiringCopy; nil: none. |
| + retiringCopy atomic.Pointer[func(string) bool] |
| // Fleet is whether this box is on a fleet, and what a labelled wake is |
| // checked against under the lease (routeCurrentUnderLease; managed |
| // fleets 1b): not on a fleet (the zero value: no check, no read), on a |
| @@ -6647,8 +6650,12 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout |
| // without the activator asking it to (StoppedOutside: systemd's shutdown, |
| // a hand stop, a crash), the stream is refused unprocessed instead of |
| // answered, and the hub sends the request to another copy whatever its |
| -// method (R26). A client that went away is never refused; every other |
| -// request is answered as before. |
| +// method (R26). The same for a route with more than one copy whose copy |
| +// is retiring on this box (the edge's retired-copy set, #511 R28 review |
| +// round 2): a request that chose the row before the edge dropped it and |
| +// then fails here, waiting in begin across RetireExcept's stop or on a |
| +// fresh wake that finds the row gone. A client that went away is never |
| +// refused; every other request is answered as before. |
| // |
| // "Before any app read" is exactly these call sites: the HA lease refusal, |
| // awaitStartup's refusal (errStartupStopped, errWakeTimeout, a cancelled |
| @@ -6660,12 +6667,30 @@ func (a *Service) serveWakeErrorBeforeApp(w http.ResponseWriter, r *http.Request |
| // An outside stop counts only for a route with more than one copy |
| // (edge.ManyCopies, review round 3): a single-copy row is answered as |
| // before, unless the box is draining. |
| - if !errors.Is(err, context.Canceled) && edge.RefuseBeforeApp(r, a.StoppedOutside(rt.Host) && edge.ManyCopies(rt)) { |
| + gone := a.StoppedOutside(rt.Host) || a.retiring(rt.Host) |
| + if !errors.Is(err, context.Canceled) && edge.RefuseBeforeApp(r, gone && edge.ManyCopies(rt)) { |
| return true |
| } |
| return a.serveWakeError(w, r, rt, err) |
| } |
| +// SetRetiringCopy takes the edge's retired-copy check (#511 R28 review |
| +// round 2): whether host's replica copy retired on this box within its |
| +// grace, the row dropped from the edge's map and RetireExcept stopping |
| +// its app. edge.New hands it over; serveWakeErrorBeforeApp reads it. |
| +func (a *Service) SetRetiringCopy(retiring func(string) bool) { |
| + a.retiringCopy.Store(&retiring) |
| +} |
| + |
| +// retiring reports whether host's replica copy is retiring on this box, |
| +// by the edge's check (SetRetiringCopy); false without one. |
| +func (a *Service) retiring(host string) bool { |
| + if f := a.retiringCopy.Load(); f != nil && *f != nil { |
| + return (*f)(host) |
| + } |
| + return false |
| +} |
| + |
| // StoppedOutside reports whether host's app last ended without the |
| // activator asking it to, when the backend can tell (ExecBackend); false |
| // otherwise (#511 R27). |
diff --git a/internal/activator/retire_refuse_e2e_test.go b/internal/activator/retire_refuse_e2e_test.go| new file mode 100644 |
| index 000000000..e7b910c6f |
| --- /dev/null |
| +++ b/internal/activator/retire_refuse_e2e_test.go |
| @@ -0,0 +1,291 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "errors" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "path/filepath" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/replicas" |
| + "github.com/carlosframework/platform/internal/tunnelclient" |
| +) |
| + |
| +// gatedRoutes is the wake's route lookup (Service.Routes) over the box's |
| +// registry, with every Get held until release closes: a wake that began |
| +// before the copy retired reads the row only after it is gone. |
| +type gatedRoutes struct { |
| + reg *registry.Registry |
| + release chan struct{} |
| + entered atomic.Int32 |
| +} |
| + |
| +func (g *gatedRoutes) Get(host string) (*registry.Route, error) { |
| + g.entered.Add(1) |
| + <-g.release |
| + return g.reg.Get(host) |
| +} |
| + |
| +type retireResult struct { |
| + method, body string |
| + code int |
| + got string |
| +} |
| + |
| +func retireSend(srvURL, method, body string) retireResult { |
| + var rd io.Reader |
| + if body != "" { |
| + rd = strings.NewReader(body) |
| + } |
| + req, err := http.NewRequest(method, srvURL+"/", rd) |
| + if err != nil { |
| + return retireResult{method, body, 0, err.Error()} |
| + } |
| + req.Host = "shop.example.com" |
| + resp, err := (&http.Client{Timeout: 10 * time.Second}).Do(req) |
| + if err != nil { |
| + return retireResult{method, body, 0, err.Error()} |
| + } |
| + b, _ := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + return retireResult{method, body, resp.StatusCode, string(b)} |
| +} |
| + |
| +func retireAwait(t *testing.T, what string, f func() bool) { |
| + t.Helper() |
| + deadline := time.Now().Add(10 * time.Second) |
| + for !f() { |
| + if time.Now().After(deadline) { |
| + t.Fatal("timed out: " + what) |
| + } |
| + time.Sleep(time.Millisecond) |
| + } |
| +} |
| + |
| +// TestRetiringCopyRefusedInBegin is #511 R28 review round 2's witness |
| +// through the REAL activator. A hub Edge and TunnelHub serve a two-copy |
| +// set of shop.example.com on fleet pi; box-1 is a real box Edge whose |
| +// asleep copy the real Service runs, behind the production tunnel loop; |
| +// box-2 is the survivor. |
| +// |
| +// A POST and a GET choose box-1's row and enter the activator's begin: |
| +// the first starts a wake, both wait on it (the wake's registry read is |
| +// held). box-1's copy then retires: its row is dropped as its provision |
| +// pass drops it (DeleteReplicaAssignment), and its edge reloads, which |
| +// records the retired copy and runs RetireExcept on the waking entry. The |
| +// wake then reads the row, finds it gone and fails; begin returns that |
| +// failure before any app read, and serveWakeErrorBeforeApp refuses both |
| +// (the copy is retiring by the edge's retired-copy set). The hub serves |
| +// both from box-2: no 503, and box-1's app reads neither. |
| +// |
| +// Without the retiring condition both get box-1's wake-failed 503. |
| +func TestRetiringCopyRefusedInBegin(t *testing.T) { |
| + requireUnixSockets(t) |
| + const host = "shop.example.com" |
| + set := registry.Route{Host: host, Kind: registry.KindForward, Region: "fleet/pi", Account: "bab", App: "shop", Stateless: true, |
| + FleetBoxes: `["box-1","box-2"]`, Copies: 2, ReplicaRevision: 1, ReplicaIncarnation: "life"} |
| + |
| + // The hub. |
| + hubReg, err := registry.Open(filepath.Join(t.TempDir(), "hub.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := hubReg.UpsertFleet(registry.Fleet{Name: "pi", Account: "bab", Bucket: "pi-data"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, b := range []string{"box-1", "box-2"} { |
| + sum := sha256.Sum256([]byte("tok-" + b)) |
| + if err := hubReg.AddFleetBox(registry.FleetBox{Fleet: "pi", Label: b, TokenHash: hex.EncodeToString(sum[:]), Status: "active"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := hubReg.PutForward(set); err != nil { |
| + t.Fatal(err) |
| + } |
| + hubEdge, err := edge.New(hubReg, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + srv := httptest.NewServer(hubEdge) |
| + t.Cleanup(srv.Close) |
| + u, err := url.Parse(srv.URL) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Setenv("CARLOS_TUNNEL_HOST", u.Hostname()) |
| + t.Setenv("CARLOS_FLEET", "") |
| + hub := edge.NewTunnelHub(u.Hostname(), nil) |
| + hubEdge.EnableTunnels(hub) |
| + // A copy is healthy while its channel is connected (no box-side probe): |
| + // the hub keeps choosing box-1 until a refusal ejects it. |
| + hubEdge.ReplicaProbe = func(_ context.Context, channel, h string) (replicas.Copy, error) { |
| + if hub.State(channel) != "connected" { |
| + return replicas.Copy{}, io.ErrUnexpectedEOF |
| + } |
| + row, err := hubReg.Get(h) |
| + if err != nil || row == nil { |
| + return replicas.Copy{}, errors.New("no row") |
| + } |
| + box := strings.TrimPrefix(channel, "pi/") |
| + return replicas.Copy{Host: h, Account: row.Account, App: row.App, Fleet: "pi", Box: box, BootID: "boot", Incarnation: row.ReplicaIncarnation, |
| + AssignmentRevision: row.ReplicaRevision, Generation: 10, Version: "v1", Digest: strings.Repeat("a", 64), State: "running", Healthy: true}, nil |
| + } |
| + if err := hubEdge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The probing jobs end with the set (Sync), before the tunnels close. |
| + t.Cleanup(func() { |
| + hubReg.DeleteForward(host) |
| + hubEdge.Reload() |
| + }) |
| + |
| + // box-1: the real activator behind a real box edge. |
| + var appReads atomic.Int32 |
| + sock := tmpSock(t) |
| + ln, err := net.Listen("unix", sock) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + app := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + appReads.Add(1) |
| + b, _ := io.ReadAll(r.Body) |
| + io.WriteString(w, "box-1 "+r.Method+" "+string(b)) |
| + })} |
| + go app.Serve(ln) |
| + t.Cleanup(func() { app.Close() }) |
| + reg1, err := registry.Open(filepath.Join(t.TempDir(), "box1.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + row := registry.Route{Host: host, Kind: "instance", Status: "ready", Socket: sock, DBPath: filepath.Join(t.TempDir(), "shop.db"), Hibernate: true, Incarnation: 1, |
| + Account: "bab", App: "shop", Provisioned: true, Region: "fleet/pi", Stateless: true, |
| + FleetBoxes: `["box-1","box-2"]`, Copies: 2, ReplicaRevision: 1, ReplicaIncarnation: "life"} |
| + if !edge.ManyCopies(row) { |
| + t.Fatalf("box-1's row is not a two-copy set: %+v", row) |
| + } |
| + if err := reg1.Upsert(row); err != nil { |
| + t.Fatal(err) |
| + } |
| + held, err := reg1.Get(host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + b := &fakeBackend{} |
| + a := New(Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg1) |
| + routes := &gatedRoutes{reg: reg1, release: make(chan struct{})} |
| + a.Routes = routes |
| + t.Cleanup(func() { |
| + select { |
| + case <-routes.release: |
| + default: |
| + close(routes.release) |
| + } |
| + }) |
| + boxEdge, err := edge.New(reg1, a) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var reached1 atomic.Int32 |
| + // Each box's loop carries a drain, as the agent gives every fleet |
| + // channel (tunnelDrainFor): that is what arms the stream refusal. It |
| + // never closes here. |
| + loop := func(label string, h http.Handler) { |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + done := make(chan struct{}) |
| + drain := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + tunnelclient.Loop(ctx, tunnelclient.Config{URL: srv.URL, Name: "pi/" + label, Token: "tok-" + label, Handler: h, Drain: drain, Logf: func(string, ...any) {}}) |
| + }() |
| + t.Cleanup(func() { cancel(); <-done }) |
| + } |
| + loop("box-1", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reached1.Add(1); boxEdge.ServeHTTP(w, r) })) |
| + var survivor atomic.Int32 |
| + loop("box-2", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + survivor.Add(1) |
| + body, _ := io.ReadAll(r.Body) |
| + io.WriteString(w, "box-2 "+r.Method+" "+string(body)) |
| + })) |
| + retireAwait(t, "both copies live at the hub", func() bool { |
| + live := 0 |
| + for _, c := range hubEdge.ReplicaSnapshots()[host].Copies { |
| + if c.Healthy { |
| + live++ |
| + } |
| + } |
| + return live == 2 |
| + }) |
| + |
| + // Two requests choose box-1's row and wait in begin on one wake. The |
| + // hub picks copies in turn, and box-2 answers at once, so each is sent |
| + // until box-1's edge has it. |
| + var parked []chan retireResult |
| + for _, c := range []struct{ method, body string }{{"POST", "order"}, {"GET", ""}} { |
| + want := reached1.Load() + 1 |
| + for landed := false; !landed; { |
| + ch := make(chan retireResult, 1) |
| + go func() { ch <- retireSend(srv.URL, c.method, c.body) }() |
| + deadline := time.After(5 * time.Second) |
| + for waiting := true; waiting; { |
| + select { |
| + case res := <-ch: |
| + if res.code != http.StatusOK || !strings.HasPrefix(res.got, "box-2 ") { |
| + t.Fatalf("%s on the survivor: %d %q", c.method, res.code, res.got) |
| + } |
| + waiting = false |
| + case <-deadline: |
| + t.Fatalf("%s never landed", c.method) |
| + case <-time.After(time.Millisecond): |
| + if reached1.Load() >= want { |
| + parked = append(parked, ch) |
| + landed, waiting = true, false |
| + } |
| + } |
| + } |
| + } |
| + } |
| + retireAwait(t, "the wake's registry read", func() bool { return routes.entered.Load() >= 1 }) |
| + retireAwait(t, "both requests waiting on the wake", func() bool { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + e := a.entries[host] |
| + return e != nil && e.state == actWaking |
| + }) |
| + time.Sleep(50 * time.Millisecond) // the second request reaches begin's wait |
| + |
| + // box-1's copy retires while they wait. |
| + if deleted, err := reg1.DeleteReplicaAssignment(*held); err != nil || !deleted { |
| + t.Fatalf("retire box-1's copy: %v %v", deleted, err) |
| + } |
| + if err := boxEdge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + retireAwait(t, "RetireExcept to retire the waking entry", func() bool { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + e := a.entries[host] |
| + return e != nil && e.retired |
| + }) |
| + close(routes.release) |
| + for _, ch := range parked { |
| + res := <-ch |
| + // TestRetiringCopyRefusedInBegin |
| + if res.code != http.StatusOK || res.got != "box-2 "+res.method+" "+res.body { |
| + t.Errorf("a request held in begin across the retirement: %s %d %q, want box-2's answer", res.method, res.code, res.got) |
| + } |
| + } |
| + if appReads.Load() != 0 { |
| + t.Fatalf("box-1's app read %d of the held requests", appReads.Load()) |
| + } |
| +} |
diff --git a/internal/activator/tunnel_refuse_test.go b/internal/activator/tunnel_refuse_test.go| index a42e144ee..1f10e8c4c 100644 |
| --- a/internal/activator/tunnel_refuse_test.go |
| +++ b/internal/activator/tunnel_refuse_test.go |
| @@ -113,17 +113,22 @@ func TestServeRefusesBeforeAppRead(t *testing.T) { |
| name string |
| rt registry.Route |
| drain, outside bool |
| + retiring bool |
| wantRefusedCode bool |
| }{ |
| - {"shutdown begun, one copy", single, true, false, true}, |
| - {"shutdown begun, two copies", set, true, false, true}, |
| - {"app stopped outside, two copies", set, false, true, true}, |
| - {"app stopped outside, one copy", single, false, true, false}, |
| - {"neither", set, false, false, false}, |
| + {"shutdown begun, one copy", single, true, false, false, true}, |
| + {"shutdown begun, two copies", set, true, false, false, true}, |
| + {"app stopped outside, two copies", set, false, true, false, true}, |
| + {"app stopped outside, one copy", single, false, true, false, false}, |
| + // #511 R28 review round 2: the edge's retired-copy set. |
| + {"copy retiring, two copies", set, false, false, true, true}, |
| + {"copy retiring, one copy", single, false, false, true, false}, |
| + {"neither", set, false, false, false, false}, |
| } { |
| t.Run(c.name, func(t *testing.T) { |
| x := newRefuseBox(t, c.rt) |
| x.b.stopped.Store(c.outside) |
| + x.a.SetRetiringCopy(func(string) bool { return c.retiring }) |
| type result struct { |
| resp *http.Response |
| err error |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 07cef8306..de4e77091 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -660,6 +660,12 @@ func newEdge(reg *registry.Registry, act Activator, hold localHold) (*Edge, erro |
| e.gens, e.genPools = gs, NewGenPools() |
| gs.OnGenRetired(e.genPools.Retire) |
| } |
| + // The activator refuses a request it fails before any app read for a |
| + // copy this edge retired (#511 R28 review round 2), so it is handed |
| + // the edge's retired-copy check before the first Reload. |
| + if rs, ok := act.(interface{ SetRetiringCopy(func(string) bool) }); ok { |
| + rs.SetRetiringCopy(e.retired.retiring) |
| + } |
| if err := e.Reload(); err != nil { |
| return nil, err |
| } |