carlos / platform Public

region HA: every edge/activator 503 carries Retry-After (#421)

Every 503 written by internal/edge and internal/activator goes through
edge.Unavailable / UnavailableHeader: Retry-After, X-Carlos-Answer (one
fixed name per call site) and X-Carlos-Box (hashed box label). The two
bare wake-error branches (rootfs-not-admitted, wake-failed) now send
Retry-After: 5. The plans turned-off page keeps no Retry-After on purpose
(UnavailableNoRetry). A go/types guard test refuses any other 503.

scripts/ha-roll-probe.sh records Retry-After, answer, box and body start
on every non-200. releaseHAClean logs per-phase times (files, sync,
record, marker).

Astra: three rounds, all findings fixed. Census approved on #280.

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

Squashed from retry-after-503 into main.
claude agent, operated by paul@keymail.dev 6c2c167afa9db90137bc405408523b50137f1596 parent 965e26f
40 files changed, +947 −73
  • docs/superpowers/notes/census-proposal-retry-after-503.md +35 −0
  • internal/activator/activator.go +9 −17
  • internal/activator/haforward.go +1 −2
  • internal/activator/harelease.go +14 −1
  • internal/activator/maintenance.go +1 −2
  • internal/activator/unavailable_answers_test.go +35 −0
  • internal/edge/assetcatch.go +1 −2
  • internal/edge/demo_api.go +8 −3
  • internal/edge/demo_banner.go +5 −1
  • internal/edge/demo_response.go +5 −1
  • internal/edge/edge.go +7 −9
  • internal/edge/forwardha.go +1 −2
  • internal/edge/group_admission.go +4 −5
  • internal/edge/haingress.go +1 −2
  • internal/edge/homemap.go +1 −2
  • internal/edge/importgate.go +1 −2
  • internal/edge/lbhealth.go +1 −2
  • internal/edge/pending.go +2 −3
  • internal/edge/pending_test.go +3 −2
  • internal/edge/plandisabled.go +1 −1
  • internal/edge/plandisabled_test.go +1 −1
  • internal/edge/regional.go +1 −2
  • internal/edge/replicaconsole.go +2 −2
  • internal/edge/replicaprobe.go +6 −6
  • internal/edge/replicaproxy.go +1 −2
  • internal/edge/status.go +1 −1
  • internal/edge/testdata/unavailable_guard/bare.go +12 −0
  • internal/edge/testdata/unavailable_guard/clean.go +12 −0
  • internal/edge/testdata/unavailable_guard/closure.go +11 −0
  • internal/edge/testdata/unavailable_guard/handed.go +13 −0
  • internal/edge/testdata/unavailable_guard/indirect.go +23 −0
  • internal/edge/testdata/unavailable_guard/named.go +9 −0
  • internal/edge/testdata/unavailable_guard/site.go +15 −0
  • internal/edge/testdata/unavailable_guard/variable.go +7 −0
  • internal/edge/unavailable.go +88 −0
  • internal/edge/unavailable_guard_test.go +434 −0
  • internal/edge/unavailable_test.go +105 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-retry-after-503.tsv +21 −0
  • scripts/ha-roll-probe.sh +48 −0

CI passed — run details

diff --git a/docs/superpowers/notes/census-proposal-retry-after-503.md b/docs/superpowers/notes/census-proposal-retry-after-503.md
new file mode 100644
index 000000000..e195f62f7
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-retry-after-503.md
@@ -0,0 +1,35 @@
+# Census approval: retry-after-503
+
+Ruling `census-ruling-retry-after-503`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/activator/activator.go` `Service.ServeScheduled` | body | unchanged (8) | the scheduled-token 503 is written through edge.UnavailableHeader (Retry-After 5 unchanged, adds X-Carlos-Answer/X-Carlos-Box); no read added |
+| `internal/activator/activator.go` `Service.serve` | body | unchanged (18) | the sidecar-asleep 503 is written through edge.Unavailable (Retry-After 5 unchanged, adds answer/box headers); no read added |
+| `internal/activator/activator.go` `Service.serveWakeError` | body | unchanged (5) | every case answers through edge.Unavailable with its own site name; Retry-After values unchanged; rootfs-not-admitted and the default wake-failed answer now carry Retry-After 5 (#421); no read added |
+| `internal/activator/haforward.go` `Service.answerForwarded` | body | unchanged (1) | the held-lease 503 is written through edge.Unavailable (Retry-After 1 unchanged); X-Carlos-Holder unchanged; no read added |
+| `internal/activator/harelease.go` `Service.releaseHAClean` | body | unchanged (7) | records four time.Now stamps and logs per-phase durations (files, sync, record, marker) on the existing marker log line; order, budgets and clean rule unchanged; no read added |
+| `internal/edge/importgate.go` `Edge.importGateAdmit` | body | unchanged (10) | the gate's 503 is written through Unavailable (adds Retry-After and answer/box headers); admission logic unchanged; no read added |
+| `internal/edge/plandisabled.go` `Edge.planDisabledAdmit` | body | unchanged (2) | the fixed 503 page status is written through UnavailableNoRetry (still no Retry-After; adds answer/box headers); body and checks unchanged; no read added |
+| `internal/edge/replicaconsole.go` `Edge.serveReplicaConsole` | body | unchanged (6) | the missing/ambiguous-console 503s go through UnavailableHeader (adds Retry-After 2 and answer/box headers); selection unchanged; no read added |
+| `internal/edge/replicaprobe.go` `Edge.serveReplicaProbe` | body | unchanged (9) | each refusal 503 goes through UnavailableHeader with its own site (adds Retry-After 2 and answer/box headers); dial and identity checks unchanged; no read added |
+
+Envelopes re-pinned: `internal/activator`, `internal/edge`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/activator/activator.go` `Service.ServeScheduled`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-plans-4d-lapse;basis=answers a scheduled request to a route the turned-off hook names with the maintenance response before serve (plans 4d). One more whole-row read: the row handed to the hook (a.disabled), as the fence and maxRunFor are asked.;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: wraps the proxy so that, after the wake, fillScheduledToken(r, rt) sets an HA host's tick bearer token from its restored env file; an error there logs (+registry:Host, rt.Host) and answers 503 with Retry-After: 5; a non-HA host's tick is left as the runner built it; +whole:Route is rt handed to fillScheduledToken; keeps legacy;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test is Route.ActivatorOwned (a hibernating instance, or an instance with a runtime) instead of Kind and Hibernate inline; reads the same fields plus Runtime through the method;rev3=census-ruling-region-ha-p1b3b-t;basis=Run the local scheduled request under WithDuty and retain existing HTTP refusal text; add route arguments to background admission and error handling. No forwarding.
+- `internal/activator/activator.go` `Service.serve`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-hotfix281;basis=Startup repeats the existing Kind and Hibernate checks; error logging moved to serveWakeError. A request held through startup re-reads its own route's Socket and Addr and can only refuse (wake-timeout 503) when recovery moved them; agent-side, deny-only, no root decision.;rev3=census-ruling-edge-request-records;basis=passes the member request r to begin's new req parameter; no read added;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test is Route.ActivatorOwned instead of Kind and Hibernate inline, so a resident rootfs instance is the activator's; same deploy-safety for binary rows;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: a verified HA hop this box cannot serve gets the holder diagnostic; two new whole:Route sites pass the route to answerForwarded/noteNoHolder; no new kind of read;rev3=census-ruling-region-ha-g2-fixes;basis=Refuse latched HA lease loss before startup wait or proxy accounting, and schedule bounded recovery; reads supplied route, no new external read here.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 2: after begin succeeds, edge.ReleaseMoveTicket(r) ends the request's in-memory admission ticket; on the sidecar path the same after BeginSidecarRequest; no read added;rev3=census-ruling-held-move-speed;basis=after begin succeeds, wraps r with an edge.StreamEnd (a cancellable child context) and tracks it under rt.Host in the in-memory moveStreams until the request ends (+registry:Host: the supplied route's Host as the map key); no new kind of read, no root decision
+- `internal/activator/activator.go` `Service.serveWakeError`: diagnostic, task C,J4. Basis: rev3=PROPOSED-seed; incarnation-keyed missing-files diagnostics and indexed retry results; throttles output only and grants no retry, stop or launch;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more case, errLeaseRefused (a born-HA host outside the nested layout or an HA acquire's refusal): logged at most once per diagnostic window (allowFilesDiagnostic(rt.Host, ...)) and answered 503 with Retry-After: 10; the other cases unchanged; +registry:Host x2 are rt.Host in that call and the log line; it only answers;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: two new answers, a resident inside its backoff gets 503 with Retry-After (RFS-3-C16), and a rootfs row refused before the lease (errRootfsNotAdmitted) gets the existing wake-failed 503; no read added;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: for a verified HA hop, a held lease answers 503 Retry-After 1 with X-Carlos-Holder (answerForwarded) and every other refusal adds X-Carlos-Holder: none (noteNoHolder); legacy routes and cancellation unchanged; same reads;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: neutral admission 503 with Retry-After before forwarded-holder diagnostics; no new read, no holder identity. Fix R1: distinguish startup from drain/shutdown using the same admission state; retain 503, Retry-After, no-store and removal of holder identity. Read sites unchanged.;rev3=census-ruling-region-ha-g2-fixes;basis=Answer latched HA loss and pool refusal with the shared unavailable response; no new read.;rev3=census-ruling-region-ha-shutting-down-retry;basis=Task 0: errShuttingDown (a request met by Shutdown, #292) is answered with the existing admission unavailable 503 (Retry-After: 10, no-store, holder removed), before answerForwarded, instead of the default wake-failed 503 with no Retry-After and a wake log line; no new read, read sites unchanged.
+- `internal/activator/haforward.go` `Service.answerForwarded`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): writes the 503 Retry-After 1 with X-Carlos-Holder for a held lease on a verified HA hop; reads the route only to check HA; root never calls it
+- `internal/activator/harelease.go` `Service.releaseHAClean`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: an HA entry's release, in order: host slice read empty through haHostEmpty (else errHostSliceUnproven and nothing written; the same check, moved into that helper by final fix F1), stop and join the files publisher, its final publish (2 min budget), the replica's final sync (Finish, 30 s), the local release record, then the release marker PUT (10 s), clean only when the final publish was complete and the sync and record succeeded; a failed PUT is a persisted lease obligation; +registry:Host, +whole:Route x4;rev3=census-ruling-region-ha-p1b3b-t;basis=Record advisory local-release basis only after ReleaseMarker succeeds. Add a whole-route argument to local duty bookkeeping; release order and lease authority unchanged.;rev3=census-ruling-region-ha-g2-fixes;basis=Latch unexpected lease loss before release and mark intentional release so ErrSpent alone is not treated as loss; no new read.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Cap Final, Finish and marker contexts by the shutdown deadline and reserves; keep calls synchronous and stop proof unchanged; record successful marker completion under the service mutex. No read added.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 5: records the written marker's clean flag on the entry (haReleaseClean) beside haReleased, for the drain report; no read added;rev3=census-ruling-held-move-speed;basis=reads the entry's drainRelease flag under a.mu; for the drain's release calls the replica's FinishSnapshot (final sync, then a litestream snapshot at the final position, before the store's close; the snapshot reader pipe is closed on every outcome) instead of Finish, and logs a snapshot failure naming rt.Host (+registry:Host, the supplied route); marker order, budgets and clean rule unchanged; no new read
+- `internal/edge/importgate.go` `Edge.importGateAdmit`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-seeded-instances;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): the import gate: a gated row admits only a GET carrying the verify token; anything else is a 503; serving only;rev3=census-ruling-agent-start-demo-3;basis=Keep demo-claim destinations gated until committed; verify exact host/seed capability before allowing console probes. Census read-site delta: +registry:Host, +registry:SeedSource.
+- `internal/edge/plandisabled.go` `Edge.planDisabledAdmit`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-plans-4d-units;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), serving only: asks the plans turned-off hook (planDisabledFor, passed the row and the request host) and answers a turned-off route with a fixed 503 page rendered from constants, before the meter, gate, cache and activator; reads only the row's kind; echoes nothing from the request (plans 4d).
+- `internal/edge/replicaconsole.go` `Edge.serveReplicaConsole`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-stateless-coordinator-route;basis=Reads existing in-memory route fields to select a unique accountless console.service local upstream; refuses missing or ambiguous console, tenant routes, remote and tunnel upstreams. Reuses proxy and version wrapper; leaves fleet identity authentication at console.
+- `internal/edge/replicaprobe.go` `Edge.serveReplicaProbe`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 I4/F1: the dialled pathname comes from the serving Gen.Socket and, for shared/foreign layouts, can originate in the registry row Socket. Dial through unixdial.Checked: refuse the instance-control directory before connect and require getpeername to match the dialled path before sending HTTP, including symlink refusal. Existing Route reads unchanged. M5 handles request construction errors before RoundTrip; M2 uses the shared reason constant. Authenticated private landing, held-leg admission, one-second bound and post-response identity checks remain.
+
+Seal: `e650a3ceb286df4457850d74ded9229d94ed9932057ae5b45b1d6c3d0d843ce2` → `eea13e9a0b04164ea3fc7f8258bd1ab0a613d1e23ffe0cd028bc85058576c248`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-retry-after-503.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 1e95f89d3..5ae375919 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -64,7 +64,6 @@ import (
"os"
"path"
"slices"
- "strconv"
"strings"
"sync"
"sync/atomic"
@@ -6442,8 +6441,7 @@ func (a *Service) ServeScheduled(w http.ResponseWriter, r *http.Request, rt regi
if err := a.fillScheduledToken(r, rt); err != nil {
log.Printf("activator: %s: scheduled tick: %v", rt.Host, err)
edge.MarkAnswered(r)
- w.Header().Set("Retry-After", "5")
- w.WriteHeader(http.StatusServiceUnavailable)
+ edge.UnavailableHeader(w, "scheduled-token", 5)
return
}
next.ServeHTTP(w, r)
@@ -6538,11 +6536,10 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout
if errors.Is(err, context.Canceled) {
return true // the sidecar hung up while queued on a wake
}
- w.Header().Set("Retry-After", "5")
// Ours, not the app's: the edge must not file this 503 as an
// edge error (edge/answered.go; spec 2026-09-07 §3.2).
edge.MarkAnswered(r)
- http.Error(w, "instance is asleep; sidecar requests do not wake it", http.StatusServiceUnavailable)
+ edge.Unavailable(w, "sidecar-asleep", "instance is asleep; sidecar requests do not wake it", 5)
return true
}
// Activity-invisible by design, so not held for a move either.
@@ -6612,9 +6609,8 @@ func (a *Service) serveWakeError(w http.ResponseWriter, r *http.Request, rt regi
case errors.As(err, &backoff):
// A resident inside its backoff (Plan 3 Task 8): the tick starts it
// when the backoff has passed, so the answer names that time.
- w.Header().Set("Retry-After", strconv.Itoa(retryAfterSeconds(backoff.retryAfter)))
edge.MarkAnswered(r)
- http.Error(w, "instance is restarting; retry shortly", http.StatusServiceUnavailable) // RFS-3-C16
+ edge.Unavailable(w, "resident-backoff", "instance is restarting; retry shortly", retryAfterSeconds(backoff.retryAfter)) // RFS-3-C16
case errors.As(err, &leaseRefused):
// The refusal outlives a request (region HA P1a: a born-HA host
// outside the nested layout, or an HA acquire's refusal): logged
@@ -6622,25 +6618,21 @@ func (a *Service) serveWakeError(w http.ResponseWriter, r *http.Request, rt regi
if a.allowFilesDiagnostic(rt.Host, err, "http") {
log.Printf("activator: wake %s: %v", rt.Host, err)
}
- w.Header().Set("Retry-After", strconv.Itoa(leaseRefusedRetryAfter))
edge.MarkAnswered(r)
- http.Error(w, "instance failed to wake", http.StatusServiceUnavailable)
+ edge.Unavailable(w, "lease-refused", "instance failed to wake", leaseRefusedRetryAfter)
case errors.As(err, &refused):
// Quiet by design: the config guard logs once per host and
// publishes the refusal in the box's status snapshot. A line per
// request here would bury that one.
- w.Header().Set("Retry-After", strconv.Itoa(configRefusedRetryAfter))
edge.MarkAnswered(r)
- http.Error(w, "instance failed to wake", http.StatusServiceUnavailable)
+ edge.Unavailable(w, "config-refused", "instance failed to wake", configRefusedRetryAfter)
case errors.As(err, &held):
retry := int(held.retryAfter/time.Second) + 1
- w.Header().Set("Retry-After", strconv.Itoa(retry))
edge.MarkAnswered(r)
- http.Error(w, "instance is waking elsewhere; retry shortly", http.StatusServiceUnavailable)
+ edge.Unavailable(w, "waking-elsewhere", "instance is waking elsewhere; retry shortly", retry)
case errors.Is(err, errWakeTimeout):
- w.Header().Set("Retry-After", "5")
edge.MarkAnswered(r)
- http.Error(w, "instance is waking; retry shortly", http.StatusServiceUnavailable)
+ edge.Unavailable(w, "wake-timeout", "instance is waking; retry shortly", 5)
case errors.Is(err, context.Canceled):
// The client hung up while queued; nothing to write.
case errors.Is(err, errRootfsNotAdmitted):
@@ -6649,7 +6641,7 @@ func (a *Service) serveWakeError(w http.ResponseWriter, r *http.Request, rt regi
// logged, and for unarmed sent as the member's event, once per
// change (noteRootfsRefusal), not once per request.
edge.MarkAnswered(r)
- http.Error(w, "instance failed to wake", http.StatusServiceUnavailable)
+ edge.Unavailable(w, "rootfs-not-admitted", "instance failed to wake", 5)
default:
// The wake failure is already the member's platform log error
// (this log line, shipped by logsink.go); marking it keeps the
@@ -6658,7 +6650,7 @@ func (a *Service) serveWakeError(w http.ResponseWriter, r *http.Request, rt regi
log.Printf("activator: wake %s: %v", rt.Host, err)
}
edge.MarkAnswered(r)
- http.Error(w, "instance failed to wake", http.StatusServiceUnavailable)
+ edge.Unavailable(w, "wake-failed", "instance failed to wake", 5)
}
return true
}
diff --git a/internal/activator/haforward.go b/internal/activator/haforward.go
index f3c124803..4cfbc429b 100644
--- a/internal/activator/haforward.go
+++ b/internal/activator/haforward.go
@@ -326,10 +326,9 @@ func (a *Service) answerForwarded(w http.ResponseWriter, r *http.Request, rt reg
var held *errLeaseHeld
if errors.As(err, &held) {
if o, ok := hafresh.ParseOwner(held.holder); ok && o.Ref != "" {
- w.Header().Set("Retry-After", "1")
w.Header().Set(holderHeader, o.Ref)
edge.MarkAnswered(r)
- http.Error(w, "instance is waking elsewhere; retry shortly", http.StatusServiceUnavailable)
+ edge.Unavailable(w, "forwarded-waking-elsewhere", "instance is waking elsewhere; retry shortly", 1)
return true
}
}
diff --git a/internal/activator/harelease.go b/internal/activator/harelease.go
index ca3a403ef..90178f966 100644
--- a/internal/activator/harelease.go
+++ b/internal/activator/harelease.go
@@ -184,6 +184,9 @@ func (a *Service) releaseHAClean(ctx context.Context, e *actEntry) error {
return err
}
hb := a.backend.(haReleaser) // haHostEmpty has checked it is one
+ // Phase times for the marker's log line: a slow T1 marker (#421, the
+ // v0.34.40 flagship roll) names the phase that took the time.
+ start := time.Now()
a.stopFiles(e)
a.mu.Lock()
f := e.files
@@ -201,6 +204,7 @@ func (a *Service) releaseHAClean(ctx context.Context, e *actEntry) error {
// The final sync's budget starts now, never before the files publish:
// a long one must not leave it a spent context, and the database's
// last writes unsynced.
+ filesDone := time.Now()
sctx, scancel := a.haReleaseContext(ctx, haFinalSyncBudget, haShutdownMarkerReserve)
var txid uint64
var finErr error
@@ -214,6 +218,7 @@ func (a *Service) releaseHAClean(ctx context.Context, e *actEntry) error {
txid, finErr = hr.Finish(sctx)
}
scancel()
+ syncDone := time.Now()
m := hb.haReleaseBase(rt)
m.TXID, m.FilesGen, m.At = txid, gen, time.Now().UTC()
m.Clean = complete && ferr == nil && finErr == nil
@@ -226,6 +231,7 @@ func (a *Service) releaseHAClean(ctx context.Context, e *actEntry) error {
}
// The marker's PUT gets its own budget too, as Close's release does:
// a final sync that ran long must not leave it a dead context.
+ recordDone := time.Now()
mctx, mcancel := a.haReleaseContext(ctx, haMarkerBudget, 0)
a.mu.Lock()
if haUnexpectedLoss(e, servingError(e)) {
@@ -241,7 +247,10 @@ func (a *Service) releaseHAClean(ctx context.Context, e *actEntry) error {
e.haReleased, e.haReleaseClean = true, m.Clean
a.mu.Unlock()
a.rememberDutyRelease(ctx, rt, m)
- log.Printf("activator: %s: released with a marker (clean %v, txid %d, files %s)", rt.Host, m.Clean, txid, gen)
+ now := time.Now()
+ log.Printf("activator: %s: released with a marker (clean %v, txid %d, files %s) in %s: files %s, sync %s, record %s, marker %s",
+ rt.Host, m.Clean, txid, gen, releaseMS(now.Sub(start)), releaseMS(filesDone.Sub(start)), releaseMS(syncDone.Sub(filesDone)),
+ releaseMS(recordDone.Sub(syncDone)), releaseMS(now.Sub(recordDone)))
}
if ferr != nil {
ferr = fmt.Errorf("files: %w", ferr)
@@ -306,3 +315,7 @@ func (a *Service) retryOwedMarkers() {
}
}()
}
+
+// releaseMS is a release phase's duration for its log line, to the
+// millisecond.
+func releaseMS(d time.Duration) time.Duration { return d.Round(time.Millisecond) }
diff --git a/internal/activator/maintenance.go b/internal/activator/maintenance.go
index 3c0f7ebf5..86915f0d9 100644
--- a/internal/activator/maintenance.go
+++ b/internal/activator/maintenance.go
@@ -358,8 +358,7 @@ func (a *Service) rememberStopLocked(host string, observation *stopObservation)
func maintenanceResponse(w http.ResponseWriter, r *http.Request) {
edge.MarkAnswered(r)
w.Header().Set("Cache-Control", "no-store")
- w.Header().Set("Retry-After", "5")
- http.Error(w, "instance failed to wake", http.StatusServiceUnavailable)
+ edge.Unavailable(w, "maintenance", "instance failed to wake", 5)
}
// cleanupFailedWake stops a failed wake's process and gives its lease back,
diff --git a/internal/activator/unavailable_answers_test.go b/internal/activator/unavailable_answers_test.go
new file mode 100644
index 000000000..682027e32
--- /dev/null
+++ b/internal/activator/unavailable_answers_test.go
@@ -0,0 +1,35 @@
+package activator
+
+import (
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// #421 finding 1: the two wake-error answers that went out with no
+// Retry-After (a rootfs row refused before the lease, and any other wake
+// failure) carry one now, and every wake-error 503 names its site.
+func TestWakeErrorAnswersCarryRetryAfterAndSite(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ err error
+ site string
+ }{
+ {"rootfs not admitted", fmt.Errorf("%w: the staged manifest names another digest", errRootfsNotAdmitted), "rootfs-not-admitted"},
+ {"other wake failure", errors.New("open directory /opt/carlos/versions/g3r1: read-only file system"), "wake-failed"},
+ {"wake timeout", errWakeTimeout, "wake-timeout"},
+ {"fenced", ErrFenced, "maintenance"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ w := httptest.NewRecorder()
+ (&Service{}).serveWakeError(w, httptest.NewRequest("GET", "/", nil), registry.Route{Host: "shop.example.com"}, tc.err)
+ if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" || w.Header().Get("X-Carlos-Answer") != tc.site {
+ t.Fatalf("%d, Retry-After %q, X-Carlos-Answer %q (want %s)", w.Code, w.Header().Get("Retry-After"), w.Header().Get("X-Carlos-Answer"), tc.site)
+ }
+ })
+ }
+}
diff --git a/internal/edge/assetcatch.go b/internal/edge/assetcatch.go
index 5612a963d..483b81946 100644
--- a/internal/edge/assetcatch.go
+++ b/internal/edge/assetcatch.go
@@ -1356,8 +1356,7 @@ func assetAcknowledged(h http.Header, key []byte, assertion string) (expires int
// (scrubBackhaulResponse, assetInformationalScrub).
func (e *Edge) farForward(w http.ResponseWriter, r *http.Request, host string) {
if !e.backhaul(&assetResultWriter{ResponseWriter: w, result: "bypass"}, r, host) {
- w.Header().Set("Retry-After", "2")
- http.Error(w, "temporarily busy", http.StatusServiceUnavailable)
+ Unavailable(w, "far-forward-busy", "temporarily busy", 2)
}
}
diff --git a/internal/edge/demo_api.go b/internal/edge/demo_api.go
index eeaf6e897..222d6b581 100644
--- a/internal/edge/demo_api.go
+++ b/internal/edge/demo_api.go
@@ -198,15 +198,20 @@ func demoAPIFilterRequest(r *http.Request, hopped bool) {
}
func demoAPIUnavailable(w http.ResponseWriter) {
- w.Header().Set("Retry-After", "2")
- w.WriteHeader(http.StatusServiceUnavailable)
+ UnavailableHeader(w, "demo-api-unavailable", 2)
}
func demoAPIProxyError(w http.ResponseWriter, _ *http.Request, _ error) { demoAPIUnavailable(w) }
func demoAPIPrivateHeader(name string) bool {
name = strings.ToLower(name)
if strings.HasPrefix(name, "x-carlos-") {
- return name != "x-carlos-version"
+ // The version, and the 503 helper's answer and box tag
+ // (unavailable.go), are meant for the client.
+ switch name {
+ case "x-carlos-version", "x-carlos-answer", "x-carlos-box":
+ return false
+ }
+ return true
}
if strings.HasPrefix(name, "carlos-") {
return true
diff --git a/internal/edge/demo_banner.go b/internal/edge/demo_banner.go
index 707e779d6..81a873b74 100644
--- a/internal/edge/demo_banner.go
+++ b/internal/edge/demo_banner.go
@@ -135,7 +135,11 @@ func serveDemoHTML(w http.ResponseWriter, r *http.Request, status int, copyID, h
w = new(Edge).beginDemoResponse(w, r)
clear(w.Header())
w.Header().Set("Content-Type", "text/html; charset=utf-8")
- w.WriteHeader(status)
+ if status == http.StatusServiceUnavailable {
+ UnavailableHeader(w, "demo-unavailable-page", 2)
+ } else {
+ w.WriteHeader(status)
+ }
if r.Method != http.MethodHead && status != 204 && status != 205 && status != 304 {
_, _ = io.WriteString(w, `<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head><body>`+markup+`<main><p>`+stdhtml.EscapeString(message)+`</p></main></body></html>`)
}
diff --git a/internal/edge/demo_response.go b/internal/edge/demo_response.go
index 96c748294..c59087d77 100644
--- a/internal/edge/demo_response.go
+++ b/internal/edge/demo_response.go
@@ -264,7 +264,11 @@ func serveDemoPlain(w http.ResponseWriter, r *http.Request, status int, copyID s
}
w = new(Edge).beginDemoResponse(w, r)
demoPlainHeaders(w.Header(), copyID)
- w.WriteHeader(status)
+ if status == http.StatusServiceUnavailable {
+ UnavailableHeader(w, "demo-unavailable", 2)
+ } else {
+ w.WriteHeader(status)
+ }
if r.Method != http.MethodHead {
_, _ = io.WriteString(w, demoCopy[copyID]+"\n")
}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index e247f30db..cdc4e3c40 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -517,7 +517,9 @@ func WithIssuerContender(c func() bool) RunOption { return func(e *Edge) { e.con
// Without it the home map excludes nothing and therefore offers nothing: an
// edge that cannot recognise its own hosts must not hand out dial targets.
// See homemap.go.
-func WithBoxLabel(label string) RunOption { return func(e *Edge) { e.box = label } }
+func WithBoxLabel(label string) RunOption {
+ return func(e *Edge) { e.box = label; setAnswerBox(label) }
+}
// WithChangeWatch hands the edge the agent's change-index watch (#336) as a
// function, called on every cert-mirror and home-map poll. A function and
@@ -3887,8 +3889,7 @@ func multiProxy(host string, p *proberSet, hold localHold) *httputil.ReverseProx
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
if errors.Is(err, errNoLiveUpstream) {
noteCause(r, apperr.CauseNoUpstream)
- w.Header().Set("Retry-After", "2")
- http.Error(w, "no healthy upstream", http.StatusServiceUnavailable)
+ Unavailable(w, "no-healthy-upstream", "no healthy upstream", 2)
return
}
// Anything else is a real proxy failure (upstream hung up
@@ -3958,8 +3959,7 @@ func tunnelUpgradeError(w http.ResponseWriter, r *http.Request, err error, hub *
switch {
case errors.Is(err, errTunnelBusy):
noteCause(r, apperr.CauseTunnelBusy)
- w.Header().Set("Retry-After", "5")
- http.Error(w, tunnelBusyBody, http.StatusServiceUnavailable)
+ Unavailable(w, "tunnel-busy", tunnelBusyBody, 5)
case errors.Is(err, errTunnelNoUpgrade):
noteCause(r, apperr.CauseTunnelUpgradeUnsupported)
var cr *channelRefusal
@@ -4067,8 +4067,7 @@ func fleetProxy(fleet, boxLabel string, authoritative bool, hub *TunnelHub) *htt
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
if errors.Is(err, errFleetDark) {
noteCause(r, apperr.CauseFleetDark)
- w.Header().Set("Retry-After", "2")
- http.Error(w, "fleet unreachable: no connected box", http.StatusServiceUnavailable)
+ Unavailable(w, "fleet-unreachable", "fleet unreachable: no connected box", 2)
return
}
if tunnelUpgradeError(w, r, err, hub) {
@@ -4444,8 +4443,7 @@ func (e *Edge) backhaulAdmit(w http.ResponseWriter, r *http.Request, eip, box st
if !ok {
e.logThrottled("backhaul-saturated "+box,
fmt.Sprintf("backhaul to %s (%s) is at its in-flight cap (%d) — answering 503 + Retry-After: 2", box, eip, backhaulMaxInflight.Load()))
- w.Header().Set("Retry-After", "2")
- http.Error(w, "temporarily busy", http.StatusServiceUnavailable)
+ Unavailable(w, "backhaul-busy", "temporarily busy", 2)
return nil, false
}
return releaseSlot, true
diff --git a/internal/edge/forwardha.go b/internal/edge/forwardha.go
index 201d84bfe..9b3cfea5e 100644
--- a/internal/edge/forwardha.go
+++ b/internal/edge/forwardha.go
@@ -551,9 +551,8 @@ func observeHolderHeaders(ctx context.Context, report func()) (context.Context,
// answerHolderUnreachable is the answer to a request whose holder could not
// be connected to, now or moments ago: 503, Retry-After: 10.
func answerHolderUnreachable(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Retry-After", "10")
MarkAnswered(r)
- http.Error(w, "instance is waking elsewhere; retry shortly", http.StatusServiceUnavailable)
+ Unavailable(w, "holder-unreachable", "instance is waking elsewhere; retry shortly", 10)
}
// forwardTransport is the cached transport to the holder at dial, as
diff --git a/internal/edge/group_admission.go b/internal/edge/group_admission.go
index e281644a4..e25c805ea 100644
--- a/internal/edge/group_admission.go
+++ b/internal/edge/group_admission.go
@@ -23,17 +23,16 @@ func (e *Edge) admissionRefuses(w http.ResponseWriter, r *http.Request, rt regis
return true
}
func AdmissionResponse(w http.ResponseWriter, r *http.Request) {
- admissionResponse(w, r, "This service is starting. Try again later.")
+ admissionResponse(w, r, "admission-starting", "This service is starting. Try again later.")
}
func AdmissionUnavailableResponse(w http.ResponseWriter, r *http.Request) {
- admissionResponse(w, r, "This service is unavailable. Try again later.")
+ admissionResponse(w, r, "admission-closed", "This service is unavailable. Try again later.")
}
-func admissionResponse(w http.ResponseWriter, r *http.Request, body string) {
+func admissionResponse(w http.ResponseWriter, r *http.Request, site, body string) {
w.Header().Del(holderHeader)
- w.Header().Set("Retry-After", "10")
w.Header().Set("Cache-Control", "no-store")
MarkAnswered(r)
- http.Error(w, body, http.StatusServiceUnavailable)
+ Unavailable(w, site, body, 10)
}
func (e *Edge) closeTenantAdmission() {
a := e.tenantAdmission()
diff --git a/internal/edge/haingress.go b/internal/edge/haingress.go
index b80bceaa0..39b6e9a7c 100644
--- a/internal/edge/haingress.go
+++ b/internal/edge/haingress.go
@@ -13,10 +13,9 @@ import (
const HAUnavailableMessage = "This instance cannot wake right now. Please try again shortly."
func HAUnavailableResponse(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Retry-After", "10")
w.Header().Set(holderHeader, "none")
MarkAnswered(r)
- http.Error(w, HAUnavailableMessage, http.StatusServiceUnavailable)
+ Unavailable(w, "ha-unavailable", HAUnavailableMessage, 10)
}
type haIngressLookup func(string) (registry.Route, bool)
diff --git a/internal/edge/homemap.go b/internal/edge/homemap.go
index 247777093..8e02f3fee 100644
--- a/internal/edge/homemap.go
+++ b/internal/edge/homemap.go
@@ -1609,8 +1609,7 @@ func stripForwardedHeaders(r *http.Request) {
// answers the refusal; it just cannot count or log one, the same "answer
// first, degrade the bookkeeping" shape Home and meshKeys already have.
func (m *homeMap) staleHopRefusal(w http.ResponseWriter, host string) {
- w.Header().Set("Retry-After", "2")
- http.Error(w, "not served here", http.StatusServiceUnavailable)
+ Unavailable(w, "stale-hop", "not served here", 2)
if m == nil {
return
}
diff --git a/internal/edge/importgate.go b/internal/edge/importgate.go
index 4f27b00be..17f38cf8a 100644
--- a/internal/edge/importgate.go
+++ b/internal/edge/importgate.go
@@ -49,8 +49,7 @@ func (e *Edge) importGateAdmit(w http.ResponseWriter, r *http.Request, host stri
if claimExact && front.Host == rt.Host && r.Method == http.MethodGet && seeds.TokenMatches(rt.ImportGate, token) {
return true
}
- w.Header().Set("Retry-After", "5")
w.Header().Set("Cache-Control", "no-store")
- http.Error(w, "this instance is being imported. Try again in a few seconds.", http.StatusServiceUnavailable)
+ Unavailable(w, "importing", "this instance is being imported. Try again in a few seconds.", 5)
return false
}
diff --git a/internal/edge/lbhealth.go b/internal/edge/lbhealth.go
index 76f2af73b..fcc58612c 100644
--- a/internal/edge/lbhealth.go
+++ b/internal/edge/lbhealth.go
@@ -36,10 +36,9 @@ func (e *Edge) lbHealthAnswer(w http.ResponseWriter, r *http.Request) bool {
return false
}
if a := e.tenantAdmission(); a != nil && !a.TenantAdmitted() && r.URL.Path == lbhealth.Path && (r.Method == http.MethodGet || r.Method == http.MethodHead) {
- w.Header().Set("Retry-After", "10")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
- w.WriteHeader(http.StatusServiceUnavailable)
+ UnavailableHeader(w, "lb-health-not-ready", 10)
if r.Method == http.MethodGet {
_, _ = w.Write([]byte("Not ready to receive traffic.\n"))
}
diff --git a/internal/edge/pending.go b/internal/edge/pending.go
index 90c816d02..3772933c3 100644
--- a/internal/edge/pending.go
+++ b/internal/edge/pending.go
@@ -58,7 +58,7 @@ import (
const (
// pendingRetryAfter is the Retry-After an API client gets, and the
// page's own retry interval, in seconds.
- pendingRetryAfter = "5"
+ pendingRetryAfter = 5
// pendingRetryWindow is how long the page keeps retrying, in
// milliseconds, measured from the visitor's first sight of it in this
// tab. Propagation is at most about half a minute once the home box
@@ -214,8 +214,7 @@ func (e *Edge) pendingHost(w http.ResponseWriter, r *http.Request) {
// no-store: this answer is about a moment, and a cache holding it would
// keep a visitor on it after the host became servable.
h.Set("Cache-Control", "no-store")
- h.Set("Retry-After", pendingRetryAfter)
- w.WriteHeader(http.StatusServiceUnavailable)
+ UnavailableHeader(w, "pending-host", pendingRetryAfter)
if r.Method != http.MethodHead {
w.Write(e.pendingBody) //nolint:errcheck
}
diff --git a/internal/edge/pending_test.go b/internal/edge/pending_test.go
index 62b875eb6..8b9af0285 100644
--- a/internal/edge/pending_test.go
+++ b/internal/edge/pending_test.go
@@ -3,6 +3,7 @@ package edge
import (
"net/http"
"net/http/httptest"
+ "strconv"
"strings"
"testing"
)
@@ -46,8 +47,8 @@ func TestPendingHostUnderAPlatformDomainIs503(t *testing.T) {
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("%s: status %d, want 503", url, rec.Code)
}
- if got := rec.Header().Get("Retry-After"); got != pendingRetryAfter {
- t.Fatalf("%s: Retry-After %q, want %q", url, got, pendingRetryAfter)
+ if got := rec.Header().Get("Retry-After"); got != strconv.Itoa(pendingRetryAfter) {
+ t.Fatalf("%s: Retry-After %q, want %d", url, got, pendingRetryAfter)
}
if got := rec.Header().Get("Cache-Control"); got != "no-store" {
t.Fatalf("%s: Cache-Control %q, want no-store", url, got)
diff --git a/internal/edge/plandisabled.go b/internal/edge/plandisabled.go
index 1946296f7..6b55307b7 100644
--- a/internal/edge/plandisabled.go
+++ b/internal/edge/plandisabled.go
@@ -81,7 +81,7 @@ func (e *Edge) planDisabledAdmit(w http.ResponseWriter, r *http.Request, host st
h := w.Header()
h.Set("Content-Type", "text/html; charset=utf-8")
h.Set("Cache-Control", "no-store")
- w.WriteHeader(http.StatusServiceUnavailable)
+ UnavailableNoRetry(w, "plan-disabled")
if r.Method != http.MethodHead {
w.Write(disabledPage)
}
diff --git a/internal/edge/plandisabled_test.go b/internal/edge/plandisabled_test.go
index 697d8a4dc..19ace8d89 100644
--- a/internal/edge/plandisabled_test.go
+++ b/internal/edge/plandisabled_test.go
@@ -50,7 +50,7 @@ func newDisabledScene(t *testing.T, listed ...string) *disabledScene {
func wantDisabledPage(t *testing.T, rec *httptest.ResponseRecorder, what string) {
t.Helper()
if rec.Code != http.StatusServiceUnavailable || rec.Header().Get("Cache-Control") != "no-store" ||
- rec.Header().Get("Retry-After") != "" || rec.Header().Get("Content-Type") != "text/html; charset=utf-8" {
+ rec.Header().Get("Retry-After") != "" || rec.Header().Get(answerHeader) != "plan-disabled" || rec.Header().Get("Content-Type") != "text/html; charset=utf-8" {
t.Fatalf("%s: %d cache %q retry %q type %q, want the disabled page's 503", what, rec.Code,
rec.Header().Get("Cache-Control"), rec.Header().Get("Retry-After"), rec.Header().Get("Content-Type"))
}
diff --git a/internal/edge/regional.go b/internal/edge/regional.go
index 3d01434f7..790308e76 100644
--- a/internal/edge/regional.go
+++ b/internal/edge/regional.go
@@ -92,8 +92,7 @@ func (e *Edge) regionalGate(w http.ResponseWriter, r *http.Request, host string,
// regionalRefuse writes the gate's 503 and logs it, throttled per row.
func (e *Edge) regionalRefuse(w http.ResponseWriter, up upstream, why string) {
- w.Header().Set("Retry-After", "2")
- http.Error(w, "not served here", http.StatusServiceUnavailable)
+ Unavailable(w, "regional-not-served", "not served here", 2)
e.logThrottled("regional "+up.regionalKey, fmt.Sprintf(
"regional name %s refused (%s): it is served only from its own region's instance on its own box", up.regionalKey, why))
}
diff --git a/internal/edge/replicaconsole.go b/internal/edge/replicaconsole.go
index 808673492..6af26c9f5 100644
--- a/internal/edge/replicaconsole.go
+++ b/internal/edge/replicaconsole.go
@@ -26,13 +26,13 @@ func (e *Edge) serveReplicaConsole(w http.ResponseWriter, r *http.Request) {
}
}
if console != nil {
- w.WriteHeader(http.StatusServiceUnavailable)
+ UnavailableHeader(w, "replica-console-ambiguous", 2)
return
}
console = up.proxy
}
if console == nil {
- w.WriteHeader(http.StatusServiceUnavailable)
+ UnavailableHeader(w, "replica-console-missing", 2)
return
}
console.ServeHTTP(w, e.withForwardKey(r))
diff --git a/internal/edge/replicaprobe.go b/internal/edge/replicaprobe.go
index 32d6a5378..4fdeffe09 100644
--- a/internal/edge/replicaprobe.go
+++ b/internal/edge/replicaprobe.go
@@ -34,14 +34,14 @@ func (e *Edge) serveReplicaProbe(w http.ResponseWriter, r *http.Request, host st
}
source, ok := e.act.(copyProbeSource)
if !ok || rt.Host != host || rt.Kind != "instance" || rt.FleetBoxes == "" || !rt.ReplicaContains(e.box) || rt.Hibernate || rt.HA {
- w.WriteHeader(http.StatusServiceUnavailable)
+ UnavailableHeader(w, "replica-probe-route", 2)
return
}
ctx, cancel := context.WithTimeout(r.Context(), replicaProbeTimeout)
defer cancel()
initial, err := source.ProbeCopy(ctx, host)
if err != nil || !e.replicaCopyMatches(initial, rt) {
- w.WriteHeader(http.StatusServiceUnavailable)
+ UnavailableHeader(w, "replica-probe-copy", 2)
return
}
// A held leg is cancelled on stop or generation switch, without keeping
@@ -49,13 +49,13 @@ func (e *Edge) serveReplicaProbe(w http.ResponseWriter, r *http.Request, host st
// so a sleeping or waking copy never enters the held-leg wait loop.
leg, err := e.act.AdmitHeldLeg(ctx, rt)
if err != nil {
- w.WriteHeader(http.StatusServiceUnavailable)
+ UnavailableHeader(w, "replica-probe-leg", 2)
return
}
defer leg.Done()
c, err := source.ProbeCopy(leg.Context(), host)
if err != nil || !e.replicaCopyMatches(c, rt) || c.Generation != initial.Generation || c.Socket != initial.Socket {
- w.WriteHeader(http.StatusServiceUnavailable)
+ UnavailableHeader(w, "replica-probe-changed", 2)
return
}
transport := &http.Transport{DisableKeepAlives: true, DisableCompression: true,
@@ -65,7 +65,7 @@ func (e *Edge) serveReplicaProbe(w http.ResponseWriter, r *http.Request, host st
defer transport.CloseIdleConnections()
probe, err := http.NewRequestWithContext(leg.Context(), http.MethodGet, "http://"+host+"/", nil)
if err != nil {
- w.WriteHeader(http.StatusServiceUnavailable)
+ UnavailableHeader(w, "replica-probe-request", 2)
return
}
// RoundTrip never follows redirects. A fresh request carries no visitor
@@ -78,7 +78,7 @@ func (e *Edge) serveReplicaProbe(w http.ResponseWriter, r *http.Request, host st
}
after, err := source.ProbeCopy(leg.Context(), host)
if err != nil || leg.Context().Err() != nil || !e.replicaCopyMatches(after, rt) || after.Generation != c.Generation || after.Socket != c.Socket || after.BootID != c.BootID || after.Version != c.Version || after.Digest != c.Digest {
- w.WriteHeader(http.StatusServiceUnavailable)
+ UnavailableHeader(w, "replica-probe-after", 2)
return
}
if !c.Healthy {
diff --git a/internal/edge/replicaproxy.go b/internal/edge/replicaproxy.go
index 52010e6f6..6e43b66c4 100644
--- a/internal/edge/replicaproxy.go
+++ b/internal/edge/replicaproxy.go
@@ -46,8 +46,7 @@ func replicaProxy(host, fleet string, p *replicaProber, hub *TunnelHub) *httputi
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
if errors.Is(err, errReplicaUnavailable) {
noteCause(r, apperr.CauseFleetDark)
- w.Header().Set("Retry-After", "2")
- http.Error(w, replicaUnavailable, http.StatusServiceUnavailable)
+ Unavailable(w, "replica-unavailable", replicaUnavailable, 2)
return
}
if tunnelUpgradeError(w, r, err, hub) {
diff --git a/internal/edge/status.go b/internal/edge/status.go
index 2975dbe8f..9b9532a13 100644
--- a/internal/edge/status.go
+++ b/internal/edge/status.go
@@ -173,7 +173,7 @@ func (h *statusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
body, ctype, err := h.get(r.Context(), rt.key, rt.ctype)
if err != nil {
log.Printf("edge: status %s: %v", rt.key, err)
- http.Error(w, "status page unavailable", http.StatusServiceUnavailable)
+ Unavailable(w, "status-page", "status page unavailable", 5)
return
}
w.Header().Set("Content-Type", ctype)
diff --git a/internal/edge/testdata/unavailable_guard/bare.go b/internal/edge/testdata/unavailable_guard/bare.go
new file mode 100644
index 000000000..b2ffb43cc
--- /dev/null
+++ b/internal/edge/testdata/unavailable_guard/bare.go
@@ -0,0 +1,12 @@
+package edge
+
+import "net/http"
+
+func zzBare(w http.ResponseWriter) {
+ w.Header().Set("Retry-After", "5")
+ http.Error(w, "busy", http.StatusServiceUnavailable)
+}
+
+func zzBareHeader(w http.ResponseWriter) {
+ w.WriteHeader(503)
+}
diff --git a/internal/edge/testdata/unavailable_guard/clean.go b/internal/edge/testdata/unavailable_guard/clean.go
new file mode 100644
index 000000000..d74e78407
--- /dev/null
+++ b/internal/edge/testdata/unavailable_guard/clean.go
@@ -0,0 +1,12 @@
+package edge
+
+import "net/http"
+
+func zzClean(w http.ResponseWriter, code int) {
+ if code == http.StatusServiceUnavailable {
+ Unavailable(w, "zz-clean", "busy", 2)
+ return
+ }
+ http.Error(w, "gone", http.StatusGone)
+ w.WriteHeader(http.StatusNoContent)
+}
diff --git a/internal/edge/testdata/unavailable_guard/closure.go b/internal/edge/testdata/unavailable_guard/closure.go
new file mode 100644
index 000000000..71c7285eb
--- /dev/null
+++ b/internal/edge/testdata/unavailable_guard/closure.go
@@ -0,0 +1,11 @@
+package edge
+
+import "net/http"
+
+var zzClosureHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(503)
+})
+
+var zzClosureError, zzClosureOther = func(w http.ResponseWriter) {
+ http.Error(w, "busy", http.StatusServiceUnavailable)
+}, 1
diff --git a/internal/edge/testdata/unavailable_guard/handed.go b/internal/edge/testdata/unavailable_guard/handed.go
new file mode 100644
index 000000000..5fa9802e6
--- /dev/null
+++ b/internal/edge/testdata/unavailable_guard/handed.go
@@ -0,0 +1,13 @@
+package edge
+
+import "net/http"
+
+func zzWriteCode(w http.ResponseWriter, code int) {
+ w.WriteHeader(code)
+}
+
+var _ = zzWriteCode
+
+func zzHanded(w http.ResponseWriter) {
+ zzWriteCode(w, http.StatusServiceUnavailable)
+}
diff --git a/internal/edge/testdata/unavailable_guard/indirect.go b/internal/edge/testdata/unavailable_guard/indirect.go
new file mode 100644
index 000000000..026711c84
--- /dev/null
+++ b/internal/edge/testdata/unavailable_guard/indirect.go
@@ -0,0 +1,23 @@
+package edge
+
+import "net/http"
+
+func zzIndirect(w http.ResponseWriter) {
+ write := w.WriteHeader
+ code := http.StatusServiceUnavailable
+ write(code)
+}
+
+func zzIndirectError(w http.ResponseWriter) {
+ fail := http.Error
+ fail(w, "busy", 503)
+}
+
+func zzParenCall(w http.ResponseWriter) {
+ (w.WriteHeader)(http.StatusServiceUnavailable)
+}
+
+func zzMethodExpr(w http.ResponseWriter) {
+ code := http.StatusServiceUnavailable
+ http.ResponseWriter.WriteHeader(w, code)
+}
diff --git a/internal/edge/testdata/unavailable_guard/named.go b/internal/edge/testdata/unavailable_guard/named.go
new file mode 100644
index 000000000..30c355a7b
--- /dev/null
+++ b/internal/edge/testdata/unavailable_guard/named.go
@@ -0,0 +1,9 @@
+package edge
+
+import "net/http"
+
+const zzBusy = http.StatusServiceUnavailable
+
+func zzNamedConst(w http.ResponseWriter) {
+ w.WriteHeader(zzBusy)
+}
diff --git a/internal/edge/testdata/unavailable_guard/site.go b/internal/edge/testdata/unavailable_guard/site.go
new file mode 100644
index 000000000..a00751b44
--- /dev/null
+++ b/internal/edge/testdata/unavailable_guard/site.go
@@ -0,0 +1,15 @@
+package edge
+
+import "net/http"
+
+func zzSiteVar(w http.ResponseWriter, site string) {
+ Unavailable(w, site, "busy", 2)
+}
+
+func zzSiteBad(w http.ResponseWriter) {
+ UnavailableHeader(w, "Bad Site", 2)
+}
+
+func zzSiteDup(w http.ResponseWriter) {
+ Unavailable(w, "wake-failed", "busy", 2)
+}
diff --git a/internal/edge/testdata/unavailable_guard/variable.go b/internal/edge/testdata/unavailable_guard/variable.go
new file mode 100644
index 000000000..1eb8f232d
--- /dev/null
+++ b/internal/edge/testdata/unavailable_guard/variable.go
@@ -0,0 +1,7 @@
+package edge
+
+import "net/http"
+
+func zzVariable(w http.ResponseWriter, code int) {
+ w.WriteHeader(code)
+}
diff --git a/internal/edge/unavailable.go b/internal/edge/unavailable.go
new file mode 100644
index 000000000..ffaf3780e
--- /dev/null
+++ b/internal/edge/unavailable.go
@@ -0,0 +1,88 @@
+package edge
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "net/http"
+ "regexp"
+ "strconv"
+ "sync/atomic"
+)
+
+// Every 503 the edge and the activator write goes through Unavailable,
+// UnavailableHeader or (no Retry-After, one caller) UnavailableNoRetry (#421 finding 1: a just-joined member's 503 reached a
+// client with no Retry-After, and nothing in the answer said which box or
+// which path wrote it). TestEvery503GoesThroughUnavailable refuses any
+// other 503 in internal/edge and internal/activator.
+//
+// Each answer carries:
+// - Retry-After, whole seconds, at least one (not UnavailableNoRetry);
+// - X-Carlos-Answer, the call site's fixed short name (unique per call
+// site, checked by the same test), so a probe can name the path;
+// - X-Carlos-Box, this box's tag: the first 12 hex digits of the SHA-256
+// of its label (WithBoxLabel). Stable per box, and not the label: an
+// operator who knows the labels can match it, a visitor learns nothing
+// about them. Absent when the edge was given no label.
+//
+// A status copied from an upstream response (the app's, or a peer edge's
+// answer passed back through a forward) is not ours and is left alone.
+
+const (
+ answerHeader = "X-Carlos-Answer"
+ boxTagHeader = "X-Carlos-Box"
+)
+
+var answerSite = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,47}$`)
+
+// answerBoxTag is this process's box tag, set by WithBoxLabel.
+var answerBoxTag atomic.Pointer[string]
+
+func setAnswerBox(label string) {
+ if label == "" {
+ return
+ }
+ sum := sha256.Sum256([]byte(label))
+ tag := hex.EncodeToString(sum[:])[:12]
+ answerBoxTag.Store(&tag)
+}
+
+// Unavailable answers 503 with body as http.Error does, after the headers
+// above. site is the call site's fixed name; retryAfter is in seconds and
+// is raised to one.
+func Unavailable(w http.ResponseWriter, site, body string, retryAfter int) {
+ unavailableHeaders(w, site, retryAfter)
+ http.Error(w, body, http.StatusServiceUnavailable)
+}
+
+// UnavailableHeader writes the 503 status line with the headers above and
+// no body, for a caller that sets its own content type first and writes its
+// own body after.
+func UnavailableHeader(w http.ResponseWriter, site string, retryAfter int) {
+ unavailableHeaders(w, site, retryAfter)
+ w.WriteHeader(http.StatusServiceUnavailable)
+}
+
+// UnavailableNoRetry is UnavailableHeader with no Retry-After, for the one
+// answer where waiting changes nothing (the plans turned-off page,
+// plandisabled.go). It still names its site and box.
+func UnavailableNoRetry(w http.ResponseWriter, site string) {
+ answerHeaders(w, site)
+ w.Header().Del("Retry-After")
+ w.WriteHeader(http.StatusServiceUnavailable)
+}
+
+func unavailableHeaders(w http.ResponseWriter, site string, retryAfter int) {
+ answerHeaders(w, site)
+ w.Header().Set("Retry-After", strconv.Itoa(max(retryAfter, 1)))
+}
+
+func answerHeaders(w http.ResponseWriter, site string) {
+ if !answerSite.MatchString(site) {
+ site = "unnamed"
+ }
+ h := w.Header()
+ h.Set(answerHeader, site)
+ if tag := answerBoxTag.Load(); tag != nil {
+ h.Set(boxTagHeader, *tag)
+ }
+}
diff --git a/internal/edge/unavailable_guard_test.go b/internal/edge/unavailable_guard_test.go
new file mode 100644
index 000000000..d579c92d3
--- /dev/null
+++ b/internal/edge/unavailable_guard_test.go
@@ -0,0 +1,434 @@
+package edge
+
+// Every 503 the edge and the activator write carries Retry-After and names
+// its site and box (#421 finding 1). The invariant is checked here over
+// both packages' own code (not tests), with go/types:
+//
+// - W1, a status write (http.Error's code, or the argument of any method
+// named WriteHeader) whose code is a constant must not be 503, except in
+// unavailable.go, which is the helper;
+// - W2, a status write whose code is not a constant is allowed only in a
+// method named WriteHeader (a wrapper passing its own caller's code on;
+// that caller's write is checked here like any other) or in a relay
+// listed in statusRelays, each with the reason it cannot be the
+// platform's own 503 or the way it routes one through the helper;
+// - W3, a constant 503 handed to any call as an argument is refused,
+// except to the relays that route a 503 through the helper
+// (unavailableRelays): so a relay or a local closure that writes its
+// code verbatim cannot be handed one;
+// - W4, every Unavailable and UnavailableHeader call names its site with
+// a constant matching answerSite, except in a site forwarder
+// (siteForwarders), whose own callers must pass a constant; and no two
+// call sites share a name;
+// - W5, a status writer (a WriteHeader method or http.Error) taken as a
+// value rather than called, outside the helper, is refused: W1-W3 see
+// calls only, so `write := w.WriteHeader; write(code)` would escape.
+//
+// Residual, by design: a 503 carried in a variable or a return value into
+// a relay that writes its code verbatim. The relays listed are an upstream
+// response's replay (the app's or a peer's), a static file's status and a
+// held stream's upstream head: none is a platform answer.
+//
+// Fixtures under testdata/unavailable_guard are laid over this package and
+// each must be reported for what it does.
+
+import (
+ "fmt"
+ "go/ast"
+ "go/constant"
+ "go/types"
+ "os"
+ "path/filepath"
+ "slices"
+ "sort"
+ "strings"
+ "testing"
+
+ "golang.org/x/tools/go/packages"
+)
+
+// statusRelays: function (Type.Method or Func) -> why its variable-code
+// write is not a bare platform 503.
+var statusRelays = map[string]string{
+ "serveDemoPlain": "routes 503 through UnavailableHeader",
+ "serveDemoHTML": "routes 503 through UnavailableHeader",
+ "writeCached": "replays a cached upstream response",
+ "heldTask.writeHeadAndBody": "writes a held stream's upstream head",
+ "staticSite.serveFile": "writes a static file's own status; its callers' constants are checked (W3)",
+ "ExecBackend.MountInstanceKeyAdoption": "its fail closure writes the constant code it is handed; W3 refuses a 503",
+ "demoTrafficWriter.commit": "a buffering wrapper: commits the status its own WriteHeader was handed, and those writes are checked like any other",
+}
+
+// unavailableRelays may be handed a constant 503 (W3): each routes it
+// through the helper.
+var unavailableRelays = []string{"serveDemoPlain", "serveDemoHTML", "demoRefusalWriter.WriteHeader"}
+
+// siteForwarders pass their site parameter on to the helper; argument
+// index of the site in their own signature.
+var siteForwarders = map[string]int{"admissionResponse": 2}
+
+const unavailableGuardFixtureDir = "testdata/unavailable_guard"
+const unavailableGuardFixturePrefix = "zz_unavailable_guard_fixture_"
+
+// unavailableGuardFixtures: fixture -> what it must be reported for.
+var unavailableGuardFixtures = map[string][]string{
+ "clean.go": nil,
+ "bare.go": {"zzBare: 503 written without the helper (http.Error)", "zzBareHeader: 503 written without the helper (WriteHeader)"},
+ "named.go": {"zzNamedConst: 503 written without the helper (WriteHeader)"},
+ "variable.go": {"zzVariable: status written from a variable outside a relay"},
+ "handed.go": {"zzHanded: constant 503 handed to zzWriteCode", "zzWriteCode: status written from a variable outside a relay"},
+ "closure.go": {"zzClosureHandler: 503 written without the helper (WriteHeader)", "zzClosureError: 503 written without the helper (http.Error)"},
+ "indirect.go": {"zzIndirect: WriteHeader taken as a value", "zzIndirectError: http.Error taken as a value", "zzIndirectError: constant 503 handed to fail", "zzParenCall: 503 written without the helper (WriteHeader)", "zzMethodExpr: WriteHeader taken as a value"},
+ "site.go": {"zzSiteVar: Unavailable site is not a constant", "zzSiteBad: Unavailable site \"Bad Site\" does not match answerSite", "zzSiteDup: Unavailable site \"wake-failed\" named twice"},
+}
+
+func loadUnavailablePackages(t *testing.T, fixtures ...string) []*packages.Package {
+ t.Helper()
+ dir, err := filepath.Abs(".")
+ if err != nil {
+ t.Fatal(err)
+ }
+ overlay := map[string][]byte{}
+ for _, f := range fixtures {
+ src, err := os.ReadFile(filepath.Join(unavailableGuardFixtureDir, f))
+ if err != nil {
+ t.Fatal(err)
+ }
+ overlay[filepath.Join(dir, unavailableGuardFixturePrefix+f)] = src
+ }
+ cfg := &packages.Config{Dir: dir, Overlay: overlay,
+ Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedImports}
+ pkgs, err := packages.Load(cfg, ".", "../activator")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(pkgs) != 2 {
+ t.Fatalf("loaded %d packages, want edge and activator", len(pkgs))
+ }
+ for _, p := range pkgs {
+ if len(p.Errors) > 0 {
+ t.Fatalf("%s: %v", p.PkgPath, p.Errors)
+ }
+ }
+ return pkgs
+}
+
+// unavailableFuncName is fd's name as statusRelays keys it.
+func unavailableFuncName(fd *ast.FuncDecl) string {
+ if fd.Recv == nil || len(fd.Recv.List) == 0 {
+ return fd.Name.Name
+ }
+ t := fd.Recv.List[0].Type
+ if s, ok := t.(*ast.StarExpr); ok {
+ t = s.X
+ }
+ if ix, ok := t.(*ast.IndexExpr); ok {
+ t = ix.X
+ }
+ if id, ok := t.(*ast.Ident); ok {
+ return id.Name + "." + fd.Name.Name
+ }
+ return fd.Name.Name
+}
+
+func is503(info *types.Info, e ast.Expr) bool {
+ tv, ok := info.Types[e]
+ if !ok || tv.Value == nil || tv.Value.Kind() != constant.Int {
+ return false
+ }
+ v, exact := constant.Int64Val(tv.Value)
+ return exact && v == 503
+}
+
+// calleeObj is the function or method a call names, or nil.
+func calleeObj(info *types.Info, call *ast.CallExpr) types.Object {
+ switch f := ast.Unparen(call.Fun).(type) {
+ case *ast.Ident:
+ return info.Uses[f]
+ case *ast.SelectorExpr:
+ if sel, ok := info.Selections[f]; ok {
+ return sel.Obj()
+ }
+ return info.Uses[f.Sel]
+ }
+ return nil
+}
+
+// objName is obj's name as statusRelays keys it (Type.Method or Func).
+func objName(obj types.Object) string {
+ fn, ok := obj.(*types.Func)
+ if !ok {
+ return obj.Name()
+ }
+ recv := fn.Type().(*types.Signature).Recv()
+ if recv == nil {
+ return fn.Name()
+ }
+ t := recv.Type()
+ if p, ok := t.(*types.Pointer); ok {
+ t = p.Elem()
+ }
+ if n, ok := t.(*types.Named); ok {
+ return n.Obj().Name() + "." + fn.Name()
+ }
+ return fn.Name()
+}
+
+func isPkgFunc(obj types.Object, pkg, name string) bool {
+ fn, ok := obj.(*types.Func)
+ return ok && fn.Pkg() != nil && fn.Pkg().Path() == pkg && fn.Name() == name && fn.Type().(*types.Signature).Recv() == nil
+}
+
+const edgePkg = "github.com/carlosframework/platform/internal/edge"
+
+type siteUse struct{ site, where string }
+
+// unavailableProblems checks one file. Sites are collected into sites for
+// the uniqueness check.
+func unavailableProblems(info *types.Info, f *ast.File, helperFile bool, sites *[]siteUse) []string {
+ var out []string
+ for _, d := range f.Decls {
+ var body ast.Node
+ var name string
+ var relay, wrapper bool
+ switch d := d.(type) {
+ case *ast.FuncDecl:
+ if d.Body == nil {
+ continue
+ }
+ body, name = d.Body, unavailableFuncName(d)
+ _, relay = statusRelays[name]
+ wrapper = d.Recv != nil && d.Name.Name == "WriteHeader"
+ case *ast.GenDecl:
+ // A package-level var or const initializer (a handler
+ // closure, say) is checked like a function body, with no
+ // relay or wrapper excuse; it is named by its first name.
+ body, name = d, genDeclName(d)
+ default:
+ continue
+ }
+ callFuns := map[ast.Expr]bool{}
+ selNames := map[*ast.Ident]bool{}
+ ast.Inspect(body, func(n ast.Node) bool {
+ // W5: a status writer taken as a value (write := w.WriteHeader,
+ // or http.Error passed on) escapes W1-W3, which see only calls.
+ if sel, ok := n.(*ast.SelectorExpr); ok {
+ selNames[sel.Sel] = true // judged as the selector, not again
+ }
+ if id, ok := n.(*ast.Ident); ok && selNames[id] {
+ return true
+ }
+ // A method expression (http.ResponseWriter.WriteHeader(w,
+ // code)) moves the code to the second argument; refuse it even
+ // when called rather than follow it.
+ if ref := statusWriterRef(info, n); ref != "" && (!callFuns[n.(ast.Expr)] || isMethodExpr(info, n)) && !helperFile {
+ out = append(out, fmt.Sprintf("%s: %s taken as a value", name, ref))
+ }
+ call, ok := n.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ callFuns[ast.Unparen(call.Fun)] = true
+ obj := calleeObj(info, call)
+ var code ast.Expr
+ kind := ""
+ switch {
+ case isPkgFunc(obj, "net/http", "Error") && len(call.Args) == 3:
+ code, kind = call.Args[2], "http.Error"
+ case obj != nil && obj.Name() == "WriteHeader" && len(call.Args) == 1:
+ if b, ok := info.TypeOf(call.Args[0]).Underlying().(*types.Basic); ok && b.Info()&types.IsInteger != 0 {
+ code, kind = call.Args[0], "WriteHeader"
+ }
+ }
+ if code != nil && !helperFile {
+ if tv := info.Types[code]; tv.Value != nil {
+ if is503(info, code) && (obj == nil || !slices.Contains(unavailableRelays, objName(obj))) {
+ out = append(out, fmt.Sprintf("%s: 503 written without the helper (%s)", name, kind))
+ }
+ } else if !wrapper && !relay {
+ out = append(out, fmt.Sprintf("%s: status written from a variable outside a relay", name))
+ }
+ }
+ // W3: a constant 503 as an argument.
+ if code == nil && !helperFile {
+ for _, a := range call.Args {
+ if is503(info, a) {
+ callee := "a call"
+ if obj != nil {
+ callee = objName(obj)
+ }
+ if !slices.Contains(unavailableRelays, callee) {
+ out = append(out, fmt.Sprintf("%s: constant 503 handed to %s", name, callee))
+ }
+ }
+ }
+ }
+ // W4: sites.
+ if obj != nil && (isPkgFunc(obj, edgePkg, "Unavailable") || isPkgFunc(obj, edgePkg, "UnavailableHeader") || isPkgFunc(obj, edgePkg, "UnavailableNoRetry")) && len(call.Args) >= 2 && !helperFile {
+ if _, fwd := siteForwarders[name]; fwd {
+ return true
+ }
+ out = append(out, siteProblem(info, call.Args[1], name, sites)...)
+ }
+ if obj != nil {
+ if i, fwd := siteForwarders[obj.Name()]; fwd && obj.Pkg() != nil && obj.Pkg().Path() == edgePkg && len(call.Args) > i {
+ out = append(out, siteProblem(info, call.Args[i], name, sites)...)
+ }
+ }
+ return true
+ })
+ }
+ return out
+}
+
+// statusWriterRef names n if it refers to a status writer (a WriteHeader
+// method or net/http.Error), whatever position it is in.
+func statusWriterRef(info *types.Info, n ast.Node) string {
+ var obj types.Object
+ switch x := n.(type) {
+ case *ast.SelectorExpr:
+ if sel, ok := info.Selections[x]; ok {
+ obj = sel.Obj()
+ } else {
+ obj = info.Uses[x.Sel]
+ }
+ case *ast.Ident:
+ obj = info.Uses[x]
+ default:
+ return ""
+ }
+ if isPkgFunc(obj, "net/http", "Error") {
+ return "http.Error"
+ }
+ if fn, ok := obj.(*types.Func); ok && fn.Name() == "WriteHeader" && fn.Type().(*types.Signature).Recv() != nil {
+ return "WriteHeader"
+ }
+ return ""
+}
+
+func isMethodExpr(info *types.Info, n ast.Node) bool {
+ sel, ok := n.(*ast.SelectorExpr)
+ if !ok {
+ return false
+ }
+ s, ok := info.Selections[sel]
+ return ok && s.Kind() == types.MethodExpr
+}
+
+// genDeclName is the first name a var or const declaration declares, for
+// the guard's report.
+func genDeclName(d *ast.GenDecl) string {
+ for _, sp := range d.Specs {
+ if vs, ok := sp.(*ast.ValueSpec); ok && len(vs.Names) > 0 {
+ return vs.Names[0].Name
+ }
+ }
+ return "declaration"
+}
+
+func siteProblem(info *types.Info, e ast.Expr, name string, sites *[]siteUse) []string {
+ tv := info.Types[e]
+ if tv.Value == nil || tv.Value.Kind() != constant.String {
+ return []string{fmt.Sprintf("%s: Unavailable site is not a constant", name)}
+ }
+ s := constant.StringVal(tv.Value)
+ if !answerSite.MatchString(s) {
+ return []string{fmt.Sprintf("%s: Unavailable site %q does not match answerSite", name, s)}
+ }
+ *sites = append(*sites, siteUse{s, name})
+ return nil
+}
+
+// duplicateSites reports every use of a site named more than once.
+func duplicateSites(sites []siteUse) []string {
+ count := map[string]int{}
+ for _, u := range sites {
+ count[u.site]++
+ }
+ var out []string
+ for _, u := range sites {
+ if count[u.site] > 1 {
+ out = append(out, fmt.Sprintf("%s: Unavailable site %q named twice", u.where, u.site))
+ }
+ }
+ return out
+}
+
+func checkUnavailable(pkgs []*packages.Package, only func(string) bool) []string {
+ var out []string
+ var sites []siteUse
+ for _, p := range pkgs {
+ for i, f := range p.Syntax {
+ path := p.CompiledGoFiles[i]
+ base := filepath.Base(path)
+ if strings.HasSuffix(base, "_test.go") {
+ continue
+ }
+ helper := p.PkgPath == edgePkg && base == "unavailable.go"
+ var fs []siteUse
+ probs := unavailableProblems(p.TypesInfo, f, helper, &fs)
+ if only == nil || only(base) {
+ out = append(out, probs...)
+ }
+ sites = append(sites, fs...)
+ }
+ }
+ dups := duplicateSites(sites)
+ for _, d := range dups {
+ if only == nil || strings.HasPrefix(d, "zz") {
+ out = append(out, d)
+ }
+ }
+ sort.Strings(out)
+ return out
+}
+
+// TestEvery503GoesThroughUnavailable is the invariant over the real code.
+func TestEvery503GoesThroughUnavailable(t *testing.T) {
+ pkgs := loadUnavailablePackages(t)
+ if probs := checkUnavailable(pkgs, nil); len(probs) > 0 {
+ t.Fatalf("503s outside the helper (#421 finding 1):\n %s", strings.Join(probs, "\n "))
+ }
+ // Every listed relay and forwarder still exists: a stale row would
+ // excuse a later function of the same name.
+ have := map[string]bool{}
+ for _, p := range pkgs {
+ for _, f := range p.Syntax {
+ for _, d := range f.Decls {
+ if fd, ok := d.(*ast.FuncDecl); ok {
+ have[unavailableFuncName(fd)] = true
+ }
+ }
+ }
+ }
+ for name := range statusRelays {
+ if !have[name] {
+ t.Errorf("statusRelays names %s, which no longer exists", name)
+ }
+ }
+ for _, name := range append(slices.Clone(unavailableRelays), "admissionResponse") {
+ if !have[name] {
+ t.Errorf("%s is listed but no longer exists", name)
+ }
+ }
+}
+
+// TestUnavailableGuardFixtures proves the guard reports each shape.
+func TestUnavailableGuardFixtures(t *testing.T) {
+ names := make([]string, 0, len(unavailableGuardFixtures))
+ for f := range unavailableGuardFixtures {
+ names = append(names, f)
+ }
+ sort.Strings(names)
+ for _, f := range names {
+ t.Run(f, func(t *testing.T) {
+ pkgs := loadUnavailablePackages(t, f)
+ got := checkUnavailable(pkgs, func(base string) bool { return base == unavailableGuardFixturePrefix+f })
+ want := slices.Clone(unavailableGuardFixtures[f])
+ sort.Strings(want)
+ if !slices.Equal(got, want) {
+ t.Fatalf("fixture %s:\n got %q\n want %q", f, got, want)
+ }
+ })
+ }
+}
diff --git a/internal/edge/unavailable_test.go b/internal/edge/unavailable_test.go
new file mode 100644
index 000000000..5fb161d54
--- /dev/null
+++ b/internal/edge/unavailable_test.go
@@ -0,0 +1,105 @@
+package edge
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func TestUnavailableCarriesRetryAfterSiteAndBox(t *testing.T) {
+ old := answerBoxTag.Load()
+ t.Cleanup(func() { answerBoxTag.Store(old) })
+ setAnswerBox("g-0123456789abcdef0")
+ for _, tc := range []struct {
+ name, site, wantSite string
+ ra int
+ wantRA string
+ header bool
+ }{
+ {"body", "wake-failed", "wake-failed", 5, "5", false},
+ {"header only", "pending-host", "pending-host", 5, "5", true},
+ {"zero raised to one", "lb-health-not-ready", "lb-health-not-ready", 0, "1", false},
+ {"negative raised to one", "x", "x", -3, "1", true},
+ {"bad site", "Bad Site", "unnamed", 2, "2", false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ rec := httptest.NewRecorder()
+ if tc.header {
+ UnavailableHeader(rec, tc.site, tc.ra)
+ } else {
+ Unavailable(rec, tc.site, "busy", tc.ra)
+ }
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("status %d", rec.Code)
+ }
+ h := rec.Header()
+ if h.Get("Retry-After") != tc.wantRA || h.Get(answerHeader) != tc.wantSite {
+ t.Fatalf("Retry-After %q (want %q), %s %q (want %q)", h.Get("Retry-After"), tc.wantRA, answerHeader, h.Get(answerHeader), tc.wantSite)
+ }
+ // sha256("g-0123456789abcdef0")[:12], never the label itself.
+ if got := h.Get(boxTagHeader); len(got) != 12 || got == "g-0123456789abcdef0" {
+ t.Fatalf("%s %q", boxTagHeader, got)
+ }
+ })
+ }
+}
+
+func TestUnavailableBoxTagIsStableAndAbsentWithoutALabel(t *testing.T) {
+ old := answerBoxTag.Load()
+ t.Cleanup(func() { answerBoxTag.Store(old) })
+ answerBoxTag.Store(nil)
+ rec := httptest.NewRecorder()
+ Unavailable(rec, "x", "busy", 1)
+ if got := rec.Header().Get(boxTagHeader); got != "" {
+ t.Fatalf("no label, %s %q", boxTagHeader, got)
+ }
+ setAnswerBox("adi")
+ a := httptest.NewRecorder()
+ Unavailable(a, "x", "busy", 1)
+ setAnswerBox("adi")
+ b := httptest.NewRecorder()
+ Unavailable(b, "x", "busy", 1)
+ setAnswerBox("leo")
+ c := httptest.NewRecorder()
+ Unavailable(c, "x", "busy", 1)
+ if a.Header().Get(boxTagHeader) != b.Header().Get(boxTagHeader) || a.Header().Get(boxTagHeader) == c.Header().Get(boxTagHeader) {
+ t.Fatalf("tags: adi %q, adi %q, leo %q", a.Header().Get(boxTagHeader), b.Header().Get(boxTagHeader), c.Header().Get(boxTagHeader))
+ }
+}
+
+// The demo's unavailable answers, plain and page, carry the headers too.
+func TestDemoUnavailableCarriesRetryAfter(t *testing.T) {
+ for name, serve := range map[string]func(http.ResponseWriter, *http.Request){
+ "plain": func(w http.ResponseWriter, r *http.Request) {
+ serveDemoPlain(w, r, http.StatusServiceUnavailable, "DEMO-UNAVAILABLE")
+ },
+ "unknown copy": func(w http.ResponseWriter, r *http.Request) { serveDemoPlain(w, r, 429, "NO-SUCH-COPY") },
+ } {
+ t.Run(name, func(t *testing.T) {
+ rec := httptest.NewRecorder()
+ serve(rec, httptest.NewRequest("GET", "http://demo.example.com/", nil))
+ if rec.Code != http.StatusServiceUnavailable || rec.Header().Get("Retry-After") == "" || rec.Header().Get(answerHeader) != "demo-unavailable" {
+ t.Fatalf("status %d, Retry-After %q, %s %q", rec.Code, rec.Header().Get("Retry-After"), answerHeader, rec.Header().Get(answerHeader))
+ }
+ })
+ }
+}
+
+// The demo API writer scrubs every other X-Carlos-* header; the helper's
+// answer and box tag still reach the client (Astra R1 #2).
+func TestDemoAPIUnavailableKeepsAnswerAndBox(t *testing.T) {
+ old := answerBoxTag.Load()
+ t.Cleanup(func() { answerBoxTag.Store(old) })
+ setAnswerBox("g-0123456789abcdef0")
+ rec := httptest.NewRecorder()
+ dw := &demoAPIResponseWriter{ResponseWriter: rec, header: make(http.Header)}
+ dw.Header().Set("X-Carlos-Holder", "g-other")
+ demoAPIUnavailable(dw)
+ h := rec.Header()
+ if rec.Code != http.StatusServiceUnavailable || h.Get("Retry-After") != "2" || h.Get(answerHeader) != "demo-api-unavailable" || len(h.Get(boxTagHeader)) != 12 {
+ t.Fatalf("status %d, headers %v", rec.Code, h)
+ }
+ if h.Get("X-Carlos-Holder") != "" {
+ t.Fatalf("private header passed: %v", h)
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 8023d731b..58c6ca4d9 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -159,3 +159,4 @@ plan14-root-reads-group-roll-dr4-lock-refusal.tsv 6d3ea7fccce1a7f4bc507b6eb8d368
plan14-root-reads-held-floor-capability.tsv b60c83f8ba4311222174284420b5327e92002882b4a1c6f291e74e69234c6f59
plan14-root-reads-litestream-unit-restart.tsv e650a3ceb286df4457850d74ded9229d94ed9932057ae5b45b1d6c3d0d843ce2
plan14-root-reads-health-check-no-redirects-845.tsv e650a3ceb286df4457850d74ded9229d94ed9932057ae5b45b1d6c3d0d843ce2
+plan14-root-reads-retry-after-503.tsv eea13e9a0b04164ea3fc7f8258bd1ab0a613d1e23ffe0cd028bc85058576c248
diff --git a/internal/provision/testdata/plan14-root-reads-retry-after-503.tsv b/internal/provision/testdata/plan14-root-reads-retry-after-503.tsv
new file mode 100644
index 000000000..d83d293f2
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-retry-after-503.tsv
@@ -0,0 +1,21 @@
+# Census overlay retry-after-503, written by census-propose (#369). census-ruling-retry-after-503, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-retry-after-503.md.
+# 9 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@legacy d9890b74e0ba1f0e8b5c6cae43cf16681c7eaa23f436ba62d1e2ac239dc24884 internal/activator/activator.go Service.ServeScheduled legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-plans-4d-lapse;basis=answers a scheduled request to a route the turned-off hook names with the maintenance response before serve (plans 4d). One more whole-row read: the row handed to the hook (a.disabled), as the fence and maxRunFor are asked.;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: wraps the proxy so that, after the wake, fillScheduledToken(r, rt) sets an HA host's tick bearer token from its restored env file; an error there logs (+registry:Host, rt.Host) and answers 503 with Retry-After: 5; a non-HA host's tick is left as the runner built it; +whole:Route is rt handed to fillScheduledToken; keeps legacy;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test is Route.ActivatorOwned (a hibernating instance, or an instance with a runtime) instead of Kind and Hibernate inline; reads the same fields plus Runtime through the method;rev3=census-ruling-region-ha-p1b3b-t;basis=Run the local scheduled request under WithDuty and retain existing HTTP refusal text; add route arguments to background admission and error handling. No forwarding.;rev3=census-ruling-retry-after-503;basis=the scheduled-token 503 is written through edge.UnavailableHeader (Retry-After 5 unchanged, adds X-Carlos-Answer/X-Carlos-Box); no read added registry:Host@669,registry:Status@146,registry:Status@165,whole:Route@1108,whole:Route@248,whole:Route@600,whole:Route@848,whole:Route@929 a05c6cb48d8e39c41e3918a2e4ef7c11871d9afbe7eca725547b7a47250f40da
+@legacy a3d125f28f3f41eb15a7f4dbe832e80532c64b06f645181b8d8bb20d3b1ed3cc internal/activator/activator.go Service.serve legacy accepted-legacy accepted-legacy;rev3=census-ruling-hotfix281;basis=Startup repeats the existing Kind and Hibernate checks; error logging moved to serveWakeError. A request held through startup re-reads its own route's Socket and Addr and can only refuse (wake-timeout 503) when recovery moved them; agent-side, deny-only, no root decision.;rev3=census-ruling-edge-request-records;basis=passes the member request r to begin's new req parameter; no read added;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test is Route.ActivatorOwned instead of Kind and Hibernate inline, so a resident rootfs instance is the activator's; same deploy-safety for binary rows;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: a verified HA hop this box cannot serve gets the holder diagnostic; two new whole:Route sites pass the route to answerForwarded/noteNoHolder; no new kind of read;rev3=census-ruling-region-ha-g2-fixes;basis=Refuse latched HA lease loss before startup wait or proxy accounting, and schedule bounded recovery; reads supplied route, no new external read here.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 2: after begin succeeds, edge.ReleaseMoveTicket(r) ends the request's in-memory admission ticket; on the sidecar path the same after BeginSidecarRequest; no read added;rev3=census-ruling-held-move-speed;basis=after begin succeeds, wraps r with an edge.StreamEnd (a cancellable child context) and tracks it under rt.Host in the in-memory moveStreams until the request ends (+registry:Host: the supplied route's Host as the map key); no new kind of read, no root decision;rev3=census-ruling-retry-after-503;basis=the sidecar-asleep 503 is written through edge.Unavailable (Retry-After 5 unchanged, adds answer/box headers); no read added registry:Addr@1131,registry:Addr@1145,registry:Host@1056,registry:Host@1256,registry:Host@3960,registry:Socket@1102,registry:Socket@1118,whole:Route@1081,whole:Route@1190,whole:Route@1324,whole:Route@198,whole:Route@261,whole:Route@2873,whole:Route@2974,whole:Route@298,whole:Route@3746,whole:Route@3809,whole:Route@526 5e53bf343234d54d35132e87549cb88304e6ff0bccc823d42740e100fd8c5fc0
+@legacy 2fff3fc1a88412d0773eccae91dc35606bb66e6ce5913f1533fdfe76a434ff12 internal/activator/haforward.go Service.answerForwarded legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): writes the 503 Retry-After 1 with X-Carlos-Holder for a held lease on a verified HA hop; reads the route only to check HA; root never calls it;rev3=census-ruling-retry-after-503;basis=the held-lease 503 is written through edge.Unavailable (Retry-After 1 unchanged); X-Carlos-Holder unchanged; no read added whole:Route@131 2be3eb0e89caa5578f42a067a902e9bbbf3d2aa551392e64d1f93f29d82ed1f3
+@legacy f3874373de5c874de7b81ce35144df4afc2c90a5e01ea96bcfe598f8b1376b39 internal/activator/harelease.go Service.releaseHAClean legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: an HA entry's release, in order: host slice read empty through haHostEmpty (else errHostSliceUnproven and nothing written; the same check, moved into that helper by final fix F1), stop and join the files publisher, its final publish (2 min budget), the replica's final sync (Finish, 30 s), the local release record, then the release marker PUT (10 s), clean only when the final publish was complete and the sync and record succeeded; a failed PUT is a persisted lease obligation; +registry:Host, +whole:Route x4;rev3=census-ruling-region-ha-p1b3b-t;basis=Record advisory local-release basis only after ReleaseMarker succeeds. Add a whole-route argument to local duty bookkeeping; release order and lease authority unchanged.;rev3=census-ruling-region-ha-g2-fixes;basis=Latch unexpected lease loss before release and mark intentional release so ErrSpent alone is not treated as loss; no new read.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Cap Final, Finish and marker contexts by the shutdown deadline and reserves; keep calls synchronous and stop proof unchanged; record successful marker completion under the service mutex. No read added.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 5: records the written marker's clean flag on the entry (haReleaseClean) beside haReleased, for the drain report; no read added;rev3=census-ruling-held-move-speed;basis=reads the entry's drainRelease flag under a.mu; for the drain's release calls the replica's FinishSnapshot (final sync, then a litestream snapshot at the final position, before the store's close; the snapshot reader pipe is closed on every outcome) instead of Finish, and logs a snapshot failure naming rt.Host (+registry:Host, the supplied route); marker order, budgets and clean rule unchanged; no new read;rev3=census-ruling-retry-after-503;basis=records four time.Now stamps and logs per-phase durations (files, sync, record, marker) on the existing marker log line; order, budgets and clean rule unchanged; no read added registry:Host@1584,registry:Host@2785,whole:Route@109,whole:Route@1710,whole:Route@1848,whole:Route@2624,whole:Route@267 39353c898133ea75aa2542d28ea6db1a81c868626aba4fc44dd43a4467a6054b
+@legacy 988be30588cdde03e38aad634d536400a17439437e5e9ec6808b64e2094d5643 internal/edge/importgate.go Edge.importGateAdmit legacy accepted-legacy accepted-legacy;rev3=census-ruling-seeded-instances;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): the import gate: a gated row admits only a GET carrying the verify token; anything else is a 503; serving only;rev3=census-ruling-agent-start-demo-3;basis=Keep demo-claim destinations gated until committed; verify exact host/seed capability before allowing console probes. Census read-site delta: +registry:Host, +registry:SeedSource.;rev3=census-ruling-retry-after-503;basis=the gate's 503 is written through Unavailable (adds Retry-After and answer/box headers); admission logic unchanged; no read added registry:Host@482,registry:Host@535,registry:Host@549,registry:ImportGate@274,registry:ImportGate@297,registry:ImportGate@609,registry:SeedSource@394,whole:Route@197,whole:Route@250,whole:Route@261 4dfc59d7f0702f867456fb45114518ee13cdd00bd3f3af0790b194b6be48fef1
+@legacy 4cf7876eec44ead223526d45b8f846138e3b2eadb158476d99f8c94a7b50ea8e internal/edge/plandisabled.go Edge.planDisabledAdmit legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4d-units;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), serving only: asks the plans turned-off hook (planDisabledFor, passed the row and the request host) and answers a turned-off route with a fixed 503 page rendered from constants, before the meter, gate, cache and activator; reads only the row's kind; echoes nothing from the request (plans 4d).;rev3=census-ruling-retry-after-503;basis=the fixed 503 page status is written through UnavailableNoRetry (still no Retry-After; adds answer/box headers); body and checks unchanged; no read added registry:Kind@156,whole:Route@185 9c262814f06d3ee9c3d4a419936e3be7b033659c4b25c4601199a2098dd8ba1c
+@legacy ec43384b0f0a176f0d0408082f3832e1563912e3463a993a527d376346ed5503 internal/edge/replicaconsole.go Edge.serveReplicaConsole legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-coordinator-route;basis=Reads existing in-memory route fields to select a unique accountless console.service local upstream; refuses missing or ambiguous console, tenant routes, remote and tunnel upstreams. Reuses proxy and version wrapper; leaves fleet identity authentication at console.;rev3=census-ruling-retry-after-503;basis=the missing/ambiguous-console 503s go through UnavailableHeader (adds Retry-After 2 and answer/box headers); selection unchanged; no read added registry:Account@237,registry:App@257,registry:Host@178,registry:Socket@355,registry:Unit@280,whole:Route@159 cd4066214c9abe0e393c0f57abf0adab3988e4916073649e1ce0231d95388906
+@legacy b3c3ab490d60a2ee9d0861e2e2c745b7c43c709c0bf23d8438f36c2ca3836089 internal/edge/replicaprobe.go Edge.serveReplicaProbe legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 I4/F1: the dialled pathname comes from the serving Gen.Socket and, for shared/foreign layouts, can originate in the registry row Socket. Dial through unixdial.Checked: refuse the instance-control directory before connect and require getpeername to match the dialled path before sending HTTP, including symlink refusal. Existing Route reads unchanged. M5 handles request construction errors before RoundTrip; M2 uses the shared reason constant. Authenticated private landing, held-leg admission, one-second bound and post-response identity checks remain.;rev3=census-ruling-retry-after-503;basis=each refusal 503 goes through UnavailableHeader with its own site (adds Retry-After 2 and answer/box headers); dial and identity checks unchanged; no read added registry:FleetBoxes@390,registry:HA@459,registry:Hibernate@443,registry:Host@346,registry:Kind@365,whole:Route@1028,whole:Route@1218,whole:Route@2279,whole:Route@708 b17068d220c00949d08e47c6420f62508d3bada1b9996bcea3d8ada9e4f18d11
+internal/activator/activator.go Service.ServeScheduled legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-plans-4d-lapse;basis=answers a scheduled request to a route the turned-off hook names with the maintenance response before serve (plans 4d). One more whole-row read: the row handed to the hook (a.disabled), as the fence and maxRunFor are asked.;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: wraps the proxy so that, after the wake, fillScheduledToken(r, rt) sets an HA host's tick bearer token from its restored env file; an error there logs (+registry:Host, rt.Host) and answers 503 with Retry-After: 5; a non-HA host's tick is left as the runner built it; +whole:Route is rt handed to fillScheduledToken; keeps legacy;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test is Route.ActivatorOwned (a hibernating instance, or an instance with a runtime) instead of Kind and Hibernate inline; reads the same fields plus Runtime through the method;rev3=census-ruling-region-ha-p1b3b-t;basis=Run the local scheduled request under WithDuty and retain existing HTTP refusal text; add route arguments to background admission and error handling. No forwarding.;rev3=census-ruling-retry-after-503;basis=the scheduled-token 503 is written through edge.UnavailableHeader (Retry-After 5 unchanged, adds X-Carlos-Answer/X-Carlos-Box); no read added registry:Host@669,registry:Status@146,registry:Status@165,whole:Route@1108,whole:Route@248,whole:Route@600,whole:Route@848,whole:Route@929 a05c6cb48d8e39c41e3918a2e4ef7c11871d9afbe7eca725547b7a47250f40da
+internal/activator/activator.go Service.serve legacy accepted-legacy accepted-legacy;rev3=census-ruling-hotfix281;basis=Startup repeats the existing Kind and Hibernate checks; error logging moved to serveWakeError. A request held through startup re-reads its own route's Socket and Addr and can only refuse (wake-timeout 503) when recovery moved them; agent-side, deny-only, no root decision.;rev3=census-ruling-edge-request-records;basis=passes the member request r to begin's new req parameter; no read added;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: the activator-managed test is Route.ActivatorOwned instead of Kind and Hibernate inline, so a resident rootfs instance is the activator's; same deploy-safety for binary rows;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: a verified HA hop this box cannot serve gets the holder diagnostic; two new whole:Route sites pass the route to answerForwarded/noteNoHolder; no new kind of read;rev3=census-ruling-region-ha-g2-fixes;basis=Refuse latched HA lease loss before startup wait or proxy accounting, and schedule bounded recovery; reads supplied route, no new external read here.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 2: after begin succeeds, edge.ReleaseMoveTicket(r) ends the request's in-memory admission ticket; on the sidecar path the same after BeginSidecarRequest; no read added;rev3=census-ruling-held-move-speed;basis=after begin succeeds, wraps r with an edge.StreamEnd (a cancellable child context) and tracks it under rt.Host in the in-memory moveStreams until the request ends (+registry:Host: the supplied route's Host as the map key); no new kind of read, no root decision;rev3=census-ruling-retry-after-503;basis=the sidecar-asleep 503 is written through edge.Unavailable (Retry-After 5 unchanged, adds answer/box headers); no read added registry:Addr@1131,registry:Addr@1145,registry:Host@1056,registry:Host@1256,registry:Host@3960,registry:Socket@1102,registry:Socket@1118,whole:Route@1081,whole:Route@1190,whole:Route@1324,whole:Route@198,whole:Route@261,whole:Route@2873,whole:Route@2974,whole:Route@298,whole:Route@3746,whole:Route@3809,whole:Route@526 5e53bf343234d54d35132e87549cb88304e6ff0bccc823d42740e100fd8c5fc0
+internal/activator/activator.go Service.serveWakeError diagnostic C,J4 rev3=PROPOSED-seed; incarnation-keyed missing-files diagnostics and indexed retry results; throttles output only and grants no retry, stop or launch;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more case, errLeaseRefused (a born-HA host outside the nested layout or an HA acquire's refusal): logged at most once per diagnostic window (allowFilesDiagnostic(rt.Host, ...)) and answered 503 with Retry-After: 10; the other cases unchanged; +registry:Host x2 are rt.Host in that call and the log line; it only answers;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: two new answers, a resident inside its backoff gets 503 with Retry-After (RFS-3-C16), and a rootfs row refused before the lease (errRootfsNotAdmitted) gets the existing wake-failed 503; no read added;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: for a verified HA hop, a held lease answers 503 Retry-After 1 with X-Carlos-Holder (answerForwarded) and every other refusal adds X-Carlos-Holder: none (noteNoHolder); legacy routes and cancellation unchanged; same reads;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: neutral admission 503 with Retry-After before forwarded-holder diagnostics; no new read, no holder identity. Fix R1: distinguish startup from drain/shutdown using the same admission state; retain 503, Retry-After, no-store and removal of holder identity. Read sites unchanged.;rev3=census-ruling-region-ha-g2-fixes;basis=Answer latched HA loss and pool refusal with the shared unavailable response; no new read.;rev3=census-ruling-region-ha-shutting-down-retry;basis=Task 0: errShuttingDown (a request met by Shutdown, #292) is answered with the existing admission unavailable 503 (Retry-After: 10, no-store, holder removed), before answerForwarded, instead of the default wake-failed 503 with no Retry-After and a wake log line; no new read, read sites unchanged.;rev3=census-ruling-retry-after-503;basis=every case answers through edge.Unavailable with its own site name; Retry-After values unchanged; rootfs-not-admitted and the default wake-failed answer now carry Retry-After 5 (#421); no read added registry:Host@1926,registry:Host@1990,registry:Host@3492,registry:Host@3556,whole:Route@1111 489e4d725cb580575404b073e9b47ced9fa372f602c995fd7773371d91c629cf
+internal/activator/haforward.go Service.answerForwarded legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): writes the 503 Retry-After 1 with X-Carlos-Holder for a held lease on a verified HA hop; reads the route only to check HA; root never calls it;rev3=census-ruling-retry-after-503;basis=the held-lease 503 is written through edge.Unavailable (Retry-After 1 unchanged); X-Carlos-Holder unchanged; no read added whole:Route@131 2be3eb0e89caa5578f42a067a902e9bbbf3d2aa551392e64d1f93f29d82ed1f3
+internal/activator/harelease.go Service.releaseHAClean legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: an HA entry's release, in order: host slice read empty through haHostEmpty (else errHostSliceUnproven and nothing written; the same check, moved into that helper by final fix F1), stop and join the files publisher, its final publish (2 min budget), the replica's final sync (Finish, 30 s), the local release record, then the release marker PUT (10 s), clean only when the final publish was complete and the sync and record succeeded; a failed PUT is a persisted lease obligation; +registry:Host, +whole:Route x4;rev3=census-ruling-region-ha-p1b3b-t;basis=Record advisory local-release basis only after ReleaseMarker succeeds. Add a whole-route argument to local duty bookkeeping; release order and lease authority unchanged.;rev3=census-ruling-region-ha-g2-fixes;basis=Latch unexpected lease loss before release and mark intentional release so ErrSpent alone is not treated as loss; no new read.;rev3=census-ruling-region-ha-graceful-terminate-t2;basis=Cap Final, Finish and marker contexts by the shutdown deadline and reserves; keep calls synchronous and stop proof unchanged; record successful marker completion under the service mutex. No read added.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 5: records the written marker's clean flag on the entry (haReleaseClean) beside haReleased, for the drain report; no read added;rev3=census-ruling-held-move-speed;basis=reads the entry's drainRelease flag under a.mu; for the drain's release calls the replica's FinishSnapshot (final sync, then a litestream snapshot at the final position, before the store's close; the snapshot reader pipe is closed on every outcome) instead of Finish, and logs a snapshot failure naming rt.Host (+registry:Host, the supplied route); marker order, budgets and clean rule unchanged; no new read;rev3=census-ruling-retry-after-503;basis=records four time.Now stamps and logs per-phase durations (files, sync, record, marker) on the existing marker log line; order, budgets and clean rule unchanged; no read added registry:Host@1584,registry:Host@2785,whole:Route@109,whole:Route@1710,whole:Route@1848,whole:Route@2624,whole:Route@267 39353c898133ea75aa2542d28ea6db1a81c868626aba4fc44dd43a4467a6054b
+internal/edge/importgate.go Edge.importGateAdmit legacy accepted-legacy accepted-legacy;rev3=census-ruling-seeded-instances;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): the import gate: a gated row admits only a GET carrying the verify token; anything else is a 503; serving only;rev3=census-ruling-agent-start-demo-3;basis=Keep demo-claim destinations gated until committed; verify exact host/seed capability before allowing console probes. Census read-site delta: +registry:Host, +registry:SeedSource.;rev3=census-ruling-retry-after-503;basis=the gate's 503 is written through Unavailable (adds Retry-After and answer/box headers); admission logic unchanged; no read added registry:Host@482,registry:Host@535,registry:Host@549,registry:ImportGate@274,registry:ImportGate@297,registry:ImportGate@609,registry:SeedSource@394,whole:Route@197,whole:Route@250,whole:Route@261 4dfc59d7f0702f867456fb45114518ee13cdd00bd3f3af0790b194b6be48fef1
+internal/edge/plandisabled.go Edge.planDisabledAdmit legacy accepted-legacy accepted-legacy;rev3=census-ruling-plans-4d-units;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos), serving only: asks the plans turned-off hook (planDisabledFor, passed the row and the request host) and answers a turned-off route with a fixed 503 page rendered from constants, before the meter, gate, cache and activator; reads only the row's kind; echoes nothing from the request (plans 4d).;rev3=census-ruling-retry-after-503;basis=the fixed 503 page status is written through UnavailableNoRetry (still no Retry-After; adds answer/box headers); body and checks unchanged; no read added registry:Kind@156,whole:Route@185 9c262814f06d3ee9c3d4a419936e3be7b033659c4b25c4601199a2098dd8ba1c
+internal/edge/replicaconsole.go Edge.serveReplicaConsole legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-coordinator-route;basis=Reads existing in-memory route fields to select a unique accountless console.service local upstream; refuses missing or ambiguous console, tenant routes, remote and tunnel upstreams. Reuses proxy and version wrapper; leaves fleet identity authentication at console.;rev3=census-ruling-retry-after-503;basis=the missing/ambiguous-console 503s go through UnavailableHeader (adds Retry-After 2 and answer/box headers); selection unchanged; no read added registry:Account@237,registry:App@257,registry:Host@178,registry:Socket@355,registry:Unit@280,whole:Route@159 cd4066214c9abe0e393c0f57abf0adab3988e4916073649e1ce0231d95388906
+internal/edge/replicaprobe.go Edge.serveReplicaProbe legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 I4/F1: the dialled pathname comes from the serving Gen.Socket and, for shared/foreign layouts, can originate in the registry row Socket. Dial through unixdial.Checked: refuse the instance-control directory before connect and require getpeername to match the dialled path before sending HTTP, including symlink refusal. Existing Route reads unchanged. M5 handles request construction errors before RoundTrip; M2 uses the shared reason constant. Authenticated private landing, held-leg admission, one-second bound and post-response identity checks remain.;rev3=census-ruling-retry-after-503;basis=each refusal 503 goes through UnavailableHeader with its own site (adds Retry-After 2 and answer/box headers); dial and identity checks unchanged; no read added registry:FleetBoxes@390,registry:HA@459,registry:Hibernate@443,registry:Host@346,registry:Kind@365,whole:Route@1028,whole:Route@1218,whole:Route@2279,whole:Route@708 b17068d220c00949d08e47c6420f62508d3bada1b9996bcea3d8ada9e4f18d11
+@coverage internal/activator d6ce24a4b55dbf89771215c105acf2156e79b17659bbb4d21dc6628a13c8b609
+@coverage internal/edge 3a80599eb7da7d390059130c0e008e76cd87a5a97596ed8191323342069c9b21
diff --git a/scripts/ha-roll-probe.sh b/scripts/ha-roll-probe.sh
new file mode 100755
index 000000000..7af1627f5
--- /dev/null
+++ b/scripts/ha-roll-probe.sh
@@ -0,0 +1,48 @@
+#!/bin/bash
+# ha-roll-probe.sh OUT SECONDS INTERVAL HOST IP...
+#
+# The roll probe (#421 finding 1). Every INTERVAL seconds, GET https://HOST/
+# through each IP (an NLB address, or a fixed box in the target group) and
+# append one line per answer to OUT:
+#
+# <UTC time> <ip> <code> ra=<Retry-After> answer=<X-Carlos-Answer> box=<X-Carlos-Box> app=<app's box=...> [body=<first 160 bytes>]
+#
+# answer and box are set on every 503 the platform writes (edge.Unavailable):
+# answer names the path, box is the answering box's tag (the first 12 hex
+# digits of the SHA-256 of its label; match it with
+# printf %s LABEL | sha256sum | cut -c1-12).
+# app is the fixture app's own box=... from a 200 body. Every non-200 also
+# records the start of its body, one line, so an answer from outside the
+# helper (an app's own 503, a load balancer's) is still told apart.
+#
+# Scratch headers go in a fresh mktemp directory, removed at the end.
+set -u
+if [ $# -lt 5 ]; then
+ echo "usage: $0 OUT SECONDS INTERVAL HOST IP..." >&2
+ exit 2
+fi
+out=$1 secs=$2 every=$3 host=$4
+shift 4
+scratch=$(mktemp -d)
+trap 'wait; rm -rf "$scratch"' EXIT
+end=$(($(date +%s) + secs))
+n=0
+while [ "$(date +%s)" -lt "$end" ]; do
+ for ip in "$@"; do
+ n=$((n + 1))
+ (
+ t=$(date -u +%T.%3N)
+ h="$scratch/h.$n" b="$scratch/b.$n"
+ c=$(curl -s -m 8 -D "$h" -o "$b" --resolve "$host:443:$ip" "https://$host/" -w '%{http_code}' 2>/dev/null)
+ hdr() { grep -i "^$1:" "$h" 2>/dev/null | head -1 | tr -d '\r' | cut -d' ' -f2- | tr -cd '[:alnum:]._:-'; }
+ app=$(grep -o 'box=[A-Za-z0-9.-]*' "$b" 2>/dev/null | head -1 | cut -d= -f2)
+ line="$t $ip ${c:-000} ra=$(hdr Retry-After) answer=$(hdr X-Carlos-Answer) box=$(hdr X-Carlos-Box) app=$app"
+ if [ "${c:-000}" != 200 ]; then
+ line="$line body=$(head -c 160 "$b" 2>/dev/null | tr '\n\r\t' ' ' | tr -cd '[:print:]')"
+ fi
+ echo "$line" >>"$out"
+ rm -f "$h" "$b"
+ ) &
+ done
+ sleep "$every"
+done