carlos / platform Public

tests: worker publish order and demo proof expiry no longer race

Two CI flakes, both test faults (#1252, #1247):
- WakeWorker returns before the wake publishes v1, so a replacement can
  make that publication stale and drop it. The worker swap tests now
  wait for it on a signal, and a new test proves a late wake publication
  never overwrites its replacement.
- The demo proof tests signed a proof with 0 to 1 s left, so a stall hit
  the deliberate empty 503. Proof checks read time through edgeProofNow
  (time.Now unless a test sets a clock), the 3 s sleeps are gone, and an
  empty reply now reports its status and headers.

Reviewed by Astra (round 1, READY).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from worker-publish-order-1252 into main.
claude agent, operated by paul@keymail.dev 0e0dec79e28067caf80f21bf5ff40e7671c4dc1f parent 5048247
9 files changed, +168 −17
  • .amadan/code-health.tsv +0 −1
  • docs/superpowers/reviews/FINDINGS-worker-publish-order-1252-R1.md +21 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-worker-publish-order-1252.md +37 −0
  • internal/activator/workerswap_test.go +61 −0
  • internal/console/apidemoreports.go +1 −1
  • internal/console/demo_api_alias_integration_test.go +9 −4
  • internal/console/demo_api_origin.go +1 −1
  • internal/console/demo_api_origin_test.go +25 −9
  • internal/console/edgeproof.go +13 −1

CI passed — run details

diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv
index 638c01f4c..ae1864170 100644
--- a/.amadan/code-health.tsv
+++ b/.amadan/code-health.tsv
@@ -768,7 +768,6 @@ sleep internal/console (*claimCase).systemJob time.Sleep 1
sleep internal/console (*dbFx).waitIdle time.Sleep 1
sleep internal/console (*dbfFixture).admitWithin time.Sleep 1
sleep internal/console (*dbfHeldWriter).Write time.Sleep 1
-sleep internal/console (*demoAPIExpiryBody).Read time.Sleep 1
sleep internal/console (*reportCDP).wait time.Sleep 1
sleep internal/console (*slowCountingStore).Get time.Sleep 1
sleep internal/console (*slowGetStore).Get time.Sleep 1
diff --git a/docs/superpowers/reviews/FINDINGS-worker-publish-order-1252-R1.md b/docs/superpowers/reviews/FINDINGS-worker-publish-order-1252-R1.md
new file mode 100644
index 000000000..1f805d422
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-worker-publish-order-1252-R1.md
@@ -0,0 +1,21 @@
+Reviewed commit `513f5c7cef4f6f272905cc3304a78acc17d2d45f` against base `5048247f`, round 1 of 3. The difference from the brief’s named commit is the brief itself.
+
+No P1, P2 or P3 findings.
+
+1. **Worker publication order (#1252).** The author’s explanation holds. Wake closes `e.ready` before publishing, so `WakeWorker` returning does not guarantee delivery (`internal/activator/activator.go:2465`). Wake and successful respawn increment `workerInc` under `a.mu`; immediate and held publications all pass through `publishWorkerServing` (`internal/activator/workerswap.go:327`). That function holds `servingMu` across both the entry/incarnation check and callback. An old publication therefore either arrives first or is dropped, including when a different entry replaces the original.
+
+ `servingWriter` maintains one drain goroutine and replaces pending values with the latest delivery (`internal/host/rollout.go:260`). Registry writes cannot overtake one another. The rollout manager excludes workers from its separate serving-version writer (`internal/rollout/manager.go:1429`). An older write can finish after a newer child is installed, but cannot finish after that newer identity’s registry write through this path.
+
+2. **Proof-clock security and concurrency (#1247).** Production continues to use `time.Now()` (`internal/console/edgeproof.go:71`). The field is private, has no request/configuration/environment setter, and its only assignment is in `demoAPIProofClock`, in a test file.
+
+ All three verification sites retain their original execution position; only the clock expression changes. No verification moves across a body read, and existing post-body calls still sample time when verification executes. Configured demo publish and claim handlers continue capturing verified attribution before reading the body.
+
+ Each test owns its server and installs the function before dispatching requests. The function remains unchanged thereafter, while its captured time uses atomic loads and increments. Independent parallel tests therefore do not share a clock or race on its value.
+
+3. **Regression coverage.** The added waits establish the initial publication required by the existing assertions. The stale-publication test still explicitly replays the old incarnation after the replacement publishes. The fallback test still detects publication before release. The new test forces the late-wake interleaving and waits for wake completion before requiring exactly `v2`.
+
+ The expiry tests advance time by `edgeproof.Skew + time.Second` on the first body read. They still require successful admission, confirm expiration, and check attribution in the stored app or claim budgets. Moving attribution behind the body read would still violate those assertions. Removing the three-second sleeps preserves the relevant coverage.
+
+Validation limitation: the targeted tests could not start because Go attempted to update `go.mod` in this read-only session. Runtime and race-test results are therefore unverified. `git diff --check` passed. No files were edited, reviewers spawned, or full suites run.
+
+READY
\ No newline at end of file
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-worker-publish-order-1252.md b/docs/superpowers/reviews/REVIEW-BRIEF-worker-publish-order-1252.md
new file mode 100644
index 000000000..a300b0602
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-worker-publish-order-1252.md
@@ -0,0 +1,37 @@
+# Review brief: branch worker-publish-order-1252, round 1 of 3
+
+Repo carlos/platform, branch `worker-publish-order-1252`, commit aa9c736a0566daa151569d36851d9f14642433f1.
+Under review: the diff `origin/main...aa9c736a0566daa151569d36851d9f14642433f1` (base 5048247f).
+Authorities: amadan #1252 and #1247, AGENTS.md ("Stopping rules").
+
+You are the independent reviewer. The author concludes both CI failures
+were test faults.
+
+## What to check
+
+1. **#1252.** Claim: a late wake publication of v1 is either delivered
+ before v2 or dropped, because publishWorkerServing checks the
+ incarnation and delivers under servingMu, the respawn raises workerInc
+ before publishing, and servingWriter keeps that order for the registry
+ write. Verify this against the code, every path included. Can a stale
+ identity ever reach the registry after a newer one?
+2. **#1247, a security gate.** Edge-proof verification now reads time
+ through a new `edgeProofNow` seam (edgeproof.go, demo_api_origin.go,
+ apidemoreports.go). Is it time.Now in production with no way for a
+ request, config or environment to change it? Is every proof check still
+ made at the same moment as before (in particular after the body read)?
+ Is the seam safe for parallel tests?
+3. Do the rewritten tests still fail against the bugs they guard? Did
+ removing the 3 s sleeps lose coverage?
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Follow-up list only.
+
+## Output
+
+Findings ranked P1, P2, P3 with file:line, failure scenario and fix. End
+with exactly one verdict: READY, READY AFTER FIXES, or NOT READY. Do not
+edit files, spawn reviewers or run full suites.
diff --git a/internal/activator/workerswap_test.go b/internal/activator/workerswap_test.go
index d6a3a8332..8d7caa677 100644
--- a/internal/activator/workerswap_test.go
+++ b/internal/activator/workerswap_test.go
@@ -583,6 +583,9 @@ func TestAnOlderWorkerPublicationIsDropped(t *testing.T) {
if err := a.WakeWorker(alwaysOnWorkerRoute(host)); err != nil {
t.Fatal(err)
}
+ // WakeWorker returns when e.ready closes, before the wake publishes. A
+ // respawn that got in first would rightly drop that publication.
+ waitFor(t, "the wake's publication", func() bool { mu.Lock(); defer mu.Unlock(); return len(got) == 1 })
a.mu.Lock()
e := a.entries[host]
firstID, firstInc := e.workerServing, e.workerInc
@@ -598,6 +601,53 @@ func TestAnOlderWorkerPublicationIsDropped(t *testing.T) {
}
}
+// Spec §7.9 (#1252): the wake publishes after WakeWorker returns, so a
+// replacement can install its child first. Holding servingMu keeps the wake's
+// v1 undelivered until B's v2 is installed, the interleaving CI hit. However
+// the two then race for the lock, v1 is out of date and only v2 is delivered,
+// so a late wake can never overwrite the replacement's serving identity.
+func TestALateWakePublicationNeverOverwritesItsReplacement(t *testing.T) {
+ shrinkFirstWake(t, 55*time.Second, 25*time.Second, 50*time.Millisecond)
+ a, _, _, _, _ := stagedActivator(t)
+ var mu sync.Mutex
+ var got []string
+ a.OnWorkerServing = func(_ string, id release.StagedIdentity) {
+ mu.Lock()
+ got = append(got, id.Version)
+ mu.Unlock()
+ }
+ host := "bot.x.internal"
+ a.servingMu.Lock()
+ locked := true
+ defer func() {
+ if locked {
+ a.servingMu.Unlock()
+ }
+ }()
+ if err := a.WakeWorker(alwaysOnWorkerRoute(host)); err != nil {
+ t.Fatal(err)
+ }
+ a.mu.Lock()
+ e, inc0 := a.entries[host], a.entries[host].workerInc
+ a.mu.Unlock()
+ results := make(chan SwapResult, 1)
+ go func() {
+ results <- a.ReplaceWorker(context.Background(), workerAttempt(CauseRelease, ModeOverlap, fakeIdentity("v2")), nil, one)
+ }()
+ waitFor(t, "B's install", func() bool { a.mu.Lock(); defer a.mu.Unlock(); return e.workerInc > inc0 })
+ a.servingMu.Unlock()
+ locked = false
+ if res := <-results; res.Outcome != SwapDone {
+ t.Fatalf("ReplaceWorker = %+v", res)
+ }
+ waitBackground(t, a) // the wake's goroutine, and with it its publication, has finished
+ mu.Lock()
+ defer mu.Unlock()
+ if !slices.Equal(got, []string{"v2"}) {
+ t.Fatalf("published %v, want only the replacement's v2", got)
+ }
+}
+
// Spec §7.9 (P5 review finding 8): a child exec'd from an external live-link
// target has no captured version. Its publication still goes out, empty,
// so the row stops naming the build the previous child ran. Skipping empty
@@ -693,11 +743,15 @@ func TestAWorkerFallbackPublishesOnlyWhenReleased(t *testing.T) {
var mu sync.Mutex
var got []string
block := make(chan struct{})
+ wakePublished := make(chan struct{})
a.OnWorkerServing = func(_ string, id release.StagedIdentity) {
mu.Lock()
got = append(got, id.Version)
n := len(got)
mu.Unlock()
+ if n == 1 {
+ close(wakePublished)
+ }
if n > 2 {
<-block // a slow registry write for the fallback's identity (the wake's v1, then B's v2, come first)
}
@@ -706,6 +760,13 @@ func TestAWorkerFallbackPublishesOnlyWhenReleased(t *testing.T) {
if err := a.WakeWorker(alwaysOnWorkerRoute(host)); err != nil {
t.Fatal(err)
}
+ // WakeWorker returns when e.ready closes, and the wake publishes v1 after
+ // that. Replacing the worker first would drop v1 as out of date (#1252).
+ select {
+ case <-wakePublished:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the wake never published its identity")
+ }
good := fakeIdentity("v1")
go func() {
waitForWorkerStarts(t, b, 2)
diff --git a/internal/console/apidemoreports.go b/internal/console/apidemoreports.go
index 1727fb853..81487f2a4 100644
--- a/internal/console/apidemoreports.go
+++ b/internal/console/apidemoreports.go
@@ -238,5 +238,5 @@ func (s *Server) demoReportForwardedByEdge(r *http.Request, xff string) bool {
return false
}
current, next := s.edgeProofKeys(r.Context())
- return edgeproof.Verify(current, next, r.Host, xff, proof, time.Now())
+ return edgeproof.Verify(current, next, r.Host, xff, proof, s.edgeProofNow())
}
diff --git a/internal/console/demo_api_alias_integration_test.go b/internal/console/demo_api_alias_integration_test.go
index 6f3fe942a..e7a3ef51d 100644
--- a/internal/console/demo_api_alias_integration_test.go
+++ b/internal/console/demo_api_alias_integration_test.go
@@ -200,22 +200,27 @@ func TestDemoAPIProofRequiredClaimExpiry(t *testing.T) {
t.Fatal(err)
}
s.markEdgeProofSeen()
+ now, expire := demoAPIProofClock(s)
const client, peer, forged = "192.0.2.1", "127.0.0.1", "203.0.113.9"
send := func(path string, fields map[string]string) *httptest.ResponseRecorder {
b, err := json.Marshal(fields)
if err != nil {
t.Fatal(err)
}
- r := httptest.NewRequest("POST", s.cfg.Origin+path, &demoAPIExpiryBody{Reader: strings.NewReader(string(b)), delay: 3 * time.Second})
+ r := httptest.NewRequest("POST", s.cfg.Origin+path, &demoAPIExpiryBody{Reader: strings.NewReader(string(b)), expire: expire})
r.RemoteAddr = peer + ":1234"
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Forwarded", "for="+forged)
r.Header.Set("X-Real-IP", forged)
r.Header.Set("X-Forwarded-For", client)
- r.Header.Set(edgeproof.Header, edgeproof.Sign(key, r.Host, client, time.Now().Add(-29*time.Second)))
+ r.Header.Set(edgeproof.Header, edgeproof.Sign(key, r.Host, client, now()))
w := httptest.NewRecorder()
s.mux.ServeHTTP(w, r)
- if edgeproof.Verify(key, nil, r.Host, client, r.Header.Get(edgeproof.Header), time.Now()) {
+ if w.Body.Len() == 0 {
+ // requireDemoAPIProof's refusal is an empty 503 by design.
+ t.Fatalf("%s: empty reply: status = %d, headers = %v", path, w.Code, w.Header())
+ }
+ if edgeproof.Verify(key, nil, r.Host, client, r.Header.Get(edgeproof.Header), now()) {
t.Fatal("proof did not expire during body read")
}
var response map[string]json.RawMessage
@@ -297,7 +302,7 @@ func TestDemoAPIProofRequiredClaimExpiry(t *testing.T) {
r.RemoteAddr = peer + ":1234"
r.Header.Set("Authorization", "Bearer "+start.Flow)
r.Header.Set("X-Forwarded-For", client)
- r.Header.Set(edgeproof.Header, edgeproof.Sign(key, r.Host, client, time.Now()))
+ r.Header.Set(edgeproof.Header, edgeproof.Sign(key, r.Host, client, now()))
w := httptest.NewRecorder()
s.mux.ServeHTTP(w, r)
want := http.StatusAccepted
diff --git a/internal/console/demo_api_origin.go b/internal/console/demo_api_origin.go
index 5d8f75bb2..68378e252 100644
--- a/internal/console/demo_api_origin.go
+++ b/internal/console/demo_api_origin.go
@@ -49,7 +49,7 @@ func (s *Server) requireDemoAPIProof(w http.ResponseWriter, r *http.Request) boo
if err == nil && origin.Host != "" && normalizeHost(r.Host) == normalizeHost(origin.Host) && len(xff) == 1 && len(proofs) == 1 {
if ip, err := demo.CanonicalIP(xff[0]); err == nil && ip == xff[0] {
current, next := s.edgeProofKeys(r.Context())
- if edgeproof.Verify(current, next, r.Host, xff[0], proofs[0], time.Now()) {
+ if edgeproof.Verify(current, next, r.Host, xff[0], proofs[0], s.edgeProofNow()) {
return true
}
}
diff --git a/internal/console/demo_api_origin_test.go b/internal/console/demo_api_origin_test.go
index 11c716d88..423a135d7 100644
--- a/internal/console/demo_api_origin_test.go
+++ b/internal/console/demo_api_origin_test.go
@@ -10,6 +10,7 @@ import (
"net/http"
"net/http/httptest"
"strings"
+ "sync/atomic"
"testing"
"time"
@@ -329,20 +330,34 @@ func TestDemoAPIHostOwnership(t *testing.T) {
}
}
-// Delay the first body read until the admitted proof has expired.
+// demoAPIExpiryBody runs expire at the first body read, so a proof admitted
+// at the door has expired by the time the handler has the body.
type demoAPIExpiryBody struct {
io.Reader
- delay time.Duration
+ expire func()
}
func (b *demoAPIExpiryBody) Read(p []byte) (int, error) {
- if b.delay != 0 {
- time.Sleep(b.delay)
- b.delay = 0
+ if b.expire != nil {
+ b.expire()
+ b.expire = nil
}
return b.Reader.Read(p)
}
+// demoAPIProofClock gives s a proof clock that moves only when expire is
+// called, past edgeproof.Skew. A proof signed at now() is therefore valid at
+// the door however slowly the machine runs. Signing 29 s in the past on the
+// real clock left at most a second, and less the later in a second it was
+// signed: a stall there got the door's empty 503 (#1247).
+func demoAPIProofClock(s *Server) (now func() time.Time, expire func()) {
+ var at atomic.Int64
+ at.Store(time.Now().UnixNano())
+ now = func() time.Time { return time.Unix(0, at.Load()) }
+ s.edgeProof.now = now
+ return now, func() { at.Add(int64(edgeproof.Skew + time.Second)) }
+}
+
func TestDemoAPIProofRequiredPublishExpiry(t *testing.T) {
s, _ := demoJobServer(t)
s.cfg.Origin = "https://console.example.com"
@@ -351,17 +366,18 @@ func TestDemoAPIProofRequiredPublishExpiry(t *testing.T) {
if _, err := s.cfg.Releases.Put(t.Context(), edgeproof.MeshKeyObject, []byte(hex.EncodeToString(key)), ""); err != nil {
t.Fatal(err)
}
- r := httptest.NewRequest("POST", s.cfg.Origin+"/api/demo/apps", &demoAPIExpiryBody{Reader: bytes.NewReader(demoHTTPSource(t)), delay: 3 * time.Second})
+ now, expire := demoAPIProofClock(s)
+ r := httptest.NewRequest("POST", s.cfg.Origin+"/api/demo/apps", &demoAPIExpiryBody{Reader: bytes.NewReader(demoHTTPSource(t)), expire: expire})
r.RemoteAddr = "127.0.0.1:1234"
r.Header.Set("Content-Type", "application/gzip")
r.Header.Set("X-Forwarded-For", "192.0.2.1")
- r.Header.Set(edgeproof.Header, edgeproof.Sign(key, r.Host, "192.0.2.1", time.Now().Add(-29*time.Second)))
+ r.Header.Set(edgeproof.Header, edgeproof.Sign(key, r.Host, "192.0.2.1", now()))
w := newDemoRecorder()
s.mux.ServeHTTP(w, r)
if w.Code != 202 {
- t.Fatalf("publish status = %d", w.Code)
+ t.Fatalf("publish status = %d, headers = %v", w.Code, w.Header())
}
- if edgeproof.Verify(key, nil, r.Host, "192.0.2.1", r.Header.Get(edgeproof.Header), time.Now()) {
+ if edgeproof.Verify(key, nil, r.Host, "192.0.2.1", r.Header.Get(edgeproof.Header), now()) {
t.Fatal("proof did not expire during upload")
}
var ip string
diff --git a/internal/console/edgeproof.go b/internal/console/edgeproof.go
index 5c929111b..3a3f336e7 100644
--- a/internal/console/edgeproof.go
+++ b/internal/console/edgeproof.go
@@ -61,6 +61,18 @@ type edgeProofState struct {
loaded atomic.Bool
seen atomic.Bool
warned atomic.Bool
+
+ // now is the clock proofs are checked against; nil means time.Now. Tests
+ // use it to expire a proof at an exact point in a request.
+ now func() time.Time
+}
+
+// edgeProofNow is the time a proof's age is measured at.
+func (s *Server) edgeProofNow() time.Time {
+ if s.edgeProof.now != nil {
+ return s.edgeProof.now()
+ }
+ return time.Now()
}
// forwardedByEdge reports whether a loopback peer's X-Forwarded-For chain
@@ -69,7 +81,7 @@ func (s *Server) forwardedByEdge(r *http.Request, xff string) bool {
st := &s.edgeProof
if proof := r.Header.Get(edgeproof.Header); proof != "" {
current, next := s.edgeProofKeys(r.Context())
- if edgeproof.Verify(current, next, r.Host, xff, proof, time.Now()) {
+ if edgeproof.Verify(current, next, r.Host, xff, proof, s.edgeProofNow()) {
s.markEdgeProofSeen()
return true
}