carlos / platform Public

edge: hold a new name's first cert order until every edge knows it (#443)

Squashed from cert-warm-propagation-443 into main.
claude agent, operated by paul@keymail.dev 4638a74076ce08ecef6d6f0b3fdca7de201a180f parent 9665606
14 files changed, +1,354 −3
  • docs/superpowers/notes/census-proposal-cert-warm-propagation-443.md +11 −0
  • docs/superpowers/reviews/CODEX-CENSUS-BRIEF-cert-warm-443.md +27 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-cert-warm-443-R2.md +151 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-cert-warm-443-R3.md +158 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-cert-warm-443.md +128 −0
  • docs/superpowers/reviews/CODEX-REVIEW-cert-warm-443-R1.md +20 −0
  • docs/superpowers/reviews/CODEX-REVIEW-cert-warm-443-R2.md +18 −0
  • docs/superpowers/reviews/CODEX-REVIEW-cert-warm-443-R3.md +24 −0
  • internal/edge/certsettle.go +185 −0
  • internal/edge/certsettle_test.go +527 −0
  • internal/edge/certsync.go +13 −1
  • internal/edge/certwarm.go +88 −2
  • internal/provision/testdata/plan14-root-reads-cert-warm-propagation-443.tsv +3 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0

CI passed — run details

landed from cert-warm-propagation-443

diff --git a/docs/superpowers/notes/census-proposal-cert-warm-propagation-443.md b/docs/superpowers/notes/census-proposal-cert-warm-propagation-443.md
new file mode 100644
index 000000000..41900aa45
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-cert-warm-propagation-443.md
@@ -0,0 +1,11 @@
+# Census approval: cert-warm-propagation-443
+
+Ruling `census-ruling-cert-warm-propagation-443`. 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).
+
+Envelopes re-pinned: `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.
+
+Seal: `886863e79986b005cf52aa11445a49c1bbc3fb9b55bce25915fc21d0e65f1b7f` → `886863e79986b005cf52aa11445a49c1bbc3fb9b55bce25915fc21d0e65f1b7f`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-cert-warm-propagation-443.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/reviews/CODEX-CENSUS-BRIEF-cert-warm-443.md b/docs/superpowers/reviews/CODEX-CENSUS-BRIEF-cert-warm-443.md
new file mode 100644
index 000000000..4643c5a27
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-CENSUS-BRIEF-cert-warm-443.md
@@ -0,0 +1,27 @@
+# Census brief: cert-warm-propagation-443, envelope re-pin after merging main
+
+Repo carlos/platform, branch `cert-warm-propagation-443`, commit named in the
+reviewer's prompt. This is a CENSUS verdict only, not a code review round:
+the code review is closed (rounds 1-3, `CODEX-REVIEW-cert-warm-443-R{1,2,3}.md`),
+and Paul ruled on #443 to merge as it stands, with the round-3 P1 filed as #456.
+Do not report code findings.
+
+Why: Astra approved the `internal/edge` envelope at 212be158 (pin
+`f89991c6…`). Merging main 9665606d (#434, edge roll blip, which changed
+`internal/edge/edge.go` and carries its own approved overlay
+`plan14-root-reads-edge-roll-blip.tsv`) moved the package's combined digest,
+so `census-propose` re-pinned it to `68445819…` in
+`internal/provision/testdata/plan14-root-reads-cert-warm-propagation-443.tsv`,
+chained last after `plan14-root-reads-edge-roll-blip.tsv`. This branch's own
+`internal/edge` diff against main is unchanged since 212be158:
+`git diff origin/main...HEAD -- internal/edge` (certsettle.go, certsettle_test.go,
+certsync.go, certwarm.go).
+
+Check, per AGENTS.md "Getting a change approved": read every changed function
+in this branch's `internal/edge` diff against current main and what it
+reaches. Does it let 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, or weaken a check root relies on? Confirm the overlay is chained last
+and that `card docs/superpowers/notes/census-proposal-cert-warm-propagation-443.md`
+matches. Answer APPROVE or REJECT for the `internal/edge` envelope, citing the
+lines you read. Do not edit files.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-cert-warm-443-R2.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-cert-warm-443-R2.md
new file mode 100644
index 000000000..e7b97d06c
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-cert-warm-443-R2.md
@@ -0,0 +1,151 @@
+# Review brief: branch cert-warm-propagation-443 (#443), round 2 of 3
+
+Repo carlos/platform, branch `cert-warm-propagation-443`, commit named in
+the reviewer's prompt.
+Under review: the diff `origin/main..cert-warm-propagation-443`, which is
+`internal/edge/certsettle.go` (new), `internal/edge/certsync.go`
+(`issuerHostPolicy`), `internal/edge/certwarm.go` (`pass`, `settling`), the
+tests in `internal/edge/certsettle_test.go`, and the census overlay
+(`internal/provision/testdata/plan14-root-reads-cert-warm-propagation-443.tsv`,
+card `docs/superpowers/notes/census-proposal-cert-warm-propagation-443.md`).
+Authorities: the code on main. The relevant earlier work is merged:
+#386 cert-warm wake (542ad2c), #277 deploymentHost gates, the cert mirror
+(certsync.go) and the home map (homemap.go).
+
+You are an independent reviewer. Read the diff, then the code it touches,
+and check every claim against that code.
+
+## The bug, with the evidence (for context, not for review)
+
+On dev, every new host homed on the issuer box (sophie, ie) failed its
+first order with autocert's "no viable challenge type found", then stayed
+dark for 5 to 12 minutes. Reproduced 2026-10-28 on v0.28.29:
+
+- 07:28:00 sophie (issuer) minted shop-cert-1028-ie.bab.dev.oncarlos.com.
+- 07:28:05-06 dennis (uk, non-issuer) logged `acme/autocert: no token cert`
+ for that name from 13.49.80.41 (AWS eu-north-1) and 54.169.36.6 (AWS
+ ap-southeast-1): Let's Encrypt's remote validators. `*.bab.dev.oncarlos.com`
+ is a geo/latency wildcard, so they resolved to dennis.
+- 07:28:07 dennis still answered `host ... not in registry` for the name;
+ by 07:28:13 it answered `not available here`, i.e. its home map (30 s poll)
+ had learned it.
+- 07:28:09 sophie: `cert warm for ...: no viable challenge type found —
+ retrying in 1h0m0s`.
+
+So the non-issuer's challenge paths (`alpnTokenCert`, `challengeResponse`,
+both bounded by `m.allowed` = `deploymentHost`) refused a name they had
+not polled yet. UK hosts never failed because the issuer learns them from
+its own home map poll, by which time the home box has them.
+
+## Fixed: do not re-argue
+
+- The non-issuer bound (`m.allowed` before any bucket read-through) stays.
+ Relaxing it lets stranger SNI drive bucket reads (#277, PR #180 rule).
+- A fixed window rather than an acknowledgement: no edge publishes what it
+ has learned, and adding that is new per-box bucket traffic (rule: no new
+ per-box polling).
+- The 45 s window lengthens a new host's first certificate in a
+ multi-edge deployment by up to about 45 s. Accepted: `carlos deploy`
+ watches for 2 minutes, and the alternative today is 5 minutes to an hour.
+
+## What to check
+
+1. Completeness. Is every path that places a NEW per-host order on the
+ issuer held? Both the warm (`certWarm.pass` → `getCert`) and an
+ on-demand handshake reach autocert's `GetCertificate`, which runs
+ `HostPolicy` before its cache (x/crypto v0.57.0 autocert.go). Renewal
+ timers do not consult HostPolicy: confirm that cannot produce a first
+ order for a new name. The wildcard manager (DNS-01) is out of scope;
+ confirm it is unaffected.
+2. No regression for names that already have a certificate. A held name is
+ refused by HostPolicy before autocert's cache read. On the issuer,
+ `certMirror.wrapGetCertificate` falls back to the mirror and the local
+ cache: confirm a moved host (new to this box, cert already in the
+ bucket) is still served during the window, and that a box with no
+ mirror (no store) has no home map and so is never held.
+3. The issuer's own live order. `HostPolicy` also gates autocert's
+ `HTTPHandler` (HTTP-01 token serving). Confirm the hold cannot refuse
+ the issuer's own token for an order it placed (an order is only placed
+ once the hold has lifted for that name).
+4. The tracker (`nameAges`). Baseline at construction (`issuerHostPolicyAt`
+ is built in Run after `e.Reload()` and the home map's boot refresh), the
+ failed-boot-refresh case (first read snapshot is a baseline),
+ pointer-change detection (`Edge.Reload` stores a new map pointer,
+ `homeMap.refreshHosts` a new snapshot pointer: is anything ever mutated
+ in place?), pruning of names that leave, a name that returns, and
+ names deploymentHost admits that neither map holds (not held).
+5. `hasPeer`: right test for "more than one edge"? Behaviour with an empty
+ box label.
+6. The warm. In `pass`, a hold must not call `fail` (no 1 h backoff, no
+ failure record), must hand back the order-budget stamp it took, and must
+ bring the next pass back just after the window (`settleWait +
+ warmSettleSlack`). Check `nextAttempt` (set with `c.now()`), `hasNewHost`
+ and the loop's `passDue` handling, and the renewal re-arm path for an
+ already-warmed name that is held (`seen == true`).
+7. Concurrency and cost on the handshake path: `nameAges.mu` is taken on
+ every issuer handshake that reaches autocert, and a rebuild is O(names)
+ under it.
+8. Wire text. `errNameSettling`'s message reaches the wire verbatim through
+ autocert's HTTPHandler; confirm it says nothing diagnostic (see
+ `errNotIssuer`'s comment).
+9. Tests: do `certsettle_test.go`'s tests pin each behaviour above, and
+ would they fail without the change?
+10. Census. Verdict on the re-pinned `internal/edge` envelope per AGENTS.md
+ "Getting a change approved": does the change let root open, run, query
+ or follow anything new from a path or input a tenant, app or box agent
+ can create, write or name, or weaken a check root relies on? (It adds
+ no reads; it adds a refusal.) Say APPROVE or ESCALATE for the envelope.
+
+## Round 2
+
+Earlier rounds: round 1, `docs/superpowers/reviews/CODEX-REVIEW-cert-warm-443-R1.md`
+(one P1, census APPROVE at 17349ef7).
+
+First give one line for round 1's P1 (a pass run for another reason drops a
+held name's retry deadline): resolved, partly, or not. The fix is commit
+115f29ce: `certWarm.settleUntil` keeps each hold's absolute deadline, set in
+`settling`, cleared on success, on failure and when the name leaves the set,
+and `earliestSettle` brings every pass back for the soonest hold still
+running. An ENDED hold deliberately does not shorten the delay (the order cap
+and the DNS-miss schedule bring those names back); check that no ended hold
+can be left with no scheduled pass at all. Regression tests:
+`TestWarmKeepsAHoldsDeadlineThroughAnUnrelatedPass`,
+`TestWarmComesBackForEachHold`; coverage added for a held re-arm
+(`TestWarmHeldReArmSpendsNoBudget`) and a failed boot refresh
+(`TestHostPolicyTakesTheFirstReadSnapshotAsABaseline`).
+
+Carry an unresolved finding forward at its severity, then add new findings
+against the whole diff. The verdict covers everything outstanding. Give the
+census verdict for `internal/edge` again at this tip (the overlay was
+re-proposed).
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review. (The
+ census, and review of any newly changed security, root, termination
+ or production-storage behaviour, still check the fix; see AGENTS.md,
+ "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section or task, the problem,
+the evidence (file:line, verified), the failure scenario, a concrete
+fix and the invariant or trust boundary it breaks (that is its fault
+family). Then the census verdict for `internal/edge`. End with exactly one
+verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites. You may run
+`go test ./internal/edge/ -run 'Settle|Settling|HoldsA|DoesNotHold|TestWarmKeepsAHolds|TestWarmComesBack|TestWarmHeldReArm|FirstReadSnapshot' -count=1` (set GOTMPDIR and GOCACHE to writable paths if the default work dir is read-only).
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-cert-warm-443-R3.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-cert-warm-443-R3.md
new file mode 100644
index 000000000..134a7e1b5
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-cert-warm-443-R3.md
@@ -0,0 +1,158 @@
+# Review brief: branch cert-warm-propagation-443 (#443), round 3 of 3
+
+Repo carlos/platform, branch `cert-warm-propagation-443`, commit named in
+the reviewer's prompt.
+Under review: the diff `origin/main..cert-warm-propagation-443`, which is
+`internal/edge/certsettle.go` (new), `internal/edge/certsync.go`
+(`issuerHostPolicy`), `internal/edge/certwarm.go` (`pass`, `settling`), the
+tests in `internal/edge/certsettle_test.go`, and the census overlay
+(`internal/provision/testdata/plan14-root-reads-cert-warm-propagation-443.tsv`,
+card `docs/superpowers/notes/census-proposal-cert-warm-propagation-443.md`).
+Authorities: the code on main. The relevant earlier work is merged:
+#386 cert-warm wake (542ad2c), #277 deploymentHost gates, the cert mirror
+(certsync.go) and the home map (homemap.go).
+
+You are an independent reviewer. Read the diff, then the code it touches,
+and check every claim against that code.
+
+## The bug, with the evidence (for context, not for review)
+
+On dev, every new host homed on the issuer box (sophie, ie) failed its
+first order with autocert's "no viable challenge type found", then stayed
+dark for 5 to 12 minutes. Reproduced 2026-10-28 on v0.28.29:
+
+- 07:28:00 sophie (issuer) minted shop-cert-1028-ie.bab.dev.oncarlos.com.
+- 07:28:05-06 dennis (uk, non-issuer) logged `acme/autocert: no token cert`
+ for that name from 13.49.80.41 (AWS eu-north-1) and 54.169.36.6 (AWS
+ ap-southeast-1): Let's Encrypt's remote validators. `*.bab.dev.oncarlos.com`
+ is a geo/latency wildcard, so they resolved to dennis.
+- 07:28:07 dennis still answered `host ... not in registry` for the name;
+ by 07:28:13 it answered `not available here`, i.e. its home map (30 s poll)
+ had learned it.
+- 07:28:09 sophie: `cert warm for ...: no viable challenge type found —
+ retrying in 1h0m0s`.
+
+So the non-issuer's challenge paths (`alpnTokenCert`, `challengeResponse`,
+both bounded by `m.allowed` = `deploymentHost`) refused a name they had
+not polled yet. UK hosts never failed because the issuer learns them from
+its own home map poll, by which time the home box has them.
+
+## Fixed: do not re-argue
+
+- The non-issuer bound (`m.allowed` before any bucket read-through) stays.
+ Relaxing it lets stranger SNI drive bucket reads (#277, PR #180 rule).
+- A fixed window rather than an acknowledgement: no edge publishes what it
+ has learned, and adding that is new per-box bucket traffic (rule: no new
+ per-box polling).
+- The 45 s window lengthens a new host's first certificate in a
+ multi-edge deployment by up to about 45 s. Accepted: `carlos deploy`
+ watches for 2 minutes, and the alternative today is 5 minutes to an hour.
+
+## What to check
+
+1. Completeness. Is every path that places a NEW per-host order on the
+ issuer held? Both the warm (`certWarm.pass` → `getCert`) and an
+ on-demand handshake reach autocert's `GetCertificate`, which runs
+ `HostPolicy` before its cache (x/crypto v0.57.0 autocert.go). Renewal
+ timers do not consult HostPolicy: confirm that cannot produce a first
+ order for a new name. The wildcard manager (DNS-01) is out of scope;
+ confirm it is unaffected.
+2. No regression for names that already have a certificate. A held name is
+ refused by HostPolicy before autocert's cache read. On the issuer,
+ `certMirror.wrapGetCertificate` falls back to the mirror and the local
+ cache: confirm a moved host (new to this box, cert already in the
+ bucket) is still served during the window, and that a box with no
+ mirror (no store) has no home map and so is never held.
+3. The issuer's own live order. `HostPolicy` also gates autocert's
+ `HTTPHandler` (HTTP-01 token serving). Confirm the hold cannot refuse
+ the issuer's own token for an order it placed (an order is only placed
+ once the hold has lifted for that name).
+4. The tracker (`nameAges`). Baseline at construction (`issuerHostPolicyAt`
+ is built in Run after `e.Reload()` and the home map's boot refresh), the
+ failed-boot-refresh case (first read snapshot is a baseline),
+ pointer-change detection (`Edge.Reload` stores a new map pointer,
+ `homeMap.refreshHosts` a new snapshot pointer: is anything ever mutated
+ in place?), pruning of names that leave, a name that returns, and
+ names deploymentHost admits that neither map holds (not held).
+5. `hasPeer`: right test for "more than one edge"? Behaviour with an empty
+ box label.
+6. The warm. In `pass`, a hold must not call `fail` (no 1 h backoff, no
+ failure record), must hand back the order-budget stamp it took, and must
+ bring the next pass back just after the window (`settleWait +
+ warmSettleSlack`). Check `nextAttempt` (set with `c.now()`), `hasNewHost`
+ and the loop's `passDue` handling, and the renewal re-arm path for an
+ already-warmed name that is held (`seen == true`).
+7. Concurrency and cost on the handshake path: `nameAges.mu` is taken on
+ every issuer handshake that reaches autocert, and a rebuild is O(names)
+ under it.
+8. Wire text. `errNameSettling`'s message reaches the wire verbatim through
+ autocert's HTTPHandler; confirm it says nothing diagnostic (see
+ `errNotIssuer`'s comment).
+9. Tests: do `certsettle_test.go`'s tests pin each behaviour above, and
+ would they fail without the change?
+10. Census. Verdict on the re-pinned `internal/edge` envelope per AGENTS.md
+ "Getting a change approved": does the change let root open, run, query
+ or follow anything new from a path or input a tenant, app or box agent
+ can create, write or name, or weaken a check root relies on? (It adds
+ no reads; it adds a refusal.) Say APPROVE or ESCALATE for the envelope.
+
+## Round 3 (the last)
+
+Earlier rounds: `docs/superpowers/reviews/CODEX-REVIEW-cert-warm-443-R1.md`
+and `-R2.md`. Each found one P1 in the retry-scheduling family ("every held
+name must keep a scheduled retry through unrelated passes"); census APPROVE
+both times. Stopping rule 2 triggered; Paul chose (on #443) option 1: one
+rule in one place, with a guard test.
+
+The rule, commit adcc542f: a name in `certWarm.settleUntil` is OWED a pass
+at max(its deadline, now). `owedWait` is the only place that turns owed
+names into the next pass's time, and it counts a deadline that has already
+passed as now. An entry leaves only through `discharge`: the name was
+ordered (success or failure), handed to the order cap or the DNS-miss
+schedule (each brings it back on its own), or left the set; a new hold
+moves the deadline. Guard: `TestWarmOwedRetryInvariantSimulation` (300
+seeds, a clock that moves inside orders, random early wakes), plus
+`TestWarmRetriesAHoldThatEndsDuringAPass` (the R2 scenario) and
+`TestWarmHandsADueHoldToTheCap`.
+
+First give one line each for R1's and R2's P1: resolved, partly, or not.
+Then check: can any held name still be left with no pass scheduled by its
+deadline (stand-down mid-pass, the gate tick, wakes dropped by the loop,
+`hasNewHost`)? Can a due owed name make the loop spin (a pass that reaches
+it without discharging it or moving its deadline)? Then the whole diff, and
+the census verdict for `internal/edge` at this tip.
+
+This is round 3 of 3. A NOT READY must also say whether its P1s share one
+cause, and whether refusing the case up front or cutting the feature would
+remove them.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review. (The
+ census, and review of any newly changed security, root, termination
+ or production-storage behaviour, still check the fix; see AGENTS.md,
+ "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section or task, the problem,
+the evidence (file:line, verified), the failure scenario, a concrete
+fix and the invariant or trust boundary it breaks (that is its fault
+family). Then the census verdict for `internal/edge`. End with exactly one
+verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites. You may run
+`go test ./internal/edge/ -run 'Settle|Settling|HoldsA|DoesNotHold|TestWarm' -count=1` (set GOTMPDIR and GOCACHE to writable paths if the default work dir is read-only).
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-cert-warm-443.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-cert-warm-443.md
new file mode 100644
index 000000000..d2513278d
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-cert-warm-443.md
@@ -0,0 +1,128 @@
+# Review brief: branch cert-warm-propagation-443 (#443), round 1 of 3
+
+Repo carlos/platform, branch `cert-warm-propagation-443`, commit named in
+the reviewer's prompt.
+Under review: the diff `origin/main..cert-warm-propagation-443`, which is
+`internal/edge/certsettle.go` (new), `internal/edge/certsync.go`
+(`issuerHostPolicy`), `internal/edge/certwarm.go` (`pass`, `settling`), the
+tests in `internal/edge/certsettle_test.go`, and the census overlay
+(`internal/provision/testdata/plan14-root-reads-cert-warm-propagation-443.tsv`,
+card `docs/superpowers/notes/census-proposal-cert-warm-propagation-443.md`).
+Authorities: the code on main. The relevant earlier work is merged:
+#386 cert-warm wake (542ad2c), #277 deploymentHost gates, the cert mirror
+(certsync.go) and the home map (homemap.go).
+
+You are an independent reviewer. Read the diff, then the code it touches,
+and check every claim against that code.
+
+## The bug, with the evidence (for context, not for review)
+
+On dev, every new host homed on the issuer box (sophie, ie) failed its
+first order with autocert's "no viable challenge type found", then stayed
+dark for 5 to 12 minutes. Reproduced 2026-10-28 on v0.28.29:
+
+- 07:28:00 sophie (issuer) minted shop-cert-1028-ie.bab.dev.oncarlos.com.
+- 07:28:05-06 dennis (uk, non-issuer) logged `acme/autocert: no token cert`
+ for that name from 13.49.80.41 (AWS eu-north-1) and 54.169.36.6 (AWS
+ ap-southeast-1): Let's Encrypt's remote validators. `*.bab.dev.oncarlos.com`
+ is a geo/latency wildcard, so they resolved to dennis.
+- 07:28:07 dennis still answered `host ... not in registry` for the name;
+ by 07:28:13 it answered `not available here`, i.e. its home map (30 s poll)
+ had learned it.
+- 07:28:09 sophie: `cert warm for ...: no viable challenge type found —
+ retrying in 1h0m0s`.
+
+So the non-issuer's challenge paths (`alpnTokenCert`, `challengeResponse`,
+both bounded by `m.allowed` = `deploymentHost`) refused a name they had
+not polled yet. UK hosts never failed because the issuer learns them from
+its own home map poll, by which time the home box has them.
+
+## Fixed: do not re-argue
+
+- The non-issuer bound (`m.allowed` before any bucket read-through) stays.
+ Relaxing it lets stranger SNI drive bucket reads (#277, PR #180 rule).
+- A fixed window rather than an acknowledgement: no edge publishes what it
+ has learned, and adding that is new per-box bucket traffic (rule: no new
+ per-box polling).
+- The 45 s window lengthens a new host's first certificate in a
+ multi-edge deployment by up to about 45 s. Accepted: `carlos deploy`
+ watches for 2 minutes, and the alternative today is 5 minutes to an hour.
+
+## What to check
+
+1. Completeness. Is every path that places a NEW per-host order on the
+ issuer held? Both the warm (`certWarm.pass` → `getCert`) and an
+ on-demand handshake reach autocert's `GetCertificate`, which runs
+ `HostPolicy` before its cache (x/crypto v0.57.0 autocert.go). Renewal
+ timers do not consult HostPolicy: confirm that cannot produce a first
+ order for a new name. The wildcard manager (DNS-01) is out of scope;
+ confirm it is unaffected.
+2. No regression for names that already have a certificate. A held name is
+ refused by HostPolicy before autocert's cache read. On the issuer,
+ `certMirror.wrapGetCertificate` falls back to the mirror and the local
+ cache: confirm a moved host (new to this box, cert already in the
+ bucket) is still served during the window, and that a box with no
+ mirror (no store) has no home map and so is never held.
+3. The issuer's own live order. `HostPolicy` also gates autocert's
+ `HTTPHandler` (HTTP-01 token serving). Confirm the hold cannot refuse
+ the issuer's own token for an order it placed (an order is only placed
+ once the hold has lifted for that name).
+4. The tracker (`nameAges`). Baseline at construction (`issuerHostPolicyAt`
+ is built in Run after `e.Reload()` and the home map's boot refresh), the
+ failed-boot-refresh case (first read snapshot is a baseline),
+ pointer-change detection (`Edge.Reload` stores a new map pointer,
+ `homeMap.refreshHosts` a new snapshot pointer: is anything ever mutated
+ in place?), pruning of names that leave, a name that returns, and
+ names deploymentHost admits that neither map holds (not held).
+5. `hasPeer`: right test for "more than one edge"? Behaviour with an empty
+ box label.
+6. The warm. In `pass`, a hold must not call `fail` (no 1 h backoff, no
+ failure record), must hand back the order-budget stamp it took, and must
+ bring the next pass back just after the window (`settleWait +
+ warmSettleSlack`). Check `nextAttempt` (set with `c.now()`), `hasNewHost`
+ and the loop's `passDue` handling, and the renewal re-arm path for an
+ already-warmed name that is held (`seen == true`).
+7. Concurrency and cost on the handshake path: `nameAges.mu` is taken on
+ every issuer handshake that reaches autocert, and a rebuild is O(names)
+ under it.
+8. Wire text. `errNameSettling`'s message reaches the wire verbatim through
+ autocert's HTTPHandler; confirm it says nothing diagnostic (see
+ `errNotIssuer`'s comment).
+9. Tests: do `certsettle_test.go`'s tests pin each behaviour above, and
+ would they fail without the change?
+10. Census. Verdict on the re-pinned `internal/edge` envelope per AGENTS.md
+ "Getting a change approved": does the change let root open, run, query
+ or follow anything new from a path or input a tenant, app or box agent
+ can create, write or name, or weaken a check root relies on? (It adds
+ no reads; it adds a refusal.) Say APPROVE or ESCALATE for the envelope.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review. (The
+ census, and review of any newly changed security, root, termination
+ or production-storage behaviour, still check the fix; see AGENTS.md,
+ "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section or task, the problem,
+the evidence (file:line, verified), the failure scenario, a concrete
+fix and the invariant or trust boundary it breaks (that is its fault
+family). Then the census verdict for `internal/edge`. End with exactly one
+verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites. You may run
+`go test ./internal/edge/ -run 'Settle|Settling|HoldsA|DoesNotHold' -count=1`.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-cert-warm-443-R1.md b/docs/superpowers/reviews/CODEX-REVIEW-cert-warm-443-R1.md
new file mode 100644
index 000000000..9a3aa2a52
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-cert-warm-443-R1.md
@@ -0,0 +1,20 @@
+Reviewed `26578a2c..17349ef79a311d9f01113b0e40590a8d92fcd8e1`, round 1.
+
+- **P1 — Brief §6: a subsequent pass can discard a settling host’s retry deadline.**
+ `pass()` skips hosts whose `nextAttempt` remains in the future at [certwarm.go:473](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certwarm.go:473), but updates `settleWait` only when it receives another settling error at [certwarm.go:519](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certwarm.go:519). Consequently, a pass that skips outstanding holds can return the hourly delay at [certwarm.go:561](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certwarm.go:561). The loop then replaces `passDue` at [certwarm.go:289](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certwarm.go:289).
+
+ **Failure scenario:** A is held for 45 seconds. At 20 seconds, an existing DNS retry for baseline host B succeeds and triggers a pass. That pass skips A, warms B, and returns one hour. Without another qualifying wake or an issuer handshake, A remains without a certificate for approximately an hour. Different hold deadlines can produce the same failure when the earliest hold expires.
+
+ **Fix:** retain outstanding settlement deadlines across passes and include skipped settling hosts when calculating the next pass. Compute the remaining delay from absolute deadlines. Add clock-controlled regressions for an intervening DNS-triggered pass and multiple hold deadlines. The current test manually deletes `nextAttempt` before retrying at [certsettle_test.go:225](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certsettle_test.go:225), so it cannot catch this.
+
+ **Fault family:** retry scheduling — every pending settlement must retain a scheduled retry through unrelated passes.
+
+No additional P2 or P3 findings.
+
+The other inspected paths preserve the existing admission checks. Mirror/local-cache fallback remains available during a hold; renewal timers require an existing certificate; wildcard issuance is unaffected. The tracker uses replaced snapshots, and the wire error is generic. Test coverage does not directly pin every requested case, including failed-boot baseline handling, an empty box label, and a held `seen == true` renewal re-arm.
+
+**Census — `internal/edge`: APPROVE** for this commit. Reviewed the new tracker and error helpers in [certsettle.go:54](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certsettle.go:54), the policy change at [certsync.go:204](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certsync.go:204), and the warm changes cited above. They add an in-memory refusal and retry bookkeeping, introduce no new external read targets or execution paths, and preserve the host and issuer checks. The scheduling defect does not expand root authority.
+
+The permitted targeted test command could not start: Go could not create its work directory on the read-only filesystem. `git diff --check` passed. No files were edited.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-cert-warm-443-R2.md b/docs/superpowers/reviews/CODEX-REVIEW-cert-warm-443-R2.md
new file mode 100644
index 000000000..c9cac594b
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-cert-warm-443-R2.md
@@ -0,0 +1,18 @@
+Round 1 P1: **partly resolved** — deadlines survive short intervening passes, but a hold that expires during a pass can still lose its prompt retry.
+
+- **P1 — Brief §6: an elapsed hold can be discarded without its host being retried.**
+ `pass` skips a host whose deadline is still ahead at [certwarm.go:476](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certwarm.go:476). After processing the remaining hosts, `earliestSettle` ignores deadlines that have elapsed at [certwarm.go:953](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certwarm.go:953). Its assumption that such hosts were attempted or deferred by the cap/DNS gate is therefore false.
+
+ **Failure scenario:** A is held until t=45s. An unrelated DNS retry triggers a pass at t=20s. The pass skips A, then spends 30 seconds successfully ordering B’s certificate. At t=50s, A’s deadline is ignored. With no cap reached or DNS retries remaining, the pass returns one hour at [certwarm.go:566](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certwarm.go:566), replacing the earlier retry through [certwarm.go:295](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certwarm.go:295). Without another qualifying wake or handshake, A remains without a certificate for approximately an hour.
+
+ **Concrete fix:** distinguish hosts skipped because their hold was active from hosts deferred by the cap or DNS gate. Preserve a prompt retry for the former even when their deadline expires during the pass. Add a clock-controlled regression that advances time inside B’s certificate call; the new tests advance time only between passes.
+
+ **Fault family:** retry scheduling — every pending settlement must retain a scheduled retry through unrelated passes. This recurs across rounds 1–2, triggering stopping rule 2. Before another fix, choose between gating the case, cutting the feature, or enforcing this invariant in one scheduling decision with a guard test; I recommend the third.
+
+No additional P2 or P3 findings.
+
+**Census — `internal/edge`: APPROVE** at `50c0bc79a0427a18f99340163f3c2924b48a66da`. Reviewed the tracker and helpers in [certsettle.go:94](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certsettle.go:94), the policy in [certsync.go:204](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certsync.go:204), and the warm changes cited above. They add in-memory refusal and scheduling state, introduce no new external read targets or execution paths, and preserve deployment membership and issuer checks. Mirror/local-cache fallback remains available; wildcard issuance is unaffected. The scheduling defect does not expand root authority.
+
+The permitted targeted tests could not start: Go could not create its work directory on the read-only filesystem. No files were edited.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-cert-warm-443-R3.md b/docs/superpowers/reviews/CODEX-REVIEW-cert-warm-443-R3.md
new file mode 100644
index 000000000..2953651eb
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-cert-warm-443-R3.md
@@ -0,0 +1,24 @@
+R1 P1: **resolved** for the reported intervening-pass scenario; outstanding deadlines now survive.
+R2 P1: **resolved** for the reported slow-order scenario; elapsed deadlines now request an immediate retry.
+
+- **P1 — Brief §6 / R3: standing down can still strand an owed name for an hour.**
+
+ Both stand-down exits return `warmInterval` without consulting `owedWait`: [certwarm.go:451](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certwarm.go:451) and [certwarm.go:488](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certwarm.go:488). The loop replaces `passDue`, then independently samples the gate at [certwarm.go:298](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certwarm.go:298).
+
+ **Failure scenario:** A has an outstanding hold. Its scheduled pass observes the issuer gate closed and stands down. Before the loop’s subsequent gate read, this box reacquires the lease. The loop records `issuer = true` alongside an hourly deadline. Later gate ticks see no transition, so they request no pass ([certwarm.go:276](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certwarm.go:276)). Without another qualifying wake, DNS retry, or handshake, A remains certificate-less until the hourly pass. Keeping A in `settleUntil` does not itself schedule work.
+
+ **Concrete fix:** preserve the pass’s observed stand-down in its result and make the loop’s scheduling decision account for that observation and outstanding holds. Recovery must trigger a pass even when reacquisition precedes the post-pass gate read; a continuously closed gate must remain non-spinning. Add a deterministic loop regression for precisely that interleaving. The simulation currently supplies a nil gate and calls `pass` directly, so it cannot detect this ([certsettle_test.go:491](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certsettle_test.go:491)).
+
+ **Fault family:** retry scheduling — every held name must retain a scheduled retry through unrelated passes and issuer transitions. This is the same invariant as rounds 1–2.
+
+No additional P2 or P3 findings.
+
+The remaining inspected paths preserve admission checks, mirror/local-cache fallback, wildcard issuance, and renewal behavior. Snapshot replacement supports the tracker’s pointer comparisons. Normal completed passes discharge due holds or move their deadlines; I found no due-hold spin there.
+
+**Census — `internal/edge`: APPROVE** at `212be158e8660f910d8bfb6e0107b6f08ddb77b8`. Reviewed the tracker in [certsettle.go:94](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certsettle.go:94), policy integration in [certsync.go:204](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/cert-warm-443/internal/edge/certsync.go:204), and warm scheduling changes above. These introduce in-memory refusal and bookkeeping, without new external read targets, execution paths, or weakened admission checks. Independently recomputed the Linux amd64/arm64 envelope: it matches `f89991c62c1ccdf40bbeff9194b2ff34a0adc571bea8d2f02df5a7d0cabfca3f`.
+
+The permitted targeted tests could not start because Go’s work directory is read-only. Production/test-code whitespace checks passed. No files were edited.
+
+This final round has one P1, sharing the earlier rounds’ cause. Refusing configurations with changing issuer ownership would exclude this scenario, at the cost of failover support. Cutting the settling feature removes this new retry obligation but restores the original propagation failure. The three-round budget is exhausted.
+
+**NOT READY**
\ No newline at end of file
diff --git a/internal/edge/certsettle.go b/internal/edge/certsettle.go
new file mode 100644
index 000000000..086363209
--- /dev/null
+++ b/internal/edge/certsettle.go
@@ -0,0 +1,185 @@
+// Name settling (#443): the issuer does not order a certificate for a name
+// until every other edge in the deployment has had the chance to learn it.
+//
+// Why. The CA validates one order from several places at once, and DNS for a
+// platform name answers with whichever edge is nearest each of them (latency
+// or geo routing), so some of those validations arrive at an edge that is not
+// the issuer. That edge answers the challenge from the bucket (certsync.go's
+// alpnTokenCert and challengeResponse), but only for names it already knows,
+// which is the bound that stops a stranger's SNI from turning into bucket
+// reads. It learns another box's names from its home map, polled every
+// homeMapInterval. The issuer, meanwhile, orders the moment it sees a name:
+// the cert warm's wake (#386) runs about a second after a route is minted,
+// and a client's first handshake does the same. So on the box that homes a
+// new name, the order went out seconds before the other edges could know the
+// name, their validations failed, and the order failed with them ("no viable
+// challenge type found"). autocert then refuses the name for a minute, the
+// warm backs off for an hour, and steering keeps most handshakes on edges
+// that never order, so a new host stayed dark for minutes (dev's ie hosts,
+// 2026-10-26 to 10-28: five of five).
+//
+// The rule: a name the issuer first saw less than nameSettleWindow ago is
+// not ordered yet. The window is one home map poll plus a margin, which is
+// long enough for every other edge to have polled once since the name was
+// published. It applies only where there IS another edge (a home map that
+// lists another box): a single box has nobody to wait for.
+//
+// It holds NEW orders only in practice. HostPolicy runs before autocert's
+// cache read, so a held name is not served from autocert's cache either; on
+// the issuer the mirror and the local cache sit behind autocert
+// (certMirror.wrapGetCertificate), so a name that already has a certificate
+// (one that moved here) keeps being served through the window.
+package edge
+
+import (
+ "errors"
+ "sync"
+ "time"
+)
+
+// nameSettleMargin is added to the poll interval to cover the home box's
+// edges file write (internal/host's 2 s registry watch plus the put) and the
+// other box's own poll, which lists and reads every edges file.
+const nameSettleMargin = 15 * time.Second
+
+// nameSettleWindow is how long the issuer waits after first seeing a name
+// before it orders for it. Derived from homeMapInterval so the two cannot
+// drift apart.
+func nameSettleWindow() time.Duration { return homeMapInterval + nameSettleMargin }
+
+// errNameSettling is the hold's sentinel. Its text is generic for
+// errNotIssuer's reason: autocert's HTTPHandler writes a HostPolicy error to
+// the wire verbatim.
+var errNameSettling = errors.New("acme: not available yet")
+
+// settlingError is the hold as HostPolicy returns it, carrying how long is
+// left so the cert warm can come back on time rather than on a guess.
+type settlingError struct {
+ left time.Duration
+}
+
+func (e *settlingError) Error() string { return errNameSettling.Error() }
+
+func (e *settlingError) Is(target error) bool { return target == errNameSettling }
+
+// settleLeft extracts the time left from a hold, and false for any other
+// error.
+func settleLeft(err error) (time.Duration, bool) {
+ var se *settlingError
+ if errors.As(err, &se) {
+ return se.left, true
+ }
+ return 0, false
+}
+
+// nameAges records when this box first saw each name it can order for: its
+// own routes and every name another box publishes. The names present when it
+// is built are dated zero (always settled), so a restart holds nothing; a
+// name that appears later is dated when it was first noticed.
+//
+// It rebuilds only when the route map or the home map snapshot changes, and
+// both are replaced whole rather than edited (Edge.Reload, homeMap.refreshHosts),
+// so a pointer comparison is enough and the handshake path pays a map lookup.
+// A rebuild drops names that have gone, so the map stays the size of the
+// deployment, and a name that comes back is new again.
+type nameAges struct {
+ now func() time.Time
+
+ mu sync.Mutex
+ own *map[string]upstream
+ homes *homeSnapshot
+ first map[string]time.Time
+}
+
+func newNameAges(e *Edge, now func() time.Time) *nameAges {
+ a := &nameAges{now: now}
+ a.mu.Lock()
+ a.rebuild(e, true)
+ a.mu.Unlock()
+ return a
+}
+
+// wait is how long until host may be ordered: zero when it may be now.
+// A name the tracker has never seen is not held. That covers names that are
+// in neither map (the tunnel host) and keeps an unexpected shape on today's
+// behaviour rather than holding it forever.
+func (a *nameAges) wait(e *Edge, host string) time.Duration {
+ if !e.homes.Load().hasPeer() {
+ return 0
+ }
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.rebuild(e, false)
+ first, ok := a.first[host]
+ if !ok || first.IsZero() {
+ return 0
+ }
+ return max(first.Add(nameSettleWindow()).Sub(a.now()), 0)
+}
+
+// rebuild re-reads both name sets when either has changed. Called with a.mu
+// held.
+func (a *nameAges) rebuild(e *Edge, baseline bool) {
+ own := e.upstreams.Load()
+ var snap *homeSnapshot
+ if hm := e.homes.Load(); hm != nil {
+ snap = hm.snapshot()
+ }
+ if !baseline && own == a.own && snap == a.homes {
+ return
+ }
+ // The first snapshot that comes from a successful read is a baseline of
+ // its own: when the boot refresh failed, the map starts empty, and the
+ // poll that finally lands is not news about every name in it.
+ homesBaseline := baseline || a.homes == nil || !a.homes.read
+ a.own, a.homes = own, snap
+ now := a.now()
+ next := make(map[string]time.Time, len(a.first))
+ note := func(h string, old bool) {
+ if _, dup := next[h]; dup {
+ return
+ }
+ switch t, ok := a.first[h]; {
+ case ok:
+ next[h] = t
+ case old:
+ next[h] = time.Time{}
+ default:
+ next[h] = now
+ }
+ }
+ if own != nil {
+ for h := range *own {
+ note(h, baseline)
+ }
+ }
+ if snap != nil {
+ for h := range snap.hosts {
+ note(h, homesBaseline)
+ }
+ }
+ a.first = next
+}
+
+// hasPeer reports whether another box publishes an edges file, which is what
+// makes this a deployment with more than one edge. With no box label every
+// file counts, which only ever errs towards holding.
+func (m *homeMap) hasPeer() bool {
+ if m == nil {
+ return false
+ }
+ for _, f := range m.snapshot().files {
+ if f.Box != "" && f.Box != m.self {
+ return true
+ }
+ }
+ return false
+}
+
+// holdIfSettling is HostPolicy's last step on the issuer.
+func (a *nameAges) holdIfSettling(e *Edge, host string) error {
+ if left := a.wait(e, host); left > 0 {
+ return &settlingError{left: left}
+ }
+ return nil
+}
diff --git a/internal/edge/certsettle_test.go b/internal/edge/certsettle_test.go
new file mode 100644
index 000000000..c6b98c900
--- /dev/null
+++ b/internal/edge/certsettle_test.go
@@ -0,0 +1,527 @@
+package edge
+
+import (
+ "context"
+ "crypto/tls"
+ "errors"
+ "fmt"
+ "math/rand/v2"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/certwarm"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// #443. The CA validates a name from several places at once, and DNS for a
+// platform name answers with whichever edge is nearest each of them, so some
+// validations arrive at an edge that is not the issuer. That edge can answer
+// only for names it knows, and it learns another box's names from its home map
+// poll. A name the issuer has just minted is not in that map yet, so an order
+// placed straight away fails before the other edges have had a chance to
+// learn the name. The fix holds a NEW order until one poll interval (and a
+// margin) has passed since the issuer first saw the name.
+
+// clockAt is a settable test clock.
+type clockAt struct {
+ mu sync.Mutex
+ t time.Time
+}
+
+func (c *clockAt) now() time.Time {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.t
+}
+
+func (c *clockAt) advance(d time.Duration) {
+ c.mu.Lock()
+ c.t = c.t.Add(d)
+ c.mu.Unlock()
+}
+
+// settleEdge is the issuer of a two-box deployment: it serves own from its
+// registry and holds the issuer lease, and box "betty" publishes homed.
+func settleEdge(t *testing.T, own []string, homed ...string) (*Edge, *homeMap) {
+ t.Helper()
+ e := testIssuerEdge(own...)
+ e.issuer = func() (context.Context, bool) { return context.Background(), true }
+ m := newHomeMap(release.NewDirStore(t.TempDir()), "annie")
+ homedOn(t, m, "betty", "2.2.2.2", homed...)
+ e.homes.Store(m)
+ return e, m
+}
+
+// mint adds host to the edge's registry the way a reload does: a new map
+// behind a new pointer.
+func mint(e *Edge, host string) {
+ next := map[string]upstream{}
+ for h, u := range e.current() {
+ next[h] = u
+ }
+ next[host] = upstream{}
+ e.upstreams.Store(&next)
+}
+
+func TestHostPolicyHoldsANameItHasJustMinted(t *testing.T) {
+ clk := &clockAt{t: time.Unix(1_800_000_000, 0)}
+ e, _ := settleEdge(t, []string{"old.test"}, "remote-old.test")
+ pol := e.issuerHostPolicyAt(clk.now)
+
+ for _, h := range []string{"old.test", "remote-old.test"} {
+ if err := pol(context.Background(), h); err != nil {
+ t.Fatalf("%s was there when the policy was built: want no hold, got %v", h, err)
+ }
+ }
+
+ mint(e, "new.test")
+ err := pol(context.Background(), "new.test")
+ if !errors.Is(err, errNameSettling) {
+ t.Fatalf("a name minted a moment ago = %v, want errNameSettling", err)
+ }
+ var se *settlingError
+ if !errors.As(err, &se) || se.left != nameSettleWindow() {
+ t.Fatalf("settling error = %#v, want the whole window (%s) left", err, nameSettleWindow())
+ }
+
+ clk.advance(nameSettleWindow() - time.Second)
+ if err := pol(context.Background(), "new.test"); !errors.Is(err, errNameSettling) {
+ t.Fatalf("one second before the window ends = %v, want still settling", err)
+ }
+ clk.advance(time.Second)
+ if err := pol(context.Background(), "new.test"); err != nil {
+ t.Fatalf("after the window: want the order allowed, got %v", err)
+ }
+}
+
+// The window covers the box that is slowest to learn the name, and that box
+// polls on its own phase, so it must be at least one home map poll.
+func TestNameSettleWindowCoversAHomeMapPoll(t *testing.T) {
+ if nameSettleWindow() <= homeMapInterval {
+ t.Fatalf("window %s must be longer than the home map poll %s", nameSettleWindow(), homeMapInterval)
+ }
+}
+
+// A name homed on ANOTHER box reaches the issuer through its own home map
+// poll, and a third box may still be a poll behind it, so it is held too.
+func TestHostPolicyHoldsANameAnotherBoxHasJustPublished(t *testing.T) {
+ clk := &clockAt{t: time.Unix(1_800_000_000, 0)}
+ e, m := settleEdge(t, []string{"old.test"}, "remote-old.test")
+ pol := e.issuerHostPolicyAt(clk.now)
+
+ homedOn(t, m, "betty", "2.2.2.2", "remote-old.test", "remote-new.test")
+ if err := pol(context.Background(), "remote-new.test"); !errors.Is(err, errNameSettling) {
+ t.Fatalf("a name another box just published = %v, want errNameSettling", err)
+ }
+ if err := pol(context.Background(), "remote-old.test"); err != nil {
+ t.Fatalf("an old remote name must not be held by a new map: %v", err)
+ }
+ clk.advance(nameSettleWindow())
+ if err := pol(context.Background(), "remote-new.test"); err != nil {
+ t.Fatalf("after the window: want the order allowed, got %v", err)
+ }
+}
+
+// One box, nobody else to wait for: a new name is ordered at once, as before.
+func TestHostPolicyDoesNotHoldWithoutAnotherEdge(t *testing.T) {
+ clk := &clockAt{t: time.Unix(1_800_000_000, 0)}
+ e := testIssuerEdge("old.test")
+ e.issuer = func() (context.Context, bool) { return context.Background(), true }
+ m := newHomeMap(release.NewDirStore(t.TempDir()), "annie")
+ homedOn(t, m, "annie", "1.1.1.1", "old.test") // only this box's own file
+ e.homes.Store(m)
+ pol := e.issuerHostPolicyAt(clk.now)
+
+ mint(e, "new.test")
+ if err := pol(context.Background(), "new.test"); err != nil {
+ t.Fatalf("single-edge deployment: want no hold, got %v", err)
+ }
+
+ // No home map at all (no deployment store): today's behaviour, too.
+ e2 := testIssuerEdge("old.test")
+ pol2 := e2.issuerHostPolicyAt(clk.now)
+ mint(e2, "new.test")
+ if err := pol2(context.Background(), "new.test"); err != nil {
+ t.Fatalf("no home map: want no hold, got %v", err)
+ }
+}
+
+// The hold is the issuer's alone and comes after the two existing refusals:
+// a non-issuer still says errNotIssuer and a stranger is still unknown.
+func TestHostPolicySettleComesAfterTheExistingRefusals(t *testing.T) {
+ clk := &clockAt{t: time.Unix(1_800_000_000, 0)}
+ e, _ := settleEdge(t, []string{"old.test"}, "remote-old.test")
+ pol := e.issuerHostPolicyAt(clk.now)
+ mint(e, "new.test")
+
+ if err := pol(context.Background(), "stranger.test"); err == nil || errors.Is(err, errNameSettling) {
+ t.Fatalf("unknown host = %v, want the registry refusal", err)
+ }
+ e.issuer = func() (context.Context, bool) { return nil, false }
+ if err := pol(context.Background(), "new.test"); !errors.Is(err, errNotIssuer) {
+ t.Fatalf("non-issuer = %v, want errNotIssuer", err)
+ }
+}
+
+// A name that leaves and comes back (a move away and back) is new again.
+func TestHostPolicyHoldsANameThatReturns(t *testing.T) {
+ clk := &clockAt{t: time.Unix(1_800_000_000, 0)}
+ e, _ := settleEdge(t, []string{"old.test", "mover.test"}, "remote-old.test")
+ pol := e.issuerHostPolicyAt(clk.now)
+ if err := pol(context.Background(), "mover.test"); err != nil {
+ t.Fatalf("baseline name: %v", err)
+ }
+ gone := map[string]upstream{"old.test": {}}
+ e.upstreams.Store(&gone)
+ if err := pol(context.Background(), "old.test"); err != nil { // rebuild without mover
+ t.Fatalf("old.test: %v", err)
+ }
+ clk.advance(time.Hour)
+ mint(e, "mover.test")
+ if err := pol(context.Background(), "mover.test"); !errors.Is(err, errNameSettling) {
+ t.Fatalf("a name that came back = %v, want errNameSettling", err)
+ }
+}
+
+// The warm meets the hold as "not yet", not as a failed order: no hourly
+// backoff, no failure record, no order budget spent, and a pass soon after
+// the window ends.
+func TestWarmWaitsOutASettlingNameWithoutFailing(t *testing.T) {
+ store := release.NewDirStore(t.TempDir())
+ settled := false
+ calls := 0
+ w := newCertWarm(
+ func() []string { return []string{"new.test"} },
+ func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
+ calls++
+ if !settled {
+ return nil, &settlingError{left: 20 * time.Second}
+ }
+ return &tls.Certificate{}, nil
+ },
+ func(string) bool { return true },
+ nil,
+ store,
+ )
+ delay := w.pass()
+ if delay > 20*time.Second+warmSettleSlack || delay < 20*time.Second {
+ t.Fatalf("pass returned %s, want the time left in the window (20s, plus at most %s)", delay, warmSettleSlack)
+ }
+ w.mu.Lock()
+ until, backing := w.nextAttempt["new.test"]
+ orders := len(w.recentOrders)
+ w.mu.Unlock()
+ if backing && time.Until(until) > time.Minute {
+ t.Fatalf("a settling name was put on a %s backoff", time.Until(until).Round(time.Second))
+ }
+ if orders != 0 {
+ t.Fatalf("a held order spent %d of the order budget", orders)
+ }
+ if keys, _ := store.List(context.Background(), certwarm.Prefix); len(keys) != 0 {
+ t.Fatalf("a held order wrote a failure record: %v", keys)
+ }
+
+ settled = true
+ w.mu.Lock()
+ delete(w.nextAttempt, "new.test") // the window has passed
+ w.mu.Unlock()
+ w.pass()
+ w.mu.Lock()
+ warmed := w.warmed["new.test"]
+ w.mu.Unlock()
+ if !warmed || calls != 2 {
+ t.Fatalf("after the window: warmed=%v calls=%d, want the order placed", warmed, calls)
+ }
+}
+
+// Round 1 (Astra, P1): a pass that runs for some other reason while a name is
+// held skips that name on its backoff floor, and must still come back when
+// the hold ends rather than in an hour.
+func TestWarmKeepsAHoldsDeadlineThroughAnUnrelatedPass(t *testing.T) {
+ clk := &clockAt{t: time.Unix(1_800_000_000, 0)}
+ holdUntil := clk.now().Add(45 * time.Second)
+ w := newCertWarm(
+ func() []string { return []string{"held.test", "other.test"} },
+ func(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
+ if h.ServerName == "held.test" && clk.now().Before(holdUntil) {
+ return nil, &settlingError{left: holdUntil.Sub(clk.now())}
+ }
+ return &tls.Certificate{}, nil
+ },
+ func(string) bool { return true },
+ nil,
+ nil,
+ )
+ w.now = clk.now
+ if d := w.pass(); d != 45*time.Second+warmSettleSlack {
+ t.Fatalf("first pass = %s, want the hold (45s) plus slack", d)
+ }
+ clk.advance(20 * time.Second)
+ if d := w.pass(); d != 25*time.Second+warmSettleSlack {
+ t.Fatalf("a pass during the hold = %s, want the 25s left plus slack, not %s", d, warmInterval)
+ }
+ clk.advance(25*time.Second + warmSettleSlack)
+ w.pass()
+ w.mu.Lock()
+ warmed := w.warmed["held.test"]
+ w.mu.Unlock()
+ if !warmed {
+ t.Fatal("the held name was not ordered once its hold ended")
+ }
+ if d := w.pass(); d != warmInterval {
+ t.Fatalf("after the hold = %s, want the hourly pass", d)
+ }
+}
+
+// Two holds with different deadlines: the pass comes back for the earlier,
+// then for the later.
+func TestWarmComesBackForEachHold(t *testing.T) {
+ clk := &clockAt{t: time.Unix(1_800_000_000, 0)}
+ start := clk.now()
+ until := map[string]time.Time{
+ "a.test": start.Add(10 * time.Second),
+ "b.test": start.Add(40 * time.Second),
+ }
+ w := newCertWarm(
+ func() []string { return []string{"a.test", "b.test"} },
+ func(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
+ if u := until[h.ServerName]; clk.now().Before(u) {
+ return nil, &settlingError{left: u.Sub(clk.now())}
+ }
+ return &tls.Certificate{}, nil
+ },
+ func(string) bool { return true },
+ nil,
+ nil,
+ )
+ w.now = clk.now
+ if d := w.pass(); d != 10*time.Second+warmSettleSlack {
+ t.Fatalf("first pass = %s, want the earlier hold (10s) plus slack", d)
+ }
+ clk.advance(10*time.Second + warmSettleSlack)
+ if d := w.pass(); d != 28*time.Second+warmSettleSlack {
+ t.Fatalf("second pass = %s, want the later hold's 28s left plus slack", d)
+ }
+}
+
+// A name already warmed (a renewal re-arm) that is held is not charged to
+// the order budget and is not marked failed.
+func TestWarmHeldReArmSpendsNoBudget(t *testing.T) {
+ held := false
+ w := newCertWarm(
+ func() []string { return []string{"warm.test"} },
+ func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
+ if held {
+ return nil, &settlingError{left: 30 * time.Second}
+ }
+ return &tls.Certificate{}, nil
+ },
+ func(string) bool { return true },
+ nil,
+ nil,
+ )
+ w.pass()
+ w.mu.Lock()
+ before := len(w.recentOrders)
+ w.mu.Unlock()
+ held = true
+ w.pass()
+ w.mu.Lock()
+ after := len(w.recentOrders)
+ w.mu.Unlock()
+ if after != before {
+ t.Fatalf("a held re-arm changed the order stamps %d -> %d", before, after)
+ }
+}
+
+// When the boot refresh failed, the map starts empty; the first snapshot
+// that is read is a baseline, not news about every name in it.
+func TestHostPolicyTakesTheFirstReadSnapshotAsABaseline(t *testing.T) {
+ clk := &clockAt{t: time.Unix(1_800_000_000, 0)}
+ e := testIssuerEdge("old.test")
+ e.issuer = func() (context.Context, bool) { return context.Background(), true }
+ m := newHomeMap(release.NewDirStore(t.TempDir()), "annie") // never refreshed
+ e.homes.Store(m)
+ pol := e.issuerHostPolicyAt(clk.now)
+
+ homedOn(t, m, "betty", "2.2.2.2", "remote.test")
+ if err := pol(context.Background(), "remote.test"); err != nil {
+ t.Fatalf("a name in the first snapshot read = %v, want no hold", err)
+ }
+ homedOn(t, m, "betty", "2.2.2.2", "remote.test", "remote-new.test")
+ if err := pol(context.Background(), "remote-new.test"); !errors.Is(err, errNameSettling) {
+ t.Fatalf("a name in a later snapshot = %v, want errNameSettling", err)
+ }
+}
+
+// A wake arriving while the name settles must not trigger a pass that would
+// only meet the hold again; the warm already has its own pass coming.
+func TestWarmDoesNotTreatASettlingNameAsNew(t *testing.T) {
+ w := newCertWarm(
+ func() []string { return []string{"new.test"} },
+ func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
+ return nil, &settlingError{left: 30 * time.Second}
+ },
+ func(string) bool { return true },
+ nil,
+ nil,
+ )
+ w.pass()
+ if w.hasNewHost() {
+ t.Fatal("a settling name read as new: every reload in the fleet would rerun the pass")
+ }
+}
+
+// Round 2 (Astra, P1): a hold that ends WHILE a pass is still running (here,
+// another host's order takes 30 s) must still bring the pass back for the
+// held name, not leave it for the hourly pass.
+func TestWarmRetriesAHoldThatEndsDuringAPass(t *testing.T) {
+ clk := &clockAt{t: time.Unix(1_800_000_000, 0)}
+ holdUntil := clk.now().Add(45 * time.Second)
+ slowFirst := true
+ w := newCertWarm(
+ func() []string { return []string{"held.test", "slow.test"} },
+ func(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
+ switch h.ServerName {
+ case "held.test":
+ if clk.now().Before(holdUntil) {
+ return nil, &settlingError{left: holdUntil.Sub(clk.now())}
+ }
+ case "slow.test":
+ if slowFirst {
+ return nil, &settlingError{left: 20 * time.Second}
+ }
+ clk.advance(30 * time.Second) // the order itself takes 30 s
+ }
+ return &tls.Certificate{}, nil
+ },
+ func(string) bool { return true },
+ nil,
+ nil,
+ )
+ w.now = clk.now
+ w.pass() // t=0: both held
+ clk.advance(20 * time.Second)
+ slowFirst = false
+ d := w.pass() // t=20: skips held.test, orders slow.test until t=50
+ if d > warmSettleSlack {
+ t.Fatalf("the hold ended during the pass; next pass in %s, want at most %s", d, warmSettleSlack)
+ }
+ clk.advance(d)
+ w.pass()
+ w.mu.Lock()
+ warmed := w.warmed["held.test"]
+ w.mu.Unlock()
+ if !warmed {
+ t.Fatal("held.test was not ordered on the pass after its hold ended")
+ }
+}
+
+// An owed name the order cap defers is handed to the cap's own schedule:
+// the pass comes back after warmCappedDelay, not in a tight loop.
+func TestWarmHandsADueHoldToTheCap(t *testing.T) {
+ clk := &clockAt{t: time.Unix(1_800_000_000, 0)}
+ var hosts []string
+ for i := range warmOrdersPerPass {
+ hosts = append(hosts, "fill"+string(rune('a'+i))+".test")
+ }
+ hosts = append(hosts, "zheld.test") // sorted last: the cap reaches it
+ held := true
+ w := newCertWarm(
+ func() []string { return hosts },
+ func(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
+ if h.ServerName == "zheld.test" && held {
+ return nil, &settlingError{left: 10 * time.Second}
+ }
+ return &tls.Certificate{}, nil
+ },
+ func(string) bool { return true },
+ nil,
+ nil,
+ )
+ w.now = clk.now
+ // First pass: zheld.test alone, so it is held (owed) with the budget
+ // untouched.
+ all := hosts
+ hosts = []string{"zheld.test"}
+ w.pass()
+ hosts = all
+ held = false
+ clk.advance(10 * time.Second)
+ // Now the fills spend the whole budget before zheld.test is reached.
+ if d := w.pass(); d != warmCappedDelay {
+ t.Fatalf("capped pass with a due hold = %s, want the cap's %s", d, warmCappedDelay)
+ }
+ w.mu.Lock()
+ _, owed := w.settleUntil["zheld.test"]
+ w.mu.Unlock()
+ if owed {
+ t.Fatal("a due hold the cap deferred is still owed: it would shorten every later pass")
+ }
+}
+
+// The guard: across random hold deadlines, order durations and pass
+// timings, after every pass each name that is still held or due is owed a
+// pass no later than its deadline (plus slack), and every name is
+// eventually warmed.
+func TestWarmOwedRetryInvariantSimulation(t *testing.T) {
+ for seed := range int64(300) {
+ rng := rand.New(rand.NewPCG(uint64(seed), 7))
+ clk := &clockAt{t: time.Unix(1_800_000_000, 0)}
+ n := 2 + rng.IntN(5)
+ names := make([]string, n)
+ until := map[string]time.Time{}
+ cost := map[string]time.Duration{}
+ for i := range names {
+ names[i] = fmt.Sprintf("h%d.test", i)
+ until[names[i]] = clk.now().Add(time.Duration(rng.IntN(90)) * time.Second)
+ cost[names[i]] = time.Duration(rng.IntN(40)) * time.Second
+ }
+ w := newCertWarm(
+ func() []string { return names },
+ func(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
+ if u := until[h.ServerName]; clk.now().Before(u) {
+ return nil, &settlingError{left: u.Sub(clk.now())}
+ }
+ clk.advance(cost[h.ServerName])
+ return &tls.Certificate{}, nil
+ },
+ func(string) bool { return true },
+ nil,
+ nil,
+ )
+ w.now = clk.now
+ for step := 0; step < 50; step++ {
+ d := w.pass()
+ now := clk.now()
+ w.mu.Lock()
+ for _, h := range names {
+ if w.warmed[h] {
+ continue
+ }
+ due := max(until[h].Sub(now), 0) + warmSettleSlack
+ if d > due {
+ w.mu.Unlock()
+ t.Fatalf("seed %d step %d: next pass in %s, but %s is owed one within %s", seed, step, d, h, due)
+ }
+ }
+ done := len(w.warmed) == n
+ w.mu.Unlock()
+ if done {
+ break
+ }
+ // Sometimes an unrelated wake runs a pass early.
+ if rng.IntN(3) == 0 {
+ d = time.Duration(rng.Int64N(int64(d) + 1))
+ }
+ clk.advance(d)
+ }
+ w.mu.Lock()
+ got := len(w.warmed)
+ w.mu.Unlock()
+ if got != n {
+ t.Fatalf("seed %d: %d of %d names warmed after 50 passes", seed, got, n)
+ }
+ }
+}
diff --git a/internal/edge/certsync.go b/internal/edge/certsync.go
index ba54d8564..bf9045dfc 100644
--- a/internal/edge/certsync.go
+++ b/internal/edge/certsync.go
@@ -190,7 +190,19 @@ func (e *Edge) armCertIssuance(inner autocert.Cache) autocert.Cache {
// days early), so there is deliberately NO fencing token here and no
// readiness predicate on the election: a fence would trade a rare duplicate
// order for a deployment that can stop issuing altogether.
+//
+// Last, on the issuer only: a name it first saw less than one home map poll
+// ago is held (certsettle.go, #443), because the other edges the CA will
+// also validate through cannot answer for it yet.
func (e *Edge) issuerHostPolicy() autocert.HostPolicy {
+ return e.issuerHostPolicyAt(time.Now)
+}
+
+// issuerHostPolicyAt is issuerHostPolicy on a given clock. The names the
+// edge serves when it is called are dated as already settled, so it must be
+// built after the registry and the home map's first refresh, as Run does.
+func (e *Edge) issuerHostPolicyAt(now func() time.Time) autocert.HostPolicy {
+ ages := newNameAges(e, now)
return func(_ context.Context, host string) error {
if !e.deploymentHost(host) {
return fmt.Errorf("acme: host %q not in registry", host)
@@ -198,7 +210,7 @@ func (e *Edge) issuerHostPolicy() autocert.HostPolicy {
if _, ok := e.issuerGate(); !ok {
return errNotIssuer
}
- return nil
+ return ages.holdIfSettling(e, host)
}
}
diff --git a/internal/edge/certwarm.go b/internal/edge/certwarm.go
index eda46391a..789903d3e 100644
--- a/internal/edge/certwarm.go
+++ b/internal/edge/certwarm.go
@@ -94,6 +94,10 @@ const (
// enough that one pass over many new hosts reads the bucket once, not once
// per host, while the bucket is down.
warmEdgeSetEmptyTTL = 30 * time.Second
+ // warmSettleSlack is how long after a held name's window ends the warm
+ // comes back for it (certsettle.go): enough that the pass lands after the
+ // window, not on its edge.
+ warmSettleSlack = 2 * time.Second
)
// certWarm proactively orders and renews per-host certificates.
@@ -151,6 +155,14 @@ type certWarm struct {
// recentOrders stamps the new orders placed in the last warmCappedDelay,
// the window warmOrdersPerPass is counted over.
recentOrders []time.Time
+ // settleUntil is the warm's one rule for held names (certsettle.go,
+ // #443): a name in it is OWED a pass at max(its deadline, now), and
+ // owedWait is the only thing that turns it into the next pass's time.
+ // An entry leaves only through discharge, which runs when the name is
+ // ordered (success or failure), when it is handed to a schedule that
+ // brings it back by itself (the order cap, the DNS-miss schedule), and
+ // when it leaves the set. A new hold simply moves the deadline.
+ settleUntil map[string]time.Time
// wake asks the loop for an early pass (nudge). Buffered one deep: a
// wake already pending covers any that arrive behind it.
@@ -183,6 +195,7 @@ func newCertWarm(hosts func() []string, getCert func(*tls.ClientHelloInfo) (*tls
nextAttempt: map[string]time.Time{},
warmed: map[string]bool{},
dnsMisses: map[string]dnsMiss{},
+ settleUntil: map[string]time.Time{},
wake: make(chan struct{}, 1),
now: time.Now,
gateTick: warmGateRecheck,
@@ -481,10 +494,14 @@ func (c *certWarm) pass() time.Duration {
// would strand exactly the domain whose resolver is briefly sick.
if !seen {
if orders >= budget {
+ // Handed to the cap: the capped delay brings it back.
capped = true
+ c.discharge(h)
continue
}
if !c.pointsHere(h) {
+ // Handed to the DNS-miss schedule.
+ c.discharge(h)
c.dnsMissed(h, now)
continue
}
@@ -499,9 +516,24 @@ func (c *certWarm) pass() time.Duration {
orders++
}
if err := c.warmOne(h); err != nil {
+ if left, ok := settleLeft(err); ok {
+ // Held, not failed (certsettle.go, #443): the other edges
+ // cannot answer for this name yet. No backoff, no record, and
+ // the order budget stamped above is handed back.
+ if !seen {
+ c.mu.Lock()
+ c.recentOrders = c.recentOrders[:len(c.recentOrders)-1]
+ c.mu.Unlock()
+ orders--
+ }
+ c.settling(h, left)
+ continue
+ }
+ c.discharge(h)
c.fail(gctx, h, err, records[h])
continue
}
+ c.discharge(h)
c.mu.Lock()
delete(c.nextAttempt, h)
first := !c.warmed[h]
@@ -527,6 +559,7 @@ func (c *certWarm) pass() time.Duration {
}
}
c.mu.Unlock()
+ owed, isOwed := c.owedWait(inSet)
// Housekeeping last: it is the least urgent thing this pass does, and
// running it after the orders means a slow bucket delays litter removal
// rather than certificate issuance (certsweep.go).
@@ -535,10 +568,29 @@ func (c *certWarm) pass() time.Duration {
// met a host it had to skip: a host attached a moment later must not be
// left for the hourly pass because its wake arrived while the budget was
// empty.
+ delay := warmInterval
if capped || (orders > 0 && orders >= budget) {
- return warmCappedDelay
+ delay = warmCappedDelay
}
- return warmInterval
+ // Back just after the soonest owed name's hold ends, so a new host gets
+ // its certificate within about a minute of being minted.
+ if isOwed {
+ delay = min(delay, owed+warmSettleSlack)
+ }
+ return delay
+}
+
+// settling puts a held name back for when its hold ends. nextAttempt is the
+// floor pass() and hasNewHost already honour, so the name is neither retried
+// early nor counted as new by a wake in the meantime; settleUntil is what
+// brings every later pass back for it on time (owedWait).
+func (c *certWarm) settling(host string, left time.Duration) {
+ until := c.now().Add(left)
+ c.mu.Lock()
+ c.nextAttempt[host] = until
+ c.settleUntil[host] = until
+ c.mu.Unlock()
+ log.Printf("edge: cert warm for %s waits %s for the other edges to learn the name", host, left.Round(time.Second))
}
// warmOne asks autocert for host's certificate, which mints it when absent
@@ -885,3 +937,37 @@ func (c *certWarm) prune(ctx context.Context, records map[string]certwarm.Record
c.clearRecord(ctx, host, "detached")
}
}
+
+// owedWait is the one place the warm's next pass is derived from held names:
+// how long until the soonest owed name may be ordered, counting a deadline
+// that has already passed as now, and false when nothing is owed. A due
+// name was not reached by the pass that just ran (it ended while another
+// order was in flight), so the next pass must come at once. That cannot
+// spin: the next pass reaches it, and every way out of that pass (ordered,
+// failed, held again, capped, DNS miss) discharges it or moves its deadline.
+// Names that left the set are discharged here.
+func (c *certWarm) owedWait(inSet map[string]bool) (time.Duration, bool) {
+ now := c.now()
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ var soonest time.Duration
+ found := false
+ for h, until := range c.settleUntil {
+ if !inSet[h] {
+ delete(c.settleUntil, h)
+ continue
+ }
+ left := max(until.Sub(now), 0)
+ if !found || left < soonest {
+ soonest, found = left, true
+ }
+ }
+ return soonest, found
+}
+
+// discharge ends what the warm owes a held name (see settleUntil).
+func (c *certWarm) discharge(host string) {
+ c.mu.Lock()
+ delete(c.settleUntil, host)
+ c.mu.Unlock()
+}
diff --git a/internal/provision/testdata/plan14-root-reads-cert-warm-propagation-443.tsv b/internal/provision/testdata/plan14-root-reads-cert-warm-propagation-443.tsv
new file mode 100644
index 000000000..d3382f272
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-cert-warm-propagation-443.tsv
@@ -0,0 +1,3 @@
+# Census overlay cert-warm-propagation-443, written by census-propose (#369). census-ruling-cert-warm-propagation-443, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-cert-warm-propagation-443.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage internal/edge 6844581972575ee102c731177887910f7b00834819920a013d2b20fed8b3962d
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index b156ee056..74b57101d 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -23,3 +23,4 @@ plan14-root-reads-team-scoped-credentials.tsv b6f3a369ca91563f1d28a9855b242125fa
plan14-root-reads-rootfs-apps-3-release.tsv 2cced1b359b64855bacc94c64e0370e6b78cfe2c4947d6d4944915b3a05c6a7c
plan14-root-reads-rootfs-overlap-demand.tsv 2cced1b359b64855bacc94c64e0370e6b78cfe2c4947d6d4944915b3a05c6a7c
plan14-root-reads-edge-roll-blip.tsv 886863e79986b005cf52aa11445a49c1bbc3fb9b55bce25915fc21d0e65f1b7f
+plan14-root-reads-cert-warm-propagation-443.tsv 886863e79986b005cf52aa11445a49c1bbc3fb9b55bce25915fc21d0e65f1b7f