activator: stop the wake health probe when the wake is cancelled
waitHealthyCtx ran a context-free waitHealthy in a goroutine and returned on ctx.Done() without stopping it, despite its comment. A cancelled wake's probe kept sending GET / every 50 ms for the rest of spawnHealthTimeout (30 s; 120 s for a rootfs row), and a retried wake binds the same socket path, so the stale probes landed on the new process. waitHealthyAddrCtx (unit routes on a TCP addr) had the same shape. The polling loops now take ctx: each probe is built with NewRequestWithContext, so a request in flight is cancelled with the wake, the pause between probes selects on ctx.Done(), and the loop checks ctx before each probe. On cancellation they return ctx.Err(), as before. waitHealthyCtx and waitHealthyAddrCtx keep their names and signatures, so the callers (exec, rootfs, generation swap, unit backend) are unchanged; the context-free waitHealthy and waitHealthyAddr are gone (only tests called them). The socket wait also closes its client's idle connection on return, as the addr wait already did. Tests (healthwait_cancel_test.go), for both the socket and the addr wait: cancelling while the instance answers 503 returns context.Canceled and no probe arrives across six poll intervals after; cancelling while the instance holds a probe unanswered releases that request within 1 s rather than at the 3 s client timeout. Both failed against the old code. Audit 2026-11-16, activator-edge finding 10d and bug 2.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+203
−59
internal/activator/activator.go+1 −1internal/activator/backend_exec.go+36 −23internal/activator/backend_unit.go+22 −27internal/activator/healthaddr_guard_test.go+4 −3internal/activator/healthcheck_redirect_test.go+6 −5internal/activator/healthwait_cancel_test.go+134 −0
CI cancelled — superseded by a newer push — run details
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index 89ee0b5a9..1aab0b8a5 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -4147,7 +4147,7 @@ var errWorkerExitedEarly = errors.New("worker exited during its settle window") |
| // awaitWorkerSettle is the socketless child's health probe: it is up once it |
| // says so over the agent socket, or once it has survived sidecarSettle without |
| -// exiting. Real time, not a.now — like waitHealthy, this bounds a real |
| +// exiting. Real time, not a.now — like waitHealthyCtx, this bounds a real |
| // process's first seconds, and the test clock exists to move idle windows, not |
| // to model a boot. |
| func (a *Service) awaitWorkerSettle(ctx context.Context, e *actEntry, proc Proc) error { |
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go| index 41bb7965e..02e019c32 100644 |
| --- a/internal/activator/backend_exec.go |
| +++ b/internal/activator/backend_exec.go |
| @@ -2923,7 +2923,7 @@ func seedVars(fileEnv map[string]string, host string) map[string]string { |
| // already happened and this wins. |
| // |
| // The two guards make "only a socket THIS backend's child bound" true |
| -// rather than merely intended. waitHealthy tolerates a squatter (its own |
| +// rather than merely intended. waitHealthyCtx tolerates a squatter (its own |
| // contract: it only dials), so a child that lost the bind race with a |
| // stray supervisor (EADDRINUSE, exits) can still see the health wait |
| // succeed off the SQUATTER's answers; a dead child means the socket is |
| @@ -4031,25 +4031,50 @@ func socketClient(socket string) *http.Client { |
| } |
| } |
| -// waitHealthy blocks until the instance answers an HTTP request on its socket, |
| -// or the timeout elapses. It retries, so it's robust to the restart window |
| -// (socket briefly absent, or a stale socket left by an abruptly-killed old |
| -// process) — and a broken binary that never becomes healthy fails the wake. |
| -func waitHealthy(socket string, timeout time.Duration) error { |
| +// waitHealthyCtx blocks until the instance answers an HTTP request on its |
| +// socket, the timeout elapses, or ctx ends. It retries, so it's robust to |
| +// the restart window (socket briefly absent, or a stale socket left by an |
| +// abruptly-killed old process) — and a broken binary that never becomes |
| +// healthy fails the wake. |
| +// |
| +// When ctx ends it returns ctx.Err() and probes no more: the request in |
| +// flight is cancelled with ctx and no further one starts. An aborted wake |
| +// must not keep probing a socket nobody wants anymore, since a retried |
| +// wake binds the same path and a stale probe would land on its process. |
| +func waitHealthyCtx(ctx context.Context, socket string, timeout time.Duration) error { |
| deadline := time.Now().Add(timeout) |
| client := healthClient(socketClient(socket)) |
| + defer client.CloseIdleConnections() |
| var last error |
| var poll time.Duration |
| for time.Now().Before(deadline) { |
| - if last = probeHealth(client, "http://carlos/"); last == nil { |
| + if err := ctx.Err(); err != nil { |
| + return err |
| + } |
| + if last = probeHealth(ctx, client, "http://carlos/"); last == nil { |
| return nil |
| } |
| poll = nextHealthPoll(poll) |
| - time.Sleep(poll) |
| + if err := healthPause(ctx, poll); err != nil { |
| + return err |
| + } |
| } |
| return fmt.Errorf("instance not healthy within %s: %v", timeout, last) |
| } |
| +// healthPause waits d between two health probes, or returns ctx.Err() as |
| +// soon as ctx ends. |
| +func healthPause(ctx context.Context, d time.Duration) error { |
| + t := time.NewTimer(d) |
| + defer t.Stop() |
| + select { |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + case <-t.C: |
| + return nil |
| + } |
| +} |
| + |
| // healthClient is c made fit for a health probe: it never follows a |
| // redirect. A redirect is an answer, and under 500, so the app is up. |
| // Following one is worse than pointless: an app with Rails' force_ssl |
| @@ -4065,8 +4090,9 @@ func healthClient(c *http.Client) *http.Client { |
| // says X-Forwarded-Proto: https, as the edge does on every real request |
| // (they all arrive over TLS), so an app that redirects plain http takes its |
| // normal path rather than answering the probe with a redirect (#845). |
| -func probeHealth(client *http.Client, url string) error { |
| - req, err := http.NewRequest(http.MethodGet, url, nil) |
| +// ctx cancels the request, in flight or not yet sent. |
| +func probeHealth(ctx context.Context, client *http.Client, url string) error { |
| + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) |
| if err != nil { |
| return err |
| } |
| @@ -4097,19 +4123,6 @@ func nextHealthPoll(d time.Duration) time.Duration { |
| return min(max(2*d, healthPollMin), healthPollMax) |
| } |
| -// waitHealthyCtx is waitHealthy bounded by ctx as well as its own timeout, so |
| -// an aborted wake doesn't keep probing a socket nobody wants anymore. |
| -func waitHealthyCtx(ctx context.Context, socket string, timeout time.Duration) error { |
| - done := make(chan error, 1) |
| - go func() { done <- waitHealthy(socket, timeout) }() |
| - select { |
| - case err := <-done: |
| - return err |
| - case <-ctx.Done(): |
| - return ctx.Err() |
| - } |
| -} |
| - |
| // readEnvFile parses a KEY=value EnvironmentFile (blank lines and #comments |
| // ignored). |
| func readEnvFile(path string) (map[string]string, error) { |
diff --git a/internal/activator/backend_unit.go b/internal/activator/backend_unit.go| index 5dff27268..63edbb2a6 100644 |
| --- a/internal/activator/backend_unit.go |
| +++ b/internal/activator/backend_unit.go |
| @@ -262,20 +262,21 @@ type unitRep struct{} |
| func (unitRep) Err() error { return nil } |
| func (unitRep) Close(context.Context) error { return nil } |
| -// waitHealthyAddr is waitHealthy for TCP upstreams (rt.Addr — unit tenants |
| -// that can't accept a unix listener yet; see the carlos-app@.socket unit's |
| -// fallback note). |
| -func waitHealthyAddr(addr string, timeout time.Duration) error { |
| - return waitHealthyAddrVia(net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}, addr, timeout) |
| -} |
| - |
| -// waitHealthyAddrVia is waitHealthyAddr dialing with base (a test sets its |
| -// Resolver) behind upstreamguard: rt.Addr is route-supplied, so a link-local |
| -// or IMDS destination is refused after resolution and before connect, and |
| -// that refusal ends the wait at once. The transport is the default one's |
| -// settings without the environment proxy, so the guard judges the upstream |
| -// itself rather than a proxy. |
| -func waitHealthyAddrVia(base net.Dialer, addr string, timeout time.Duration) error { |
| +// waitHealthyAddrCtx is waitHealthyCtx for TCP upstreams (rt.Addr — unit |
| +// tenants that can't accept a unix listener yet; see the |
| +// carlos-app@.socket unit's fallback note), and stops probing when ctx |
| +// ends in the same way. |
| +func waitHealthyAddrCtx(ctx context.Context, addr string, timeout time.Duration) error { |
| + return waitHealthyAddrVia(ctx, net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}, addr, timeout) |
| +} |
| + |
| +// waitHealthyAddrVia is waitHealthyAddrCtx dialing with base (a test sets |
| +// its Resolver) behind upstreamguard: rt.Addr is route-supplied, so a |
| +// link-local or IMDS destination is refused after resolution and before |
| +// connect, and that refusal ends the wait at once. The transport is the |
| +// default one's settings without the environment proxy, so the guard |
| +// judges the upstream itself rather than a proxy. |
| +func waitHealthyAddrVia(ctx context.Context, base net.Dialer, addr string, timeout time.Duration) error { |
| tr := http.DefaultTransport.(*http.Transport).Clone() |
| tr.Proxy = nil |
| tr.DialContext = upstreamguard.Dialer(base).DialContext |
| @@ -285,29 +286,23 @@ func waitHealthyAddrVia(base net.Dialer, addr string, timeout time.Duration) err |
| var last error |
| var poll time.Duration |
| for time.Now().Before(deadline) { |
| - if last = probeHealth(client, "http://"+addr+"/"); last == nil { |
| + if err := ctx.Err(); err != nil { |
| + return err |
| + } |
| + if last = probeHealth(ctx, client, "http://"+addr+"/"); last == nil { |
| return nil |
| } |
| if errors.Is(last, upstreamguard.ErrLinkLocal) { |
| return fmt.Errorf("instance health check: %w", last) |
| } |
| poll = nextHealthPoll(poll) |
| - time.Sleep(poll) |
| + if err := healthPause(ctx, poll); err != nil { |
| + return err |
| + } |
| } |
| return fmt.Errorf("instance not healthy within %s: %v", timeout, last) |
| } |
| -func waitHealthyAddrCtx(ctx context.Context, addr string, timeout time.Duration) error { |
| - done := make(chan error, 1) |
| - go func() { done <- waitHealthyAddr(addr, timeout) }() |
| - select { |
| - case err := <-done: |
| - return err |
| - case <-ctx.Done(): |
| - return ctx.Err() |
| - } |
| -} |
| - |
| // SplitBackend composes the two production backends behind the one Backend |
| // seam the state machine sees: each call dispatches on the route's Backing, |
| // so exec children and unit tenants share the singleflight wakes, idle |
diff --git a/internal/activator/healthaddr_guard_test.go b/internal/activator/healthaddr_guard_test.go| index 38b44aad1..7d118d7aa 100644 |
| --- a/internal/activator/healthaddr_guard_test.go |
| +++ b/internal/activator/healthaddr_guard_test.go |
| @@ -1,6 +1,7 @@ |
| package activator |
| import ( |
| + "context" |
| "errors" |
| "net" |
| "net/http" |
| @@ -24,8 +25,8 @@ func TestWaitHealthyAddrRefusesLinkLocal(t *testing.T) { |
| name string |
| wait func() error |
| }{ |
| - {"name resolving to IMDS", func() error { return waitHealthyAddrVia(base, "imds.test:80", 5*time.Second) }}, |
| - {"IMDS literal, production dialer", func() error { return waitHealthyAddr("169.254.169.254:80", 5*time.Second) }}, |
| + {"name resolving to IMDS", func() error { return waitHealthyAddrVia(context.Background(), base, "imds.test:80", 5*time.Second) }}, |
| + {"IMDS literal, production dialer", func() error { return waitHealthyAddrCtx(context.Background(), "169.254.169.254:80", 5*time.Second) }}, |
| } { |
| t.Run(tc.name, func(t *testing.T) { |
| start := time.Now() |
| @@ -43,7 +44,7 @@ func TestWaitHealthyAddrRefusesLinkLocal(t *testing.T) { |
| func TestWaitHealthyAddrLoopbackStillWorks(t *testing.T) { |
| srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) |
| t.Cleanup(srv.Close) |
| - if err := waitHealthyAddr(strings.TrimPrefix(srv.URL, "http://"), 2*time.Second); err != nil { |
| + if err := waitHealthyAddrCtx(context.Background(), strings.TrimPrefix(srv.URL, "http://"), 2*time.Second); err != nil { |
| t.Fatalf("waitHealthyAddr on loopback: %v", err) |
| } |
| } |
diff --git a/internal/activator/healthcheck_redirect_test.go b/internal/activator/healthcheck_redirect_test.go| index c7d98be84..eac83b3cc 100644 |
| --- a/internal/activator/healthcheck_redirect_test.go |
| +++ b/internal/activator/healthcheck_redirect_test.go |
| @@ -1,6 +1,7 @@ |
| package activator |
| import ( |
| + "context" |
| "net" |
| "net/http" |
| "strings" |
| @@ -51,7 +52,7 @@ func TestWaitHealthySaysHTTPS(t *testing.T) { |
| t.Fatal(err) |
| } |
| https := forceSSLApp(t, ln) |
| - if err := waitHealthy(sock, 2*time.Second); err != nil { |
| + if err := waitHealthyCtx(context.Background(), sock, 2*time.Second); err != nil { |
| t.Fatalf("waitHealthy: %v", err) |
| } |
| if https.Load() == 0 { |
| @@ -69,7 +70,7 @@ func TestWaitHealthyDoesNotFollowRedirects(t *testing.T) { |
| t.Fatal(err) |
| } |
| redirectingApp(t, ln) |
| - if err := waitHealthy(sock, 2*time.Second); err != nil { |
| + if err := waitHealthyCtx(context.Background(), sock, 2*time.Second); err != nil { |
| t.Fatalf("waitHealthy on a redirecting app: %v", err) |
| } |
| } |
| @@ -81,7 +82,7 @@ func TestWaitHealthyAddrSaysHTTPSAndDoesNotFollowRedirects(t *testing.T) { |
| t.Fatal(err) |
| } |
| https := forceSSLApp(t, ln) |
| - if err := waitHealthyAddr(ln.Addr().String(), 2*time.Second); err != nil { |
| + if err := waitHealthyAddrCtx(context.Background(), ln.Addr().String(), 2*time.Second); err != nil { |
| t.Fatalf("waitHealthyAddr: %v", err) |
| } |
| if https.Load() == 0 { |
| @@ -93,7 +94,7 @@ func TestWaitHealthyAddrSaysHTTPSAndDoesNotFollowRedirects(t *testing.T) { |
| t.Fatal(err) |
| } |
| redirectingApp(t, ln2) |
| - if err := waitHealthyAddr(ln2.Addr().String(), 2*time.Second); err != nil { |
| + if err := waitHealthyAddrCtx(context.Background(), ln2.Addr().String(), 2*time.Second); err != nil { |
| t.Fatalf("waitHealthyAddr on a redirecting app: %v", err) |
| } |
| } |
| @@ -110,7 +111,7 @@ func TestWaitHealthyStillFailsA500(t *testing.T) { |
| })} |
| go srv.Serve(ln) |
| t.Cleanup(func() { srv.Close() }) |
| - err = waitHealthyAddr(ln.Addr().String(), 200*time.Millisecond) |
| + err = waitHealthyAddrCtx(context.Background(), ln.Addr().String(), 200*time.Millisecond) |
| if err == nil || !strings.Contains(err.Error(), "HTTP 500") { |
| t.Fatalf("waitHealthyAddr on a 500 = %v, want HTTP 500", err) |
| } |
diff --git a/internal/activator/healthwait_cancel_test.go b/internal/activator/healthwait_cancel_test.go| new file mode 100644 |
| index 000000000..ca51e2e31 |
| --- /dev/null |
| +++ b/internal/activator/healthwait_cancel_test.go |
| @@ -0,0 +1,134 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net" |
| + "net/http" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// healthWaitKinds are the two health waits a wake runs: on the instance's |
| +// unix socket (exec, rootfs, generations) and on a unit route's TCP addr. |
| +// Each listens with h and returns the wait to run against it. |
| +type healthWaitKind func(t *testing.T, h http.Handler) func(ctx context.Context) error |
| + |
| +var healthWaitKinds = map[string]healthWaitKind{ |
| + "socket": func(t *testing.T, h http.Handler) func(ctx context.Context) error { |
| + requireUnixSockets(t) |
| + sock := tmpSock(t) |
| + ln, err := net.Listen("unix", sock) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + serveHealth(t, ln, h) |
| + return func(ctx context.Context) error { return waitHealthyCtx(ctx, sock, 30*time.Second) } |
| + }, |
| + "addr": func(t *testing.T, h http.Handler) func(ctx context.Context) error { |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + serveHealth(t, ln, h) |
| + addr := ln.Addr().String() |
| + return func(ctx context.Context) error { return waitHealthyAddrCtx(ctx, addr, 30*time.Second) } |
| + }, |
| +} |
| + |
| +func serveHealth(t *testing.T, ln net.Listener, h http.Handler) { |
| + t.Helper() |
| + srv := &http.Server{Handler: h} |
| + go srv.Serve(ln) |
| + t.Cleanup(func() { srv.Close() }) |
| +} |
| + |
| +// runWait starts wait in the background and returns its result channel. |
| +func runWait(ctx context.Context, wait func(context.Context) error) <-chan error { |
| + done := make(chan error, 1) |
| + go func() { done <- wait(ctx) }() |
| + return done |
| +} |
| + |
| +func wantCanceled(t *testing.T, done <-chan error) { |
| + t.Helper() |
| + select { |
| + case err := <-done: |
| + if !errors.Is(err, context.Canceled) { |
| + t.Fatalf("wait = %v, want context.Canceled", err) |
| + } |
| + case <-time.After(time.Second): |
| + t.Fatal("the wait did not return within 1s of its context ending") |
| + } |
| +} |
| + |
| +// TestHealthWaitStopsProbingWhenCancelled: a wake that is cancelled while |
| +// its instance answers 503 stops probing. Before, the wait returned but |
| +// left its polling loop running for the rest of its 30 s (120 s rootfs), so |
| +// a retried wake's process on the same socket got the stale probes. |
| +func TestHealthWaitStopsProbingWhenCancelled(t *testing.T) { |
| + for name, listen := range healthWaitKinds { |
| + t.Run(name, func(t *testing.T) { |
| + var probes atomic.Int32 |
| + wait := listen(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + probes.Add(1) |
| + w.WriteHeader(http.StatusServiceUnavailable) |
| + })) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + done := runWait(ctx, wait) |
| + waitFor(t, "two probes", func() bool { return probes.Load() >= 2 }) |
| + cancel() |
| + wantCanceled(t, done) |
| + // A probe already on the wire may still reach the handler just |
| + // after the return; let it land, then expect silence across |
| + // several poll intervals (healthPollMax is 50 ms). |
| + time.Sleep(100 * time.Millisecond) |
| + n := probes.Load() |
| + time.Sleep(6 * healthPollMax) |
| + if got := probes.Load(); got != n { |
| + t.Fatalf("%d probes after the wait returned; a cancelled wait must stop probing", got-n) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestHealthWaitCancelsTheProbeInFlight: an instance that accepts the probe |
| +// and never answers does not hold a cancelled wait's request for the |
| +// probe's 3 s client timeout; the request is cancelled with the wake. |
| +func TestHealthWaitCancelsTheProbeInFlight(t *testing.T) { |
| + for name, listen := range healthWaitKinds { |
| + t.Run(name, func(t *testing.T) { |
| + entered := make(chan struct{}, 1) |
| + released := make(chan struct{}) |
| + wait := listen(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + select { |
| + case entered <- struct{}{}: |
| + default: |
| + } |
| + <-r.Context().Done() |
| + select { |
| + case <-released: |
| + default: |
| + close(released) |
| + } |
| + })) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + done := runWait(ctx, wait) |
| + select { |
| + case <-entered: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("the probe never reached the instance") |
| + } |
| + cancel() |
| + wantCanceled(t, done) |
| + select { |
| + case <-released: |
| + case <-time.After(time.Second): |
| + t.Fatal("the instance still holds the probe 1s after the wake was cancelled") |
| + } |
| + }) |
| + } |
| +} |