fix: demo publish review round 2
internal/console/apidemo.go+6 −3internal/console/demo_jobs.go+1 −1internal/console/demo_publish.go+55 −22internal/console/demo_publish_test.go+1 −1internal/console/demo_settlement_r2_test.go+334 −0internal/console/demo_settlement_test.go+1 −1
CI failed — run details
Intent
<task-notification> <task-id>bb7zgckwd</task-id> <tool-use-id>toolu_01YTigxbdoPwNq1heyEvcrTZ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/bb7zgckwd.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 7 continuation" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>b60ug16i5</task-id> <tool-use-id>toolu_01QaqXxuGbw8BAoodKnXae6X</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/b60ug16i5.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 8 Codex run" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>aa40537188543c637</task-id> <tool-use-id>toolu_01VCsGocCYFnFUkajm62xXNu</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/aa40537188543c637.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 7 fix round 1" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Verdict: NOT READY (one new P1, P1-1).** The full review is in `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-1/.superpowers/sdd/2026-11-02-agent-start-demo-1-anonymous-apps/task-7-review-r2.md`. Line numbers are at 9c4b34bd. **Round-1 findings** - P2-1 retry: ADDRESSED (demo_publish.go:297-305, :28-34; demo_policy.go:38,54). Transient errors retry at the recorded stage, spend no update and stop at `starting_until` (:83-85). - P2-1 R18 settlement: ADDRESSED in shape (demo_publish.go:336-485, demo_spool.go:236-246), but it introduces the new P1-1 and P2-1 below. - P3-1: NOT ADDRESSED. It was deferred as allowed, and settlement now makes it worse. - P3-2: ADDRESSED (demo_domains.go:31-46; hostsused.go:570; lifetimes_create.go:64; apiinstances.go:1667; domainattach.go:136). - P3-3: ADDRESSED (demo_domains.go:23). - P3-4: ADDRESSED (server.go:4273). - P3-5: ADDRESSED (apidemo.go:519-536). - P3-6: ADDRESSED (demo_review_test.go:234). - P3-7: ADDRESSED (appregionset.go:262). - P3-8: ADDRESSED (apitemporary.go:15). **Guard repairs** (none weakens a guard) - TestNoUnjudgedRecordReads: ADDRESSED by code. It now reads through `s.readRecord` (demo_publish.go:205), with no exemption added. - TestEveryInstanceRecordCreatorIsUnderTheAccountLock: ADDRESSED by code (account lock at demo_publish.go:44) plus inventory entries that name the real callers with exact counts (recordcreators_guard_test.go:23-41). - TestEveryCreateWriterMarksFirst: ADDRESSED by inventory. The entry moved to the function that really calls markBeforeCreate and then CreateRecord, keeping the same rule (hostsused_writers_test.go:443). - TestClaimConsoleMutationInvariant: ADDRESSED by inventory, using a rule-5 reason (claim_invariant_test.go:185-187). The reason holds: demo paths refuse HostClaim, and the TestDemoSQLClaimsRefuseBuildState witness exists. - TestControlPlaneLookupFailureRefuses: ADDRESSED by code. A lookup failure now returns a logged 503 DEMO-CHECK-FAILED (demo_domains.go:21-25). **Your two questions** - No retry path can publish an older generation after a newer one. The active slot stays held, settlement only acts when the channel's head is this job's own version, and the newer-head check refuses a change in between. - Nothing keeps retrying after expiry or retirement. `withDemoLocked` returns errDemoJob, and the reconcile step (demo_spool.go:163-167) marks expired `ready` jobs failed. **Census reader:** no new root read from agent, app or tenant-writable input. No root-binary source changed. **New findings** - **P1-1** (demo_publish.go:396-403, :423-428): rolling back to a previous version that never passed readiness wedges the demo until it expires. If gen1 fails (say `/` returns 404 or 500), then gen2 fails too, the channel goes back to v1 and the console waits forever for v1 to pass. The job keeps its slot and status says "starting" for up to 24 hours, so every further update is refused. No test covers a previous version that never becomes ready. Fault family: bounded starting window and slot release. - Fix: roll back only to a generation that was seen live, or put a time limit on the restore wait and then report a plain failure. - **P2-1** (demo_publish.go:302-304, :318-320, with :398-401): a settlement error aborts the whole publication pass. A restore probe that errors or times out, or a busy policy-writer lease, makes `publishReadyDemos` return early. Every job after it misses that tick and spools are not cleaned. Combined with P1-1, one demo can stall everyone else's demos until it expires. Fault family: per-job failure isolation. - Fix: treat a probe error as "not ready" and `continue` past the failing job. - **P3s:** - Status says "starting" during settlement, and still shows the rejected version after rollback. - The policy writer attempt is held across the 5 s restore probe. - An unreadable or changed channel during settlement can never resolve except by expiry.</result> <usage><subagent_tokens>116176</subagent_tokens><tool_uses>24</tool_uses><duration_ms>361940</duration_ms></usage> </task-notification>
<task-notification> <task-id>bgcu43dp8</task-id> <tool-use-id>toolu_014EZxNUGYMz9iAZCe14uibc</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/bgcu43dp8.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 8, then start Task 7 last fix" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 27.6 g CO₂e (3,455,569 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, 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/internal/console/apidemo.go b/internal/console/apidemo.go| index e9e7f2c30..4fe69305e 100644 |
| --- a/internal/console/apidemo.go |
| +++ b/internal/console/apidemo.go |
| @@ -513,14 +513,17 @@ func (s *Server) handleDemoStatus(w http.ResponseWriter, r *http.Request) { |
| } |
| w.Header().Set("Content-Type", "application/json") |
| diagnostics, truncated := demoResultDiagnosticStatus(row.Result) |
| - response := map[string]any{"jobID": id, "status": state, "diagnostics": diagnostics, "diagnosticsTruncated": truncated} |
| var stage string |
| if err := s.store.db.QueryRowContext(r.Context(), `SELECT publish_stage FROM demo_jobs WHERE id=?`, id).Scan(&stage); err != nil { |
| jsonError(w, http.StatusServiceUnavailable, demoCopy["DEMO-BUILD"]) |
| return |
| } |
| - publishedStage := strings.TrimPrefix(strings.TrimPrefix(stage, "settling:"), "timeout:") |
| - shipped := publishedStage == "shipped" || publishedStage == "promoted" || publishedStage == "starting" || strings.HasPrefix(stage, "rollback:") || strings.HasPrefix(stage, "restoring:") || stage == "rolled-back" |
| + if demoSettlementPending(stage) || stage == "rolled-back" || stage == "settlement-failed" { |
| + state = "failed" |
| + } |
| + response := map[string]any{"jobID": id, "status": state, "diagnostics": diagnostics, "diagnosticsTruncated": truncated} |
| + publishedStage := strings.TrimPrefix(stage, "timeout:") |
| + shipped := publishedStage == "shipped" || publishedStage == "promoted" || publishedStage == "starting" |
| if shipped { |
| response["version"] = demoVersion(row.Job) |
| } |
diff --git a/internal/console/demo_jobs.go b/internal/console/demo_jobs.go| index 6fe704cb8..2f29f1bfd 100644 |
| --- a/internal/console/demo_jobs.go |
| +++ b/internal/console/demo_jobs.go |
| @@ -57,7 +57,7 @@ func (s *Store) migrateDemoJobs() error { |
| return err |
| } |
| for _, column := range []struct{ name, ddl string }{ |
| - {"publish_stage", "TEXT NOT NULL DEFAULT ''"}, {"starting_until", "INTEGER NOT NULL DEFAULT 0"}, {"spool_path", "TEXT NOT NULL DEFAULT ''"}, {"binary_sha256", "TEXT NOT NULL DEFAULT ''"}, {"binary_size", "INTEGER NOT NULL DEFAULT 0"}, |
| + {"publish_stage", "TEXT NOT NULL DEFAULT ''"}, {"starting_until", "INTEGER NOT NULL DEFAULT 0"}, {"settlement_until", "INTEGER NOT NULL DEFAULT 0"}, {"spool_path", "TEXT NOT NULL DEFAULT ''"}, {"binary_sha256", "TEXT NOT NULL DEFAULT ''"}, {"binary_size", "INTEGER NOT NULL DEFAULT 0"}, |
| } { |
| var n int |
| if err := s.db.QueryRow(`SELECT count(*) FROM pragma_table_info('demo_jobs') WHERE name=?`, column.name).Scan(&n); err != nil { |
diff --git a/internal/console/demo_publish.go b/internal/console/demo_publish.go| index 1c5dfb313..36acaf565 100644 |
| --- a/internal/console/demo_publish.go |
| +++ b/internal/console/demo_publish.go |
| @@ -300,7 +300,7 @@ func (s *Server) publishReadyDemos(ctx context.Context) error { |
| continue |
| } |
| if e := s.finishDemoPublish(ctx, row.Job, false); e != nil && !errors.Is(e, ErrDemoToken) && !errors.Is(e, errDemoJob) { |
| - return e |
| + log.Printf("console: demo settlement %s: %v", row.Job.ID, e) |
| } |
| continue |
| } |
| @@ -311,12 +311,16 @@ func (s *Server) publishReadyDemos(ctx context.Context) error { |
| ready := false |
| if time.Now().UnixNano() < until { |
| probeCtx, cancel := context.WithDeadline(ctx, time.Unix(0, until)) |
| - ready, _ = s.demoReady(probeCtx, d, demoVersion(row.Job)) |
| + ready, err = s.demoReady(probeCtx, d, demoVersion(row.Job)) |
| + if err != nil { |
| + log.Printf("console: demo readiness %s: %v", row.Job.ID, err) |
| + ready = false |
| + } |
| cancel() |
| } |
| if ready || time.Now().UnixNano() >= until { |
| if err = s.finishDemoPublish(ctx, row.Job, ready); err != nil && !errors.Is(err, ErrDemoToken) && !errors.Is(err, errDemoJob) { |
| - return err |
| + log.Printf("console: demo completion %s: %v", row.Job.ID, err) |
| } |
| } |
| } |
| @@ -339,8 +343,8 @@ func (s *Server) finishDemoPublish(ctx context.Context, j demobuild.Job, live bo |
| return errDemoJob |
| } |
| var stage string |
| - var until int64 |
| - if err := s.store.db.QueryRowContext(ctx, `SELECT publish_stage,starting_until FROM demo_jobs WHERE id=?`, j.ID).Scan(&stage, &until); err != nil { |
| + var until, settlementUntil int64 |
| + if err := s.store.db.QueryRowContext(ctx, `SELECT publish_stage,starting_until,settlement_until FROM demo_jobs WHERE id=?`, j.ID).Scan(&stage, &until, &settlementUntil); err != nil { |
| return err |
| } |
| if live { |
| @@ -353,15 +357,32 @@ func (s *Server) finishDemoPublish(ctx context.Context, j demobuild.Job, live bo |
| stage = "timeout:" + stage |
| } |
| stage = "settling:" + stage |
| - if _, err := s.store.db.ExecContext(ctx, `UPDATE demo_jobs SET publish_stage=? WHERE id=? AND state='ready'`, stage, j.ID); err != nil { |
| - return err |
| - } |
| } |
| - var settled bool |
| - stage, settled, err = s.settleDemoPublishLocked(ctx, d, j, stage) |
| - if err != nil || !settled { |
| + // Recovery gets one durable start-sized window, including retries, |
| + // channel reads and the restore probe. Restart never renews it. |
| + if settlementUntil == 0 { |
| + settlementUntil = min(time.Now().Add(demoStartWindow).UnixNano(), time.Unix(life.ExpiresAt, 0).UnixNano()) |
| + } |
| + if _, err := s.store.db.ExecContext(ctx, `UPDATE demo_jobs SET publish_stage=?,settlement_until=? WHERE id=? AND state='ready'`, stage, settlementUntil, j.ID); err != nil { |
| return err |
| } |
| + if time.Now().UnixNano() >= settlementUntil { |
| + stage = "settlement-failed" |
| + } else { |
| + settleCtx, cancel := context.WithDeadline(ctx, time.Unix(0, settlementUntil)) |
| + var settled bool |
| + stage, settled, err = s.settleDemoPublishLocked(settleCtx, d, j, stage) |
| + cancel() |
| + if ctx.Err() != nil { |
| + return ctx.Err() |
| + } |
| + if time.Now().UnixNano() >= settlementUntil { |
| + // A timeout cannot establish that any version is serving. |
| + stage = "settlement-failed" |
| + } else if err != nil || !settled { |
| + return err |
| + } |
| + } |
| } |
| if !demoLifeValid(d, &life, time.Now()) { |
| return errDemoJob |
| @@ -391,13 +412,29 @@ func demoSettlementPending(stage string) bool { |
| // Persist the target before rollback: after a lost acknowledgment, rolling back |
| // again would select the rejected version. Keep the active job until a GET |
| -// observes the restored process. The starting deadline bounds the new version's |
| -// trial, not recovery from an unavailable store or box. Expiry still fences both. |
| +// observes the restored process or the durable settlement deadline expires. |
| +// Published job rows are the readiness record; channel history alone is not. |
| func (s *Server) settleDemoPublishLocked(ctx context.Context, d DemoRow, j demobuild.Job, stage string) (string, bool, error) { |
| + var generation uint64 |
| + if err := s.store.db.QueryRowContext(ctx, `SELECT coalesce(max(generation),0) FROM demo_jobs WHERE demo_id=? AND generation<? AND state='published'`, d.ID, j.Generation).Scan(&generation); err != nil { |
| + return stage, false, err |
| + } |
| + if generation == 0 { |
| + // R20: nothing ever passed readiness. Leave the possibly broken |
| + // channel intact, report no serving version, and release the slot. |
| + return "settlement-failed", true, nil |
| + } |
| + lastReady := demoVersion(demobuild.Job{Generation: generation}) |
| if target, restoring := strings.CutPrefix(stage, "restoring:"); restoring { |
| + if target != lastReady { |
| + return "settlement-failed", true, nil |
| + } |
| ready, err := s.demoReady(ctx, d, target) |
| + if err != nil { |
| + log.Printf("console: demo restore readiness %s: %v", j.ID, err) |
| + } |
| if err != nil || !ready { |
| - return stage, false, err |
| + return stage, false, nil |
| } |
| return "rolled-back", true, nil |
| } |
| @@ -420,12 +457,7 @@ func (s *Server) settleDemoPublishLocked(ctx context.Context, d DemoRow, j demob |
| if ptr.Version != demoVersion(j) { |
| return stage, false, release.ErrCASConflict |
| } |
| - if len(ptr.History) == 0 { |
| - // R18: a first publication has nothing to restore. Leave its record |
| - // and channel intact, fail without a URL, and allow another update. |
| - return original, true, nil |
| - } |
| - target = ptr.History[0] |
| + target = lastReady |
| stage = "rollback:" + target |
| if _, err := s.store.db.ExecContext(ctx, `UPDATE demo_jobs SET publish_stage=? WHERE id=? AND state='ready'`, stage, j.ID); err != nil { |
| return stage, false, err |
| @@ -434,7 +466,7 @@ func (s *Server) settleDemoPublishLocked(ctx context.Context, d DemoRow, j demob |
| if err != nil { |
| return stage, false, err |
| } |
| - if target == "" || target == demoVersion(j) || (ptr.Version != target && ptr.Version != demoVersion(j)) { |
| + if target != lastReady || (ptr.Version != target && ptr.Version != demoVersion(j)) { |
| return stage, false, release.ErrCASConflict |
| } |
| if ptr.Version != target { |
| @@ -443,8 +475,8 @@ func (s *Server) settleDemoPublishLocked(ctx context.Context, d DemoRow, j demob |
| return stage, false, demoPublishRefusal(ref) |
| } |
| attemptCtx, done, ref := s.policyAttempt(ctx, hold) |
| - defer done() |
| if ref != nil { |
| + done() |
| return stage, false, demoPublishRefusal(ref) |
| } |
| err = release.RootSigner(s.cfg.Key).RollbackAuthorized(attemptCtx, s.cfg.Releases, j.Account, j.App, "edge", func(_ *release.Pipeline) error { |
| @@ -471,6 +503,7 @@ func (s *Server) settleDemoPublishLocked(ctx context.Context, d DemoRow, j demob |
| } |
| return nil |
| }) |
| + done() |
| if err != nil { |
| return stage, false, err |
| } |
diff --git a/internal/console/demo_publish_test.go b/internal/console/demo_publish_test.go| index 96f31772c..02d3cc7fc 100644 |
| --- a/internal/console/demo_publish_test.go |
| +++ b/internal/console/demo_publish_test.go |
| @@ -393,7 +393,7 @@ func TestDemoPublishTimeoutReleasesSlot(t *testing.T) { |
| r.SetPathValue("jobID", j.ID) |
| w := httptest.NewRecorder() |
| s.handleDemoStatus(w, r) |
| - if !strings.Contains(w.Body.String(), demoCopy["DEMO-BUILD-TIMEOUT"]) || !strings.Contains(w.Body.String(), demoVersion(j)) { |
| + if !strings.Contains(w.Body.String(), demoCopy["DEMO-BUILD-FAILED"]) || strings.Contains(w.Body.String(), demoVersion(j)) { |
| t.Fatalf("timeout status: %s", w.Body.String()) |
| } |
| } |
diff --git a/internal/console/demo_settlement_r2_test.go b/internal/console/demo_settlement_r2_test.go| new file mode 100644 |
| index 000000000..3850a943b |
| --- /dev/null |
| +++ b/internal/console/demo_settlement_r2_test.go |
| @@ -0,0 +1,334 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "os" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func demoNextPublication(t *testing.T, s *Server, id string, previous demobuild.Job) (DemoRow, demobuild.Job) { |
| + t.Helper() |
| + d, err := s.store.demoByID(t.Context(), id) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + j, err := s.enqueueDemo(t.Context(), d, demoJobSource()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return demoStartPublication(t, s, j, previous) |
| +} |
| + |
| +func demoStartPublication(t *testing.T, s *Server, j, previous demobuild.Job) (DemoRow, demobuild.Job) { |
| + t.Helper() |
| + old, err := s.readDemoJob(t.Context(), previous.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var out demobuild.Result |
| + if err := json.Unmarshal(old.Result, &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.pickupDemo(t.Context(), j.ID, j.Attempt, j.Fleet, j.Box); err != nil { |
| + t.Fatal(err) |
| + } |
| + row, err := s.readDemoJob(t.Context(), j.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + j = row.Job |
| + out.JobID, out.Attempt, out.BinaryPath = j.ID, j.Attempt, "" |
| + if err := s.storeDemoResult(t.Context(), j, out, []byte("demo executable bytes")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.store.db.QueryRow(`SELECT spool_path FROM demo_jobs WHERE id=?`, j.ID).Scan(&out.BinaryPath); err != nil { |
| + t.Fatal(err) |
| + } |
| + d, err := s.store.demoByID(t.Context(), j.DemoID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.publishDemo(t.Context(), d, j, out); err != nil { |
| + t.Fatal(err) |
| + } |
| + return d, j |
| +} |
| + |
| +func demoAssertPlainFailure(t *testing.T, s *Server, j demobuild.Job) { |
| + t.Helper() |
| + status := demoSettlementStatus(t, s, j) |
| + if status["status"] != "failed" || status["url"] != nil || status["message"] != demoCopy["DEMO-BUILD-FAILED"] || status["version"] != nil { |
| + t.Errorf("not a plain failure: %v", status) |
| + } |
| + d, err := s.store.demoByID(t.Context(), j.DemoID) |
| + if err != nil || d.ActiveJobID != "" { |
| + t.Fatalf("slot held: %+v %v", d, err) |
| + } |
| + row, err := s.readDemoJob(t.Context(), j.ID) |
| + if err != nil || row.State != "failed" { |
| + t.Fatalf("job not failed: %+v %v", row, err) |
| + } |
| +} |
| + |
| +func TestDemoPublishSettlementNeverReady(t *testing.T) { |
| + s, d, j := demoSettlementFixture(t, false) |
| + demoAcceptReadiness(s, "not-ready") |
| + if err := s.finishDemoPublish(t.Context(), j, false); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, next := demoNextPublication(t, s, d.ID, j) |
| + if err := s.finishDemoPublish(t.Context(), next, false); err != nil { |
| + t.Fatal(err) |
| + } |
| + demoAssertPlainFailure(t, s, next) |
| + ptr, err := release.Channel(t.Context(), s.cfg.Releases, s.cfg.ReleasePub, next.Account, next.App, "edge") |
| + if err != nil || ptr.Version != demoVersion(next) { |
| + t.Fatalf("rolled back to unready generation: %+v %v", ptr, err) |
| + } |
| + current, err := s.store.demoByID(t.Context(), d.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + third, err := s.enqueueDemo(t.Context(), current, demoJobSource()) |
| + if err != nil || third.Generation != 3 { |
| + t.Fatalf("third update refused: %+v %v", third, err) |
| + } |
| +} |
| + |
| +func TestDemoPublishSettlementRestoreBound(t *testing.T) { |
| + s, _, j := demoSettlementFixture(t, true) |
| + demoAcceptReadiness(s, demoVersion(j)) |
| + before := time.Now() |
| + if err := s.finishDemoPublish(t.Context(), j, false); err != nil { |
| + t.Fatal(err) |
| + } |
| + var until int64 |
| + if err := s.store.db.QueryRow(`SELECT settlement_until FROM demo_jobs WHERE id=?`, j.ID).Scan(&until); err != nil { |
| + t.Fatal(err) |
| + } |
| + if until < before.Add(60*time.Second).UnixNano() || until > time.Now().Add(60*time.Second).UnixNano() { |
| + t.Fatalf("unbounded restore deadline: %d", until) |
| + } |
| + s = reopenDemoJobs(t, s) |
| + demoAcceptReadiness(s, demoVersion(j)) |
| + if err := s.publishReadyDemos(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + var after int64 |
| + if err := s.store.db.QueryRow(`SELECT settlement_until FROM demo_jobs WHERE id=?`, j.ID).Scan(&after); err != nil || after != until { |
| + t.Fatalf("restart extended restore deadline: %d -> %d: %v", until, after, err) |
| + } |
| + if _, err := s.store.db.Exec(`UPDATE demo_jobs SET settlement_until=? WHERE id=?`, time.Now().Add(-time.Second).UnixNano(), j.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.demoTransport = demoReadyTransport(func(*http.Request) (*http.Response, error) { t.Fatal("probe after restore deadline"); return nil, nil }) |
| + if err := s.publishReadyDemos(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + demoAssertPlainFailure(t, s, j) |
| + current, err := s.store.demoByID(t.Context(), j.DemoID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.enqueueDemo(t.Context(), current, demoJobSource()); err != nil { |
| + t.Fatalf("next update refused: %v", err) |
| + } |
| +} |
| + |
| +func TestDemoPublishSettlementStatusTruth(t *testing.T) { |
| + s, _, j := demoSettlementFixture(t, true) |
| + for _, stage := range []string{"settling:starting", "rollback:v0.0.0-demo.1", "restoring:v0.0.0-demo.1"} { |
| + if _, err := s.store.db.Exec(`UPDATE demo_jobs SET publish_stage=? WHERE id=?`, stage, j.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + status := demoSettlementStatus(t, s, j) |
| + if status["status"] != "failed" || status["url"] != nil || status["version"] != nil || status["message"] != demoCopy["DEMO-BUILD-FAILED"] { |
| + t.Errorf("misleading %s status: %v", stage, status) |
| + } |
| + } |
| + demoAcceptReadiness(s, "v0.0.0-demo.1") |
| + if err := s.finishDemoPublish(t.Context(), j, false); err != nil { |
| + t.Fatal(err) |
| + } |
| + status := demoSettlementStatus(t, s, j) |
| + if status["status"] != "failed" || status["version"] != nil || status["message"] != demoCopy["DEMO-ROLLED-BACK"] { |
| + t.Errorf("misleading restored status: %v", status) |
| + } |
| +} |
| + |
| +func TestDemoPublishSettlementErrorsIsolated(t *testing.T) { |
| + for _, fault := range []string{"probe", "channel"} { |
| + t.Run(fault, func(t *testing.T) { |
| + s, d, a := demoSettlementFixture(t, true) |
| + in := demoTestAdmission(t, s.cfg.Demo) |
| + in.AccountSqid = s.cfg.Demo.Account |
| + in.job = func(ctx context.Context, tx *sql.Tx, d DemoRow, life AppLife) error { |
| + _, err := s.insertDemoJob(ctx, tx, d, life, demoJobSource()) |
| + return err |
| + } |
| + other, err := s.store.ReserveDemo(t.Context(), in) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, b := demoNextPublication(t, s, other.ID, a) |
| + // Give the other app a real published generation, then prepare its update. |
| + if err := s.finishDemoPublish(t.Context(), b, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, b = demoNextPublication(t, s, other.ID, b) |
| + if b.ID < a.ID { |
| + a, b = b, a |
| + } |
| + demoAcceptReadiness(s, "not-ready") |
| + if fault == "probe" { |
| + if err := s.finishDemoPublish(t.Context(), a, false); err != nil { |
| + t.Fatal(err) |
| + } |
| + } else { |
| + if _, err := s.store.db.Exec(`UPDATE demo_jobs SET publish_stage='settling:starting' WHERE id=?`, a.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.cfg.Releases = demoSettlementReadFault{Store: s.cfg.Releases, key: release.ChannelKey(a.Account, a.App, "edge")} |
| + } |
| + s.demoTransport = demoReadyTransport(func(r *http.Request) (*http.Response, error) { |
| + if r.URL.Host == a.Host { |
| + return nil, errors.New("probe unavailable") |
| + } |
| + return &http.Response{StatusCode: 200, Header: http.Header{"X-Carlos-Version": {demoVersion(b)}}, Body: http.NoBody, Request: r}, nil |
| + }) |
| + var spool string |
| + if err := s.store.db.QueryRow(`SELECT spool_path FROM demo_jobs WHERE id=?`, b.ID).Scan(&spool); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.publishReadyDemos(t.Context()); err != nil { |
| + t.Errorf("job failure escaped pass: %v", err) |
| + } |
| + row, err := s.readDemoJob(t.Context(), b.ID) |
| + if err != nil || row.State != "published" { |
| + t.Errorf("healthy job blocked: %s %v (first app %s)", row.State, err, d.ID) |
| + } |
| + if _, err := os.Stat(spool); !errors.Is(err, os.ErrNotExist) { |
| + t.Errorf("terminal spool not cleaned: %v", err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type demoSettlementReadFault struct { |
| + release.Store |
| + key string |
| +} |
| + |
| +func (s demoSettlementReadFault) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if key == s.key { |
| + return nil, "", errors.New("channel unreadable") |
| + } |
| + return s.Store.Get(ctx, key) |
| +} |
| + |
| +func TestDemoPublishSettlementChannelBound(t *testing.T) { |
| + for _, fault := range []string{"unreadable", "changed"} { |
| + t.Run(fault, func(t *testing.T) { |
| + s, _, j := demoSettlementFixture(t, true) |
| + if fault == "unreadable" { |
| + s.cfg.Releases = demoSettlementReadFault{Store: s.cfg.Releases, key: release.ChannelKey(j.Account, j.App, "edge")} |
| + } else { |
| + // An out-of-band rollback changed the channel before settlement. |
| + if err := release.RootSigner(s.cfg.Key).RollbackAuthorized(t.Context(), s.cfg.Releases, j.Account, j.App, "edge", nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + _ = s.finishDemoPublish(t.Context(), j, false) |
| + if _, err := s.store.db.Exec(`UPDATE demo_jobs SET settlement_until=? WHERE id=?`, time.Now().Add(-time.Second).UnixNano(), j.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.publishReadyDemos(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + demoAssertPlainFailure(t, s, j) |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoPublishSettlementReleasesWriterBeforeProbe(t *testing.T) { |
| + s, _, j := demoSettlementFixture(t, true) |
| + f := &fakePolicyLeaser{} |
| + s.cfg.Bucket, s.cfg.PolicyLease = "demo-test", f.leaser |
| + t.Cleanup(func() { s.ReleasePolicyWriter(context.Background()) }) |
| + probed := false |
| + s.demoTransport = demoReadyTransport(func(r *http.Request) (*http.Response, error) { |
| + probed = true |
| + s.policyStateMu.Lock() |
| + active := len(s.policyCur.attempts) |
| + s.policyStateMu.Unlock() |
| + if active != 0 { |
| + t.Errorf("policy attempt held across probe: %d", active) |
| + } |
| + return &http.Response{StatusCode: 200, Header: http.Header{"X-Carlos-Version": {"v0.0.0-demo.1"}}, Body: http.NoBody, Request: r}, nil |
| + }) |
| + if err := s.finishDemoPublish(t.Context(), j, false); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !probed { |
| + t.Fatal("restore was not probed") |
| + } |
| +} |
| + |
| +func TestDemoPublishSettlementLastReadyGeneration(t *testing.T) { |
| + s, d, second := demoSettlementFixture(t, true) |
| + demoAcceptReadiness(s, demoVersion(second)) |
| + if err := s.publishReadyDemos(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, third := demoNextPublication(t, s, d.ID, second) |
| + s = reopenDemoJobs(t, s) |
| + demoAcceptReadiness(s, demoVersion(second)) |
| + if err := s.finishDemoPublish(t.Context(), third, false); err != nil { |
| + t.Fatal(err) |
| + } |
| + ptr, err := release.Channel(t.Context(), s.cfg.Releases, s.cfg.ReleasePub, third.Account, third.App, "edge") |
| + if err != nil || ptr.Version != demoVersion(second) { |
| + t.Fatalf("did not restore last ready generation: %+v %v", ptr, err) |
| + } |
| + status := demoSettlementStatus(t, s, third) |
| + if status["status"] != "failed" || status["version"] != nil || status["message"] != demoCopy["DEMO-ROLLED-BACK"] { |
| + t.Fatalf("restoration: %v", status) |
| + } |
| +} |
| + |
| +func TestDemoPublishSettlementProbeConsumesBound(t *testing.T) { |
| + s, _, j := demoSettlementFixture(t, true) |
| + demoAcceptReadiness(s, demoVersion(j)) |
| + if err := s.finishDemoPublish(t.Context(), j, false); err != nil { |
| + t.Fatal(err) |
| + } |
| + until := time.Now().Add(100 * time.Millisecond) |
| + if _, err := s.store.db.Exec(`UPDATE demo_jobs SET settlement_until=? WHERE id=?`, until.UnixNano(), j.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + probed := false |
| + s.demoTransport = demoReadyTransport(func(r *http.Request) (*http.Response, error) { |
| + probed = true |
| + deadline, ok := r.Context().Deadline() |
| + if !ok || deadline.After(until) { |
| + t.Errorf("probe not bounded by restore deadline: %v", deadline) |
| + } |
| + <-r.Context().Done() |
| + return nil, r.Context().Err() |
| + }) |
| + if err := s.publishReadyDemos(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !probed { |
| + t.Fatal("probe did not run") |
| + } |
| + demoAssertPlainFailure(t, s, j) |
| +} |
diff --git a/internal/console/demo_settlement_test.go b/internal/console/demo_settlement_test.go| index 8ea59bd40..acc2828e2 100644 |
| --- a/internal/console/demo_settlement_test.go |
| +++ b/internal/console/demo_settlement_test.go |
| @@ -173,7 +173,7 @@ func TestDemoPublishSettlementRestart(t *testing.T) { |
| t.Fatal(err) |
| } |
| status := demoSettlementStatus(t, s, j) |
| - if status["status"] != "starting" || strings.Contains(status["message"].(string), "previous version still running") { |
| + if status["status"] != "failed" || status["version"] != nil || strings.Contains(status["message"].(string), "previous version still running") { |
| t.Fatalf("premature restoration claim: %v", status) |
| } |
| s = reopenDemoJobs(t, s) |