carlos / platform Public

activator tests: wait for the fake app, not its timeout

About 30 tests launched a fake app that records what it was handed and
exits without binding its socket, then sat out Start's whole 2 s health
context; the refusal tests sat out a further 1-2 s for an outcome file
that was never coming. Both waits had a real condition behind them.

childwait_test.go reads /proc for it: the app has recorded (its file
exists and no child of the test binary is still running), or nothing can
still record (no child is running at all). It never asks the code under
test. Where /proc cannot answer, or an unrelated child is alive, the old
bound still applies. Goroutine-style tests that observe during the
health wait cancel it once they have seen what they came for.

A mutation that runs the app and still reports the refusal is caught by
the replica tests in 10 ms, where before it took the 2 s wait.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 58fcb3050b5ebb32189fe6b5b976cc36af20dc77 parent f54aa2f
9 files changed, +180 −43
  • internal/activator/activator_test.go +21 −13
  • internal/activator/backend_exec_test.go +2 −2
  • internal/activator/childwait_test.go +135 −0
  • internal/activator/generations_backend_test.go +1 −0
  • internal/activator/gensocket_rev19_test.go +1 −0
  • internal/activator/instancekey_delivery_test.go +1 −1
  • internal/activator/instancekey_test.go +14 −16
  • internal/activator/replica_instancekey_linux_test.go +1 −1
  • internal/activator/replica_instancekey_test.go +4 −10
diff --git a/internal/activator/activator_test.go b/internal/activator/activator_test.go
index fc1b86555..decb3a9ca 100644
--- a/internal/activator/activator_test.go
+++ b/internal/activator/activator_test.go
@@ -5055,6 +5055,9 @@ func TestExecBackendStartPassesControlSocketInEnvAndStartsPurgeListener(t *testi
gotArgv := strings.Fields(waitForFile(t, argvPath, time.Second))
gotEnv := strings.TrimSpace(waitForFile(t, envPath, time.Second))
+ // Everything above was seen while the health wait ran; the fake never
+ // binds, so end the wait rather than sit out its timeout.
+ cancel()
<-done
if proc != nil {
defer proc.Stop(context.Background())
@@ -5128,6 +5131,9 @@ func TestExecBackendStartWithNilCacheStillBindsControlSocket(t *testing.T) {
}
}
+ // Everything above was seen while the health wait ran; the fake never
+ // binds, so end the wait rather than sit out its timeout.
+ cancel()
<-done
if proc != nil {
defer proc.Stop(context.Background())
@@ -5315,7 +5321,7 @@ func TestExecBackendStartMergesConfigEnvUnderOwnEnv(t *testing.T) {
Socket: filepath.Join(t.TempDir(), "instance.sock"),
}
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ ctx, cancel := recordedCtx(2*time.Second, envPath)
defer cancel()
proc, _, _ := b.Start(ctx, rt) // health-wait error from the fake binary is expected and irrelevant here
if proc != nil {
@@ -5362,7 +5368,7 @@ func TestExecBackendStartAdvertisesHeaderPurgeChannel(t *testing.T) {
Socket: tmpSock(t),
}
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ ctx, cancel := recordedCtx(2*time.Second, envPath)
defer cancel()
proc, _, _ := b.Start(ctx, rt) // health-wait error from the fake binary is expected and irrelevant here
if proc != nil {
@@ -5401,7 +5407,7 @@ func TestExecBackendStartWithNilCacheSetsNoPurgeVar(t *testing.T) {
Socket: filepath.Join(t.TempDir(), "instance.sock"),
}
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ ctx, cancel := recordedCtx(2*time.Second, envPath)
defer cancel()
proc, _, _ := b.Start(ctx, rt)
if proc != nil {
@@ -5446,7 +5452,7 @@ func TestExecBackendStartTenantCannotClaimAbsentPurgeChannel(t *testing.T) {
Socket: tmpSock(t),
}
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ ctx, cancel := recordedCtx(2*time.Second, envPath)
defer cancel()
proc, _, _ := b.Start(ctx, rt)
if proc != nil {
@@ -5494,7 +5500,7 @@ func TestExecBackendStartOverridesTenantSuppliedPurgeVars(t *testing.T) {
Socket: tmpSock(t),
}
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ ctx, cancel := recordedCtx(2*time.Second, envPath)
defer cancel()
proc, _, _ := b.Start(ctx, rt)
if proc != nil {
@@ -5535,7 +5541,16 @@ func TestExecBackendStartPurgesHostCacheOnSpawn(t *testing.T) {
})
}
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ // GetFor is the cache's request-time lookup (the by-VaryValue one is
+ // package-internal); both entries were stored from responses with no Vary,
+ // so any request for the URL reaches them.
+ cached := func(k edge.CacheKey) bool {
+ _, ok := cache.GetFor(k, httptest.NewRequest("GET", "http://"+k.Host+k.Path, nil))
+ return ok
+ }
+ // The purge comes before the health wait, which the fake never answers:
+ // once it has happened that wait has nothing left to show.
+ ctx, cancel := ctxUntil(2*time.Second, func() bool { return !cached(stale) })
defer cancel()
rt := registry.Route{
Host: "deploy.example.com",
@@ -5547,13 +5562,6 @@ func TestExecBackendStartPurgesHostCacheOnSpawn(t *testing.T) {
defer proc.Stop(context.Background())
}
- // GetFor is the cache's request-time lookup (the by-VaryValue one is
- // package-internal); both entries were stored from responses with no Vary,
- // so any request for the URL reaches them.
- cached := func(k edge.CacheKey) bool {
- _, ok := cache.GetFor(k, httptest.NewRequest("GET", "http://"+k.Host+k.Path, nil))
- return ok
- }
if cached(stale) {
t.Fatal("spawning a fresh process for a host must drop that host's cached responses")
}
diff --git a/internal/activator/backend_exec_test.go b/internal/activator/backend_exec_test.go
index c3c5b9b5c..d5fa6a12b 100644
--- a/internal/activator/backend_exec_test.go
+++ b/internal/activator/backend_exec_test.go
@@ -94,7 +94,7 @@ func TestExecBackendStartChildRegion(t *testing.T) {
t.Fatal(err)
}
rt := registry.Route{Host: host, Kind: "instance", Socket: filepath.Join(t.TempDir(), "instance.sock")}
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ ctx, cancel := recordedCtx(2*time.Second, envPath)
defer cancel()
proc, _, _ := b.Start(ctx, rt) // fake binary never binds the socket; health-wait error expected
if proc != nil {
@@ -126,7 +126,7 @@ func TestExecBackendStartChildHandsTheHost(t *testing.T) {
t.Fatal(err)
}
rt := registry.Route{Host: host, Kind: "instance", Socket: filepath.Join(t.TempDir(), "instance.sock")}
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ ctx, cancel := recordedCtx(2*time.Second, envPath)
defer cancel()
proc, _, _ := b.Start(ctx, rt) // fake binary never binds the socket; health-wait error expected
if proc != nil {
diff --git a/internal/activator/childwait_test.go b/internal/activator/childwait_test.go
new file mode 100644
index 000000000..cc7240d06
--- /dev/null
+++ b/internal/activator/childwait_test.go
@@ -0,0 +1,135 @@
+package activator
+
+import (
+ "bytes"
+ "context"
+ "os"
+ "path/filepath"
+ "strconv"
+ "time"
+)
+
+// The fake apps these tests launch (stageRecordingLive, stageHelperApp and
+// their kin) record what they were handed to a file and exit. They never
+// bind their socket, so a Start against one waits out its whole health
+// context, and a test that wants to see that NO app ran used to wait out a
+// fixed timeout for a file that was never coming. Both waits had a real
+// condition behind them, and the helpers here wait for that instead:
+//
+// - the app has recorded: its file exists AND it has exited, so whatever
+// it was going to write is written;
+// - nothing can still record: no child of this test binary is running,
+// so no process exists that could write the file later.
+//
+// Both read /proc, not the code under test, so they rest on what the kernel
+// says ran, never on the launch's own account of itself. Where /proc cannot
+// answer, or an unrelated child of this binary is still running, they fall
+// back to the original bound, which only makes them slower.
+
+// runningChildren reports how many children of this test binary are still
+// running. A zombie (exited, not yet reaped) is not running: it has written
+// all it ever will. ok is false when /proc cannot be read.
+func runningChildren() (n int, ok bool) {
+ entries, err := os.ReadDir("/proc")
+ if err != nil {
+ return 0, false
+ }
+ self := strconv.Itoa(os.Getpid())
+ for _, e := range entries {
+ name := e.Name()
+ if name == "" || name[0] < '0' || name[0] > '9' {
+ continue
+ }
+ raw, err := os.ReadFile(filepath.Join("/proc", name, "stat"))
+ if err != nil {
+ continue // gone since the listing
+ }
+ // "pid (comm) state ppid ...": comm may hold spaces and parens.
+ i := bytes.LastIndexByte(raw, ')')
+ if i < 0 {
+ continue
+ }
+ f := bytes.Fields(raw[i+1:])
+ if len(f) < 2 || string(f[1]) != self {
+ continue
+ }
+ if s := string(f[0]); s != "Z" && s != "X" {
+ n++
+ }
+ }
+ return n, true
+}
+
+// noChildRunning is runningChildren's "none, for certain".
+func noChildRunning() bool {
+ n, ok := runningChildren()
+ return ok && n == 0
+}
+
+// awaitChildFile returns path's contents once it exists, or "" once no
+// child of this test binary is running, so nothing is left to write it,
+// or once within has passed (the old fixed wait, still the bound). Call it
+// only after the launch under test has returned: a launch still in flight
+// could spawn after the check.
+func awaitChildFile(path string, within time.Duration) string {
+ deadline := time.Now().Add(within)
+ for {
+ if raw, err := os.ReadFile(path); err == nil {
+ return string(raw)
+ }
+ if noChildRunning() {
+ // A child that exited between the read and the check wrote its
+ // file before it exited.
+ if raw, err := os.ReadFile(path); err == nil {
+ return string(raw)
+ }
+ return ""
+ }
+ if !time.Now().Before(deadline) {
+ return ""
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+}
+
+// recordedCtx is the bounded context a fake-app test hands Start, also
+// cancelled the moment the fake app has recorded: every path in paths
+// exists and no child of this test binary is still running. The health
+// wait the app never answers has nothing left to show after that; before,
+// the test sat out the whole timeout. Start then fails on the cancel
+// rather than the deadline, which these tests ignore.
+func recordedCtx(within time.Duration, paths ...string) (context.Context, context.CancelFunc) {
+ return ctxUntil(within, func() bool { return allExist(paths) && noChildRunning() })
+}
+
+// ctxUntil is a context bounded by within and also cancelled once done
+// reports true (polled every 5 ms): the condition a test was really waiting
+// for when it sat out the timeout.
+func ctxUntil(within time.Duration, done func() bool) (context.Context, context.CancelFunc) {
+ ctx, cancel := context.WithTimeout(context.Background(), within)
+ go func() {
+ t := time.NewTicker(5 * time.Millisecond)
+ defer t.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ }
+ if done() {
+ cancel()
+ return
+ }
+ }
+ }()
+ return ctx, cancel
+}
+
+func allExist(paths []string) bool {
+ for _, p := range paths {
+ if _, err := os.Stat(p); err != nil {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/activator/generations_backend_test.go b/internal/activator/generations_backend_test.go
index a4dacf0e4..3cfb77e1f 100644
--- a/internal/activator/generations_backend_test.go
+++ b/internal/activator/generations_backend_test.go
@@ -66,6 +66,7 @@ func TestStartGenWithGenerationsOffIsStart(t *testing.T) {
}()
gotArgv := strings.Fields(waitForFile(t, argvPath, time.Second))
gotEnv := strings.TrimSpace(waitForFile(t, envPath, time.Second))
+ cancel() // recorded: end the health wait the recorder never answers
<-done
if proc != nil {
defer proc.Stop(context.Background())
diff --git a/internal/activator/gensocket_rev19_test.go b/internal/activator/gensocket_rev19_test.go
index 975120111..b1f11df72 100644
--- a/internal/activator/gensocket_rev19_test.go
+++ b/internal/activator/gensocket_rev19_test.go
@@ -117,6 +117,7 @@ func TestFlatGenerationLaunchMatchesTheFlagOffLaunch(t *testing.T) {
}()
argv := strings.Split(strings.TrimSpace(waitForFile(t, argvPath, 3*time.Second)), "\n")
env := envMap(t, strings.Split(strings.TrimSpace(waitForFile(t, envPath, 3*time.Second)), "\n"))
+ cancel() // recorded: end the health wait the recorder never answers
<-done
if proc != nil {
_ = proc.Stop(context.Background())
diff --git a/internal/activator/instancekey_delivery_test.go b/internal/activator/instancekey_delivery_test.go
index 35ffc7d9d..627a0724f 100644
--- a/internal/activator/instancekey_delivery_test.go
+++ b/internal/activator/instancekey_delivery_test.go
@@ -168,7 +168,7 @@ func TestFirstStartWaitsForTheConfiguredKey(t *testing.T) {
// The helper exits once it has recorded its outcome, so Start's health
// wait never sees a live socket: the outcome is the proof, as in the
// replica tests, and the error only must not be the deferral.
- ctx2, cancel2 := context.WithTimeout(context.Background(), 2*time.Second) // ctx was spent waiting for the first outcome
+ ctx2, cancel2 := recordedCtx(2*time.Second, out) // ctx was spent waiting for the first outcome
defer cancel2()
proc, _, err = b.Start(ctx2, rt)
if proc != nil {
diff --git a/internal/activator/instancekey_test.go b/internal/activator/instancekey_test.go
index c632af017..7c9301a64 100644
--- a/internal/activator/instancekey_test.go
+++ b/internal/activator/instancekey_test.go
@@ -646,9 +646,10 @@ func TestEnsureInstanceKeySymlinkErrorNamesThePathOnce(t *testing.T) {
}
// startRecorded starts host on b with the recording binary and returns the
-// environment the child saw, or nil when no child ran within a second. The
-// route's socket is a temp path, so the row classifies as foreign;
-// startRecordedRoute takes the row as given.
+// environment the child saw, or nil when no child ran (none recorded within a
+// second, or none is left running that could). The route's socket is a temp
+// path, so the row classifies as foreign; startRecordedRoute takes the row as
+// given.
func startRecorded(t *testing.T, b *ExecBackend, host string) (map[string]string, error) {
t.Helper()
return startRecordedRoute(t, b, registry.Route{Host: host, Kind: "instance", Socket: tmpSock(t)})
@@ -657,26 +658,23 @@ func startRecorded(t *testing.T, b *ExecBackend, host string) (map[string]string
func startRecordedRoute(t *testing.T, b *ExecBackend, rt registry.Route) (map[string]string, error) {
t.Helper()
_, envPath := stageRecordingLiveFullEnv(t, b, rt.Host, "v1")
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ ctx, cancel := recordedCtx(2*time.Second, envPath)
defer cancel()
proc, _, err := b.Start(ctx, rt) // the fake binary never binds: the health wait fails, as in the sibling tests
if proc != nil {
defer proc.Stop(context.Background())
}
- deadline := time.Now().Add(time.Second)
- for time.Now().Before(deadline) {
- if raw, rerr := os.ReadFile(envPath); rerr == nil {
- child := map[string]string{}
- for _, line := range strings.Split(string(raw), "\n") {
- if k, v, ok := strings.Cut(line, "="); ok {
- child[k] = v
- }
- }
- return child, err
+ raw := awaitChildFile(envPath, time.Second)
+ if raw == "" {
+ return nil, err
+ }
+ child := map[string]string{}
+ for _, line := range strings.Split(raw, "\n") {
+ if k, v, ok := strings.Cut(line, "="); ok {
+ child[k] = v
}
- time.Sleep(10 * time.Millisecond)
}
- return nil, err
+ return child, err
}
// Start hands the child the key it minted, and a second Start (a restart, a
diff --git a/internal/activator/replica_instancekey_linux_test.go b/internal/activator/replica_instancekey_linux_test.go
index 66c5cfe36..ad0d04c5a 100644
--- a/internal/activator/replica_instancekey_linux_test.go
+++ b/internal/activator/replica_instancekey_linux_test.go
@@ -44,7 +44,7 @@ func TestKeylessReplicaWithAControlSocketLeavesTheHelperToRefuse(t *testing.T) {
t.Fatal(err)
}
out := stageHelperApp(t, b, rt.Host, "v1")
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ ctx, cancel := recordedCtx(2*time.Second, out)
defer cancel()
proc, _, _ := b.Start(ctx, rt)
if proc != nil {
diff --git a/internal/activator/replica_instancekey_test.go b/internal/activator/replica_instancekey_test.go
index 2bc52c544..0e15f8b18 100644
--- a/internal/activator/replica_instancekey_test.go
+++ b/internal/activator/replica_instancekey_test.go
@@ -96,16 +96,10 @@ func stageHelperApp(t *testing.T, b *ExecBackend, host, ver string) string {
}
// outcomeOf waits up to two seconds for the helper's outcome; "" is no app
-// ran at all.
+// ran at all: none recorded, and no child of this test binary is left
+// running that could (awaitChildFile). Call it once the launch returned.
func outcomeOf(path string) string {
- deadline := time.Now().Add(2 * time.Second)
- for time.Now().Before(deadline) {
- if raw, err := os.ReadFile(path); err == nil {
- return string(raw)
- }
- time.Sleep(10 * time.Millisecond)
- }
- return ""
+ return awaitChildFile(path, 2*time.Second)
}
// noControlSocket is a socket path too long to bind, so the launch's
@@ -198,7 +192,7 @@ func TestReplicaLaunchWithoutAControlSocket(t *testing.T) {
}
b.ConfiguredKey = freshConfig(tc)
out := stageHelperApp(t, b, rt.Host, "v1")
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ ctx, cancel := recordedCtx(2*time.Second, out)
defer cancel()
proc, _, err := b.Start(ctx, rt)
if proc != nil {