fix: demo build jobs review round 2
internal/console/apidemo.go+5 −1internal/console/demo_jobs_test.go+51 −5internal/console/demo_spool.go+7 −3internal/console/demo_spool_test.go+104 −0internal/host/demo_jobs.go+3 −2internal/host/demo_jobs_test.go+8 −3
CI failed — run details
Intent
<task-notification> <task-id>bf29qk0go</task-id> <tool-use-id>toolu_013AeUs4nu8EPMeXDKhk4JFU</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/bf29qk0go.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 6 fix" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a30a016cc35863493</task-id> <tool-use-id>toolu_019CPNmPx9MQjLiGbbNWqbra</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/a30a016cc35863493.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 6 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>Round 2 verdict: **READY**. The fix diff has no P1 or P2, and the three behaviours you asked about all hold. Review written to `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-1/.superpowers/sdd/2026-11-02-agent-start-demo-1-anonymous-apps/task-6-review-r2.md`. **Round 1 findings** - **P2-1 startup takes down root control:** ADDRESSED. In `internal/demobuild/worker.go`, the bundle check, recovery and probe moved from `NewWorker` to `Initialize`/`initialize`. `internal/instancectl/server.go` `Serve` now runs them in a background goroutine. One residual: configuration errors, including a held `worker.lock`, still call `log.Fatalf` in `runWithClaim`. The report says this follows your fix instruction, so I accepted it. - **P3-1 hash before parse:** ADDRESSED. `Build` in `worker.go` reads at most 5,000,000 bytes and compares their SHA-256 with the signed `SourceSHA256` before `ValidateSource` runs. - **P3-3 torn marker:** ADDRESSED. `reserve` in `worker.go` sets `w.poisoned = true` when the marker scan fails. - **P3-7 cleanup deadline:** ADDRESSED. The cleanup closure in `prepareUnit` (`unit.go`) now gets its own 5-second timeout from when cleanup starts. - **P3-4 clock skew:** ADDRESSED by Task 5 (`BuildWindow+ClockSkew` in `validate`), and the fix keeps it. - **P3-2, P3-5, P3-6, P3-8:** NOT ADDRESSED. They were deferred on purpose and stay on the follow-up list. **Requested checks** - **Ordinary verbs during and after a failed init:** served. A test drives real `/stop` and `/reset` over a loopback listener while init is blocked and again after it fails. - **Cancellation and shutdown:** `Serve` cancels and waits for the init goroutine before it returns, so nothing leaks. The process lock is released only after that wait. - **Not-ready worker:** it advertises no `anonymous-demo-v1` capability and refuses builds. Readiness, grant checks and builds are all gated on ready-and-not-poisoned. Both HTTP routes answer 503 before reading the request body. **New findings in the fix diff** - **P1:** none. - **P2:** none. - **P3-A, recovery from transient faults:** `initialize` (worker.go) runs only once and never retries. If the first nested probe fails once at boot, `/demo-build/ready` answers 503 until root control restarts, even after later probes pass. Instance control is unaffected and it fails closed, but the box silently stops building. Fix: retry while not ready. - **P3-B, shutdown timing:** `CheckBundle` ignores the context. Shutdown during startup can wait for a full bundle hash and may run into `TimeoutStopSec`. - **P3-C, route surface:** in `server.go` `Handler`, the `/demo-build` routes now exist on every demo box, even without a worker, and answer 503 instead of 404. This is harmless because the agent treats any non-200 as unavailable. But it no longer matches the round 1 census wording and has no test. **Census, per changed root unit** None of the changed units reads anything new from tenant, app or agent input. - **No change:** `NewWorker`, `Initialize`/`initialize`, `available`, `Readiness`, `validate`, `GrantDeadline`, `reserve`, the `prepareUnit` cleanup, `runWithClaim`, `Serve`, `probeLoop` and `handleDemoBuildReady`. - **`Handler`:** no new input. The routes now exist on worker-less demo boxes but refuse before reading anything (P3-C). - **`Worker.Build`:** same input, narrowed. Only bytes that match the signed hash reach the parser. - **`handleDemoBuild`:** no new input, narrowed. It checks readiness before reading the body. **Verdict:** READY.</result> <usage><subagent_tokens>83306</subagent_tokens><tool_uses>7</tool_uses><duration_ms>170991</duration_ms></usage> </task-notification>
Attributed to this commit: 12.4 g CO₂e (1,541,635 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 ad723a2bf..c7617c018 100644 |
| --- a/internal/console/apidemo.go |
| +++ b/internal/console/apidemo.go |
| @@ -372,7 +372,11 @@ func (s *Server) handleDemoPublish(w http.ResponseWriter, r *http.Request) { |
| } |
| // Check writer authority and a connected, root-ready worker before reserving |
| // the anonymous name. No weaker fallback is available. |
| - if !s.policyHeld() || len(s.demoEligiblePeers()) == 0 { |
| + if len(s.demoEligiblePeers()) == 0 { |
| + demoError(w, errDemoJob) |
| + return |
| + } |
| + if _, ref := s.policyWriter(r.Context()); ref != nil { |
| demoError(w, errDemoJob) |
| return |
| } |
diff --git a/internal/console/demo_jobs_test.go b/internal/console/demo_jobs_test.go| index f17f6be6d..c4b8b0f57 100644 |
| --- a/internal/console/demo_jobs_test.go |
| +++ b/internal/console/demo_jobs_test.go |
| @@ -1003,22 +1003,34 @@ func TestDemoJobBoxRouting(t *testing.T) { |
| } |
| } |
| -func TestDemoJobAnonymousDoesNotAcquireLease(t *testing.T) { |
| +func TestDemoJobAnonymousAcquiresLeaseAfterFreshStart(t *testing.T) { |
| s, _ := demoJobServer(t) |
| lease := &fakePolicyLeaser{} |
| s.cfg.Bucket = "deployment" |
| s.cfg.PolicyLease = lease.leaser |
| defer s.ReleasePolicyWriter(context.Background()) |
| + if s.policyHeld() || lease.callCount() != 0 { |
| + t.Fatal("fresh console already acquired a policy lease") |
| + } |
| r := httptest.NewRequest("POST", "/api/demo/apps", bytes.NewReader(demoHTTPSource(t))) |
| r.RemoteAddr = "192.0.2.1:1" |
| r.Header.Set("Content-Type", "application/gzip") |
| out := newDemoRecorder() |
| s.mux.ServeHTTP(out, r) |
| - if calls := lease.callCount(); calls != 0 { |
| - t.Fatalf("anonymous request acquired lease: %d", calls) |
| + if out.Code != http.StatusAccepted { |
| + t.Fatalf("fresh console create: status=%d body=%s", out.Code, out.Body.String()) |
| + } |
| + if calls := lease.callCount(); calls != 1 || !s.policyHeld() { |
| + t.Fatalf("writer lease: acquisitions=%d held=%v", calls, s.policyHeld()) |
| } |
| - if out.Code != 503 { |
| - t.Fatalf("unheld writer accepted: %d", out.Code) |
| + // The next create reuses the same holding. |
| + r = httptest.NewRequest("POST", "/api/demo/apps", bytes.NewReader(demoHTTPSource(t))) |
| + r.RemoteAddr = "192.0.2.2:1" |
| + r.Header.Set("Content-Type", "application/gzip") |
| + out = newDemoRecorder() |
| + s.mux.ServeHTTP(out, r) |
| + if out.Code != http.StatusAccepted || lease.callCount() != 1 { |
| + t.Fatalf("second create: status=%d acquisitions=%d body=%s", out.Code, lease.callCount(), out.Body.String()) |
| } |
| } |
| @@ -1186,3 +1198,37 @@ func TestDemoJobLegacyBlobRecovery(t *testing.T) { |
| t.Fatalf("legacy blob column=%d: %v", n, err) |
| } |
| } |
| + |
| +func TestDemoJobAnonymousLeaseRefusal(t *testing.T) { |
| + for _, kind := range []string{"unavailable", "no-worker", "invalid-source"} { |
| + t.Run(kind, func(t *testing.T) { |
| + s, _ := demoJobServer(t) |
| + lease := &fakePolicyLeaser{err: errors.New("lease unavailable")} |
| + s.cfg.Bucket = "deployment" |
| + s.cfg.PolicyLease = lease.leaser |
| + defer s.ReleasePolicyWriter(context.Background()) |
| + source := demoHTTPSource(t) |
| + wantCalls, wantStatus := 1, http.StatusServiceUnavailable |
| + switch kind { |
| + case "no-worker": |
| + s.demoJobs.peers = nil |
| + wantCalls = 0 |
| + case "invalid-source": |
| + source = []byte("invalid gzip") |
| + wantCalls, wantStatus = 0, http.StatusBadRequest |
| + } |
| + r := httptest.NewRequest("POST", "/api/demo/apps", bytes.NewReader(source)) |
| + r.RemoteAddr = "192.0.2.1:1" |
| + r.Header.Set("Content-Type", "application/gzip") |
| + out := newDemoRecorder() |
| + s.mux.ServeHTTP(out, r) |
| + if out.Code != wantStatus || lease.callCount() != wantCalls { |
| + t.Fatalf("status=%d acquisitions=%d, want %d/%d", out.Code, lease.callCount(), wantStatus, wantCalls) |
| + } |
| + var jobs, demos int |
| + if err := s.store.db.QueryRow(`SELECT (SELECT count(*) FROM demo_jobs), (SELECT count(*) FROM demo_apps)`).Scan(&jobs, &demos); err != nil || jobs != 0 || demos != 0 { |
| + t.Fatalf("refused admission reserved rows: jobs=%d demos=%d err=%v", jobs, demos, err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/demo_spool.go b/internal/console/demo_spool.go| index d41f79889..282dc7956 100644 |
| --- a/internal/console/demo_spool.go |
| +++ b/internal/console/demo_spool.go |
| @@ -7,6 +7,7 @@ import ( |
| "encoding/json" |
| "errors" |
| "io" |
| + "log" |
| "os" |
| "path/filepath" |
| "strings" |
| @@ -22,6 +23,9 @@ func (s *Server) newDemoSpool() (*os.File, error) { |
| if err := os.MkdirAll(s.store.demoSpoolDir, 0700); err != nil { |
| return nil, err |
| } |
| + if err := os.Chmod(s.store.demoSpoolDir, 0700); err != nil { |
| + return nil, err |
| + } |
| return os.CreateTemp(s.store.demoSpoolDir, ".upload-*") |
| } |
| @@ -235,6 +239,7 @@ func (s *Server) recoverDemoSpools(ctx context.Context) error { |
| if _, err := s.store.db.ExecContext(ctx, `UPDATE demo_jobs SET state='failed' WHERE id=? AND state='ready'`, r.id); err != nil { |
| return err |
| } |
| + log.Printf("console: demo job %q: invalid spool %q; marked failed", r.id, r.path) |
| } |
| } |
| return nil |
| @@ -247,9 +252,8 @@ func (s *Server) cleanDemoSpools(ctx context.Context, startup bool) error { |
| } |
| for _, r := range rows { |
| if !demobuild.ValidJobID(r.id) || r.path != filepath.Join(s.store.demoSpoolDir, r.id+".bin") { |
| - return errDemoJob |
| - } |
| - if err := os.Remove(r.path); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + log.Printf("console: demo job %q: non-canonical spool %q; clearing reference without accessing path", r.id, r.path) |
| + } else if err := os.Remove(r.path); err != nil && !errors.Is(err, os.ErrNotExist) { |
| return err |
| } |
| if _, err := s.store.db.ExecContext(ctx, `UPDATE demo_jobs SET spool_path='' WHERE id=? AND state IN ('failed','published') AND spool_path!=''`, r.id); err != nil { |
diff --git a/internal/console/demo_spool_test.go b/internal/console/demo_spool_test.go| new file mode 100644 |
| index 000000000..87c10b9f0 |
| --- /dev/null |
| +++ b/internal/console/demo_spool_test.go |
| @@ -0,0 +1,104 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "log" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestDemoJobSpoolRecoveryInvalidPath(t *testing.T) { |
| + for _, state := range []string{"ready", "failed", "published"} { |
| + for _, damage := range []string{"moved", "relative", "malformed"} { |
| + t.Run(state+"/"+damage, func(t *testing.T) { |
| + s, _ := demoJobServer(t) |
| + d, j := reserveDemoJob(t, s) |
| + _, healthy := reserveDemoJob(t, s) |
| + outside := filepath.Join(t.TempDir(), j.ID+".bin") |
| + const contents = "unrelated file must survive recovery" |
| + if err := os.WriteFile(outside, []byte(contents), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + path := outside |
| + switch damage { |
| + case "relative": |
| + path = j.ID + ".bin" |
| + case "malformed": |
| + path = "\x00bad-path" |
| + } |
| + if _, err := s.store.db.Exec(`UPDATE demo_jobs SET state=?,spool_path=? WHERE id=?`, state, path, j.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + s = reopenDemoJobs(t, s) |
| + var logs bytes.Buffer |
| + previous := log.Writer() |
| + log.SetOutput(&logs) |
| + t.Cleanup(func() { log.SetOutput(previous) }) |
| + if err := s.ReconcileDemoJobs(t.Context(), true); err != nil { |
| + t.Fatalf("startup failed over one bad spool: %v", err) |
| + } |
| + if row, err := s.readDemoJob(t.Context(), healthy.ID); err != nil || row.State != "queued" { |
| + t.Fatalf("unrelated job changed: state=%q err=%v", row.State, err) |
| + } |
| + var gotState, gotPath string |
| + if err := s.store.db.QueryRow(`SELECT state,spool_path FROM demo_jobs WHERE id=?`, j.ID).Scan(&gotState, &gotPath); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := state |
| + if state == "ready" { |
| + want = "failed" |
| + } |
| + if gotState != want || gotPath != "" { |
| + t.Fatalf("recovered state=%q path=%q, want %q and cleared path", gotState, gotPath, want) |
| + } |
| + if state != "published" { |
| + var active string |
| + if err := s.store.db.QueryRow(`SELECT active_job_id FROM demo_apps WHERE demo_id=?`, d.ID).Scan(&active); err != nil || active != "" { |
| + t.Fatalf("failed job still active: %q %v", active, err) |
| + } |
| + } |
| + data, err := os.ReadFile(outside) |
| + if err != nil || string(data) != contents { |
| + t.Fatalf("unrelated spool changed: %q %v", data, err) |
| + } |
| + if !strings.Contains(logs.String(), j.ID) || !strings.Contains(logs.String(), "spool") { |
| + t.Fatalf("missing job spool recovery log: %q", logs.String()) |
| + } |
| + // A second startup must not repeat the damaged-row handling. |
| + logs.Reset() |
| + if err := s.ReconcileDemoJobs(t.Context(), true); err != nil { |
| + t.Fatal(err) |
| + } |
| + if logs.Len() != 0 { |
| + t.Fatalf("recovery was not durable: %s", logs.String()) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +func TestDemoJobSpoolTightensExistingDirectory(t *testing.T) { |
| + s, _ := demoJobServer(t) |
| + if err := os.MkdirAll(s.store.demoSpoolDir, 0755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Chmod(s.store.demoSpoolDir, 0777); err != nil { |
| + t.Fatal(err) |
| + } |
| + f, err := s.newDemoSpool() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer f.Close() |
| + for path, want := range map[string]os.FileMode{s.store.demoSpoolDir: 0700, f.Name(): 0600} { |
| + info, err := os.Stat(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if info.Mode().Perm() != want { |
| + t.Errorf("%s permissions=%o want=%o", path, info.Mode().Perm(), want) |
| + } |
| + } |
| +} |
diff --git a/internal/host/demo_jobs.go b/internal/host/demo_jobs.go| index 1799eecd8..b5c2b036e 100644 |
| --- a/internal/host/demo_jobs.go |
| +++ b/internal/host/demo_jobs.go |
| @@ -420,10 +420,11 @@ func (w *demoWorker) readSource(ctx context.Context, j demobuild.Job) (demobuild |
| return src, nil |
| } |
| -// CARLOS_CONSOLE names the operator-configured console origin. The reserved |
| +// CARLOS_DEMO_CONSOLE_URL names the console origin in this box's root-owned |
| +// host.env. It stays out of shared/region hostenv parameters. The reserved |
| // tunnel host serves registration and store reads, never console box doors. |
| func demoConsoleOrigin(getenv func(string) string) (string, error) { |
| - u, err := url.Parse(getenv("CARLOS_CONSOLE")) |
| + u, err := url.Parse(getenv("CARLOS_DEMO_CONSOLE_URL")) |
| if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.Opaque != "" { |
| return "", demobuild.ErrJob |
| } |
diff --git a/internal/host/demo_jobs_test.go b/internal/host/demo_jobs_test.go| index 808b0fee6..806379117 100644 |
| --- a/internal/host/demo_jobs_test.go |
| +++ b/internal/host/demo_jobs_test.go |
| @@ -27,6 +27,7 @@ import ( |
| "github.com/carlosframework/platform/internal/demo" |
| "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/hostenv" |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| @@ -333,7 +334,7 @@ func TestDemoJobsWorkerDelivery(t *testing.T) { |
| front := httptest.NewServer(e) |
| defer front.Close() |
| t.Setenv("CARLOS_TUNNEL_URL", "https://tunnel.example.com") |
| - t.Setenv("CARLOS_CONSOLE", "https://"+front.Listener.Addr().String()) |
| + t.Setenv("CARLOS_DEMO_CONSOLE_URL", "https://"+front.Listener.Addr().String()) |
| origin, err := demoConsoleOrigin(os.Getenv) |
| if err != nil { |
| t.Fatal(err) |
| @@ -376,14 +377,18 @@ func TestDemoJobsWorkerDelivery(t *testing.T) { |
| } |
| func TestDemoWorkerConsoleOrigin(t *testing.T) { |
| + if hostenv.Allowed("CARLOS_DEMO_CONSOLE_URL") { |
| + t.Fatal("per-box console origin allowed in shared/region parameters") |
| + } |
| + t.Setenv("CARLOS_CONSOLE", "https://cli.example.com") |
| t.Setenv("CARLOS_TUNNEL_URL", "https://tunnel.example.com") |
| - t.Setenv("CARLOS_CONSOLE", "https://console.example.com/") |
| + t.Setenv("CARLOS_DEMO_CONSOLE_URL", "https://console.example.com/") |
| got, err := demoConsoleOrigin(os.Getenv) |
| if err != nil || got != "https://console.example.com" { |
| t.Fatalf("worker origin=%q err=%v", got, err) |
| } |
| for _, bad := range []string{"", "https://tunnel.example.com", "http://console.example.com", "https://user:secret@console.example.com", "https://console.example.com/api", "https://console.example.com?x=1", "https://console.example.com#x"} { |
| - t.Setenv("CARLOS_CONSOLE", bad) |
| + t.Setenv("CARLOS_DEMO_CONSOLE_URL", bad) |
| if got, err := demoConsoleOrigin(os.Getenv); err == nil { |
| t.Errorf("accepted origin %q as %q", bad, got) |
| } |