carlos / platform Public

edge: close a demo API connection on an early answer; log placements

Two fixes from the Go code-health follow-ups (#1123):
- #1248: on the demo API alias, an answer sent while the upload was
  still arriving could panic net/http ("invalid concurrent Body.Read
  call") or make the next keep-alive request answer 400 (41 of 72
  reproducer cases). An HTTP/1 answer sent before the body has fully
  arrived now sends Connection: close, and the handler discards the rest
  for at most 1 s. Whole uploads keep their connection; HTTP/2 is
  unchanged.
- #1246: the replica placement worker logs retire, acquire, publish,
  registry-read and incarnation failures, at most once per backoff step
  or assignment. Retry timing is unchanged.

Reviewed by Astra (round 1, READY AFTER FIXES; scoped check passed).
Census approved on #280.

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

Squashed from small-fixes-1246-1248 into main.
claude agent, operated by paul@keymail.dev 8c861346e478b8c41b143a3060fb9d5204c65953 parent 08b87a2
11 files changed, +1,031 −4
  • docs/superpowers/notes/census-proposal-small-fixes-1246-1248.md +19 −0
  • docs/superpowers/reviews/CHECK-BRIEF-small-fixes-1246-1248-R1-fix.md +22 −0
  • docs/superpowers/reviews/CHECK-small-fixes-1246-1248-R1-fix.md +22 −0
  • docs/superpowers/reviews/FINDINGS-small-fixes-1246-1248-R1.md +47 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-small-fixes-1246-1248.md +47 −0
  • internal/edge/demo_api.go +15 −0
  • internal/edge/demo_api_duplex_test.go +510 −0
  • internal/host/replicaplacement.go +60 −4
  • internal/host/replicaplacement_log_test.go +282 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-small-fixes-1246-1248.tsv +6 −0

CI passed — run details

diff --git a/docs/superpowers/notes/census-proposal-small-fixes-1246-1248.md b/docs/superpowers/notes/census-proposal-small-fixes-1246-1248.md
new file mode 100644
index 000000000..c2e97a5b7
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-small-fixes-1246-1248.md
@@ -0,0 +1,19 @@
+# Census approval: small-fixes-1246-1248
+
+Ruling `census-ruling-small-fixes-1246-1248`. 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/host/replicaplacement.go` `replicaPlacementWorker.run` | body | unchanged (6) | Logs the retire, acquire, publish, registry-read and incarnation failures it used to drop, throttled per backoff step (incarnation: per assignment), outside the worker lock. The retry decision, the incarnation skip, backoff arithmetic, deadlines and read sites are unchanged; no read added. |
+
+Envelopes re-pinned: `internal/edge`, `internal/host`.
+
+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/host/replicaplacement.go` `replicaPlacementWorker.run`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-stateless-replicas-2;basis=Final fix I3: retain completed lifetime/revision observations and skip their work; only confirmed current binding publication after coordinator acquisition, or existing successful/fenced retirement ACK, completes work. Existing local registry read, authority and retirement checks, and 30-second request deadline remain. No new reads or polling.;rev3=census-ruling-staticcheck-sa4006;basis=SA4006 dead store: publishCurrent's error is discarded explicitly (done, _ =) with a comment; it was assigned to err and never read, and publishCurrent returns false with every error, so done and the retry backoff are exactly as before. No read added, read sites unchanged (6).
+
+Seal: `f9be26c06eb1c844b91a75f65faa51997048cb2900f3ed078be2ae28c65c0e98` → `c6d366dcf2211b714977b7a69180289555b362dfe5f36a5780af90b5ece82998`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-small-fixes-1246-1248.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/reviews/CHECK-BRIEF-small-fixes-1246-1248-R1-fix.md b/docs/superpowers/reviews/CHECK-BRIEF-small-fixes-1246-1248-R1-fix.md
new file mode 100644
index 000000000..95d43413d
--- /dev/null
+++ b/docs/superpowers/reviews/CHECK-BRIEF-small-fixes-1246-1248-R1-fix.md
@@ -0,0 +1,22 @@
+# Scoped check: small-fixes-1246-1248, after round 1 (not a review round)
+
+Repo carlos/platform, branch `small-fixes-1246-1248` (tip in the prompt).
+Round 1 (`docs/superpowers/reviews/FINDINGS-small-fixes-1246-1248-R1.md`) ended
+READY AFTER FIXES with two P2s. The fixes are commits 43b20c17 and 2209b04f.
+Scope: `git show 43b20c17 2209b04f` and the census card
+`docs/superpowers/notes/census-proposal-small-fixes-1246-1248.md`.
+
+Check:
+1. Each round-1 P2: resolved, partly, not.
+2. replicaPlacementWorker.run: the new "read route" and Incarnation
+ diagnostics change logging only? Retry timing, the Incarnation skip,
+ retirement, acquisition and completion rules unchanged? Can a log line
+ carry anything a tenant should not see in the journal?
+3. The stalled-upload test: does it enforce exitLingerBound on all four
+ cases, and is the 2 s tolerance sound on a loaded runner?
+4. Census verdicts for replicaPlacementWorker.run and the internal/host
+ envelope at this tip.
+
+Answer each: OK, or a finding with file:line, failure scenario and fix,
+marked P1 or P2. End with exactly one line: CHECK PASSED, or CHECK FAILED
+with the P1s. Do not edit files, spawn reviewers or run full suites.
diff --git a/docs/superpowers/reviews/CHECK-small-fixes-1246-1248-R1-fix.md b/docs/superpowers/reviews/CHECK-small-fixes-1246-1248-R1-fix.md
new file mode 100644
index 000000000..0b70684c9
--- /dev/null
+++ b/docs/superpowers/reviews/CHECK-small-fixes-1246-1248-R1-fix.md
@@ -0,0 +1,22 @@
+Scoped check at `96e2df1ce76811595c6d8c94c28a365d52682bfa`, covering fixes `43b20c17` and `2209b04f` and the census card. This is the follow-up to round 1, not another review round. No P1 or P2 findings.
+
+1. **OK — Both round-1 P2s resolved.** Registry errors now enter the existing throttled reporting path as `"read route"`. Incarnation failures receive one diagnostic per assignment while retaining their skip. The added tests check diagnostics, unchanged backoff, suppression across repeated ticks, and renewed reporting after an assignment revision. See [replicaplacement_log_test.go:127](/home/paulca/amadan.net/carlos/platform-small-fixes-1246-1248/internal/host/replicaplacement_log_test.go:127). The stalled-upload test now measures closure and covers the requested four cases.
+
+2. **OK — Placement behavior and journal contents.** Reviewed [replicaplacement.go:94](/home/paulca/amadan.net/carlos/platform-small-fixes-1246-1248/internal/host/replicaplacement.go:94) through line 202. The changes affect logging and its suppression state only. Registry failure still prevents retirement and acquisition; malformed incarnation still skips before creating the request context. Retirement proof, successful/fenced retirement completion, acquisition gates, publication completion, the 30-second deadline, and retry arithmetic remain unchanged. Logging occurs outside both locks.
+
+ The new diagnostics contain the host, a fixed step name, and the error. Incarnation errors are fixed sentinels; registry errors come from the existing query/scan path. No credentials, request bodies, or complete records are added to the journal. I found no new secret-disclosure path.
+
+3. **OK — Stalled-upload bound and tolerance.** [demo_api_duplex_test.go:402](/home/paulca/amadan.net/carlos/platform-small-fixes-1246-1248/internal/edge/demo_api_duplex_test.go:402) starts measurement after the complete answer, requires an actual closure error, and rejects elapsed time above `exitLingerBound + 2s`—currently three seconds. A read timeout cannot satisfy `demoDuplexGone`. Both declared-length and chunked uploads use this assertion on local and backhaul paths.
+
+ Two seconds is a reasonable scheduling allowance for this integration test. Setup has a separate timeout, and the assertion still catches substantially delayed cleanup. It establishes a three-second observed bound, not an exact one-second guarantee; extreme runner starvation can still cause a timing failure.
+
+4. **OK — Census verdicts at this tip.**
+
+ | Unit or envelope | Verdict |
+ |---|---|
+ | `replicaPlacementWorker.run` | **APPROVE**, retaining `legacy / accepted-legacy`. The existing six read sites and authority checks remain intact; no new root read source or completion authority. |
+ | `internal/host` envelope | **APPROVE**. Reviewed the changed worker and both new helpers at [replicaplacement.go:188](/home/paulca/amadan.net/carlos/platform-small-fixes-1246-1248/internal/host/replicaplacement.go:188). The helper mutates only diagnostic suppression state under the existing mutex; the logging helper preserves the previous format. No expanded root access or weakened validation. |
+
+Validation: `git diff --check` passed for the two fix commits. Targeted tests could not start because the read-only sandbox prevented Go from creating its build directory. No full suites ran, no files were edited, and no reviewers were spawned. Census approval has not been posted to #280.
+
+CHECK PASSED
\ No newline at end of file
diff --git a/docs/superpowers/reviews/FINDINGS-small-fixes-1246-1248-R1.md b/docs/superpowers/reviews/FINDINGS-small-fixes-1246-1248-R1.md
new file mode 100644
index 000000000..2aa2e6625
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-small-fixes-1246-1248-R1.md
@@ -0,0 +1,47 @@
+Reviewed `origin/main...9217723bbce3ef573136b0f90cb53bc80e1c06b5`, round 1 of 3. The brief names `31210ccb`; the requested tip adds only the brief.
+
+No P1 findings.
+
+1. **P2 — Registry failures still leave placement retries silent.**
+ Evidence: [replicaplacement.go:120](/home/paulca/amadan.net/carlos/platform-small-fixes-1246-1248/internal/host/replicaplacement.go:120), with reporting gated at line 155.
+
+ If `reg.Get` fails, neither retirement nor acquisition runs, `failure` remains nil, and the worker advances its backoff without reporting why placement is stuck. Registry query and scan failures are real errors, distinct from an absent route.
+
+ **Fix:** capture this error as a named step and pass it through the existing throttled reporting path. Add a failing-registry test that checks the diagnostic and unchanged retry timing. The `Incarnation` error at lines 109–111 should also receive a suppressed diagnostic if encountered, while preserving its existing skip behavior.
+
+ **Fault family:** placement failures must remain diagnosable without producing a log on every tick.
+
+2. **P2 — The stalled-upload test does not enforce the promised linger bound.**
+ Evidence: [demo_api_duplex_test.go:397](/home/paulca/amadan.net/carlos/platform-small-fixes-1246-1248/internal/edge/demo_api_duplex_test.go:397).
+
+ The test sets a ten-second connection deadline and accepts any connection closure before it expires. Cleanup taking several seconds would pass despite the stated `exitLingerBound` of one second. It also covers only the local path with a declared content length; the backhaul matrix explicitly skips its handler-return cases.
+
+ **Fix:** measure closure after receiving the complete answer and assert `exitLingerBound` plus reasonable scheduling tolerance. Cover stalled chunked uploads and the backhaul path as well. Keep a separate, generous timeout for setup so runner load does not consume the cleanup allowance.
+
+ **Fault family:** early-answer cleanup must release stalled uploads within its stated bound.
+
+No P3 findings.
+
+The request-path fix is sound on inspection. [serveDemoAPIAlias](/home/paulca/amadan.net/carlos/platform-small-fixes-1246-1248/internal/edge/demo_api.go:122) installs tracking before both local and backhaul dispatch, including admission refusals. [WriteHeader](/home/paulca/amadan.net/carlos/platform-small-fixes-1246-1248/internal/edge/demo_api.go:303) adds `Connection: close` after header filtering whenever the HTTP/1 body remains incomplete.
+
+The deferred [finishEarlyAnswer](/home/paulca/amadan.net/carlos/platform-small-fixes-1246-1248/internal/edge/replay.go:179) drains through the underlying synchronized body reader before handler return. Combined with the close header, this prevents unfinished upload bytes from becoming another request. I found no remaining unsafe connection-reuse window on either path. The deadline bounds upload cleanup after response relay finishes; it does not bound the response relay itself.
+
+Fully consumed uploads retain keep-alive, and HTTP/2 bypasses the new tracking. Closing unread-body 503 and 429 responses is appropriate because those paths have already enabled full duplex. The earlier disallowed-path 404 remains outside full duplex.
+
+Placement completion conditions, retry arithmetic, and request deadlines remain unchanged. Reporting occurs outside both locks. One diagnostic during continuously changing `RecordSeq` values satisfies the specified once-per-backoff-step policy, although that step can remain open indefinitely.
+
+The incomplete-upload regression cases should fail against the old implementation through their missing-close assertion. The positive keep-alive and quiet-worker tests appropriately preserve behavior that already worked. The log tests use controlled timestamps and synchronized capture, reducing scheduling sensitivity.
+
+Validation was limited to source inspection and a clean `git diff --check`. The targeted test command stopped before execution because Go attempted to update `go.mod` in the read-only workspace. Network restrictions prevented reading amadan #1246 and #1248. No files were edited.
+
+Census verdicts for the reviewed tip:
+
+| Unit or envelope | Verdict and basis |
+|---|---|
+| `replicaPlacementWorker.run` | **APPROVE**, retaining `legacy / accepted-legacy`. Reviewed [replicaplacement.go:94](/home/paulca/amadan.net/carlos/platform-small-fixes-1246-1248/internal/host/replicaplacement.go:94) through line 175. Existing registry reads, retirement proof, acquisition gates, publication checks, and completion rules remain intact. No new authority or read source. |
+| `internal/host` envelope | **APPROVE.** The added bookkeeping in `replicaPlacementWork` and `observe` controls logging only. The changed worker and new test helpers introduce no production authority expansion. |
+| `internal/edge` envelope | **APPROVE.** The changed alias handler, response writer, and reached cleanup helpers constrain connection lifetime. Destination eligibility, authentication checks, request filtering, and response filtering remain intact. No new root-accessible path or authority. |
+
+These approvals apply to the current diff. The P2 fixes need the scoped census/request-path checks required by the stopping rules, without reopening the whole review. Approval has not been posted to #280.
+
+READY AFTER FIXES
\ No newline at end of file
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-small-fixes-1246-1248.md b/docs/superpowers/reviews/REVIEW-BRIEF-small-fixes-1246-1248.md
new file mode 100644
index 000000000..bd7f7aee2
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-small-fixes-1246-1248.md
@@ -0,0 +1,47 @@
+# Review brief: branch small-fixes-1246-1248, round 1 of 3
+
+Repo carlos/platform, branch `small-fixes-1246-1248`, commit 31210ccba1a758f040304a6b4a72a208a28a12b2.
+Under review: the diff `origin/main...31210ccba1a758f040304a6b4a72a208a28a12b2`.
+Authorities: amadan #1246 and #1248, AGENTS.md ("The census", "Stopping rules").
+
+You are the independent reviewer and census reviewer (card:
+`docs/superpowers/notes/census-proposal-small-fixes-1246-1248.md`).
+
+## What to check
+
+1. **#1248, the tenant request path (internal/edge/demo_api.go).** On the old
+ code an early answer on the demo API alias, with the upload still
+ arriving, could panic net/http ("invalid concurrent Body.Read call") or
+ make the next keep-alive request answer 400. The fix: an HTTP/1 answer
+ sent before the body has fully arrived sends Connection: close, and the
+ handler discards the rest of the body for at most exitLingerBound (1 s)
+ through watchBody and finishEarlyAnswer.
+ - Is the root cause right, and is the fix complete on the local and
+ backhaul paths? Any window left where the transport still reads the
+ body when the handler returns?
+ - Request smuggling: can bytes after the early answer ever be read as a
+ new request on any path?
+ - Can a slow client hold a handler past the bound?
+ - Does a normal upload, fully received before the answer, keep its
+ connection? HTTP/2 unchanged?
+ - Alias refusals (503, 429) that leave the body unread also close the
+ connection: right choice?
+2. **#1246 (internal/host/replicaplacement.go).** Failures log at most once
+ per backoff step; retry timing unchanged. Should the provision.Incarnation
+ and reg.Get errors log too? Is one line enough when a record changes on
+ every attempt and the backoff never advances?
+3. Tests: does each fail on the old code; flake risk on a loaded runner?
+4. Census verdicts.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+- **P2**: wrong or missing. Fixed without reopening this review (request-path
+ and census changes in the fix still get a scoped check).
+- **P3**: clarity or polish. Follow-up list only.
+
+## Output
+
+Findings ranked P1, P2, P3 with file:line, failure scenario and fix. Then
+census verdicts. End with exactly one verdict: READY, READY AFTER FIXES, or
+NOT READY. Do not edit files, spawn reviewers or run full suites.
diff --git a/internal/edge/demo_api.go b/internal/edge/demo_api.go
index 222d6b581..e5fca43d5 100644
--- a/internal/edge/demo_api.go
+++ b/internal/edge/demo_api.go
@@ -120,6 +120,7 @@ func (e *Edge) serveDemoAPIAlias(w http.ResponseWriter, r *http.Request, host st
return false
}
dw := &demoAPIResponseWriter{ResponseWriter: w, header: make(http.Header)}
+ defer func() { finishEarlyAnswer(w, dw.body) }()
defer dw.finish()
if !allowed {
dw.WriteHeader(http.StatusNotFound)
@@ -130,6 +131,14 @@ func (e *Edge) serveDemoAPIAlias(w http.ResponseWriter, r *http.Request, host st
// refusal, so a client waiting for the response can stall both edges.
// HTTP/2 already permits concurrent reads and writes.
_ = http.NewResponseController(w).EnableFullDuplex()
+ // Full duplex lets the proxy's transport still be reading the body when
+ // the handler returns. If net/http then reads the next request from this
+ // connection it panics, and an unfinished chunked body is misread as a
+ // request (#1248). So an HTTP/1 answer that beats the body closes the
+ // connection (demoAPIResponseWriter.WriteHeader, finishEarlyAnswer).
+ if r.ProtoMajor == 1 {
+ r, dw.body = watchBody(r)
+ }
_, door := doorCallerFrom(r.Context())
if door || hopDoorFrom(r.Context()) || fromTunnel(r.Context()) || hopPresent && !hopped {
demoAPIUnavailable(dw)
@@ -272,6 +281,8 @@ type demoAPIResponseWriter struct {
header http.Header
committed bool
trailers []string
+ // body is the HTTP/1 request body still being relayed, nil otherwise.
+ body *streamedBody
}
func (w *demoAPIResponseWriter) Header() http.Header { return w.header }
@@ -291,6 +302,10 @@ func (w *demoAPIResponseWriter) WriteHeader(code int) {
}
if code >= 200 {
w.committed = true
+ if w.body != nil && !w.body.done.Load() {
+ dst.Set("Connection", "close")
+ w.body.closing.Store(true)
+ }
for _, v := range h.Values("Trailer") {
for _, n := range strings.Split(v, ",") {
w.trailers = append(w.trailers, http.CanonicalHeaderKey(strings.TrimSpace(n)))
diff --git a/internal/edge/demo_api_duplex_test.go b/internal/edge/demo_api_duplex_test.go
new file mode 100644
index 000000000..a3b6c5da4
--- /dev/null
+++ b/internal/edge/demo_api_duplex_test.go
@@ -0,0 +1,510 @@
+package edge
+
+import (
+ "bufio"
+ "crypto/tls"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "slices"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// #1248: the demo API alias turns on full duplex and leaves the connection
+// open for another request. These tests answer a request while its body is
+// still arriving, finish the body, and send a second request on the same
+// connection. Run them with -race.
+
+// How the console answers the upload before it has read it.
+type demoDuplexConsole int
+
+const (
+ // Answers with Connection: close and returns, with the body unread: how
+ // a plain net/http handler refuses an upload without waiting for it.
+ demoConsoleAnswersAndReturns demoDuplexConsole = iota
+ // Answers, then reads the rest of the body.
+ demoConsoleAnswersThenReads
+ // Answers whole on the raw connection, and holds it open unread.
+ demoConsoleAnswersAndHolds
+ // Answers with Connection: close and closes.
+ demoConsoleAnswersAndCloses
+)
+
+func (c demoDuplexConsole) String() string {
+ return [...]string{"answers-and-returns", "answers-then-reads", "answers-and-holds", "answers-and-closes"}[c]
+}
+
+// A request hidden in the tail of the upload: it is body, and must never be
+// parsed as a request of its own.
+const demoDuplexSmuggled = "/api/demo/jobs/smuggled"
+
+const demoDuplexRefusal = "refused"
+
+type demoDuplexScene struct {
+ console atomic.Int32
+ done atomic.Pointer[chan struct{}]
+ mu sync.Mutex
+ seen []string
+ held []net.Conn
+}
+
+func (s *demoDuplexScene) paths() []string {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return slices.Clone(s.seen)
+}
+
+func (s *demoDuplexScene) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ s.mu.Lock()
+ s.seen = append(s.seen, r.URL.Path)
+ s.mu.Unlock()
+ if r.Method != http.MethodPost {
+ io.WriteString(w, "second")
+ return
+ }
+ mode := demoDuplexConsole(s.console.Load())
+ if mode == demoConsoleAnswersAndHolds || mode == demoConsoleAnswersAndCloses {
+ conn, _, err := http.NewResponseController(w).Hijack()
+ if err != nil {
+ panic(err)
+ }
+ head := "HTTP/1.1 403 Forbidden\r\nContent-Length: " + fmt.Sprint(len(demoDuplexRefusal)) + "\r\n"
+ if mode == demoConsoleAnswersAndCloses {
+ io.WriteString(conn, head+"Connection: close\r\n\r\n"+demoDuplexRefusal)
+ conn.Close()
+ return
+ }
+ io.WriteString(conn, head+"\r\n"+demoDuplexRefusal)
+ s.mu.Lock()
+ s.held = append(s.held, conn)
+ s.mu.Unlock()
+ return
+ }
+ rc := http.NewResponseController(w)
+ if mode == demoConsoleAnswersAndReturns {
+ w.Header().Set("Connection", "close")
+ w.WriteHeader(http.StatusForbidden)
+ io.WriteString(w, demoDuplexRefusal)
+ return
+ }
+ if err := rc.EnableFullDuplex(); err != nil {
+ panic(err)
+ }
+ // A declared length ends the answer for the client while this handler
+ // is still reading the upload.
+ w.Header().Set("Content-Length", fmt.Sprint(len(demoDuplexRefusal)))
+ w.WriteHeader(http.StatusForbidden)
+ io.WriteString(w, demoDuplexRefusal)
+ rc.Flush()
+ if mode == demoConsoleAnswersThenReads {
+ io.Copy(io.Discard, r.Body)
+ }
+}
+
+func (s *demoDuplexScene) closeHeld() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ for _, c := range s.held {
+ c.Close()
+ }
+ s.held = nil
+}
+
+// When the client sends the rest of the upload.
+type demoDuplexTiming int
+
+const (
+ // As soon as it has read the answer.
+ demoSendsAfterAnswer demoDuplexTiming = iota
+ // Once the edge's handler has returned.
+ demoSendsAfterHandler
+ // As soon as it has read the answer, with the second request in the same
+ // write.
+ demoSendsPipelined
+ // Before any answer: the whole upload and the second request in one
+ // write, so the transport is still copying the body as the handler ends.
+ demoSendsWhole
+)
+
+func (d demoDuplexTiming) String() string {
+ return [...]string{"after-answer", "after-handler", "pipelined", "whole"}[d]
+}
+
+type demoDuplexCase struct {
+ console demoDuplexConsole
+ timing demoDuplexTiming
+ chunked bool
+ expect bool
+ // padding is added to the upload's tail, past net/http's post-handler
+ // read limit when it is large.
+ padding int
+}
+
+func (c demoDuplexCase) name() string {
+ name := c.console.String() + "/" + c.timing.String()
+ if c.chunked {
+ name += "/chunked"
+ }
+ if c.expect {
+ name += "/expect-continue"
+ }
+ if c.padding > 0 {
+ name += "/large"
+ }
+ return name
+}
+
+// demoDuplexGone is whether err is the far side having closed the connection.
+func demoDuplexGone(err error) bool {
+ return errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, net.ErrClosed) ||
+ errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.EPIPE)
+}
+
+// runDemoDuplexCase drives one connection and reports whether the edge
+// reused it ("reused") or closed it ("closed"). Anything else fails the test:
+// a wrong answer, a stall, or the upload's tail parsed as a request.
+func runDemoDuplexCase(t *testing.T, conn net.Conn, s *demoDuplexScene, c demoDuplexCase, handlerDone <-chan struct{}) string {
+ t.Helper()
+ if err := conn.SetDeadline(time.Now().Add(8 * time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ first := "first-part-"
+ rest := strings.Repeat("x", c.padding) + "\r\n\r\nGET " + demoDuplexSmuggled + " HTTP/1.1\r\nHost: " + demoAPISite + "\r\n\r\n"
+ head := "POST /api/demo/apps HTTP/1.1\r\nHost: " + demoAPISite + "\r\nContent-Type: application/json\r\n"
+ if c.expect {
+ head += "Expect: 100-continue\r\n"
+ }
+ var opening, closing string
+ if c.chunked {
+ opening = head + "Transfer-Encoding: chunked\r\n\r\n" + fmt.Sprintf("%x\r\n%s\r\n", len(first), first)
+ closing = fmt.Sprintf("%x\r\n%s\r\n0\r\n\r\n", len(rest), rest)
+ } else {
+ opening = head + fmt.Sprintf("Content-Length: %d\r\n\r\n", len(first)+len(rest)) + first
+ closing = rest
+ }
+ second := "GET /api/demo/jobs/second HTTP/1.1\r\nHost: " + demoAPISite + "\r\n\r\n"
+ if c.timing == demoSendsWhole {
+ opening += closing + second
+ }
+
+ if _, err := io.WriteString(conn, opening); err != nil {
+ t.Fatalf("sending the start of the upload: %v", err)
+ }
+ br := bufio.NewReader(conn)
+ resp, err := http.ReadResponse(br, &http.Request{Method: http.MethodPost})
+ for err == nil && resp.StatusCode < 200 {
+ resp, err = http.ReadResponse(br, &http.Request{Method: http.MethodPost})
+ }
+ if err != nil {
+ t.Fatalf("the early answer: %v", err)
+ }
+ body, err := io.ReadAll(resp.Body)
+ if err != nil || resp.StatusCode != http.StatusForbidden || string(body) != demoDuplexRefusal {
+ t.Fatalf("the early answer: %d %q, %v", resp.StatusCode, body, err)
+ }
+ // Sent before the upload ended, the answer must end the connection.
+ if c.timing != demoSendsWhole && !resp.Close {
+ t.Fatal("an answer that beat the upload left the connection open")
+ }
+
+ if c.timing == demoSendsAfterHandler {
+ select {
+ case <-handlerDone:
+ case <-time.After(15 * time.Second):
+ t.Fatal("the edge's handler did not return after the answer")
+ }
+ }
+ var wrote error
+ if c.timing == demoSendsWhole {
+ // Everything is on its way already.
+ } else if c.timing == demoSendsPipelined {
+ _, wrote = io.WriteString(conn, closing+second)
+ } else if _, wrote = io.WriteString(conn, closing); wrote == nil {
+ _, wrote = io.WriteString(conn, second)
+ }
+ if wrote != nil {
+ if !demoDuplexGone(wrote) {
+ t.Fatalf("sending the rest: %v", wrote)
+ }
+ return "closed"
+ }
+ next, err := http.ReadResponse(br, &http.Request{Method: http.MethodGet})
+ if err != nil {
+ if !demoDuplexGone(err) {
+ t.Fatalf("the second answer: %v", err)
+ }
+ return "closed"
+ }
+ got, err := io.ReadAll(next.Body)
+ if err != nil || next.StatusCode != http.StatusOK || string(got) != "second" {
+ t.Fatalf("the second request was answered %d %q, %v", next.StatusCode, got, err)
+ }
+ return "reused"
+}
+
+func checkDemoDuplexPaths(t *testing.T, s *demoDuplexScene, outcome string) {
+ t.Helper()
+ paths := s.paths()
+ if slices.Contains(paths, demoDuplexSmuggled) {
+ t.Fatalf("the upload's tail reached the console as a request: %v", paths)
+ }
+ if outcome == "reused" && !slices.Contains(paths, "/api/demo/jobs/second") {
+ t.Fatalf("a second answer with no second request at the console: %v", paths)
+ }
+}
+
+func checkDemoDuplexLog(t *testing.T, who string, logs *lockedBuffer) {
+ t.Helper()
+ if text := logs.String(); strings.Contains(text, "panic") {
+ t.Fatalf("net/http panicked in %s:\n%s", who, text)
+ }
+}
+
+func demoDuplexCases() []demoDuplexCase {
+ var cases []demoDuplexCase
+ for _, console := range []demoDuplexConsole{demoConsoleAnswersAndReturns, demoConsoleAnswersThenReads, demoConsoleAnswersAndHolds, demoConsoleAnswersAndCloses} {
+ // The handler lingers for its bound here, so one case is enough.
+ cases = append(cases, demoDuplexCase{console: console, timing: demoSendsAfterHandler})
+ for _, timing := range []demoDuplexTiming{demoSendsAfterAnswer, demoSendsPipelined} {
+ cases = append(cases,
+ demoDuplexCase{console: console, timing: timing},
+ demoDuplexCase{console: console, timing: timing, chunked: true},
+ demoDuplexCase{console: console, timing: timing, expect: true},
+ // More than net/http will read for a handler that has returned.
+ demoDuplexCase{console: console, timing: timing, padding: 512 << 10},
+ )
+ }
+ // A console closing on an unread upload may reset its own answer away,
+ // and one holding its connection promised a keep-alive it will not
+ // serve: with the whole upload written, the transport would reuse it.
+ if console != demoConsoleAnswersAndCloses && console != demoConsoleAnswersAndHolds {
+ cases = append(cases, demoDuplexCase{console: console, timing: demoSendsWhole, padding: 128 << 10})
+ }
+ }
+ return cases
+}
+
+// The console is on this box: the alias's own reverse proxy.
+func TestDemoAPIAliasEarlyAnswerKeepAliveLocal(t *testing.T) {
+ logs := captureLog(t)
+ demoAPISettings(t)
+ e, err := New(openReg(t), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ demoAPIArm(t, e)
+ s := &demoDuplexScene{}
+ t.Cleanup(s.closeHeld)
+ demoAPIBackend(t, e, s)
+ front := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ done := s.done.Load()
+ e.ServeHTTP(w, r)
+ if r.Method == http.MethodPost && done != nil {
+ close(*done)
+ }
+ }))
+ // Apart from the console's log: this is the connection under test.
+ edgeLogs := &lockedBuffer{}
+ front.Config.ErrorLog = log.New(edgeLogs, "", 0)
+ front.Start()
+ t.Cleanup(front.Close)
+ for _, c := range demoDuplexCases() {
+ t.Run(c.name(), func(t *testing.T) {
+ logs.Reset()
+ edgeLogs.Reset()
+ // The transport may have pooled a held connection, and the console
+ // will never answer on it again.
+ t.Cleanup(s.closeHeld)
+ s.console.Store(int32(c.console))
+ done := make(chan struct{})
+ s.done.Store(&done)
+ conn, err := net.Dial("tcp", front.Listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ outcome := runDemoDuplexCase(t, conn, s, c, done)
+ t.Logf("connection %s", outcome)
+ checkDemoDuplexPaths(t, s, outcome)
+ checkDemoDuplexLog(t, "the edge's server", edgeLogs)
+ checkDemoDuplexLog(t, "the console", logs)
+ })
+ }
+}
+
+// The console is on another box: the alias hops to it over the backhaul.
+func TestDemoAPIAliasEarlyAnswerKeepAliveHop(t *testing.T) {
+ logs := captureLog(t)
+ s := &demoDuplexScene{}
+ t.Cleanup(s.closeHeld)
+ scene := NewDemoAPITestIngress(t, s, release.NewDirStore(t.TempDir()))
+ for _, c := range demoDuplexCases() {
+ // This ingress offers no signal for its handler returning.
+ if c.timing == demoSendsAfterHandler {
+ continue
+ }
+ t.Run(c.name(), func(t *testing.T) {
+ logs.Reset()
+ // The transport may have pooled a held connection, and the console
+ // will never answer on it again.
+ t.Cleanup(s.closeHeld)
+ s.console.Store(int32(c.console))
+ conn, err := tls.Dial("tcp", scene.servers[1].Listener.Addr().String(), &tls.Config{RootCAs: scene.ca.pool, ServerName: demoAPISite, MinVersion: tls.VersionTLS12, NextProtos: []string{"http/1.1"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ outcome := runDemoDuplexCase(t, conn, s, c, nil)
+ t.Logf("connection %s", outcome)
+ checkDemoDuplexPaths(t, s, outcome)
+ checkDemoDuplexLog(t, "an edge or the console", logs)
+ })
+ }
+}
+
+// demoDuplexLocalFront is the alias on a real HTTP/1.1 server, with the
+// console on this box.
+func demoDuplexLocalFront(t *testing.T, s *demoDuplexScene) *httptest.Server {
+ t.Helper()
+ demoAPISettings(t)
+ e, err := New(openReg(t), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ demoAPIArm(t, e)
+ t.Cleanup(s.closeHeld)
+ demoAPIBackend(t, e, s)
+ front := httptest.NewServer(e)
+ t.Cleanup(front.Close)
+ return front
+}
+
+// demoStalledCloseTolerance is what a loaded runner may add to
+// exitLingerBound between the edge's deadline and the client seeing the close.
+const demoStalledCloseTolerance = 2 * time.Second
+
+// checkDemoStalledUploadCloses sends the start of an upload, reads the early
+// answer and sends nothing more. The clock starts when the whole answer has
+// arrived, so a slow setup takes nothing from the cleanup's allowance.
+func checkDemoStalledUploadCloses(t *testing.T, conn net.Conn, framing string) {
+ t.Helper()
+ if err := conn.SetDeadline(time.Now().Add(time.Minute)); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := io.WriteString(conn, "POST /api/demo/apps HTTP/1.1\r\nHost: "+demoAPISite+"\r\n"+framing); err != nil {
+ t.Fatal(err)
+ }
+ br := bufio.NewReader(conn)
+ resp, err := http.ReadResponse(br, &http.Request{Method: http.MethodPost})
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, err := io.ReadAll(resp.Body)
+ answered := time.Now()
+ if err != nil || resp.StatusCode != http.StatusForbidden || string(body) != demoDuplexRefusal || !resp.Close {
+ t.Fatalf("the early answer: %d %q close=%v, %v", resp.StatusCode, body, resp.Close, err)
+ }
+ // Long enough to report how late a slow close was.
+ if err := conn.SetReadDeadline(answered.Add(30 * time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := br.ReadByte(); !demoDuplexGone(err) {
+ t.Fatalf("the stalled connection after %s: %v, want it closed", time.Since(answered), err)
+ }
+ if took, limit := time.Since(answered), exitLingerBound+demoStalledCloseTolerance; took > limit {
+ t.Fatalf("the stalled connection closed %s after the answer, want at most %s", took, limit)
+ }
+}
+
+// A client that stops sending after the early answer does not hold the
+// connection: the edge closes it at the linger bound.
+func TestDemoAPIAliasEarlyAnswerStalledUploadCloses(t *testing.T) {
+ framings := []struct{ name, start string }{
+ {"content-length", "Content-Length: 100\r\n\r\nstart"},
+ {"chunked", "Transfer-Encoding: chunked\r\n\r\n5\r\nstart\r\n"},
+ }
+ t.Run("local", func(t *testing.T) {
+ front := demoDuplexLocalFront(t, &demoDuplexScene{})
+ for _, f := range framings {
+ t.Run(f.name, func(t *testing.T) {
+ conn, err := net.Dial("tcp", front.Listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ checkDemoStalledUploadCloses(t, conn, f.start)
+ })
+ }
+ })
+ t.Run("backhaul", func(t *testing.T) {
+ scene := NewDemoAPITestIngress(t, &demoDuplexScene{}, release.NewDirStore(t.TempDir()))
+ for _, f := range framings {
+ t.Run(f.name, func(t *testing.T) {
+ conn, err := tls.Dial("tcp", scene.servers[1].Listener.Addr().String(), &tls.Config{RootCAs: scene.ca.pool, ServerName: demoAPISite, MinVersion: tls.VersionTLS12, NextProtos: []string{"http/1.1"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ checkDemoStalledUploadCloses(t, conn, f.start)
+ })
+ }
+ })
+}
+
+// An upload the console read to its end before answering keeps its
+// connection, as every ordinary request does.
+func TestDemoAPIAliasWholeUploadKeepsConnection(t *testing.T) {
+ var calls atomic.Int32
+ reader := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ io.Copy(io.Discard, r.Body)
+ io.WriteString(w, "ok")
+ })
+ demoAPISettings(t)
+ e, err := New(openReg(t), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ demoAPIArm(t, e)
+ demoAPIBackend(t, e, reader)
+ front := httptest.NewServer(e)
+ t.Cleanup(front.Close)
+ conn, err := net.Dial("tcp", front.Listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ if err := conn.SetDeadline(time.Now().Add(10 * time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ br := bufio.NewReader(conn)
+ for _, framing := range []string{"Content-Length: 5\r\n\r\nhello", "Transfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n\r\n"} {
+ if _, err := io.WriteString(conn, "POST /api/demo/apps HTTP/1.1\r\nHost: "+demoAPISite+"\r\n"+framing); err != nil {
+ t.Fatal(err)
+ }
+ resp, err := http.ReadResponse(br, &http.Request{Method: http.MethodPost})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if body, err := io.ReadAll(resp.Body); err != nil || string(body) != "ok" || resp.Close {
+ t.Fatalf("%q: answer %q close=%v, %v", framing, body, resp.Close, err)
+ }
+ }
+ if calls.Load() != 2 {
+ t.Fatalf("%d requests reached the console on one connection, want 2", calls.Load())
+ }
+}
diff --git a/internal/host/replicaplacement.go b/internal/host/replicaplacement.go
index ad40559be..c145fadfd 100644
--- a/internal/host/replicaplacement.go
+++ b/internal/host/replicaplacement.go
@@ -3,6 +3,7 @@ package host
import (
"context"
"errors"
+ "log"
"net/http"
"slices"
"strings"
@@ -21,6 +22,9 @@ type replicaPlacementWork struct {
retry time.Time
delay time.Duration
done bool
+ // logged: this backoff step has reported its failure. A step ends when
+ // the backoff advances; attempts a moved record repeats at once share it.
+ logged bool
}
type replicaPlacementWorker struct {
@@ -57,6 +61,7 @@ func (w *replicaPlacementWorker) observe(rec provision.Record) {
old.retry = time.Time{}
old.delay = 0
old.done = false
+ old.logged = false
}
old.rec = rec
w.pending[rec.Host] = old
@@ -103,14 +108,24 @@ func (w *replicaPlacementWorker) run(ctx context.Context, now time.Time) {
}
inc, err := provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
if err != nil {
+ // Skipped with no backoff, so every tick comes back here: one line
+ // for each assignment.
+ if w.firstSkipReport(rec) {
+ logReplicaPlacementFailure(rec.Host, "incarnation", err)
+ }
continue
}
id := replicas.Identity{Account: rec.Account, App: rec.App, Host: rec.Host, Incarnation: inc}
rctx, cancel := context.WithTimeout(ctx, 30*time.Second)
done := false
+ var step string
+ var failure error
// Serialize local removal/proof against reconcile minting a new lifetime.
reconcileMu.Lock()
rt, err := w.reg.Get(rec.Host)
+ if err != nil {
+ step, failure = "read route", err
+ }
proven := false
if err == nil && slices.Contains(a.Retiring, w.box) && rt == nil && w.quiet != nil && w.quiet(rec.Host) && w.empty != nil {
proof := provision.RouteFor(rec, w.dataDir, "", false, nil)
@@ -120,31 +135,72 @@ func (w *replicaPlacementWorker) run(ctx context.Context, now time.Time) {
if proven && w.retired != nil {
err = w.retired(rctx, id, a.Revision)
done = err == nil || errors.Is(err, replicas.ErrFenced)
+ if !done {
+ step, failure = "retire", err
+ }
} else if err == nil && a.Contains(w.box) && rt != nil && rt.ReplicaIncarnation == inc && rt.ReplicaRevision == a.Revision && provision.ReplicaCoordinatorBox(&rec, now) == w.box && w.coordinator != nil {
- if _, err = w.coordinator.Acquire(rctx, id); err == nil && w.publisher != nil {
+ if _, err = w.coordinator.Acquire(rctx, id); err != nil {
+ step, failure = "acquire", err
+ } else if w.publisher != nil {
// Acquire's new term reaches the publisher through the next record pass.
// publishCurrent answers false with every error, so done alone
- // decides the retry. Like Acquire's, the error is not logged.
- done, _ = w.publisher.publishCurrent(rctx, rec, *rt)
+ // decides the retry.
+ if done, err = w.publisher.publishCurrent(rctx, rec, *rt); err != nil {
+ step, failure = "publish", err
+ }
}
}
cancel()
w.mu.Lock()
current := w.pending[rec.Host]
- if current.rec.RecordSeq == rec.RecordSeq && current.rec.CreatedAt == rec.CreatedAt && current.rec.ReplicaAssignment != nil && current.rec.ReplicaAssignment.Revision == a.Revision {
+ sameAssignment := current.rec.CreatedAt == rec.CreatedAt && current.rec.ReplicaAssignment != nil && current.rec.ReplicaAssignment.Revision == a.Revision
+ // An attempt the assignment has moved past answers for its own step.
+ logged := p.logged
+ if sameAssignment {
+ logged = current.logged
+ }
+ // A worker stopping fails what it was doing; that is not news.
+ report := failure != nil && !logged && ctx.Err() == nil
+ if sameAssignment && current.rec.RecordSeq == rec.RecordSeq {
if done {
current.done = true
w.pending[rec.Host] = current
} else {
p.delay = min(max(p.delay*2, time.Second), time.Minute)
p.retry = now.Add(p.delay)
+ p.logged = false
w.pending[rec.Host] = p
}
+ } else if sameAssignment && report {
+ current.logged = true
+ w.pending[rec.Host] = current
}
w.mu.Unlock()
+ if report {
+ logReplicaPlacementFailure(rec.Host, step, failure)
+ }
}
}
+// firstSkipReport says whether rec's assignment has yet to report a failure
+// that skips the attempt, and marks it reported. observe clears the mark when
+// the assignment changes.
+func (w *replicaPlacementWorker) firstSkipReport(rec provision.Record) bool {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ current, ok := w.pending[rec.Host]
+ if !ok || current.logged || current.rec.CreatedAt != rec.CreatedAt || current.rec.ReplicaAssignment == nil || current.rec.ReplicaAssignment.Revision != rec.ReplicaAssignment.Revision {
+ return false
+ }
+ current.logged = true
+ w.pending[rec.Host] = current
+ return true
+}
+
+func logReplicaPlacementFailure(host, step string, err error) {
+ log.Printf("agent: replica placement %s: %s failed, will retry: %v", host, step, err)
+}
+
func newReplicaPlacementWorker(ctx context.Context, reg *registry.Registry, svc *activator.Service, backend *activator.ExecBackend, publisher *statelessBindingPublisher, base, token, dataDir string) *replicaPlacementWorker {
ctx, cancel := context.WithCancel(ctx)
api := &replicaCoordinatorAPI{base: strings.TrimRight(base, "/"), fleet: publisher.fleet, box: publisher.box, token: token, client: &http.Client{Timeout: 30 * time.Second}}
diff --git a/internal/host/replicaplacement_log_test.go b/internal/host/replicaplacement_log_test.go
new file mode 100644
index 000000000..c2b039c37
--- /dev/null
+++ b/internal/host/replicaplacement_log_test.go
@@ -0,0 +1,282 @@
+package host
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+const replicaPlacementLogPrefix = "agent: replica placement "
+
+// replicaRetiringWorker is a worker whose only work is to report rec's host
+// retired from box a, through retired.
+func replicaRetiringWorker(t *testing.T, retired func(context.Context, replicas.Identity, uint64) error) (*replicaPlacementWorker, provision.Record) {
+ t.Helper()
+ rec := provision.Record{Account: "bab", App: "shop", Host: "shop.example.com", Region: "fleet/pi", CreatedAt: time.Unix(1, 0), RecordSeq: 1, ReplicaAssignment: &replicas.Assignment{Revision: 3, Desired: 1, Boxes: []string{"b"}, Retiring: []string{"a"}}}
+ w := &replicaPlacementWorker{reg: testRegistry(t), box: "a", quiet: func(string) bool { return true }, empty: func(registry.Route) error { return nil }, retired: retired}
+ w.observe(rec)
+ return w, rec
+}
+
+// A placement that keeps failing says so once for each wait of its backoff,
+// with the host, the step and the error.
+func TestReplicaPlacementLogsOncePerBackoffStep(t *testing.T) {
+ logs := captureLogBuffer(t)
+ ctx := context.Background()
+ attempts := 0
+ w, rec := replicaRetiringWorker(t, func(context.Context, replicas.Identity, uint64) error {
+ attempts++
+ return errors.New("console said no")
+ })
+ now := time.Now()
+ for _, c := range []struct {
+ at time.Duration
+ attempts int
+ }{
+ {0, 1},
+ {0, 1}, // inside the first second's wait
+ {time.Second, 2},
+ {2 * time.Second, 2}, // the wait is two seconds now
+ {3 * time.Second, 3},
+ {6 * time.Second, 3},
+ {7 * time.Second, 4},
+ } {
+ w.run(ctx, now.Add(c.at))
+ if attempts != c.attempts {
+ t.Fatalf("at +%s: %d attempts, want %d: the backoff changed", c.at, attempts, c.attempts)
+ }
+ if got := logs.count(replicaPlacementLogPrefix); got != c.attempts {
+ t.Fatalf("at +%s: %d lines for %d backoff steps:\n%s", c.at, got, c.attempts, logs.String())
+ }
+ }
+ line, _, _ := strings.Cut(logs.String(), "\n")
+ for _, want := range []string{rec.Host, "retire", "console said no"} {
+ if !strings.Contains(line, want) {
+ t.Errorf("log line %q does not name %q", line, want)
+ }
+ }
+}
+
+// A record that moves while an attempt is out leaves the backoff where it
+// was, so the next tick tries again at once. Those attempts share one step
+// and one line, however many there are.
+func TestReplicaPlacementTightRetryLoopLogsOnce(t *testing.T) {
+ logs := captureLogBuffer(t)
+ ctx := context.Background()
+ attempts := 0
+ var moved func()
+ w, rec := replicaRetiringWorker(t, func(context.Context, replicas.Identity, uint64) error {
+ attempts++
+ if moved != nil {
+ moved()
+ }
+ return errors.New("console said no")
+ })
+ moved = func() {
+ rec.RecordSeq++
+ w.observe(rec)
+ }
+ now := time.Now()
+ for i := 1; i <= 20; i++ {
+ w.run(ctx, now)
+ if attempts != i {
+ t.Fatalf("pass %d: %d attempts: a moved record must still retry at once", i, attempts)
+ }
+ }
+ if got := logs.count(replicaPlacementLogPrefix); got != 1 {
+ t.Fatalf("%d lines for 20 attempts in one backoff step, want 1:\n%s", got, logs.String())
+ }
+
+ // With the record still, this attempt ends the step: it has been logged
+ // already, and the next step gets its own line.
+ moved = nil
+ w.run(ctx, now)
+ if p := w.pending[rec.Host]; p.delay != time.Second || !p.retry.Equal(now.Add(time.Second)) {
+ t.Fatalf("backoff after the step: delay %s, retry %s", p.delay, p.retry.Sub(now))
+ }
+ if got := logs.count(replicaPlacementLogPrefix); got != 1 {
+ t.Fatalf("%d lines after the step ended, want 1:\n%s", got, logs.String())
+ }
+ w.run(ctx, now.Add(time.Second))
+ if got := logs.count(replicaPlacementLogPrefix); got != 2 {
+ t.Fatalf("%d lines in the second step, want 2:\n%s", got, logs.String())
+ }
+
+ // A new revision starts its backoff again, and its first failure is news.
+ next := *rec.ReplicaAssignment
+ next.Revision++
+ rec.ReplicaAssignment = &next
+ rec.RecordSeq++
+ w.observe(rec)
+ w.run(ctx, now.Add(time.Second))
+ if got := logs.count(replicaPlacementLogPrefix); got != 3 {
+ t.Fatalf("%d lines after a new revision, want 3:\n%s", got, logs.String())
+ }
+}
+
+// A registry that cannot answer is a failure of its own, not an absent route:
+// it is named once per backoff step, and the backoff runs as it always did.
+func TestReplicaPlacementLogsRegistryFailure(t *testing.T) {
+ logs := captureLogBuffer(t)
+ ctx := context.Background()
+ w, rec := replicaRetiringWorker(t, func(context.Context, replicas.Identity, uint64) error {
+ t.Error("retired with no route read")
+ return nil
+ })
+ if err := w.reg.Close(); err != nil {
+ t.Fatal(err)
+ }
+ _, cause := w.reg.Get(rec.Host)
+ if cause == nil {
+ t.Fatal("a closed registry answered")
+ }
+ now := time.Now()
+ for _, c := range []struct {
+ at, delay, retry time.Duration
+ lines int
+ }{
+ {0, time.Second, time.Second, 1},
+ {0, time.Second, time.Second, 1}, // inside the first wait
+ {time.Second, 2 * time.Second, 3 * time.Second, 2},
+ {2 * time.Second, 2 * time.Second, 3 * time.Second, 2}, // inside the second
+ {3 * time.Second, 4 * time.Second, 7 * time.Second, 3},
+ } {
+ w.run(ctx, now.Add(c.at))
+ if p := w.pending[rec.Host]; p.delay != c.delay || !p.retry.Equal(now.Add(c.retry)) {
+ t.Fatalf("at +%s: delay %s, retry +%s, want %s and +%s", c.at, p.delay, p.retry.Sub(now), c.delay, c.retry)
+ }
+ if got := logs.count(replicaPlacementLogPrefix); got != c.lines {
+ t.Fatalf("at +%s: %d lines, want %d:\n%s", c.at, got, c.lines, logs.String())
+ }
+ }
+ line, _, _ := strings.Cut(logs.String(), "\n")
+ for _, want := range []string{rec.Host, "read route", cause.Error()} {
+ if !strings.Contains(line, want) {
+ t.Errorf("log line %q does not name %q", line, want)
+ }
+ }
+}
+
+// A record whose lifetime cannot be worked out is skipped on every tick, with
+// no backoff to pace a log line: it says so once for each assignment.
+func TestReplicaPlacementLogsIncarnationFailureOnce(t *testing.T) {
+ logs := captureLogBuffer(t)
+ ctx := context.Background()
+ w, rec := replicaRetiringWorker(t, func(context.Context, replicas.Identity, uint64) error {
+ t.Error("retired with no lifetime")
+ return nil
+ })
+ rec.Account, rec.CreatedAt = "NOT VALID", time.Time{}
+ w.observe(rec)
+ now := time.Now()
+ for i := range 5 {
+ w.run(ctx, now.Add(time.Duration(i)*time.Minute))
+ }
+ if got := logs.count(replicaPlacementLogPrefix); got != 1 {
+ t.Fatalf("%d lines for five skipped ticks, want 1:\n%s", got, logs.String())
+ }
+ for _, want := range []string{rec.Host, "incarnation", provision.ErrMalformedIncarnation.Error()} {
+ if !strings.Contains(logs.String(), want) {
+ t.Errorf("log %q does not name %q", logs.String(), want)
+ }
+ }
+ if p := w.pending[rec.Host]; p.delay != 0 || !p.retry.IsZero() {
+ t.Fatalf("a skipped record gained a backoff: delay %s, retry %s", p.delay, p.retry)
+ }
+ next := *rec.ReplicaAssignment
+ next.Revision++
+ rec.ReplicaAssignment = &next
+ w.observe(rec)
+ w.run(ctx, now)
+ if got := logs.count(replicaPlacementLogPrefix); got != 2 {
+ t.Fatalf("%d lines after a new revision, want 2:\n%s", got, logs.String())
+ }
+}
+
+// What is not a failure to retry is not logged as one.
+func TestReplicaPlacementQuietWhenNothingFailed(t *testing.T) {
+ t.Run("a fenced retirement is finished", func(t *testing.T) {
+ logs := captureLogBuffer(t)
+ w, rec := replicaRetiringWorker(t, func(context.Context, replicas.Identity, uint64) error { return replicas.ErrFenced })
+ w.run(context.Background(), time.Now())
+ if !w.pending[rec.Host].done || logs.count(replicaPlacementLogPrefix) != 0 {
+ t.Fatalf("done %v, log:\n%s", w.pending[rec.Host].done, logs.String())
+ }
+ })
+ t.Run("the worker stopping", func(t *testing.T) {
+ logs := captureLogBuffer(t)
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ w, _ := replicaRetiringWorker(t, func(ctx context.Context, _ replicas.Identity, _ uint64) error { return ctx.Err() })
+ w.run(ctx, time.Now())
+ if logs.count(replicaPlacementLogPrefix) != 0 {
+ t.Fatalf("shutdown logged as a failure:\n%s", logs.String())
+ }
+ })
+}
+
+// placementPutRefusal refuses every write.
+type placementPutRefusal struct {
+ release.Store
+ err error
+}
+
+func (s *placementPutRefusal) Put(context.Context, string, []byte, string) (string, error) {
+ return "", s.err
+}
+
+// The coordinator's two steps name themselves.
+func TestReplicaPlacementLogsCoordinatorSteps(t *testing.T) {
+ now := time.Now()
+ lease := replicas.Coordinator{Term: "term", Box: "a", BootID: "boot", ExpiresAt: now.Add(time.Hour)}
+ for _, c := range []struct {
+ name, step, cause string
+ acquire error
+ put error
+ }{
+ {name: "acquire", step: "acquire", cause: "no coordinator today", acquire: errors.New("no coordinator today")},
+ {name: "publish", step: "publish", cause: "bucket refused", put: errors.New("bucket refused")},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ logs := captureLogBuffer(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ reg := testRegistry(t)
+ rec := provision.Record{Account: "bab", App: "shop", Host: "shop.example.com", Region: "fleet/pi", FleetBox: "a", CreatedAt: time.Unix(1, 0), Hibernate: new(bool), RecordSeq: 1, Coordinator: &lease, ReplicaAssignment: &replicas.Assignment{Revision: 1, Desired: 2, Boxes: []string{"a", "b"}}}
+ client := activator.NewCoordinatorClient("a", "boot", func(context.Context, replicas.Identity, replicas.CoordinatorChange) (replicas.CoordinatorReply, error) {
+ if c.acquire != nil {
+ return replicas.CoordinatorReply{}, c.acquire
+ }
+ return replicas.CoordinatorReply{Lease: lease, RemainingMS: replicas.CoordinatorTTL.Milliseconds()}, nil
+ }, nil)
+ defer client.Close(ctx)
+ store := &placementPutRefusal{Store: release.NewDirStore(t.TempDir()), err: c.put}
+ w := &replicaPlacementWorker{reg: reg, box: "a", coordinator: client, publisher: &statelessBindingPublisher{store: store, fleet: "pi", box: "a", coordinator: client}}
+ if err := reg.Upsert(provision.RouteFor(rec, t.TempDir(), "", false, nil)); err != nil {
+ t.Fatal(err)
+ }
+ w.observe(rec)
+ w.run(ctx, now)
+ w.run(ctx, now) // inside the wait
+ if got := logs.count(replicaPlacementLogPrefix); got != 1 {
+ t.Fatalf("%d lines, want 1:\n%s", got, logs.String())
+ }
+ for _, want := range []string{rec.Host, c.step, c.cause} {
+ if !strings.Contains(logs.String(), want) {
+ t.Errorf("log %q does not name %q", logs.String(), want)
+ }
+ }
+ if w.pending[rec.Host].done {
+ t.Fatal("a failed step counted as done")
+ }
+ })
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index f34c52319..940f64fd6 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -250,3 +250,4 @@ plan14-root-reads-aws-followups-1143.tsv 33e5eaaa9b2d80f6f8f5de8d04e908e39ecfc82
plan14-root-reads-fix-dbforward-reuse-1032.tsv ec3c40098ec0a652c735d54925f334b9b9680c9e2b6cd0c3d9497b8a615fb86f
plan14-root-reads-staticcheck-sa1012.tsv 5fcd060180e923773dad3faee7cc60ee250779a242b1dc14f4576f413dc8a774
plan14-root-reads-staticcheck-sa1019.tsv f9be26c06eb1c844b91a75f65faa51997048cb2900f3ed078be2ae28c65c0e98
+plan14-root-reads-small-fixes-1246-1248.tsv c6d366dcf2211b714977b7a69180289555b362dfe5f36a5780af90b5ece82998
diff --git a/internal/provision/testdata/plan14-root-reads-small-fixes-1246-1248.tsv b/internal/provision/testdata/plan14-root-reads-small-fixes-1246-1248.tsv
new file mode 100644
index 000000000..fdc88492c
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-small-fixes-1246-1248.tsv
@@ -0,0 +1,6 @@
+# Census overlay small-fixes-1246-1248, written by census-propose (#369). census-ruling-small-fixes-1246-1248, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-small-fixes-1246-1248.md.
+# 1 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@legacy 829a818bbf74f19a8c6c55d2dd6bb0b4c3e3ecd52e95255ac3f4916d7f844d4c internal/host/replicaplacement.go replicaPlacementWorker.run legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-2;basis=Final fix I3: retain completed lifetime/revision observations and skip their work; only confirmed current binding publication after coordinator acquisition, or existing successful/fenced retirement ACK, completes work. Existing local registry read, authority and retirement checks, and 30-second request deadline remain. No new reads or polling.;rev3=census-ruling-staticcheck-sa4006;basis=SA4006 dead store: publishCurrent's error is discarded explicitly (done, _ =) with a comment; it was assigned to err and never read, and publishCurrent returns false with every error, so done and the retry backoff are exactly as before. No read added, read sites unchanged (6).;rev3=census-ruling-small-fixes-1246-1248;basis=Logs the retire, acquire, publish, registry-read and incarnation failures it used to drop, throttled per backoff step (incarnation: per assignment), outside the worker lock. The retry decision, the incarnation skip, backoff arithmetic, deadlines and read sites are unchanged; no read added. registry:ReplicaIncarnation@1591,registry:ReplicaRevision@1623,whole:Route@1151,whole:Route@1303,whole:Route@1578,whole:Route@2097 fa330ce1355ac7df5d298a300e768ecd647e0eb9927d853ebea3881b51b2d09b
+internal/host/replicaplacement.go replicaPlacementWorker.run legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-2;basis=Final fix I3: retain completed lifetime/revision observations and skip their work; only confirmed current binding publication after coordinator acquisition, or existing successful/fenced retirement ACK, completes work. Existing local registry read, authority and retirement checks, and 30-second request deadline remain. No new reads or polling.;rev3=census-ruling-staticcheck-sa4006;basis=SA4006 dead store: publishCurrent's error is discarded explicitly (done, _ =) with a comment; it was assigned to err and never read, and publishCurrent returns false with every error, so done and the retry backoff are exactly as before. No read added, read sites unchanged (6).;rev3=census-ruling-small-fixes-1246-1248;basis=Logs the retire, acquire, publish, registry-read and incarnation failures it used to drop, throttled per backoff step (incarnation: per assignment), outside the worker lock. The retry decision, the incarnation skip, backoff arithmetic, deadlines and read sites are unchanged; no read added. registry:ReplicaIncarnation@1591,registry:ReplicaRevision@1623,whole:Route@1151,whole:Route@1303,whole:Route@1578,whole:Route@2097 fa330ce1355ac7df5d298a300e768ecd647e0eb9927d853ebea3881b51b2d09b
+@coverage internal/edge 1e5c93a58480e74ed8a19030c25220a30e324f8cd9ff78aea95026da4e7f213f
+@coverage internal/host 18c0b56671016a77b432c9d09a3b97fdb11e90897ec6aa010b30be314cd26518