carlos / platform Public

Fix anonymous demo launch, retries and job status

Read the starter's socket and database paths from the platform argv.
Create root control's private release state before namespace setup, and
preserve wildcard retry deadlines across refreshes and issuer changes.

Document every potential housekeeper's demo tuple and DNS grant. Report
older jobs as superseded and give unavailable builds a 15-second retry
hint without spending admission budgets. Add regression tests and the
generated root-read census proposal.
codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev da8f93bb37efae75cf8872f8df7113f170adc791 parent 2914921
14 files changed, +405 −22
  • README.md +2 −2
  • docs/superpowers/notes/census-agent-start-demo-1-followups-claims.md +1 −0
  • docs/superpowers/notes/census-proposal-agent-start-demo-1-followups.md +19 −0
  • internal/console/apidemo.go +17 −7
  • internal/console/demo_e2e_test.go +2 −2
  • internal/console/demo_followups_test.go +138 −0
  • internal/console/testdata/demo/main.go +6 −3
  • internal/edge/wildcard.go +26 −7
  • internal/edge/wildcard_retry_test.go +130 −0
  • internal/edge/wildcard_zonecheck_test.go +1 −1
  • internal/host/claimunit.go +3 −0
  • internal/host/demo_control_paths_test.go +54 −0
  • internal/provision/testdata/plan14-root-reads-agent-start-demo-1-followups.tsv +5 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0

CI cancelled — superseded by a newer push — run details

Intent

Human

<paseo-system version="1" kind="agent-message" source-agent-id="32157efb-ed29-443f-b428-8c9e3320fa50" message-id="0c892a4e-9f52-49b6-be07-2198cc8ce563"> Correction to my last message (the shell dropped one part): the merge step for the follow-ups branch is amadan branch merge carlos/platform &lt;branch&gt; -squash -expect &lt;full 40-char sha&gt; with a subject under 80 characters, only after the Opus review is clean and CI is green on that exact tip. Everything else in the message stands. </paseo-system>

Attributed to this commit: 60.1 g CO₂e (3,330,759 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on agent-start-demo-1-followups, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/README.md b/README.md
index bfb9463bb..ae16dcc03 100644
--- a/README.md
+++ b/README.md
@@ -631,11 +631,11 @@ Build the toolchain bundle on the operator side before enabling a worker. Use na
Make the directory and its ancestors root-owned and safe from agent writes. Bundle files must be regular files with mode `0444` or `0555`; symlinks, hard links and unlisted files are refused. Write `MANIFEST` with LF endings and a final LF. Its first lines are `go<TAB>1.26.10` and `modules<TAB><Lock.ModulesDigest()>`. Follow them with one tab-separated row per file other than `MANIFEST`, sorted by relative path: relative path, four-digit octal mode, decimal size, lowercase SHA-256. `Lock.ModulesDigest()` hashes the canonical dependency lock; the worker's bundle digest separately hashes the exact manifest bytes. `host.CheckDemoToolchain` checks the entire bundle, then worker initialization must pass the nested isolation check and compile its trusted probe in the disposable offline service. There is no download fallback. To replace a bundle, drain builds, install a new immutable directory, update the per-box path and restart root control.
-On every ingress box that fronts the demo domain, set the same `CARLOS_DEMO_ACCOUNT`, `CARLOS_DEMO_FLEET` and `CARLOS_DEMO_DOMAIN` in root-owned `/etc/carlos/host.env`, without `CARLOS_DEMO_BOX`. Preserve these per-box values through host.env rewrites. Configure the ingress DNS provider for the wildcard parent. The edge reads these settings at startup, so restart `carlos-edge` as part of the rollout after changing them.
+On every ingress box that fronts the demo domain and every box that can become the housekeeper, set the same `CARLOS_DEMO_ACCOUNT`, `CARLOS_DEMO_FLEET` and `CARLOS_DEMO_DOMAIN` in root-owned `/etc/carlos/host.env`, without `CARLOS_DEMO_BOX`. Preserve these per-box values through host.env rewrites. The housekeeper is the deployment's certificate issuer and orders the demo wildcard. Give every box that can hold that role the DNS-01 grant on the demo zone, even if it does not serve ingress traffic. The edge reads these settings at startup, so restart `carlos-edge` on each affected box as part of the rollout after changing them.
For an approved rollout, point wildcard DNS for your demo domain at the existing ingress and install wildcard TLS through the deployment's existing certificate workflow. The edge includes `CARLOS_DEMO_DOMAIN` among its explicit wildcard parents. Roll out the built boxes and ingress first, then the console. Confirm the box reports `anonymous-demo-v1` with the expected verified bundle digest, the policy writer can acquire its lease, and change delivery is working before enabling admission. Verify an ordinary app through its own hostname as well.
-For the smoke check, gzip a tar archive of the locked starter's files without a wrapper directory. Submit it without logging in to `POST /api/demo/apps` as `application/gzip`; the compressed limit is 5,000,000 bytes. Keep the returned claim token private. Both create and update return `202` with `jobId`, `name`, `statusUrl` and `expiresAt` (Unix seconds). Create also returns `claimToken`, `claimUrl` and `claimAvailable:false`. Send your harness name in `X-Carlos-Client`; the stored value is trimmed to 100 bytes. Poll `statusUrl` (`GET /api/demo/jobs/<jobId>`) until its `state` is `live`. The other states are `building`, `starting` and `failed`. Then GET its exact HTTPS URL and check `X-Carlos-Version`. Write a SQLite value, submit changed source to the same POST endpoint with `Authorization: Bearer <claimToken>`, and verify that a new version serves the saved value. An update must not extend the 24-hour lifetime. An unavailable worker or failed policy check must refuse admission.
+For the smoke check, gzip a tar archive of the locked starter's files without a wrapper directory. Submit it without logging in to `POST /api/demo/apps` as `application/gzip`; the compressed limit is 5,000,000 bytes. Keep the returned claim token private. Both create and update return `202` with `jobId`, `name`, `statusUrl` and `expiresAt` (Unix seconds). Create also returns `claimToken`, `claimUrl` and `claimAvailable:false`. Send your harness name in `X-Carlos-Client`; the stored value is trimmed to 100 bytes. Poll `statusUrl` (`GET /api/demo/jobs/<jobId>`) until its `state` is `live`. The other states are `building`, `starting`, `failed` and `superseded`. An earlier job becomes `superseded` when a newer update is accepted, even if the earlier job was live. Use the new update's `statusUrl` to follow its progress. Then GET its exact HTTPS URL and check `X-Carlos-Version`. Write a SQLite value, submit changed source to the same POST endpoint with `Authorization: Bearer <claimToken>`, and verify that a new version serves the saved value. An update must not extend the 24-hour lifetime. An unavailable worker or failed policy check must refuse admission. If a worker has not reconnected after a console restart, create and update return `503` with `Retry-After: 15`. Retry after that many seconds; this refusal does not spend a create or update attempt.
Run `CARLOS_DEMO_DEV_WITNESS=1 go test ./internal/host -run '^TestDemoDevKernelAndPurge$' -count=1 -v` only on an explicitly designated disposable, idle linux-arm64 systemd sandbox. Install the built binary and this checkout's unit templates first. The application witness needs no pre-existing demo drop-ins; the builder witness needs root control active with its worker switch off, concurrency one, and `CARLOS_DEMO_TOOLCHAIN_DIR` pointing at the verified bundle. The root release/adoption gate must be available for the purge witness. The test exercises application and builder isolation, root stop-before-delete, and the local protocol and durability checks. A skipped test is outstanding evidence, not a rollout pass. Real DNS, TLS and fleet activation still need a separately recorded deployment check.
diff --git a/docs/superpowers/notes/census-agent-start-demo-1-followups-claims.md b/docs/superpowers/notes/census-agent-start-demo-1-followups-claims.md
new file mode 100644
index 000000000..3f95cf957
--- /dev/null
+++ b/docs/superpowers/notes/census-agent-start-demo-1-followups-claims.md
@@ -0,0 +1 @@
+internal/host/claimunit.go:claimUnitContent In demo box mode, declare StateDirectory=carlos-release/private with mode 0700 so systemd creates root-owned release state before namespace setup and keeps it writable. Existing ReadWritePaths and ordinary/claims rendering stay unchanged. No new read site or caller-controlled path.
diff --git a/docs/superpowers/notes/census-proposal-agent-start-demo-1-followups.md b/docs/superpowers/notes/census-proposal-agent-start-demo-1-followups.md
new file mode 100644
index 000000000..562493946
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-agent-start-demo-1-followups.md
@@ -0,0 +1,19 @@
+# Census approval: agent-start-demo-1-followups
+
+Ruling `census-ruling-agent-start-demo-1-followups`. 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/claimunit.go` `claimUnitContent` | body | unchanged (1) | In demo box mode, declare StateDirectory=carlos-release/private with mode 0700 so systemd creates root-owned release state before namespace setup and keeps it writable. Existing ReadWritePaths and ordinary/claims rendering stay unchanged. No new read site or caller-controlled path. |
+
+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/claimunit.go` `claimUnitContent`: authority, task E1,E3. Basis: rev3=PROPOSED-p3;identity=root claim/adoption controller uid 0;basis=adds write permission for exactly the public retry directory only when the root settings reader has verified a complete census and prepared that directory;rev3=census-ruling-agent-start-demo-1;basis=Demo-only ReadWritePaths for instance data/runtime, staged files and root release lock; ordinary rendering unchanged.
+
+Seal: `526d434888d043a8b09d8fe196f6324782d6ca20d759b080f99daa528adf6a32` → `526d434888d043a8b09d8fe196f6324782d6ca20d759b080f99daa528adf6a32`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-agent-start-demo-1-followups.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/internal/console/apidemo.go b/internal/console/apidemo.go
index c910a7933..9eca3401b 100644
--- a/internal/console/apidemo.go
+++ b/internal/console/apidemo.go
@@ -25,7 +25,7 @@ import (
"github.com/carlosframework/platform/internal/release"
)
-// Approved by delegation: Luna copy pass, 2026-11-03 (R22).
+// Initial copy approved by delegation: Luna copy pass, 2026-11-03 (R22).
// DEMO-LIVE-LIMIT uses a read-only pre-check before spending an attempt and
// a five-minute retry; ReserveDemo still enforces the ceiling transactionally.
var demoCopy = map[string]string{
@@ -39,9 +39,10 @@ var demoCopy = map[string]string{
"DEMO-LIVE-LIMIT": "The maximum number of live demos has been reached. Try again later. Existing demos will keep running.",
"DEMO-TOKEN": "This demo token is invalid or no longer available.",
"DEMO-UPDATE": "This demo is already being updated or has reached its update limit. Updates do not extend its expiry.",
- "DEMO-BUILD": "Demo builds are unavailable right now. Try again later.",
+ "DEMO-BUILD": "Demo builds are unavailable right now. Try again shortly.",
"DEMO-BUILD-STARTING": "The demo is starting.",
"DEMO-BUILD-FINISHING": "The update is finishing. Try again shortly.",
+ "DEMO-SUPERSEDED": "A newer update replaced this job.",
"DEMO-BUILD-LIVE": "The demo is live.",
"DEMO-BUILD-FAILED": "The demo could not start. Send another update with the same token.",
"DEMO-ROLLED-BACK": "The update failed, but the previous version is still running. Send another update with the same token.",
@@ -286,6 +287,7 @@ func demoError(w http.ResponseWriter, err error) {
case errors.Is(err, ErrDemoUpdateLimit):
jsonError(w, 429, demoCopy["DEMO-UPDATE"])
default:
+ w.Header().Set("Retry-After", "15")
jsonError(w, 503, demoCopy["DEMO-BUILD"])
}
}
@@ -523,9 +525,13 @@ func (s *Server) handleDemoStatus(w http.ResponseWriter, r *http.Request) {
state := "failed"
currentJob := false
if err := s.withDemoLocked(r.Context(), row.Job.DemoID, func(d DemoRow, life AppLife) error {
- if d.Generation != int64(row.Job.Generation) || life.Lifetime != row.Job.Lifetime {
+ if life.Lifetime != row.Job.Lifetime || d.Generation < int64(row.Job.Generation) {
return errDemoJob
}
+ if d.Generation > int64(row.Job.Generation) {
+ state = "superseded"
+ return nil
+ }
currentJob = true
if row.State == "queued" || row.State == "picked" {
state = "building"
@@ -545,10 +551,12 @@ func (s *Server) handleDemoStatus(w http.ResponseWriter, r *http.Request) {
jsonError(w, http.StatusServiceUnavailable, demoCopy["DEMO-BUILD"])
return
}
- if demoSettlementPending(stage) {
- state = "starting"
- } else if stage == "rolled-back" || stage == "settlement-failed" {
- state = "failed"
+ if currentJob {
+ if demoSettlementPending(stage) {
+ state = "starting"
+ } else if stage == "rolled-back" || stage == "settlement-failed" {
+ state = "failed"
+ }
}
response := map[string]any{"jobId": id, "state": state, "diagnostics": diagnostics, "diagnosticsTruncated": truncated}
publishedStage := strings.TrimPrefix(stage, "timeout:")
@@ -557,6 +565,8 @@ func (s *Server) handleDemoStatus(w http.ResponseWriter, r *http.Request) {
response["version"] = demoVersion(row.Job)
}
switch state {
+ case "superseded":
+ response["message"] = demoCopy["DEMO-SUPERSEDED"]
case "starting":
response["message"] = demoCopy["DEMO-BUILD-STARTING"]
if demoSettlementPending(stage) {
diff --git a/internal/console/demo_e2e_test.go b/internal/console/demo_e2e_test.go
index b42706a94..49557ce46 100644
--- a/internal/console/demo_e2e_test.go
+++ b/internal/console/demo_e2e_test.go
@@ -552,9 +552,9 @@ func demoE2EBuilds(t *testing.T) (archives [2][]byte, arm [2][]byte, native [2]s
}
func demoE2EStart(t *testing.T, binary, db, socket string) func() {
t.Helper()
- cmd := exec.Command(binary)
+ cmd := exec.Command(binary, "--socket", socket, "--db", db)
cmd.Dir = filepath.Dir(db)
- cmd.Env = []string{"CARLOS_DB=" + db, "CARLOS_SOCKET=" + socket}
+ cmd.Env = []string{} // The box supplies socket and database paths only through argv.
log, err := os.Create(filepath.Join(filepath.Dir(db), filepath.Base(socket)+".log"))
if err != nil {
t.Fatal(err)
diff --git a/internal/console/demo_followups_test.go b/internal/console/demo_followups_test.go
new file mode 100644
index 000000000..04ca25d81
--- /dev/null
+++ b/internal/console/demo_followups_test.go
@@ -0,0 +1,138 @@
+package console
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/demobuild"
+)
+
+func TestDemoSupersededJobStatus(t *testing.T) {
+ for _, original := range []string{"published", "failed"} {
+ t.Run(original, func(t *testing.T) {
+ s, d, j, _ := demoPublishFixture(t)
+ if original == "published" {
+ demoAcceptReadiness(s, demoVersion(j))
+ if err := s.publishReadyDemos(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ if got := demoSettlementStatus(t, s, j); got["state"] != "live" {
+ t.Fatalf("before update: %v", got)
+ }
+ } else {
+ if _, err := s.store.db.Exec(`UPDATE demo_jobs SET state='failed',publish_stage='rolled-back' WHERE id=?`, j.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.store.db.Exec(`UPDATE demo_apps SET active_job_id='' WHERE demo_id=?`, d.ID); err != nil {
+ t.Fatal(err)
+ }
+ }
+ current, err := s.store.demoByID(t.Context(), d.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ next, err := s.enqueueDemo(t.Context(), current, demoJobSource())
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, nextState := range []string{"queued", "published", "failed"} {
+ if _, err := s.store.db.Exec(`UPDATE demo_jobs SET state=? WHERE id=?`, nextState, next.ID); err != nil {
+ t.Fatal(err)
+ }
+ got := demoSettlementStatus(t, s, j)
+ if got["state"] != "superseded" || got["message"] != "A newer update replaced this job." || got["url"] != nil {
+ t.Fatalf("previous %s, next %s: %v", original, nextState, got)
+ }
+ }
+ // A new lifetime or expired app must never be described as supersession.
+ if _, err := s.store.db.Exec(`UPDATE apps SET lifetime='replacement' WHERE demo_id=?`, d.ID); err != nil {
+ t.Fatal(err)
+ }
+ if got := demoSettlementStatus(t, s, j); got["state"] != "failed" {
+ t.Fatalf("replaced lifetime: %v", got)
+ }
+ if _, err := s.store.db.Exec(`UPDATE apps SET lifetime=? WHERE demo_id=?`, j.Lifetime, d.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.store.db.Exec(`UPDATE apps SET expires_at=1 WHERE demo_id=?`, d.ID); err != nil {
+ t.Fatal(err)
+ }
+ if got := demoSettlementStatus(t, s, j); got["state"] == "superseded" {
+ t.Fatalf("expired: %v", got)
+ }
+ })
+ }
+}
+
+func TestDemoWorkerReconnectRefusal(t *testing.T) {
+ for _, update := range []bool{false, true} {
+ t.Run(map[bool]string{false: "create", true: "update"}[update], func(t *testing.T) {
+ s, _ := demoJobServer(t)
+ source := demoHTTPSource(t)
+ publish := func(token string) *demoRecorder {
+ r := httptest.NewRequest("POST", "/api/demo/apps", bytes.NewReader(source))
+ r.RemoteAddr = "192.0.2.1:1"
+ r.Header.Set("Content-Type", "application/gzip")
+ if token != "" {
+ r.Header.Set("Authorization", "Bearer "+token)
+ }
+ w := newDemoRecorder()
+ s.mux.ServeHTTP(w, r)
+ return w
+ }
+ token := ""
+ if update {
+ w := publish("")
+ if w.Code != 202 {
+ t.Fatalf("create: %d %s", w.Code, w.Body.String())
+ }
+ var got struct{ ClaimToken, JobID string }
+ if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
+ t.Fatal(err)
+ }
+ token = got.ClaimToken
+ if token == "" || !demobuild.ValidJobID(got.JobID) {
+ t.Fatal("missing create credential/job")
+ }
+ if _, err := s.store.db.Exec(`UPDATE demo_jobs SET state='published' WHERE id=?`, got.JobID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.store.db.Exec(`UPDATE demo_apps SET active_job_id=''`); err != nil {
+ t.Fatal(err)
+ }
+ }
+ snapshot := func() [3]int {
+ var out [3]int
+ if err := s.store.db.QueryRow(`SELECT (SELECT count(*) FROM demo_admissions), (SELECT coalesce(sum(update_attempts),0) FROM demo_apps), (SELECT count(*) FROM demo_jobs)`).Scan(&out[0], &out[1], &out[2]); err != nil {
+ t.Fatal(err)
+ }
+ return out
+ }
+ before := snapshot()
+ peers := s.demoJobs.peers
+ s.demoJobs.peers = nil
+ for range 2 {
+ w := publish(token)
+ if w.Code != 503 || w.Header().Get("Retry-After") != "15" || w.Header().Get("Cache-Control") != "no-store" {
+ t.Errorf("refusal: %d %v %s", w.Code, w.Header(), w.Body.String())
+ }
+ var got map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
+ t.Fatal(err)
+ }
+ if got["error"] != "Demo builds are unavailable right now. Try again shortly." {
+ t.Errorf("message: %v", got)
+ }
+ if after := snapshot(); after != before {
+ t.Fatalf("refusal charged budget or made job: %v -> %v", before, after)
+ }
+ }
+ s.demoJobs.peers = peers
+ if w := publish(token); w.Code != 202 {
+ t.Fatalf("reconnected: %d %s", w.Code, w.Body.String())
+ }
+ })
+ }
+}
diff --git a/internal/console/testdata/demo/main.go b/internal/console/testdata/demo/main.go
index 1f66dd6dc..406c03511 100644
--- a/internal/console/testdata/demo/main.go
+++ b/internal/console/testdata/demo/main.go
@@ -1,11 +1,11 @@
package main
import (
+ "flag"
"fmt"
"log"
"net"
"net/http"
- "os"
"amadan.net/rastrillo/rastrillo"
)
@@ -13,12 +13,15 @@ import (
const revision = "one"
func main() {
- db, err := rastrillo.OpenDB(os.Getenv("CARLOS_DB"), []string{`CREATE TABLE IF NOT EXISTS state (id INTEGER PRIMARY KEY, value TEXT NOT NULL)`})
+ socket := flag.String("socket", "", "Unix socket path")
+ database := flag.String("db", "", "SQLite database path")
+ flag.Parse()
+ db, err := rastrillo.OpenDB(*database, []string{`CREATE TABLE IF NOT EXISTS state (id INTEGER PRIMARY KEY, value TEXT NOT NULL)`})
if err != nil {
log.Fatal(err)
}
defer db.Close()
- listener, err := net.Listen("unix", os.Getenv("CARLOS_SOCKET"))
+ listener, err := net.Listen("unix", *socket)
if err != nil {
log.Fatal(err)
}
diff --git a/internal/edge/wildcard.go b/internal/edge/wildcard.go
index c7c88b2c3..067c090d5 100644
--- a/internal/edge/wildcard.go
+++ b/internal/edge/wildcard.go
@@ -491,18 +491,24 @@ func (w *wildcardManager) run() {
// should wait before the next one. Split out of run() so the gating and
// backoff decisions are testable without spinning the loop.
func (w *wildcardManager) pass() time.Duration {
+ return w.passWithClock(time.Now)
+}
+
+func (w *wildcardManager) passWithClock(now func() time.Time) time.Duration {
delay := 12 * time.Hour
w.mu.Lock()
parents := append([]string(nil), w.parents...)
w.mu.Unlock()
standDowns := 0
+ var retries []string
for _, p := range parents {
- if !w.needsObtain(p, time.Now()) {
+ if !w.needsObtain(p, now()) {
continue
}
- if w.backingOff(p, time.Now()) {
+ if w.backingOff(p, now()) {
// A wake (fired because some OTHER parent needs a cert) does
// not shorten this parent's own hourly retry.
+ retries = append(retries, p)
continue
}
// Another process (or pool sibling) may have obtained it already.
@@ -512,7 +518,7 @@ func (w *wildcardManager) pass() time.Duration {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
w.loadCached(ctx, p)
cancel()
- if !w.needsObtain(p, time.Now()) {
+ if !w.needsObtain(p, now()) {
continue
}
// The order gate (certsync.go): one elected issuer talks to the CA.
@@ -540,12 +546,10 @@ func (w *wildcardManager) pass() time.Duration {
retry = noZoneRetry
}
log.Printf("edge: wildcard *.%s: %v — per-host issuance keeps covering; retrying in %s", p, err, retry)
- if retry < delay {
- delay = retry
- }
w.mu.Lock()
- w.nextAttempt[p] = time.Now().Add(retry)
+ w.nextAttempt[p] = now().Add(retry)
w.mu.Unlock()
+ retries = append(retries, p)
continue
}
w.mu.Lock()
@@ -565,6 +569,21 @@ func (w *wildcardManager) pass() time.Duration {
delay = time.Hour
}
}
+ // A refresh can interrupt the retry timer. Preserve every current parent's
+ // deadline, including retries skipped above and time spent ordering others.
+ // An expired retry that stood down uses the non-issuer delay instead.
+ at := now()
+ for _, p := range retries {
+ if !w.needsObtain(p, at) {
+ continue
+ }
+ w.mu.Lock()
+ next, retrying := w.nextAttempt[p]
+ w.mu.Unlock()
+ if retrying {
+ delay = min(delay, max(time.Duration(0), next.Sub(at)))
+ }
+ }
return delay
}
diff --git a/internal/edge/wildcard_retry_test.go b/internal/edge/wildcard_retry_test.go
new file mode 100644
index 000000000..a9c38a838
--- /dev/null
+++ b/internal/edge/wildcard_retry_test.go
@@ -0,0 +1,130 @@
+package edge
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "golang.org/x/crypto/acme/autocert"
+)
+
+func TestWildcardRetrySurvivesRefresh(t *testing.T) {
+ for _, standDown := range []bool{false, true} {
+ t.Run(map[bool]string{false: "issuer", true: "another-parent-stands-down"}[standDown], func(t *testing.T) {
+ ca, requests := countingCA(t)
+ w := newWildcardManager([]string{"demo.example.com"}, "", func() []string { return nil }, nil, "", autocert.DirCache(t.TempDir()), &fakeDNS{})
+ w.directory = ca.URL
+ now := time.Now()
+ clock := func() time.Time { return now }
+ w.refresh()
+ if got := w.passWithClock(clock); got != time.Hour {
+ t.Fatalf("failure delay = %s", got)
+ }
+ first := requests.Load()
+ if first == 0 {
+ t.Fatal("first order was not attempted")
+ }
+ // Startup refresh leaves a wake queued; later route refreshes do the same.
+ <-w.wake
+ if got := w.passWithClock(clock); got != time.Hour {
+ t.Fatalf("queued refresh lost retry: %s", got)
+ }
+ now = now.Add(15 * time.Minute)
+ if standDown {
+ w.staticDomains = append(w.staticDomains, "other.example.com")
+ w.issuer = func() (context.Context, bool) { return context.Background(), false }
+ }
+ w.refresh()
+ <-w.wake
+ delay := w.passWithClock(clock)
+ if delay != 45*time.Minute {
+ t.Fatalf("refresh delay = %s, want 45m", delay)
+ }
+ if got := requests.Load(); got != first {
+ t.Fatalf("retried early: %d -> %d", first, got)
+ }
+ now = now.Add(delay)
+ w.issuer = nil
+ w.passWithClock(clock)
+ if requests.Load() <= first {
+ t.Fatal("no retry at the deadline without another refresh")
+ }
+ })
+ }
+}
+
+type wildcardRetryDNS struct {
+ fakeDNS
+ check func(string) error
+}
+
+func (d *wildcardRetryDNS) checkZone(_ context.Context, name string) error { return d.check(name) }
+
+func TestWildcardRetryDeadlines(t *testing.T) {
+ t.Run("missing-zone", func(t *testing.T) {
+ dns := &zoneCheckingDNS{}
+ w := newWildcardManager([]string{"demo.example.com"}, "", func() []string { return nil }, nil, "", autocert.DirCache(t.TempDir()), dns)
+ now := time.Now()
+ clock := func() time.Time { return now }
+ w.refresh()
+ if got := w.passWithClock(clock); got != noZoneRetry {
+ t.Fatalf("first delay: %s", got)
+ }
+ now = now.Add(time.Hour)
+ w.refresh()
+ if got := w.passWithClock(clock); got != noZoneRetry-time.Hour {
+ t.Fatalf("refresh delay: %s", got)
+ }
+ if len(dns.checked) != 1 {
+ t.Fatal("retried missing zone early")
+ }
+ now = now.Add(noZoneRetry - time.Hour)
+ w.passWithClock(clock)
+ if len(dns.checked) != 2 {
+ t.Fatal("did not retry missing zone")
+ }
+ w.staticDomains = nil
+ w.refresh()
+ if got := w.passWithClock(clock); got != 12*time.Hour {
+ t.Fatalf("removed parent still scheduled: %s", got)
+ }
+ })
+ t.Run("other-order-overruns-deadline", func(t *testing.T) {
+ now := time.Now()
+ dns := &wildcardRetryDNS{check: func(name string) error {
+ if name == "_acme-challenge.b.example.com" {
+ now = now.Add(2 * time.Hour)
+ }
+ return context.DeadlineExceeded
+ }}
+ w := newWildcardManager([]string{"a.example.com", "b.example.com"}, "", func() []string { return nil }, nil, "", autocert.DirCache(t.TempDir()), dns)
+ w.refresh()
+ if got := w.passWithClock(func() time.Time { return now }); got != 0 {
+ t.Fatalf("overdue parent must retry immediately: %s", got)
+ }
+ })
+}
+
+func TestWildcardRetryAfterIssuerStandDown(t *testing.T) {
+ ca, requests := countingCA(t)
+ w := newWildcardManager([]string{"demo.example.com"}, "", func() []string { return nil }, nil, "", autocert.DirCache(t.TempDir()), &fakeDNS{})
+ w.directory = ca.URL
+ now := time.Now()
+ clock := func() time.Time { return now }
+ w.refresh()
+ w.passWithClock(clock)
+ first := requests.Load()
+ now = now.Add(time.Hour)
+ w.issuer = func() (context.Context, bool) { return context.Background(), false }
+ if delay := w.passWithClock(clock); delay != time.Hour {
+ t.Fatalf("expired retry must not spin after losing issuer: %s", delay)
+ }
+ if requests.Load() != first {
+ t.Fatal("non-issuer ordered a certificate")
+ }
+ w.issuer = nil
+ w.passWithClock(clock)
+ if requests.Load() <= first {
+ t.Fatal("new issuer did not retry expired order")
+ }
+}
diff --git a/internal/edge/wildcard_zonecheck_test.go b/internal/edge/wildcard_zonecheck_test.go
index 685db6769..f685b1255 100644
--- a/internal/edge/wildcard_zonecheck_test.go
+++ b/internal/edge/wildcard_zonecheck_test.go
@@ -93,7 +93,7 @@ func TestPassBacksOffANoZoneParentLonger(t *testing.T) {
w.parents = []string{"bad.carlos.exciting.io"}
w.mu.Unlock()
start := time.Now()
- if delay := w.pass(); delay != noZoneRetry {
+ if delay := w.passWithClock(func() time.Time { return start }); delay != noZoneRetry {
t.Fatalf("pass delay = %s, want %s", delay, noZoneRetry)
}
w.mu.Lock()
diff --git a/internal/host/claimunit.go b/internal/host/claimunit.go
index bdd8bbe36..6fdd08d9d 100644
--- a/internal/host/claimunit.go
+++ b/internal/host/claimunit.go
@@ -120,6 +120,9 @@ func claimUnitContent(name string, content []byte, cfg claimUnitSettings) []byte
}
if !cfg.enabled {
if cfg.demo.BoxMode() {
+ // systemd creates this root-owned directory before mounting writable
+ // paths, including on boxes that have never written release state.
+ content = bytes.Replace(content, []byte("[Service]\n"), []byte("[Service]\nStateDirectory=carlos-release/private\nStateDirectoryMode=0700\n"), 1)
content = bytes.Replace(content, []byte("[Service]\n"), []byte("[Service]\nReadWritePaths=/data /run/carlos/instances /opt/carlos/live /opt/carlos/versions /var/lib/carlos-release/private\n"), 1)
content = bytes.Replace(content, []byte("[Service]\n"), []byte("[Service]\n"+claimControlEnvironment), 1)
if cfg.demo.BuildWorker {
diff --git a/internal/host/demo_control_paths_test.go b/internal/host/demo_control_paths_test.go
new file mode 100644
index 000000000..6fef6492f
--- /dev/null
+++ b/internal/host/demo_control_paths_test.go
@@ -0,0 +1,54 @@
+package host
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/demo"
+)
+
+func TestDemoControlFreshBoxPaths(t *testing.T) {
+ root := t.TempDir()
+ if err := bootstrap(root, nil); err != nil {
+ t.Fatal(err)
+ }
+ raw, err := unitsFS.ReadFile("units/" + claimControlUnit)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, worker := range []bool{false, true} {
+ cfg := claimUnitSettings{demo: demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com", BuildWorker: worker, BuildConcurrency: 1}}
+ content := string(claimUnitContent(claimControlUnit, raw, cfg))
+ stateDirs := map[string]bool{}
+ for _, line := range strings.Split(content, "\n") {
+ if value, ok := strings.CutPrefix(line, "StateDirectory="); ok {
+ for _, dir := range strings.Fields(value) {
+ stateDirs["/var/lib/"+dir] = true
+ }
+ }
+ }
+ if !stateDirs[rootReleasePrivate] || !strings.Contains(content, "StateDirectoryMode=0700\n") {
+ t.Errorf("worker=%v: private release state must be created with mode 0700 before namespace setup", worker)
+ }
+ for _, line := range strings.Split(content, "\n") {
+ if strings.HasPrefix(line, "User=") || strings.HasPrefix(line, "Group=") {
+ t.Fatalf("root control changed identity: %s", line)
+ }
+ value, ok := strings.CutPrefix(line, "ReadWritePaths=/data ")
+ if !ok {
+ continue
+ }
+ for _, path := range strings.Fields("/data " + value) {
+ if stateDirs[path] {
+ continue
+ }
+ info, err := os.Stat(filepath.Join(root, path))
+ if err != nil || !info.IsDir() {
+ t.Errorf("worker=%v: writable path %s is absent on fresh bootstrap: %v", worker, path, err)
+ }
+ }
+ }
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-agent-start-demo-1-followups.tsv b/internal/provision/testdata/plan14-root-reads-agent-start-demo-1-followups.tsv
new file mode 100644
index 000000000..b05a98767
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-agent-start-demo-1-followups.tsv
@@ -0,0 +1,5 @@
+# Census overlay agent-start-demo-1-followups, written by census-propose (#369). census-ruling-agent-start-demo-1-followups, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-agent-start-demo-1-followups.md.
+# 1 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+internal/host/claimunit.go claimUnitContent authority E1,E3 rev3=PROPOSED-p3;identity=root claim/adoption controller uid 0;basis=adds write permission for exactly the public retry directory only when the root settings reader has verified a complete census and prepared that directory;rev3=census-ruling-agent-start-demo-1;basis=Demo-only ReadWritePaths for instance data/runtime, staged files and root release lock; ordinary rendering unchanged.;rev3=census-ruling-agent-start-demo-1-followups;basis=In demo box mode, declare StateDirectory=carlos-release/private with mode 0700 so systemd creates root-owned release state before namespace setup and keeps it writable. Existing ReadWritePaths and ordinary/claims rendering stay unchanged. No new read site or caller-controlled path. data-literal@883 aaf9e1117cbd60500cbfbbf5939d3b15f09e31269265565003e9c511e08550e1
+@coverage internal/edge b0c75df47e7dedf6c19173403b1a0e835f79ad49d0f6e5f3c9d893e04aa57b56
+@coverage internal/host bb74004e6be2ff0863d77ae84a0fffd551c24eab163d623d5f9e854e9e5d83c5
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index d9cc40bbc..e4fb70ab1 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -87,3 +87,4 @@ plan14-root-reads-stateless-replicas-3.tsv 703d9a189185e2075ec088bf9349e58132573
plan14-root-reads-region-ha-p3b.tsv face84b4c688cd3c179b0a34ced4d3521e71de8e63cbd45f21c27972c5b1a921
plan14-root-reads-stateless-coordinator-oneboxfleet.tsv face84b4c688cd3c179b0a34ced4d3521e71de8e63cbd45f21c27972c5b1a921
plan14-root-reads-region-ha-group-rtb.tsv 526d434888d043a8b09d8fe196f6324782d6ca20d759b080f99daa528adf6a32
+plan14-root-reads-agent-start-demo-1-followups.tsv 526d434888d043a8b09d8fe196f6324782d6ca20d759b080f99daa528adf6a32