feat: commit demo claims and retire their anonymous source
Coordinate authenticated source freeze and snapshot transfer with a durable claim decision. Retry destination opening, moved publication and signed retirement without reopening a committed source. Fence uncommitted seed orphan cleanup and preserve claim retention through source purge. Targeted transfer, recovery, publication, expiry and worker tests pass; independent review and the final root-read census approval remain with the controller.
internal/console/apidemo.go+3 −0internal/console/apidemobox.go+187 −0internal/console/claim_invariant_test.go+5 −0internal/console/demo_claim_auth.go+13 −2internal/console/demo_claim_recovery_test.go+448 −0internal/console/demo_claim_seed.go+17 −8internal/console/demo_claim_store.go+8 −0internal/console/demo_claim_target.go+1 −6internal/console/demo_claim_transfer.go+929 −0internal/console/demo_claim_transfer_test.go+597 −0internal/console/demo_expiry.go+43 −3internal/console/demo_jobs.go+14 −0internal/console/demo_store.go+7 −1internal/console/server.go+2 −1internal/console/store_gate.go+4 −0internal/demobuild/retirement.go+1 −1internal/demobuild/retirement_test.go+19 −0internal/provision/agent_start_demo_3_census_test.go+20 −2internal/provision/demo_claim_hold.go+67 −0internal/provision/demo_claim_seed.go+74 −0internal/provision/demo_claim_seed_test.go+76 −0internal/provision/demo_claim_test.go+32 −0internal/provision/reconcile.go+9 −0internal/provision/record_sequence.go+2 −2
CI failed — run details
Intent
<task-notification> <task-id>b8q5sajtf</task-id> <tool-use-id>toolu_01KcyrASCNPJZfYqawfSNyji</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/b8q5sajtf.output</output-file> <status>completed</status> <summary>Background command "S=/home/paulca/.cache/tmp/claude-1001/agent-start-demo-3; until [ -f $S/t4.done ]; do sleep 30; done; tail -1 $S/t4.log" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a5391946210ed7e06</task-id> <tool-use-id>toolu_017U7ZLWvgnYNaPybgBcCUJL</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/a5391946210ed7e06.output</output-file> <status>completed</status> <summary>Agent "Review Task 4 (Opus)" 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>**1) Spec compliance: ✅**, with three items I could not verify from the diff: - ⚠️ Rollback binaries are excluded only if the deployment's seeds floor publication actually carries `min: 2`. Root boxes verify a signed publication (`internal/host/rootseedsfloor_publication.go:19`), and nothing in the tree writes one. The console door now writes `Min: seeds.ProtocolVersion` (`internal/console/seedfloor.go:192`), but only unsigned. `demoClaimSeedReady` and `seedRegionReady` both read the same key, so they agree. Task 8's activation run should confirm the signed floor is `{min:2}`. - ⚠️ `TestDemoClaimSeedCommit` has no explicit `ordinaryReplicaAndImport => unchanged` subcase. The report relies on the existing Seed/Import suites for this. - ⚠️ The coordinator side belongs to Task 5. Commit and abort must both run under the app lock, the phase must be set to aborting before finish, and a rotated key must lead to abort, not a new hash. The helpers enforce what they can; the rest is in the report's contracts. **2) Findings** No P1. No P2. **P3-1. Leftover claim data when a box misses the abort.** Fault family: abort cleanup completeness. - `internal/provision/demo_claim_seed.go:1678-1750`: on a box with no row, the abort still fences, finds no matching marker, and moves the record to rolled-back. - Scenario: box A held the row and ran the claim. Box B has no row and rolls back first. A's lease is free (idled out, or A's agent is restarting). The console finishes, deleting the replica and the record (`seedfinish.go:271`). A's next pass then sees no record and removes the row through the ordinary orphan path (`reconcile.go:~2436`), which purges no local data. The claim's database stays at `NestedDBPath(host)`. - Impact: a later instance at the same host (same account, same app name) could open that file as a warm cache, the problem `purgeAbortedFromLocal` guards against for `--from` seeds. Existing `--from` seeds have the same race, so this matches current behaviour. The new rolled-back-with-row case (`seedreconcile.go:2454`) narrows the window. - Fix: before the orphan path deletes a row whose `seed_source` is an uncommitted demo-claim, fence it, check the marker against the row's seed ID and run `RemoveLocal`. The row carries the seed ID, so no record is needed. **P3-2. No byte-level test for unchanged wire format.** Fault family: wire compatibility. - The risk list asked for a fingerprint test. Only the CLI `apiSeed` is checked (`instances_demo_claim_test.go:63`). - It is correct by construction: `omitempty` on `ClaimID` in `provision.SeedSource` (`seed.go:279`) and `seeds.RowSeed` (`row.go:608`). - Fix: add golden tests that `SeedColumn` and `json.Marshal(SeedSource)` produce the old bytes for replica and import seeds without a claim ID. **P3-3. The floor door can no longer publish a protocol-1 floor.** Fault family: ordinary seed compatibility (judgment call 2). - After this change (`seedfloor.go:192`), any republish, even one made only for ordinary seeds, raises the floor to protocol 2. `seedRegionReady` uses `max(RequiredProtocol, floor.Min)`, so ordinary seeds then need every box and every rollback binary at protocol 2. - This only refuses more, so it is safe. It should go in the runbook. **P3-4. Committed claim records keep shape limits forever.** Fault family: "ordinary after commit." - `validateDemoClaimSeed` (`demo_claim_seed.go:1598-1600`) still refuses HA, a runtime, addrs and a non-instance kind once committed. - None of these can change after create today. If a later feature lets them change, a claimed app would be the odd one out. **P3-5. Census false positives.** - `validateDemoClaimSeed`'s "+file:Open" is `RunState.Open()`, a method that touches no file. - `CompareSeedGate`/`DeleteSeedRoute`'s "+file:Exec" is a SQL `Exec`. **Root review (ahead of the census)** - Every new read runs in the agent (user `carlos`) or the console: - the `claimSeedWakeHook` record read - `abortDemoClaimSeed`'s registry and record reads, and its marker read through instancefs - the edge's `SeedSource` parse - the console's edges, status and floor reads - The removal path comes from `NestedDBPath(cfg.DataDir, rec.Host)` and runs only after a fence, proven stop and a marker match. No tenant-named path reaches root. - The only root-side change is indirect. `rootgeneration_requirements.go:59` and `wakeidentity.go:252` call `ValidateShape`, which now refuses more and never less. - Nothing weakens a check root relies on. **3) Strengths** - The route and its gate are created in one insert (`CreateSeedRoute`, guard `AND 0`). `upsertRoute` never updates `import_gate`, so ordinary convergence cannot open the gate. Gate changes are compare-and-swap writes bound to seed, owner and lifetime. - The claim kind never reaches swap or journal code, and it is explicitly kept out of `journalPass`. - The durable record is re-read after the lease and before any restore or exec. Together with the console refusing to finish while the lease is held, this stops a stale wake from restarting an aborted destination. - A missing or unready snapshot always fails the wake instead of booting empty. - The verify token is HMAC-SHA256 of `"carlos demo claim verify v1\n"` plus the operation ID under `cfg.Key.Seed()`. Only its hash is stored, and it is re-derived after transfer, so a rotated key is refused. - Uploads are create-only and the stored bytes are re-verified. No lock is held during transfer. - Edge: exact host and GET only, header stripped, cache bypassed, and alias and path routes are tested. - No new reads on unchanged watch ticks (tested). **4) Verdict: READY** The P3s can go on the follow-up list. P3-1 is worth carrying into Task 5 or Task 8.</result> <usage><subagent_tokens>210339</subagent_tokens><tool_uses>45</tool_uses><duration_ms>527534</duration_ms></usage> </task-notification>
Attributed to this commit: 13.0 g CO₂e (1,420,054 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-3, 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 580bef0ca..f367c0899 100644 |
| --- a/internal/console/apidemo.go |
| +++ b/internal/console/apidemo.go |
| @@ -273,6 +273,9 @@ func (s *Server) registerDemoRoutes() { |
| s.registerRoute("POST /api/demo/claims/verify", s.handleDemoClaimVerify) |
| s.registerRoute("POST /api/demo/claims/select", s.handleDemoClaimSelect) |
| s.registerRoute("GET /api/demo/claims/status", s.handleDemoClaimStatus) |
| + s.registerRoute("POST /api/box/demo-claims/{operationID}/pickup", s.handleDemoClaimPickup) |
| + s.registerRoute("POST /api/box/demo-claims/{operationID}/snapshot", s.handleDemoClaimSnapshot) |
| + s.registerRoute("POST /api/box/demo-claims/{operationID}/ack", s.handleDemoClaimAck) |
| s.registerRoute("GET /demo/claim", func(w http.ResponseWriter, r *http.Request) { |
| w.Header().Set("Cache-Control", "no-store") |
| jsonError(w, http.StatusServiceUnavailable, demoCopy["DEMO-CLAIM-LATER"]) |
diff --git a/internal/console/apidemobox.go b/internal/console/apidemobox.go| index 665a42e35..8fd8d629f 100644 |
| --- a/internal/console/apidemobox.go |
| +++ b/internal/console/apidemobox.go |
| @@ -7,11 +7,13 @@ import ( |
| "net/http" |
| "os" |
| "sort" |
| + "strconv" |
| "strings" |
| "time" |
| "github.com/carlosframework/platform/internal/demo" |
| "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/democlaim" |
| "github.com/carlosframework/platform/internal/interactive" |
| "golang.org/x/net/websocket" |
| ) |
| @@ -228,6 +230,17 @@ func (s *Server) sendDemoPending(ctx context.Context, p *demoPeer, replayRetirem |
| } |
| } |
| } |
| + if replayRetirements && ready.ClaimCapability == democlaim.Capability { |
| + claims, err := s.pendingDemoClaims(ctx, p.box()) |
| + if err != nil { |
| + return err |
| + } |
| + for _, wire := range claims { |
| + if err = send(demobuild.StreamMessage{Claim: wire}); err != nil { |
| + return err |
| + } |
| + } |
| + } |
| if err := send(demobuild.StreamMessage{Reconcile: hint}); err != nil { |
| return err |
| } |
| @@ -383,3 +396,177 @@ func (s *Server) handleDemoResult(w http.ResponseWriter, r *http.Request) { |
| w.Header().Set("Cache-Control", "no-store") |
| w.WriteHeader(http.StatusNoContent) |
| } |
| + |
| +// Box claim requests use the existing fleet identity and the operation's |
| +// immutable assigned box. Request bodies never name a source path or host. |
| +func (s *Server) authenticatedDemoClaim(w http.ResponseWriter, r *http.Request) (claimOp, bool) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + if !s.demoClaimEnabled() { |
| + jsonError(w, 503, demoClaimUnavailable) |
| + return claimOp{}, false |
| + } |
| + name, _, ok := s.demoBoxAuth(r) |
| + id := r.PathValue("operationID") |
| + if !ok || !demobuild.ValidJobID(id) { |
| + http.NotFound(w, r) |
| + return claimOp{}, false |
| + } |
| + op, err := s.store.demoClaimOp(r.Context(), id) |
| + if err != nil || name != s.cfg.Demo.Fleet+"/"+op.SourceBox { |
| + http.NotFound(w, r) |
| + return claimOp{}, false |
| + } |
| + return op, true |
| +} |
| +func (s *Server) demoClaimPickup(ctx context.Context, id, action string, generation uint64) (democlaim.PickupResponse, error) { |
| + op, err := s.store.demoClaimOp(ctx, id) |
| + if err != nil { |
| + return democlaim.PickupResponse{}, err |
| + } |
| + p, err := s.claimProgress(ctx, id) |
| + if err != nil { |
| + return democlaim.PickupResponse{}, err |
| + } |
| + valid := action == "freeze" && op.Phase == "freezing" && p.HoldReady || action == "export" && (op.Phase == "copying" || op.Phase == "verifying") && p.HoldAck || action == "abort" && op.Phase == "aborting" && p.Cleanup |
| + if !valid || generation != uint64(op.Generation) || p.Action != action { |
| + return democlaim.PickupResponse{}, ErrDemoToken |
| + } |
| + work, err := democlaim.VerifyWork(s.cfg.ReleasePub, p.Wire, time.Now()) |
| + if err != nil { |
| + return democlaim.PickupResponse{}, err |
| + } |
| + d, err := s.store.demoByID(ctx, op.DemoID) |
| + if err != nil { |
| + return democlaim.PickupResponse{}, err |
| + } |
| + life, err := s.store.AppLife(d.AccountID, d.App) |
| + if err != nil { |
| + return democlaim.PickupResponse{}, err |
| + } |
| + if !demoClaimSourceMatches(op, d, life) || work.ID != id || work.Action != action || work.Generation != generation { |
| + return democlaim.PickupResponse{}, ErrDemoToken |
| + } |
| + if action != "abort" && !time.Now().Before(op.Deadline) { |
| + return democlaim.PickupResponse{}, ErrDemoToken |
| + } |
| + return democlaim.PickupResponse{Work: p.Wire, RollbackProven: action == "abort" && p.Cleanup}, nil |
| +} |
| +func (s *Server) handleDemoClaimPickup(w http.ResponseWriter, r *http.Request) { |
| + op, ok := s.authenticatedDemoClaim(w, r) |
| + if !ok { |
| + return |
| + } |
| + defer r.Body.Close() |
| + raw, err := io.ReadAll(io.LimitReader(r.Body, 1025)) |
| + var in democlaim.PickupRequest |
| + if err != nil || len(raw) > 1024 || demobuild.DecodeMessage(raw, &in) != nil { |
| + jsonError(w, 409, demoClaimUnavailable) |
| + return |
| + } |
| + defer s.acctLocks.lock("demo-claim:" + op.ID)() |
| + out, err := s.demoClaimPickup(r.Context(), op.ID, in.Action, in.Generation) |
| + if err != nil { |
| + jsonError(w, 409, demoClaimUnavailable) |
| + return |
| + } |
| + demoClaimReply(w, 200, out) |
| +} |
| +func (s *Server) ackDemoClaim(ctx context.Context, id, action string, generation uint64) error { |
| + defer s.acctLocks.lock("demo-claim:" + id)() |
| + if _, err := s.demoClaimPickup(ctx, id, action, generation); err != nil { |
| + return err |
| + } |
| + switch action { |
| + case "freeze": |
| + _, err := s.store.db.ExecContext(ctx, `UPDATE demo_claim_progress SET hold_ack=1,retry_at=0 WHERE operation_id=?`, id) |
| + if err != nil { |
| + return err |
| + } |
| + case "export": // Successful snapshot receipt already advanced the operation. |
| + case "abort": |
| + _, err := s.store.db.ExecContext(ctx, `UPDATE demo_claim_progress SET abort_ack=1,retry_at=0 WHERE operation_id=? AND cleanup=1`, id) |
| + if err != nil { |
| + return err |
| + } |
| + default: |
| + return ErrDemoToken |
| + } |
| + s.signalDemoJobs() |
| + return nil |
| +} |
| +func (s *Server) handleDemoClaimAck(w http.ResponseWriter, r *http.Request) { |
| + op, ok := s.authenticatedDemoClaim(w, r) |
| + if !ok { |
| + return |
| + } |
| + defer r.Body.Close() |
| + raw, err := io.ReadAll(io.LimitReader(r.Body, 1025)) |
| + var in democlaim.AckRequest |
| + if err != nil || len(raw) > 1024 || demobuild.DecodeMessage(raw, &in) != nil || s.ackDemoClaim(r.Context(), op.ID, in.Action, in.Generation) != nil { |
| + jsonError(w, 409, demoClaimUnavailable) |
| + return |
| + } |
| + w.WriteHeader(http.StatusNoContent) |
| +} |
| +func (s *Server) handleDemoClaimSnapshot(w http.ResponseWriter, r *http.Request) { |
| + op, ok := s.authenticatedDemoClaim(w, r) |
| + if !ok { |
| + return |
| + } |
| + defer r.Body.Close() |
| + sha := r.Header.Get(democlaim.SnapshotSHA256Header) |
| + size, err := strconv.ParseInt(r.Header.Get(democlaim.SnapshotBytesHeader), 10, 64) |
| + if err != nil || size <= 0 || size > democlaim.MaxSnapshotBytes || r.ContentLength != size || r.Header.Get("Content-Type") != "application/vnd.sqlite3" || len(r.Header.Values(democlaim.SnapshotSHA256Header)) != 1 || len(r.Header.Values(democlaim.SnapshotBytesHeader)) != 1 { |
| + jsonError(w, 409, demoClaimUnavailable) |
| + return |
| + } |
| + deadline := time.Now().Add(democlaim.SnapshotWindow) |
| + if op.Deadline.Before(deadline) { |
| + deadline = op.Deadline |
| + } |
| + if err = http.NewResponseController(w).SetReadDeadline(deadline); err != nil { |
| + jsonError(w, 503, demoClaimUnavailable) |
| + return |
| + } |
| + r.Body = http.MaxBytesReader(w, r.Body, democlaim.MaxSnapshotBytes) |
| + if err = s.acceptDemoClaimSnapshot(r.Context(), op.ID, r.Body, sha, size); err != nil { |
| + jsonError(w, 409, demoClaimUnavailable) |
| + return |
| + } |
| + w.WriteHeader(http.StatusNoContent) |
| +} |
| + |
| +func (s *Server) pendingDemoClaims(ctx context.Context, box string) ([][]byte, error) { |
| + rows, err := s.store.db.QueryContext(ctx, `SELECT o.id FROM demo_claim_ops o JOIN demo_claim_progress p ON p.operation_id=o.id WHERE o.source_box=? AND (o.phase='freezing' AND p.hold_ready=1 AND p.hold_ack=0 OR o.phase='copying' OR o.phase='aborting' AND p.cleanup=1 AND p.abort_ack=0) ORDER BY o.id LIMIT ?`, box, demobuild.QueueLimit) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var ids []string |
| + for rows.Next() { |
| + var id string |
| + if err = rows.Scan(&id); err != nil { |
| + break |
| + } |
| + ids = append(ids, id) |
| + } |
| + err = errors.Join(err, rows.Err(), rows.Close()) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var out [][]byte |
| + for _, id := range ids { |
| + op, err := s.store.demoClaimOp(ctx, id) |
| + if err != nil { |
| + return nil, err |
| + } |
| + p, err := s.claimProgress(ctx, id) |
| + if err != nil { |
| + return nil, err |
| + } |
| + response, err := s.demoClaimPickup(ctx, id, p.Action, uint64(op.Generation)) |
| + if err == nil { |
| + out = append(out, response.Work) |
| + } |
| + } |
| + return out, nil |
| +} |
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go| index 5dc118a5b..fbd34f00a 100644 |
| --- a/internal/console/claim_invariant_test.go |
| +++ b/internal/console/claim_invariant_test.go |
| @@ -183,6 +183,11 @@ type claimWindow struct { |
| // every writer is reached. A new boundary method or gated table fails the |
| // coverage step until a door reaches it or a reason is written here. |
| var claimWriterReasons = map[string]string{ |
| + "sql/demo_claim_progress": "demo claim coordination refuses claims mode; TestDemoClaimTransferSQLGate proves writes are denied", |
| + "sql/demo_claim_commits": "demo claim coordination refuses claims mode; TestDemoClaimTransferSQLGate proves writes are denied", |
| + "sql/demo_claim_outbox": "demo claim coordination refuses claims mode; TestDemoClaimTransferSQLGate proves writes are denied", |
| + "sql/demo_moved_notices": "demo claim coordination refuses claims mode; TestDemoClaimTransferSQLGate proves writes are denied", |
| + |
| "sql/demo_claim_ops": "demo claim reservations refuse claims mode; TestDemoClaimReservationSQLGate proves writes are denied", |
| "sql/demo_claim_flows": "demo claim proof refuses claims mode; TestDemoClaimProofSQLGate proves every write is denied even with an app permit", |
| "sql/demo_reports": "demo reports refuse claims mode; TestDemoSQLClaimsRefuseBuildState proves every write is denied even with an app permit", |
diff --git a/internal/console/demo_claim_auth.go b/internal/console/demo_claim_auth.go| index cb0286fe1..b93a10a41 100644 |
| --- a/internal/console/demo_claim_auth.go |
| +++ b/internal/console/demo_claim_auth.go |
| @@ -342,7 +342,7 @@ func (s *Server) demoClaimAccountChoice(w http.ResponseWriter, r *http.Request, |
| s.demoClaimAccountError(w, r, err) |
| return |
| } |
| - demoClaimReply(w, 202, map[string]any{"state": "claiming", "phase": op.Phase, "retryAfter": 2}) |
| + s.demoClaimStatusReply(w, r, op) |
| } |
| func (s *Server) handleDemoClaimSelect(w http.ResponseWriter, r *http.Request) { |
| @@ -376,7 +376,7 @@ func (s *Server) handleDemoClaimStatus(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| if op, err := s.store.demoClaimOpForFlow(r.Context(), flow.Hash); err == nil { |
| - demoClaimReply(w, 202, map[string]any{"state": "claiming", "phase": op.Phase, "retryAfter": 2}) |
| + s.demoClaimStatusReply(w, r, op) |
| return |
| } else if !errors.Is(err, sql.ErrNoRows) { |
| jsonError(w, 503, demoClaimUnavailable) |
| @@ -435,3 +435,14 @@ func (s *Server) demoClaimLink(w http.ResponseWriter, r *http.Request, link stri |
| w.Header().Set("Content-Type", "text/plain; charset=utf-8") |
| fmt.Fprintln(w, demoClaimLinkDone) |
| } |
| + |
| +func (s *Server) demoClaimStatusReply(w http.ResponseWriter, r *http.Request, op claimOp) { |
| + switch op.Phase { |
| + case "done": |
| + demoClaimReply(w, 200, map[string]any{"state": "claimed", "accountId": op.Target.Sqid, "app": op.Target.App, "url": "https://" + op.Target.Host, "next": "cli_login"}) |
| + case "aborted": |
| + demoClaimReply(w, 200, map[string]any{"state": "aborted"}) |
| + default: |
| + demoClaimReply(w, 202, map[string]any{"state": "claiming", "phase": op.Phase, "retryAfter": 2, "recoveryPending": op.Phase == "aborting" || op.Phase == "committed"}) |
| + } |
| +} |
diff --git a/internal/console/demo_claim_recovery_test.go b/internal/console/demo_claim_recovery_test.go| new file mode 100644 |
| index 000000000..d4a1f8c31 |
| --- /dev/null |
| +++ b/internal/console/demo_claim_recovery_test.go |
| @@ -0,0 +1,448 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "fmt" |
| + "github.com/carlosframework/platform/internal/lease/leasetest" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/seeds" |
| + "io" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestDemoClaimCommitRecovery(t *testing.T) { |
| + for _, boundary := range []string{"commit", "open", "moved", "retire", "done"} { |
| + t.Run(boundary, func(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + claimToVerify(t, s, op, data) |
| + claimPlace(t, s, op) |
| + fired := false |
| + s.demoClaimBoundary = func(at string) error { |
| + if at == boundary && !fired { |
| + fired = true |
| + return errors.New("injected crash") |
| + } |
| + return nil |
| + } |
| + _ = s.advanceDemoClaim(t.Context(), op.ID) |
| + if !fired { |
| + t.Fatalf("missing boundary %s", boundary) |
| + } |
| + s.demoClaimBoundary = nil |
| + s.demoClaimTestEnabled = false // Admission off must not undo a durable commit. |
| + claimAdvance(t, s, op) |
| + got, err := s.store.demoClaimOp(t.Context(), op.ID) |
| + if err != nil || got.Phase != "done" { |
| + t.Fatalf("recovery %s %v", got.Phase, err) |
| + } |
| + if err := s.abortDemoClaim(t.Context(), op.ID, "test"); err == nil { |
| + t.Fatal("post-commit rollback") |
| + } |
| + var n int |
| + if err := s.store.db.QueryRow(`SELECT count(*) FROM apps WHERE demo_claim_op=? OR (account_id=? AND app=?)`, op.ID, op.Target.AccountID, op.Target.App).Scan(&n); err != nil || n != 1 { |
| + t.Fatalf("destinations %d %v", n, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A fresh Server and reopened SQLite file must continue each durable phase. |
| +// Workers and object stores here are local fixtures; no real box is contacted. |
| +func TestDemoClaimCommitRecoveryBeforeCommit(t *testing.T) { |
| + for _, boundary := range []string{"pipeline", "seed-record", "artifact", "freezing", "hold", "copying", "snapshot-metadata", "snapshot-object", "snapshot", "before-commit"} { |
| + t.Run(boundary, func(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + fired := false |
| + s.demoClaimBoundary = func(at string) error { |
| + if at == boundary && !fired { |
| + fired = true |
| + return errors.New("injected crash") |
| + } |
| + return nil |
| + } |
| + drive := func() error { |
| + current, err := s.store.demoClaimOp(t.Context(), op.ID) |
| + if err != nil { |
| + return err |
| + } |
| + switch current.Phase { |
| + case "freezing": |
| + p, err := s.claimProgress(t.Context(), op.ID) |
| + if err != nil { |
| + return err |
| + } |
| + if p.HoldReady && !p.HoldAck { |
| + if err = s.ackDemoClaim(t.Context(), op.ID, "freeze", uint64(op.Generation)); err != nil { |
| + return err |
| + } |
| + } |
| + case "copying": |
| + if err = claimSnapshot(t, s, op, data); err != nil { |
| + return err |
| + } |
| + case "verifying": |
| + claimPlace(t, s, op) |
| + } |
| + return s.advanceDemoClaim(t.Context(), op.ID) |
| + } |
| + for i := 0; i < 8 && !fired; i++ { |
| + _ = drive() |
| + } |
| + if !fired { |
| + t.Fatal("missing boundary", boundary) |
| + } |
| + var committed int |
| + if err := s.store.db.QueryRow(`SELECT count(*) FROM demo_claim_commits WHERE operation_id=?`, op.ID).Scan(&committed); err != nil || committed != 0 { |
| + t.Fatal("precommit crash consumed source", err) |
| + } |
| + old := s |
| + s = reopenDemoJobs(t, old) |
| + s.demoClaimTestEnabled = true |
| + s.demoTransport = old.demoTransport |
| + s.seedScratch = old.seedScratch |
| + s.dbReplica = old.dbReplica |
| + for i := 0; i < 8; i++ { |
| + if err := drive(); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, _ := s.store.demoClaimOp(t.Context(), op.ID) |
| + if got.Phase == "done" { |
| + return |
| + } |
| + } |
| + t.Fatal("recovery did not finish") |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimCommitRecoveryFlowRetention(t *testing.T) { |
| + var flow string |
| + s, op, data := claimTransferFixture(t, &flow) |
| + claimToVerify(t, s, op, data) |
| + claimPlace(t, s, op) |
| + claimAdvance(t, s, op) |
| + st := &demoCountingStore{Store: s.cfg.Releases} |
| + s.cfg.Releases = st |
| + for range 3 { |
| + r := httptest.NewRequest("GET", "/api/demo/claims/status", nil) |
| + r.Header.Set("Authorization", "Bearer "+flow) |
| + w := httptest.NewRecorder() |
| + s.handleDemoClaimStatus(w, r) |
| + if w.Code != 200 || !strings.Contains(w.Body.String(), `"state":"claimed"`) || !strings.Contains(w.Body.String(), `"next":"cli_login"`) { |
| + t.Fatalf("lost reply result: %d %s", w.Code, w.Body) |
| + } |
| + } |
| + if st.gets.Load() != 0 || st.puts.Load() != 0 { |
| + t.Fatal("status contacted store") |
| + } |
| + if err := s.pruneDemoClaims(t.Context(), time.Unix(op.SourceExpiresAt, 0).Add(24*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + fresh, _ := s.store.demoClaimOp(t.Context(), op.ID) |
| + if fresh.FlowHash != "" { |
| + t.Fatal("flow capability retained") |
| + } |
| + if _, err := s.store.demoClaimStatusFlow(t.Context(), flow, time.Now()); err == nil { |
| + t.Fatal("erased flow still usable") |
| + } |
| +} |
| + |
| +func claimLocalLeaseServer(t *testing.T, s *Server) { |
| + t.Helper() |
| + bucket := leasetest.NewVersionedBucket() |
| + bucket.AddBucket(s.cfg.HibernateBucket) |
| + h, _ := leasetest.NewS3Server(bucket) |
| + server := httptest.NewServer(h) |
| + t.Cleanup(server.Close) |
| + t.Setenv("AWS_ACCESS_KEY_ID", "test-key") |
| + t.Setenv("AWS_SECRET_ACCESS_KEY", "test-secret") |
| + t.Setenv("AWS_SESSION_TOKEN", "") |
| + t.Setenv("AWS_EC2_METADATA_DISABLED", "true") |
| + t.Setenv("AWS_CONFIG_FILE", filepath.Join(t.TempDir(), "absent")) |
| + t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(t.TempDir(), "absent")) |
| + t.Setenv("CARLOS_S3_ENDPOINT", server.URL) |
| + s.cfg.HibernateRegion = "test-region" |
| +} |
| +func TestDemoClaimCommitRecoveryAbort(t *testing.T) { |
| + for _, mode := range []string{"normal", "expired", "operator"} { |
| + t.Run(mode, func(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + claimToVerify(t, s, op, data) |
| + claimLocalLeaseServer(t, s) |
| + if mode == "operator" { |
| + d, _ := s.store.demoByID(t.Context(), op.DemoID) |
| + if err := s.retireDemoLocked(t.Context(), d, time.Now(), "operator"); !errors.Is(err, ErrDemoBusy) { |
| + t.Fatalf("operator bypass: %v", err) |
| + } |
| + } else if err := s.abortDemoClaim(t.Context(), op.ID, "test"); err != nil { |
| + t.Fatal(err) |
| + } |
| + rec, err := provision.GetRecord(t.Context(), s.cfg.Releases, op.Target.Sqid, op.Target.App, op.Target.Host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if rec.Seed.State != seeds.StateAborted && mode != "operator" { |
| + t.Fatal("destination not closed") |
| + } |
| + d, _ := s.store.demoByID(t.Context(), op.DemoID) |
| + source, err := provision.GetRecord(t.Context(), s.cfg.Releases, d.AccountSqid, d.App, d.Host) |
| + if err != nil || source.DemoClaim == nil { |
| + t.Fatal("source released before proof", err) |
| + } |
| + if mode == "operator" { |
| + if err = s.abortDemoClaim(t.Context(), op.ID, "retry"); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if _, err = provision.SetRecordSeed(t.Context(), s.cfg.Releases, op.Target.Sqid, op.Target.App, op.Target.Host, provision.SeedRolledBack(op.Target.SeedID)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if mode == "expired" { |
| + // Move the entire bound lifetime together, so this is expiry rather |
| + // than a mismatched-lifetime rejection. |
| + expiry := time.Now().Add(-time.Second).Unix() |
| + if _, err = s.store.db.Exec(`UPDATE apps SET expires_at=? WHERE demo_id=?`, expiry, op.DemoID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = s.store.db.Exec(`UPDATE demo_claim_ops SET source_expires_at=? WHERE id=?`, expiry, op.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + claimAdvance(t, s, op) |
| + current, _ := s.store.demoClaimOp(t.Context(), op.ID) |
| + if mode == "normal" { |
| + if current.Phase != "aborting" { |
| + t.Fatal("finished before source release ack") |
| + } |
| + source, err = provision.GetRecord(t.Context(), s.cfg.Releases, d.AccountSqid, d.App, d.Host) |
| + if err != nil || source.DemoClaim != nil { |
| + t.Fatal("durable hold not cleared after cleanup", err) |
| + } |
| + if err = s.ackDemoClaim(t.Context(), op.ID, "abort", uint64(op.Generation)); err != nil { |
| + t.Fatal(err) |
| + } |
| + claimAdvance(t, s, op) |
| + } else { |
| + got, _ := s.store.demoByID(t.Context(), op.DemoID) |
| + if got.State != "retiring" { |
| + t.Fatal("expired/operator source resumed") |
| + } |
| + } |
| + current, _ = s.store.demoClaimOp(t.Context(), op.ID) |
| + if current.Phase != "aborted" { |
| + t.Fatal("abort incomplete", current.Phase) |
| + } |
| + target, _ := s.store.AppLife(op.Target.AccountID, op.Target.App) |
| + if target != nil { |
| + t.Fatal("reservation not released") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimCommitRecoverySQLRollback(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + claimToVerify(t, s, op, data) |
| + claimPlace(t, s, op) |
| + if _, err := s.store.db.Exec(`CREATE TRIGGER reject_claim_outbox BEFORE INSERT ON demo_claim_outbox BEGIN SELECT RAISE(ABORT,'injected failure'); END`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.advanceDemoClaim(t.Context(), op.ID); err == nil { |
| + t.Fatal("missing transaction failure") |
| + } |
| + var token sql.NullString |
| + var n int |
| + if err := s.store.db.QueryRow(`SELECT claim_token_hash FROM demo_apps WHERE demo_id=?`, op.DemoID).Scan(&token); err != nil || !token.Valid { |
| + t.Fatal("transaction spent token", err) |
| + } |
| + if err := s.store.db.QueryRow(`SELECT count(*) FROM demo_claim_commits`).Scan(&n); err != nil || n != 0 { |
| + t.Fatal("partial commitment", err) |
| + } |
| + rec, err := provision.GetRecord(t.Context(), s.cfg.Releases, op.Target.Sqid, op.Target.App, op.Target.Host) |
| + if err != nil || rec.Seed.State != seeds.StatePlaced { |
| + t.Fatal("opened before transaction", err) |
| + } |
| + if _, err = s.store.db.Exec(`DROP TRIGGER reject_claim_outbox`); err != nil { |
| + t.Fatal(err) |
| + } |
| + claimAdvance(t, s, op) |
| +} |
| + |
| +func TestDemoClaimCommitRecoveryIdentity(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + claimToVerify(t, s, op, data) |
| + claimPlace(t, s, op) |
| + if _, err := s.store.db.Exec(`DELETE FROM memberships WHERE account_id=? AND address=?`, op.Target.AccountID, op.Person); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.advanceDemoClaim(t.Context(), op.ID); err == nil { |
| + t.Fatal("removed member committed") |
| + } |
| + current, _ := s.store.demoClaimOp(t.Context(), op.ID) |
| + if current.Phase != "verifying" { |
| + t.Fatal("removed member changed phase") |
| + } |
| +} |
| + |
| +type claimUploadStore struct { |
| + release.Store |
| + puts int |
| + lose bool |
| +} |
| + |
| +func (s *claimUploadStore) Open(ctx context.Context, key string) (io.ReadCloser, string, error) { |
| + return release.OpenObjectStreaming(ctx, s.Store, key) |
| +} |
| +func (s *claimUploadStore) PutFrom(ctx context.Context, key string, r io.ReadSeeker, n int64, tag string) (string, error) { |
| + s.puts++ |
| + out, err := release.PutObjectFrom(ctx, s.Store, key, r, n, tag) |
| + if err == nil && s.lose { |
| + s.lose = false |
| + return "", errors.New("lost upload reply") |
| + } |
| + return out, err |
| +} |
| +func TestDemoClaimRequestCostLostSnapshot(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + claimAdvance(t, s, op) |
| + if err := s.ackDemoClaim(t.Context(), op.ID, "freeze", uint64(op.Generation)); err != nil { |
| + t.Fatal(err) |
| + } |
| + claimAdvance(t, s, op) |
| + store := &claimUploadStore{Store: s.cfg.SeedData, lose: true} |
| + s.cfg.SeedData = store |
| + s.demoClaimBoundary = func(at string) error { |
| + if at == "snapshot-object" { |
| + return errors.New("lost SQL response") |
| + } |
| + return nil |
| + } |
| + if err := claimSnapshot(t, s, op, data); err == nil { |
| + t.Fatal("missing crash") |
| + } |
| + s.demoClaimBoundary = nil |
| + // Recover the stored snapshot without asking the source to export again. |
| + claimAdvance(t, s, op) |
| + got, _ := s.store.demoClaimOp(t.Context(), op.ID) |
| + if got.Phase != "verifying" { |
| + t.Fatal("stored snapshot did not recover") |
| + } |
| + if store.puts != 1 { |
| + t.Fatalf("snapshot PUTs: %d", store.puts) |
| + } |
| + work, err := s.pendingDemoClaims(t.Context(), op.SourceBox) |
| + if err != nil || len(work) != 0 { |
| + t.Fatal("export replayed", err) |
| + } |
| +} |
| + |
| +type claimObjectFault struct { |
| + at, count int |
| + after, fired bool |
| + keys []string |
| +} |
| +type claimObjectFaultStore struct { |
| + release.Store |
| + fault *claimObjectFault |
| +} |
| + |
| +func (s *claimObjectFaultStore) mutation(key string, write func() (string, error)) (string, error) { |
| + f := s.fault |
| + f.count++ |
| + f.keys = append(f.keys, key) |
| + fail := f.count == f.at && !f.fired |
| + if fail && !f.after { |
| + f.fired = true |
| + return "", errors.New("object boundary before write") |
| + } |
| + tag, err := write() |
| + if fail && err == nil { |
| + f.fired = true |
| + return "", errors.New("object boundary after write") |
| + } |
| + return tag, err |
| +} |
| +func (s *claimObjectFaultStore) Put(ctx context.Context, key string, b []byte, tag string) (string, error) { |
| + return s.mutation(key, func() (string, error) { return s.Store.Put(ctx, key, b, tag) }) |
| +} |
| +func (s *claimObjectFaultStore) PutFrom(ctx context.Context, key string, r io.ReadSeeker, n int64, tag string) (string, error) { |
| + return s.mutation(key, func() (string, error) { return release.PutObjectFrom(ctx, s.Store, key, r, n, tag) }) |
| +} |
| +func (s *claimObjectFaultStore) Open(ctx context.Context, key string) (io.ReadCloser, string, error) { |
| + return release.OpenObjectStreaming(ctx, s.Store, key) |
| +} |
| +func (s *claimObjectFaultStore) Delete(ctx context.Context, key string) error { |
| + _, err := s.mutation(key, func() (string, error) { return "", s.Store.Delete(ctx, key) }) |
| + return err |
| +} |
| + |
| +func driveClaimObjects(t *testing.T, s *Server, op claimOp, data []byte) { |
| + t.Helper() |
| + var last error |
| + for range 24 { |
| + current, err := s.store.demoClaimOp(t.Context(), op.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if current.Phase == "done" { |
| + return |
| + } |
| + switch current.Phase { |
| + case "freezing": |
| + p, err := s.claimProgress(t.Context(), op.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if p.HoldReady && !p.HoldAck { |
| + last = s.ackDemoClaim(t.Context(), op.ID, "freeze", uint64(op.Generation)) |
| + if last != nil { |
| + continue |
| + } |
| + } |
| + case "copying": |
| + last = claimSnapshot(t, s, op, data) |
| + if last != nil { |
| + continue |
| + } |
| + } |
| + last = s.advanceDemoClaim(t.Context(), op.ID) |
| + } |
| + current, _ := s.store.demoClaimOp(t.Context(), op.ID) |
| + t.Fatalf("object recovery stayed %s: %v", current.Phase, last) |
| +} |
| +func TestDemoClaimCommitRecoveryObjectBoundaries(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + baseline := &claimObjectFault{} |
| + s.cfg.Releases = &claimObjectFaultStore{s.cfg.Releases, baseline} |
| + s.cfg.SeedData = &claimObjectFaultStore{s.cfg.SeedData, baseline} |
| + driveClaimObjects(t, s, op, data) |
| + t.Logf("injecting before and after each of %d object mutation boundaries", baseline.count) |
| + for i := 1; i <= baseline.count; i++ { |
| + for _, after := range []bool{false, true} { |
| + t.Run(fmt.Sprintf("%02d/after=%v", i, after), func(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + fault := &claimObjectFault{at: i, after: after} |
| + s.cfg.Releases = &claimObjectFaultStore{s.cfg.Releases, fault} |
| + s.cfg.SeedData = &claimObjectFaultStore{s.cfg.SeedData, fault} |
| + driveClaimObjects(t, s, op, data) |
| + if !fault.fired { |
| + t.Fatal("fault boundary was not reached") |
| + } |
| + var n int |
| + if err := s.store.db.QueryRow(`SELECT count(*) FROM apps WHERE account_id=? AND app=?`, op.Target.AccountID, op.Target.App).Scan(&n); err != nil || n != 1 { |
| + t.Fatal("destination duplicated", err) |
| + } |
| + if err := s.abortDemoClaim(t.Context(), op.ID, "late"); err == nil { |
| + t.Fatal("committed claim rolled back") |
| + } |
| + }) |
| + } |
| + } |
| +} |
diff --git a/internal/console/demo_claim_seed.go b/internal/console/demo_claim_seed.go| index 37de9a1f7..fbce95695 100644 |
| --- a/internal/console/demo_claim_seed.go |
| +++ b/internal/console/demo_claim_seed.go |
| @@ -23,7 +23,7 @@ import ( |
| // The token is reproducible after a console restart but never persisted. |
| func (s *Server) demoClaimVerifyToken(id string) (string, error) { |
| - if !s.demoClaimEnabled() || len(s.cfg.Key) != ed25519.PrivateKeySize || !demobuild.ValidJobID(id) { |
| + if s.cfg.HostClaim || s.store.claimGated() || len(s.cfg.Key) != ed25519.PrivateKeySize || !demobuild.ValidJobID(id) { |
| return "", errors.New(demoClaimUnavailable) |
| } |
| mac := hmac.New(sha256.New, s.cfg.Key.Seed()) |
| @@ -35,7 +35,7 @@ func (s *Server) demoClaimVerifyToken(id string) (string, error) { |
| // Protocol 2's existing seeds floor excludes an older rollback binary. |
| func (s *Server) demoClaimSeedReady(ctx context.Context, region string) error { |
| refuse := func() error { return errors.New(demoClaimUnavailable) } |
| - if !s.demoClaimEnabled() || s.cfg.Releases == nil || region != s.cfg.Region || s.haRegion(region) { |
| + if s.cfg.HostClaim || s.store.claimGated() || s.cfg.Releases == nil || region != s.cfg.Region || s.haRegion(region) { |
| return refuse() |
| } |
| if ref := s.seedRegionReady(ctx, region, false); ref != nil { |
| @@ -83,7 +83,7 @@ func (s *Server) demoClaimSeedReady(ctx context.Context, region string) error { |
| // Call while holding the app lock. Stored identity, not a caller's target, |
| // authorizes all operation-owned record and snapshot writes. |
| func (s *Server) demoClaimSeedOperation(ctx context.Context, op claimOp) (claimOp, error) { |
| - if !s.demoClaimEnabled() { |
| + if s.cfg.HostClaim || s.store.claimGated() { |
| return claimOp{}, errors.New(demoClaimUnavailable) |
| } |
| fresh, err := scanDemoClaimOp(s.store.db.QueryRowContext(ctx, `SELECT `+demoClaimOpColumns+` FROM demo_claim_ops WHERE id=?`, op.ID)) |
| @@ -193,6 +193,11 @@ func (s *Server) publishDemoClaimSeed(ctx context.Context, op claimOp, path, sha |
| if s.cfg.SeedData == nil { |
| return errors.New(demoClaimUnavailable) |
| } |
| + // A configured wrapper must retain streaming writes. Do not fall back |
| + // to buffering a database through Store.Put, even below its size cap. |
| + if _, ok := s.cfg.SeedData.(release.PutStreamer); !ok { |
| + return errors.New(demoClaimUnavailable) |
| + } |
| file, err := os.Open(path) |
| if err != nil { |
| return err |
| @@ -223,12 +228,16 @@ func (s *Server) publishDemoClaimSeed(ctx context.Context, op claimOp, path, sha |
| return err |
| } |
| key := seeds.SnapshotKey(op.Target.Host, op.Target.SeedID) |
| - _, err = release.PutObjectFrom(ctx, s.cfg.SeedData, key, file, size, "") |
| - if err != nil && !errors.Is(err, release.ErrCASConflict) { |
| - return err |
| - } |
| - // Verify what was persisted, including a create whose reply was lost. |
| + // Read before a retry PUT. A lost response must not cause a second |
| + // upload when the identical immutable snapshot is already present. |
| stored, _, err := release.OpenObjectStreaming(ctx, s.cfg.SeedData, key) |
| + if errors.Is(err, os.ErrNotExist) { |
| + _, putErr := release.PutObjectFrom(ctx, s.cfg.SeedData, key, file, size, "") |
| + stored, _, err = release.OpenObjectStreaming(ctx, s.cfg.SeedData, key) |
| + if err != nil { |
| + return errors.Join(putErr, err) |
| + } |
| + } |
| if err != nil { |
| return err |
| } |
diff --git a/internal/console/demo_claim_store.go b/internal/console/demo_claim_store.go| index 396edc1ca..96699042e 100644 |
| --- a/internal/console/demo_claim_store.go |
| +++ b/internal/console/demo_claim_store.go |
| @@ -31,6 +31,14 @@ func (s *Store) migrateDemoClaims() error { |
| app TEXT NOT NULL, host TEXT NOT NULL, target_lifetime TEXT NOT NULL, |
| region TEXT NOT NULL, seed_id TEXT NOT NULL, deadline INTEGER NOT NULL, source_expires_at INTEGER NOT NULL); |
| CREATE UNIQUE INDEX IF NOT EXISTS demo_claim_flow_active ON demo_claim_ops(flow_hash) WHERE flow_hash != ''; |
| + CREATE TABLE IF NOT EXISTS demo_claim_progress ( |
| + operation_id TEXT PRIMARY KEY, work BLOB NOT NULL DEFAULT X'', action TEXT NOT NULL DEFAULT '', |
| + hold_ready INTEGER NOT NULL DEFAULT 0, hold_ack INTEGER NOT NULL DEFAULT 0, snapshot_sha TEXT NOT NULL DEFAULT '', snapshot_bytes INTEGER NOT NULL DEFAULT 0, |
| + copied INTEGER NOT NULL DEFAULT 0, cleanup INTEGER NOT NULL DEFAULT 0, abort_ack INTEGER NOT NULL DEFAULT 0, |
| + reason TEXT NOT NULL DEFAULT '', retry_at INTEGER NOT NULL DEFAULT 0, phase_until INTEGER NOT NULL DEFAULT 0); |
| + CREATE TABLE IF NOT EXISTS demo_claim_commits (operation_id TEXT PRIMARY KEY, demo_id TEXT NOT NULL UNIQUE, committed_at INTEGER NOT NULL); |
| + CREATE TABLE IF NOT EXISTS demo_claim_outbox (operation_id TEXT NOT NULL, step TEXT NOT NULL, PRIMARY KEY(operation_id,step)); |
| + CREATE TABLE IF NOT EXISTS demo_moved_notices (demo_id TEXT PRIMARY KEY, host TEXT NOT NULL, target_host TEXT NOT NULL, expires_at INTEGER NOT NULL); |
| CREATE UNIQUE INDEX IF NOT EXISTS demo_claim_active ON demo_claim_ops(demo_id) WHERE phase != 'aborted';`) |
| return err |
| } |
diff --git a/internal/console/demo_claim_target.go b/internal/console/demo_claim_target.go| index 8feb3b81d..f0a642e39 100644 |
| --- a/internal/console/demo_claim_target.go |
| +++ b/internal/console/demo_claim_target.go |
| @@ -71,9 +71,6 @@ func (s *Server) chooseDemoClaimAccount(ctx context.Context, f claimFlow, select |
| } |
| } |
| -// Task 5 installs the worker, seed and edge capability floor here before freeze. |
| -func (s *Server) demoClaimCapabilitiesReady(context.Context) error { return nil } |
| - |
| // Reservation writes only a fresh, private destination. Transfer and publication |
| // are owned by the later coordinator. The account lock shares normal create caps. |
| func (s *Server) reserveDemoClaim(ctx context.Context, f claimFlow, acct *Account, rq regionReq) (claimOp, error) { |
| @@ -138,9 +135,6 @@ func (s *Server) reserveDemoClaim(ctx context.Context, f claimFlow, acct *Accoun |
| if err = s.roomIn(ctx, region, ""); err != nil { |
| return claimOp{}, errDemoClaimPlacement |
| } |
| - if err = s.demoClaimCapabilitiesReady(ctx); err != nil { |
| - return claimOp{}, err |
| - } |
| id, err := demobuild.NewJobID() |
| if err != nil { |
| return claimOp{}, err |
| @@ -238,6 +232,7 @@ func (s *Server) finishDemoClaimReservation(ctx context.Context, op claimOp) err |
| if _, err := release.SetPipeline(withDemoClaimOperation(ctx, op.ID), s.cfg.Releases, s.cfg.Key, op.Target.Sqid, op.Target.App, release.DefaultPipelineChannels(), op.Person); err != nil { |
| log.Printf("console: claim %s/%s: set default pipeline: %v", op.Target.Sqid, op.Target.App, err) |
| } |
| + s.signalDemoJobs() |
| return nil |
| } |
diff --git a/internal/console/demo_claim_transfer.go b/internal/console/demo_claim_transfer.go| new file mode 100644 |
| index 000000000..3ba4c6fa5 |
| --- /dev/null |
| +++ b/internal/console/demo_claim_transfer.go |
| @@ -0,0 +1,929 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "database/sql" |
| + "encoding/hex" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "os" |
| + "sort" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/democlaim" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/seeds" |
| +) |
| + |
| +type demoClaimProgress struct { |
| + Wire []byte |
| + Action, SHA, Reason string |
| + HoldReady, HoldAck, Copied, Cleanup, AbortAck bool |
| + Bytes, RetryAt, Until int64 |
| +} |
| + |
| +func (s *Store) demoClaimOp(ctx context.Context, id string) (claimOp, error) { |
| + return scanDemoClaimOp(s.db.QueryRowContext(ctx, `SELECT `+demoClaimOpColumns+` FROM demo_claim_ops WHERE id=?`, id)) |
| +} |
| +func (s *Server) claimProgress(ctx context.Context, id string) (demoClaimProgress, error) { |
| + var p demoClaimProgress |
| + err := s.store.db.QueryRowContext(ctx, `SELECT work,action,hold_ready,hold_ack,snapshot_sha,snapshot_bytes,copied,cleanup,abort_ack,reason,retry_at,phase_until FROM demo_claim_progress WHERE operation_id=?`, id).Scan(&p.Wire, &p.Action, &p.HoldReady, &p.HoldAck, &p.SHA, &p.Bytes, &p.Copied, &p.Cleanup, &p.AbortAck, &p.Reason, &p.RetryAt, &p.Until) |
| + return p, err |
| +} |
| +func (s *Server) claimBoundary(at string) error { |
| + if s.demoClaimBoundary != nil { |
| + return s.demoClaimBoundary(at) |
| + } |
| + return nil |
| +} |
| + |
| +// TODO(Task 6): replace this seam with the edge moved-page capability check. |
| +func (s *Server) demoClaimMovedReady(context.Context) error { return nil } |
| +func (s *Server) demoClaimCapabilitiesReady(ctx context.Context, op claimOp) error { |
| + found := false |
| + for _, p := range s.demoEligiblePeers() { |
| + if p.box() == op.SourceBox && p.ready.ClaimCapability == democlaim.Capability { |
| + found = true |
| + } |
| + } |
| + if !found { |
| + return errors.New(demoClaimUnavailable) |
| + } |
| + if err := s.demoClaimSeedReady(ctx, op.Target.Region); err != nil { |
| + return err |
| + } |
| + return s.demoClaimMovedReady(ctx) |
| +} |
| + |
| +// The operation mutex serializes pickup, upload, abort and recovery. It is |
| +// separate from lifecycle locks, which are acquired in the normal order. |
| +func (s *Server) advanceDemoClaim(ctx context.Context, id string) error { |
| + if !demobuild.ValidJobID(id) || s.cfg.HostClaim || s.store.claimGated() { |
| + return ErrDemoToken |
| + } |
| + defer s.acctLocks.lock("demo-claim:" + id)() |
| + return s.lifetimesStep(withDemoClaimOperation(ctx, id), true, func(ctx context.Context) error { |
| + op, err := s.store.demoClaimOp(ctx, id) |
| + if err != nil { |
| + return err |
| + } |
| + if op.Phase == "done" || op.Phase == "aborted" { |
| + return nil |
| + } |
| + if _, err = s.store.db.ExecContext(ctx, `INSERT OR IGNORE INTO demo_claim_progress(operation_id) VALUES(?)`, id); err != nil { |
| + return err |
| + } |
| + p, err := s.claimProgress(ctx, id) |
| + if err != nil { |
| + return err |
| + } |
| + if op.Phase == "committed" { |
| + return s.finishDemoClaim(ctx, op) |
| + } |
| + if op.Phase == "aborting" { |
| + return s.continueDemoClaimAbort(ctx, op) |
| + } |
| + now := time.Now() |
| + if !now.Before(op.Deadline) || now.Unix() >= op.SourceExpiresAt || (p.Until != 0 && now.UnixNano() >= p.Until) { |
| + return s.beginDemoClaimAbort(ctx, op, "deadline") |
| + } |
| + bounded, cancel := context.WithDeadline(ctx, op.Deadline) |
| + defer cancel() |
| + ctx = bounded |
| + switch op.Phase { |
| + case "reserved": |
| + if err = s.demoClaimCapabilitiesReady(ctx, op); err != nil { |
| + return s.beginDemoClaimAbort(ctx, op, "capability") |
| + } |
| + if err = s.pinDemoClaim(ctx, &op); err != nil { |
| + return s.beginDemoClaimAbort(ctx, op, "source_unready") |
| + } |
| + if _, err = release.SetPipeline(ctx, s.cfg.Releases, s.cfg.Key, op.Target.Sqid, op.Target.App, release.DefaultPipelineChannels(), op.Person); err != nil { |
| + return err |
| + } |
| + if err = s.claimBoundary("pipeline"); err != nil { |
| + return err |
| + } |
| + if _, err = s.createDemoClaimSeed(ctx, op); err != nil { |
| + return err |
| + } |
| + if err = s.claimBoundary("seed-record"); err != nil { |
| + return err |
| + } |
| + if !p.Copied { |
| + if err = s.copyDemoClaimArtifact(ctx, op); err != nil { |
| + return err |
| + } |
| + if _, err = s.store.db.ExecContext(ctx, `UPDATE demo_claim_progress SET copied=1 WHERE operation_id=?`, id); err != nil { |
| + return err |
| + } |
| + if err = s.claimBoundary("artifact"); err != nil { |
| + return err |
| + } |
| + } |
| + // Persist the phase before setting the record hold. Recovery of freezing |
| + // re-ensures the hold before delivering signed work. |
| + if _, err = s.store.db.ExecContext(ctx, `UPDATE demo_claim_ops SET phase='freezing' WHERE id=? AND phase='reserved'`, id); err != nil { |
| + return err |
| + } |
| + if err = s.claimBoundary("freezing"); err != nil { |
| + return err |
| + } |
| + op.Phase = "freezing" |
| + if err = s.setDemoClaimWork(ctx, op, "freeze", 30*time.Second); err != nil { |
| + return err |
| + } |
| + return s.ensureDemoClaimHold(ctx, op, false) |
| + case "freezing": |
| + if !p.HoldAck { |
| + if len(p.Wire) == 0 { |
| + if err = s.setDemoClaimWork(ctx, op, "freeze", 30*time.Second); err != nil { |
| + return err |
| + } |
| + } |
| + return s.ensureDemoClaimHold(ctx, op, false) |
| + } |
| + if p.Action != "export" { |
| + if err = s.setDemoClaimWork(ctx, op, "export", 120*time.Second); err != nil { |
| + return err |
| + } |
| + } |
| + _, err = s.store.db.ExecContext(ctx, `UPDATE demo_claim_ops SET phase='copying' WHERE id=? AND phase='freezing'`, id) |
| + s.wakeDemoBox(op.SourceBox) |
| + if err != nil { |
| + return err |
| + } |
| + return s.claimBoundary("copying") |
| + case "copying": |
| + if p.SHA != "" { |
| + stored, _, err := release.OpenObjectStreaming(ctx, s.cfg.SeedData, seeds.SnapshotKey(op.Target.Host, op.Target.SeedID)) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + defer stored.Close() |
| + return s.acceptDemoClaimSnapshotLocked(ctx, op.ID, stored, p.SHA, p.Bytes) |
| + } |
| + return nil // The upload owns this transition; no store polling. |
| + case "verifying": |
| + ready, err := s.verifyDemoClaim(ctx, op, true) |
| + if err != nil { |
| + return err |
| + } |
| + if !ready { |
| + return nil |
| + } |
| + if err = s.claimBoundary("before-commit"); err != nil { |
| + return err |
| + } |
| + if err = s.commitDemoClaim(ctx, op); err != nil { |
| + return err |
| + } |
| + if err = s.claimBoundary("commit"); err != nil { |
| + return err |
| + } |
| + op.Phase = "committed" |
| + return s.finishDemoClaim(ctx, op) |
| + default: |
| + return ErrDemoToken |
| + } |
| + }) |
| +} |
| + |
| +func (s *Server) pinDemoClaim(ctx context.Context, op *claimOp) error { |
| + d, err := s.store.demoByID(ctx, op.DemoID) |
| + if err != nil { |
| + return err |
| + } |
| + defer s.lockApp(d.AccountSqid, d.App)() |
| + d, err = s.store.demoByID(ctx, op.DemoID) |
| + if err != nil { |
| + return err |
| + } |
| + life, err := s.store.AppLife(d.AccountID, d.App) |
| + if err != nil { |
| + return err |
| + } |
| + if !demoClaimSourceMatches(*op, d, life) || d.ActiveJobID != "" { |
| + return ErrDemoBusy |
| + } |
| + var busy int |
| + if err = s.store.db.QueryRowContext(ctx, `SELECT count(*) FROM demo_jobs WHERE demo_id=? AND (state IN ('queued','picked','ready') OR publish_stage LIKE 'settling:%' OR publish_stage LIKE 'rollback:%' OR publish_stage LIKE 'restoring:%')`, d.ID).Scan(&busy); err != nil { |
| + return err |
| + } |
| + if busy != 0 { |
| + return ErrDemoBusy |
| + } |
| + ptr, err := release.Channel(ctx, s.cfg.Releases, s.cfg.ReleasePub, d.AccountSqid, d.App, "edge") |
| + if err != nil { |
| + return err |
| + } |
| + if ptr == nil || ptr.Version == "" { |
| + return ErrDemoToken |
| + } |
| + m, err := release.GetManifest(ctx, s.cfg.Releases, d.AccountSqid, d.App, ptr.Version) |
| + if err != nil { |
| + return err |
| + } |
| + art := m.Artifacts["linux-arm64"] |
| + if m.Kind != "binary" || len(m.Artifacts) != 1 || !demobuild.ValidDigest(art.SHA256) || art.Size <= 0 || art.Size > demobuild.BinaryMaxBytes { |
| + return ErrDemoToken |
| + } |
| + var published int |
| + if err = s.store.db.QueryRowContext(ctx, `SELECT count(*) FROM demo_jobs WHERE demo_id=? AND state='published' AND binary_sha256=?`, d.ID, art.SHA256).Scan(&published); err != nil { |
| + return err |
| + } |
| + if published == 0 { |
| + return ErrDemoToken |
| + } |
| + p, err := s.claimProgress(ctx, op.ID) |
| + if err != nil { |
| + return err |
| + } |
| + if p.Copied && (op.Version != ptr.Version || op.ArtifactSHA256 != art.SHA256) { |
| + return ErrDemoToken |
| + } |
| + op.Version, op.ArtifactSHA256 = ptr.Version, art.SHA256 |
| + _, err = s.store.db.ExecContext(ctx, `UPDATE demo_claim_ops SET version=?,artifact_sha256=? WHERE id=? AND phase='reserved'`, op.Version, op.ArtifactSHA256, op.ID) |
| + return err |
| +} |
| +func demoClaimSourceMatches(op claimOp, d DemoRow, life *AppLife) bool { |
| + return demoLifeValid(d, life, time.Now()) && d.ID == op.DemoID && life.Lifetime == op.SourceLifetime && life.ExpiresAt == op.SourceExpiresAt && d.Generation == op.Generation && d.AssignedBox == op.SourceBox |
| +} |
| +func claimDescriptor(op claimOp, d DemoRow) demo.Descriptor { |
| + return demo.Descriptor{ID: d.ID, Host: d.Host, Lifetime: op.SourceLifetime, ExpiresAt: op.SourceExpiresAt} |
| +} |
| +func (s *Server) ensureDemoClaimHold(ctx context.Context, op claimOp, clear bool) error { |
| + d, err := s.store.demoByID(ctx, op.DemoID) |
| + if err != nil { |
| + return err |
| + } |
| + defer s.lockApp(d.AccountSqid, d.App)() |
| + life, err := s.store.AppLife(d.AccountID, d.App) |
| + if err != nil { |
| + return err |
| + } |
| + if !demoClaimSourceMatches(op, d, life) { |
| + return ErrDemoToken |
| + } |
| + fresh, err := s.store.demoClaimOp(ctx, op.ID) |
| + if err != nil { |
| + return err |
| + } |
| + if fresh.Target != op.Target || fresh.SourceLifetime != op.SourceLifetime || fresh.Generation != op.Generation || fresh.SourceBox != op.SourceBox { |
| + return ErrDemoToken |
| + } |
| + if clear { |
| + p, err := s.claimProgress(ctx, op.ID) |
| + if err != nil { |
| + return err |
| + } |
| + if fresh.Phase != "aborting" || !p.Cleanup { |
| + return ErrDemoToken |
| + } |
| + } else if fresh.Phase != "freezing" { |
| + return ErrDemoToken |
| + } |
| + if err = provision.SetDemoClaimHold(ctx, s.cfg.Releases, d.AccountSqid, d.App, claimDescriptor(op, d), op.SourceBox, democlaim.Hold{ID: op.ID, Generation: uint64(op.Generation)}, clear); err != nil { |
| + return err |
| + } |
| + if !clear { |
| + if _, err = s.store.db.ExecContext(ctx, `UPDATE demo_claim_progress SET hold_ready=1 WHERE operation_id=?`, op.ID); err != nil { |
| + return err |
| + } |
| + } |
| + s.NotifyDemoBox(op.SourceBox) |
| + if !clear { |
| + return s.claimBoundary("hold") |
| + } |
| + return nil |
| +} |
| +func (s *Server) setDemoClaimWork(ctx context.Context, op claimOp, action string, window time.Duration) error { |
| + d, err := s.store.demoByID(ctx, op.DemoID) |
| + if err != nil { |
| + return err |
| + } |
| + until := time.Now().Add(window) |
| + if action != "abort" && op.Deadline.Before(until) { |
| + until = op.Deadline |
| + } |
| + work := democlaim.Work{ID: op.ID, Demo: claimDescriptor(op, d), Account: d.AccountSqid, App: d.App, Fleet: d.Fleet, Box: op.SourceBox, Generation: uint64(op.Generation), Action: action, Deadline: until} |
| + wire, err := democlaim.SignWork(s.cfg.Key, work) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = s.store.db.ExecContext(ctx, `UPDATE demo_claim_progress SET work=?,action=?,phase_until=?,retry_at=0 WHERE operation_id=?`, wire, action, until.UnixNano(), op.ID) |
| + if err == nil { |
| + s.wakeDemoBox(op.SourceBox) |
| + } |
| + return err |
| +} |
| + |
| +func (s *Server) copyDemoClaimArtifact(ctx context.Context, op claimOp) error { |
| + d, err := s.store.demoByID(ctx, op.DemoID) |
| + if err != nil { |
| + return err |
| + } |
| + m, err := release.GetManifest(ctx, s.cfg.Releases, d.AccountSqid, d.App, op.Version) |
| + if err != nil { |
| + return err |
| + } |
| + a := m.Artifacts["linux-arm64"] |
| + if a.SHA256 != op.ArtifactSHA256 || a.Size <= 0 || a.Size > demobuild.BinaryMaxBytes || len(m.Artifacts) != 1 { |
| + return ErrDemoToken |
| + } |
| + if s.seedScratch == nil { |
| + return errors.New(demoClaimUnavailable) |
| + } |
| + free, ref := s.seedScratch.reserve(op.Target.Sqid+"/"+op.Target.App, 768<<20) |
| + if ref != nil { |
| + return errors.New(demoClaimUnavailable) |
| + } |
| + defer free() |
| + f, err := os.CreateTemp(s.seedScratch.dir(), seedScratchPrefix+"claim-artifact-") |
| + if err != nil { |
| + return err |
| + } |
| + defer os.Remove(f.Name()) |
| + defer f.Close() |
| + body, _, err := release.OpenObjectStreaming(ctx, s.cfg.Releases, release.ArtifactKey(d.AccountSqid, d.App, op.Version, a.File)) |
| + if err != nil { |
| + return err |
| + } |
| + h := sha256.New() |
| + n, err := io.Copy(io.MultiWriter(f, h), io.LimitReader(body, a.Size+1)) |
| + closeErr := body.Close() |
| + if err != nil { |
| + return err |
| + } |
| + if closeErr != nil { |
| + return closeErr |
| + } |
| + if n != a.Size || hex.EncodeToString(h.Sum(nil)) != op.ArtifactSHA256 { |
| + return ErrDemoToken |
| + } |
| + if err = f.Close(); err != nil { |
| + return err |
| + } |
| + m.App = op.Target.App |
| + if err = release.ShipSpooled(ctx, s.cfg.Releases, op.Target.Sqid, *m, map[string]string{"linux-arm64": f.Name()}); err != nil { |
| + return err |
| + } |
| + _, err = release.RootSigner(s.cfg.Key).PromoteOnLadder(ctx, s.cfg.Releases, op.Target.Sqid, op.Target.App, "edge", op.Version, release.PromoteOptions{Actor: op.Person, Authorize: func(*release.Pipeline) error { |
| + fresh, e := s.store.demoClaimOp(ctx, op.ID) |
| + if e != nil { |
| + return e |
| + } |
| + if fresh.Phase != "reserved" || !time.Now().Before(fresh.Deadline) { |
| + return ErrDemoToken |
| + } |
| + return nil |
| + }}) |
| + return err |
| +} |
| + |
| +// The console independently hashes and integrity-checks every request, even |
| +// an identical retry. Only metadata is held in memory. Publication happens |
| +// after all bytes are checked and while the operation still owns its seed. |
| +func (s *Server) acceptDemoClaimSnapshot(ctx context.Context, id string, body io.Reader, sha string, size int64) error { |
| + if size <= 0 || size > democlaim.MaxSnapshotBytes || !demobuild.ValidDigest(sha) { |
| + return ErrDemoToken |
| + } |
| + defer s.acctLocks.lock("demo-claim:" + id)() |
| + return s.acceptDemoClaimSnapshotLocked(ctx, id, body, sha, size) |
| +} |
| +func (s *Server) acceptDemoClaimSnapshotLocked(ctx context.Context, id string, body io.Reader, sha string, size int64) error { |
| + op, err := s.store.demoClaimOp(ctx, id) |
| + if err != nil { |
| + return err |
| + } |
| + p, err := s.claimProgress(ctx, id) |
| + if err != nil { |
| + return err |
| + } |
| + if (op.Phase != "copying" && op.Phase != "verifying") || !p.HoldAck || !time.Now().Before(op.Deadline) { |
| + return ErrDemoToken |
| + } |
| + if p.SHA != "" && (p.SHA != sha || p.Bytes != size) { |
| + return ErrDemoToken |
| + } |
| + until := min(op.Deadline.UnixNano(), p.Until) |
| + if until == 0 || time.Now().UnixNano() >= until { |
| + return ErrDemoToken |
| + } |
| + ctx, cancel := context.WithDeadline(withDemoClaimOperation(ctx, id), time.Unix(0, until)) |
| + defer cancel() |
| + if s.seedScratch == nil { |
| + return errors.New(demoClaimUnavailable) |
| + } |
| + free, ref := s.seedScratch.reserve(op.Target.Sqid+"/"+op.Target.App, 768<<20) |
| + if ref != nil { |
| + return errors.New(demoClaimUnavailable) |
| + } |
| + defer free() |
| + dir, err := os.MkdirTemp(s.seedScratch.dir(), seedScratchPrefix+"claim-") |
| + if err != nil { |
| + return err |
| + } |
| + defer os.RemoveAll(dir) |
| + f, err := os.CreateTemp(dir, "snapshot-") |
| + if err != nil { |
| + return err |
| + } |
| + defer f.Close() |
| + h := sha256.New() |
| + n, err := io.Copy(io.MultiWriter(f, h), io.LimitReader(body, size+1)) |
| + if err != nil { |
| + return err |
| + } |
| + if n != size || hex.EncodeToString(h.Sum(nil)) != sha { |
| + return ErrDemoToken |
| + } |
| + if err = f.Close(); err != nil { |
| + return err |
| + } |
| + if err = lease.CheckDBContext(ctx, f.Name()); err != nil { |
| + return err |
| + } |
| + if op.Phase == "verifying" { |
| + return nil |
| + } |
| + // Pin the first fully checked upload before any object PUT. An ambiguous |
| + // upload cannot replace these bytes on its next attempt. |
| + if _, err = s.store.db.ExecContext(ctx, `UPDATE demo_claim_progress SET snapshot_sha=?,snapshot_bytes=? WHERE operation_id=? AND (snapshot_sha='' OR (snapshot_sha=? AND snapshot_bytes=?))`, sha, size, id, sha, size); err != nil { |
| + return err |
| + } |
| + if err = s.claimBoundary("snapshot-metadata"); err != nil { |
| + return err |
| + } |
| + return s.lifetimesStep(ctx, true, func(ctx context.Context) error { |
| + if err := s.publishDemoClaimSeed(ctx, op, f.Name(), sha, size); err != nil { |
| + return err |
| + } |
| + if err := s.claimBoundary("snapshot-object"); err != nil { |
| + return err |
| + } |
| + tx, err := s.store.demoTx(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + res, err := tx.ExecContext(ctx, `UPDATE demo_claim_ops SET phase='verifying' WHERE id=? AND phase='copying' AND deadline>?`, id, time.Now().Unix()) |
| + if err != nil { |
| + return err |
| + } |
| + n, err := res.RowsAffected() |
| + if err != nil { |
| + return err |
| + } |
| + if n != 1 { |
| + return ErrDemoToken |
| + } |
| + if _, err = tx.ExecContext(ctx, `UPDATE demo_claim_progress SET phase_until=?,retry_at=0 WHERE operation_id=?`, min(op.Deadline.UnixNano(), time.Now().Add(60*time.Second).UnixNano()), id); err != nil { |
| + return err |
| + } |
| + if err = tx.Commit(); err != nil { |
| + return err |
| + } |
| + s.signalDemoJobs() |
| + return s.claimBoundary("snapshot") |
| + }) |
| +} |
| + |
| +func (s *Server) verifyDemoClaim(ctx context.Context, op claimOp, gated bool) (bool, error) { |
| + rec, _, err := s.readRecord(ctx, op.Target.Sqid, op.Target.App, op.Target.Host) |
| + if err != nil { |
| + return false, err |
| + } |
| + want := seeds.StateCommitted |
| + if gated { |
| + want = seeds.StatePlaced |
| + } |
| + if !demoClaimRecordMatches(rec, op) || (rec.Seed.State != want && !(gated && rec.Seed.State == seeds.StateReady)) { |
| + return false, nil |
| + } |
| + if op.Target.Host != s.apexHost(op.Target.Sqid, op.Target.App) || !provision.ValidHost(op.Target.Host, op.Target.Sqid+"."+s.cfg.AppsDomain) { |
| + return false, ErrDemoToken |
| + } |
| + token := "" |
| + if gated { |
| + token, err = s.demoClaimSeedVerifyToken(ctx, op) |
| + if err != nil { |
| + return false, err |
| + } |
| + } |
| + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) |
| + defer cancel() |
| + req, err := http.NewRequestWithContext(ctx, "GET", "https://"+op.Target.Host+"/", nil) |
| + if err != nil { |
| + return false, err |
| + } |
| + req.Header.Set("Cache-Control", "no-cache") |
| + if gated { |
| + req.Header.Set("Carlos-Import-Verify", token) |
| + } |
| + transport := s.demoTransport |
| + if transport == nil { |
| + transport = &http.Transport{Proxy: nil, DisableKeepAlives: true, TLSHandshakeTimeout: 5 * time.Second} |
| + } |
| + client := &http.Client{Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| + resp, err := client.Do(req) |
| + if err != nil { |
| + return false, err |
| + } |
| + defer resp.Body.Close() |
| + if resp.StatusCode < 200 || resp.StatusCode >= 300 || resp.Header.Get("X-Carlos-Version") != op.Version { |
| + return false, nil |
| + } |
| + if gated { |
| + // The authenticated GET wakes a ready seed. Placement (including the |
| + // first replica) is checked after that wake, never as its prerequisite. |
| + placed, _, err := s.readRecord(ctx, op.Target.Sqid, op.Target.App, op.Target.Host) |
| + if err != nil { |
| + return false, err |
| + } |
| + return demoClaimRecordMatches(placed, op) && placed.Seed.State == seeds.StatePlaced, nil |
| + } |
| + return true, nil |
| +} |
| + |
| +func (s *Server) lockDemoClaimApps(d DemoRow, op claimOp) func() { |
| + keys := [][2]string{{d.AccountSqid, d.App}, {op.Target.Sqid, op.Target.App}} |
| + sort.Slice(keys, func(i, j int) bool { |
| + if keys[i][0] != keys[j][0] { |
| + return keys[i][0] < keys[j][0] |
| + } |
| + return keys[i][1] < keys[j][1] |
| + }) |
| + a := s.lockApp(keys[0][0], keys[0][1]) |
| + b := s.lockApp(keys[1][0], keys[1][1]) |
| + return func() { b(); a() } |
| +} |
| +func (s *Server) commitDemoClaim(ctx context.Context, op claimOp) error { |
| + defer s.lockAccount(op.Target.Sqid)() |
| + d, err := s.store.demoByID(ctx, op.DemoID) |
| + if err != nil { |
| + return err |
| + } |
| + defer s.lockDemoClaimApps(d, op)() |
| + defer s.lockHostname(op.Target.Host)() |
| + acct, err := s.store.AccountByID(op.Target.AccountID) |
| + if err != nil { |
| + return err |
| + } |
| + if acct == nil || acct.Sqid != op.Target.Sqid { |
| + return ErrDemoToken |
| + } |
| + if err = s.checkRunningThings(ctx, acct, 0); err != nil { |
| + return err |
| + } |
| + life, err := s.store.AppLife(d.AccountID, d.App) |
| + if err != nil { |
| + return err |
| + } |
| + d, err = s.store.demoByID(ctx, op.DemoID) |
| + if err != nil { |
| + return err |
| + } |
| + if !demoClaimSourceMatches(op, d, life) || d.ActiveJobID != "" { |
| + return ErrDemoToken |
| + } |
| + source, _, err := s.readRecord(ctx, d.AccountSqid, d.App, d.Host) |
| + if err != nil { |
| + return err |
| + } |
| + if source.Demo == nil || *source.Demo != claimDescriptor(op, d) || source.DemoClaim == nil || source.DemoClaim.ID != op.ID || source.DemoClaim.Generation != uint64(op.Generation) { |
| + return ErrDemoToken |
| + } |
| + target, _, err := s.readRecord(ctx, op.Target.Sqid, op.Target.App, op.Target.Host) |
| + if err != nil { |
| + return err |
| + } |
| + if !demoClaimRecordMatches(target, op) || target.Seed.State != seeds.StatePlaced { |
| + return ErrDemoToken |
| + } |
| + tx, err := s.store.demoTx(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + var n int |
| + err = tx.QueryRowContext(ctx, `SELECT count(*) FROM demo_claim_ops o JOIN demo_claim_progress p ON p.operation_id=o.id |
| + JOIN apps a ON a.account_id=o.account_id AND a.app=o.app |
| + JOIN memberships m ON m.account_id=o.account_id AND m.address=o.person |
| + JOIN accounts c ON c.id=o.account_id |
| + JOIN demo_apps d ON d.demo_id=o.demo_id JOIN apps src ON src.account_id=d.account_id AND src.app=d.app |
| + WHERE o.id=? AND o.phase='verifying' AND o.deadline>? AND o.source_expires_at>? |
| + AND p.hold_ack=1 AND p.snapshot_sha!='' AND p.phase_until>? |
| + AND a.demo_claim_op=o.id AND a.lifetime=o.target_lifetime AND a.deleted_at=0 AND a.expires_at=0 AND a.demo_id='' AND a.restoring=0 |
| + AND c.deleted_at=0 AND c.sqid=o.target_sqid AND m.role IN ('owner','member') |
| + AND d.state='anonymous' AND d.purged_at=0 AND d.active_job_id='' AND d.claim_token_hash IS NOT NULL |
| + AND d.generation=o.generation AND d.assigned_box=o.source_box |
| + AND src.demo_id=d.demo_id AND src.lifetime=o.source_lifetime AND src.expires_at=o.source_expires_at AND src.deleted_at=0 AND src.restoring=0`, op.ID, time.Now().Unix(), time.Now().Unix(), time.Now().UnixNano()).Scan(&n) |
| + if err != nil { |
| + return err |
| + } |
| + if n != 1 { |
| + return ErrDemoToken |
| + } |
| + for _, q := range []struct { |
| + sql string |
| + args []any |
| + }{ |
| + {`INSERT INTO demo_claim_commits(operation_id,demo_id,committed_at) VALUES(?,?,?)`, []any{op.ID, op.DemoID, time.Now().Unix()}}, |
| + {`UPDATE demo_claim_ops SET phase='committed' WHERE id=?`, []any{op.ID}}, |
| + {`UPDATE demo_apps SET claim_token_hash=NULL WHERE demo_id=?`, []any{op.DemoID}}, |
| + {`DELETE FROM demo_claim_flows WHERE demo_id=?`, []any{op.DemoID}}, |
| + {`INSERT INTO demo_moved_notices(demo_id,host,target_host,expires_at) VALUES(?,?,?,?)`, []any{op.DemoID, d.Host, op.Target.Host, op.SourceExpiresAt}}, |
| + {`INSERT INTO demo_claim_outbox(operation_id,step) VALUES(?,'open'),(?,'moved'),(?,'retire')`, []any{op.ID, op.ID, op.ID}}, |
| + } { |
| + if _, err = tx.ExecContext(ctx, q.sql, q.args...); err != nil { |
| + return err |
| + } |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +// Task 6 replaces this stub. The notice itself is already durable in the |
| +// same transaction as commitment (controller ruling R4). |
| +func (s *Server) publishDemoMoved(context.Context, string) error { return nil } |
| + |
| +func (s *Server) finishDemoClaim(ctx context.Context, op claimOp) error { |
| + for _, step := range []string{"open", "moved", "retire"} { |
| + var n int |
| + if err := s.store.db.QueryRowContext(ctx, `SELECT count(*) FROM demo_claim_outbox WHERE operation_id=? AND step=?`, op.ID, step).Scan(&n); err != nil { |
| + return err |
| + } |
| + if n == 0 { |
| + continue |
| + } |
| + var err error |
| + switch step { |
| + case "open": |
| + err = func() error { |
| + defer s.lockApp(op.Target.Sqid, op.Target.App)() |
| + if _, err := s.demoClaimSeedOperation(ctx, op); err != nil { |
| + return err |
| + } |
| + rec, _, err := s.readRecord(ctx, op.Target.Sqid, op.Target.App, op.Target.Host) |
| + if err != nil { |
| + return err |
| + } |
| + if !demoClaimRecordMatches(rec, op) { |
| + return ErrDemoToken |
| + } |
| + if rec.Seed.State != seeds.StateCommitted { |
| + if _, err = provision.SetRecordSeed(ctx, s.cfg.Releases, op.Target.Sqid, op.Target.App, op.Target.Host, provision.SeedCommitDemoClaim(op.Target.SeedID, op.ID)); err != nil { |
| + return err |
| + } |
| + s.bumpSerial(ctx) |
| + } |
| + return nil |
| + }() |
| + if err == nil { |
| + var ok bool |
| + ok, err = s.verifyDemoClaim(ctx, op, false) |
| + if err == nil && !ok { |
| + return nil |
| + } |
| + } |
| + case "moved": |
| + err = s.publishDemoMoved(ctx, op.DemoID) |
| + case "retire": |
| + var d DemoRow |
| + d, err = s.store.demoByID(ctx, op.DemoID) |
| + if err == nil { |
| + func() { |
| + defer s.lockApp(d.AccountSqid, d.App)() |
| + err = s.retireDemoLocked(ctx, d, time.Now(), "claimed") |
| + }() |
| + } |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if err = s.claimBoundary(step); err != nil { |
| + return err |
| + } |
| + if _, err = s.store.db.ExecContext(ctx, `DELETE FROM demo_claim_outbox WHERE operation_id=? AND step=?`, op.ID, step); err != nil { |
| + return err |
| + } |
| + } |
| + defer s.lockAccount(op.Target.Sqid)() |
| + defer s.lockApp(op.Target.Sqid, op.Target.App)() |
| + tx, err := s.store.demoTx(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + if _, err = tx.ExecContext(ctx, `UPDATE apps SET demo_claim_op='' WHERE account_id=? AND app=? AND lifetime=? AND demo_claim_op=?`, op.Target.AccountID, op.Target.App, op.Target.Lifetime, op.ID); err != nil { |
| + return err |
| + } |
| + if _, err = tx.ExecContext(ctx, `UPDATE demo_claim_ops SET phase='done' WHERE id=? AND phase='committed' AND NOT EXISTS(SELECT 1 FROM demo_claim_outbox WHERE operation_id=?)`, op.ID, op.ID); err != nil { |
| + return err |
| + } |
| + if err = tx.Commit(); err != nil { |
| + return err |
| + } |
| + return s.claimBoundary("done") |
| +} |
| + |
| +func (s *Server) abortDemoClaim(ctx context.Context, id, reason string) error { |
| + defer s.acctLocks.lock("demo-claim:" + id)() |
| + return s.lifetimesStep(withDemoClaimOperation(ctx, id), true, func(ctx context.Context) error { |
| + op, err := s.store.demoClaimOp(ctx, id) |
| + if err != nil { |
| + return err |
| + } |
| + return s.beginDemoClaimAbort(ctx, op, reason) |
| + }) |
| +} |
| +func (s *Server) beginDemoClaimAbort(ctx context.Context, op claimOp, reason string) error { |
| + if op.Phase == "committed" || op.Phase == "done" { |
| + return ErrDemoToken |
| + } |
| + if op.Phase == "aborted" { |
| + return nil |
| + } |
| + tx, err := s.store.demoTx(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + if _, err = tx.ExecContext(ctx, `INSERT OR IGNORE INTO demo_claim_progress(operation_id) VALUES(?)`, op.ID); err != nil { |
| + return err |
| + } |
| + if _, err = tx.ExecContext(ctx, `UPDATE demo_claim_ops SET phase='aborting' WHERE id=? AND phase NOT IN ('committed','done','aborted')`, op.ID); err != nil { |
| + return err |
| + } |
| + if _, err = tx.ExecContext(ctx, `UPDATE demo_claim_progress SET reason=CASE WHEN reason='operator' THEN reason ELSE ? END,retry_at=0 WHERE operation_id=?`, reason, op.ID); err != nil { |
| + return err |
| + } |
| + if err = tx.Commit(); err != nil { |
| + return err |
| + } |
| + op.Phase = "aborting" |
| + return s.continueDemoClaimAbort(ctx, op) |
| +} |
| +func (s *Server) continueDemoClaimAbort(ctx context.Context, op claimOp) error { |
| + p, err := s.claimProgress(ctx, op.ID) |
| + if err != nil { |
| + return err |
| + } |
| + if !p.Cleanup { |
| + ok, err := s.abortDemoClaimSeed(ctx, op) |
| + if err != nil || !ok { |
| + return err |
| + } |
| + if _, err = s.store.db.ExecContext(ctx, `UPDATE demo_claim_progress SET cleanup=1 WHERE operation_id=?`, op.ID); err != nil { |
| + return err |
| + } |
| + p.Cleanup = true |
| + } |
| + d, err := s.store.demoByID(ctx, op.DemoID) |
| + if err != nil { |
| + return err |
| + } |
| + // Never release an expired or independently retired source. |
| + if time.Now().Unix() >= op.SourceExpiresAt || d.State != "anonymous" || p.Reason == "operator" { |
| + if err = func() error { |
| + defer s.lockApp(d.AccountSqid, d.App)() |
| + reason := "expired" |
| + if p.Reason == "operator" { |
| + reason = "operator" |
| + } |
| + return s.retireDemoLocked(ctx, d, time.Now(), reason) |
| + }(); err != nil { |
| + return err |
| + } |
| + p.AbortAck = true |
| + } else if !p.AbortAck && p.Action == "" { |
| + p.AbortAck = true |
| + } else if !p.AbortAck { |
| + if err = s.ensureDemoClaimHold(ctx, op, true); err != nil { |
| + return err |
| + } |
| + work, e := democlaim.VerifyWork(s.cfg.ReleasePub, p.Wire, time.Now()) |
| + if e != nil || work.Action != "abort" { |
| + return s.setDemoClaimWork(ctx, op, "abort", democlaim.AbortDeliveryWindow) |
| + } |
| + return nil |
| + } |
| + if !p.AbortAck { |
| + return nil |
| + } |
| + return s.finishDemoClaimAbort(ctx, op) |
| +} |
| +func (s *Server) finishDemoClaimAbort(ctx context.Context, op claimOp) error { |
| + defer s.lockAccount(op.Target.Sqid)() |
| + defer s.lockApp(op.Target.Sqid, op.Target.App)() |
| + if _, err := s.demoClaimSeedOperation(ctx, op); err != nil { |
| + return err |
| + } |
| + // No destination can run and its seed/instance cleanup is acknowledged. |
| + // Keep the app reservation until every operation-owned object is removed. |
| + at := time.Unix(op.Deadline.Unix(), 0) |
| + if err := release.TrashApp(ctx, s.cfg.Releases, op.Target.Sqid, op.Target.App, "demo-claim", at); err != nil { |
| + return err |
| + } |
| + if err := release.PurgeAppExcept(ctx, s.cfg.Releases, s.cfg.ReleasePub, op.Target.Sqid, op.Target.App, at, time.Now(), func(key string) bool { return provision.IsRecordKey(key) }); err != nil { |
| + return err |
| + } |
| + tx, err := s.store.demoTx(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + if _, err = tx.ExecContext(ctx, `DELETE FROM apps WHERE account_id=? AND app=? AND lifetime=? AND demo_claim_op=?`, op.Target.AccountID, op.Target.App, op.Target.Lifetime, op.ID); err != nil { |
| + return err |
| + } |
| + if _, err = tx.ExecContext(ctx, `UPDATE demo_claim_ops SET phase='aborted' WHERE id=? AND phase='aborting'`, op.ID); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +// ReconcileDemoClaims reads only SQL when idle or waiting for a worker. |
| +// Object work has a persisted retry clock and uses the existing job loop. |
| +func (s *Server) ReconcileDemoClaims(ctx context.Context, restart bool) error { |
| + if s.cfg.HostClaim || s.store.claimGated() { |
| + return nil |
| + } |
| + now := time.Now() |
| + if err := s.pruneDemoClaims(ctx, now); err != nil { |
| + return err |
| + } |
| + rows, err := s.store.db.QueryContext(ctx, `SELECT o.id FROM demo_claim_ops o LEFT JOIN demo_claim_progress p ON p.operation_id=o.id |
| + WHERE o.phase NOT IN ('done','aborted') AND (p.operation_id IS NULL OR ? OR p.retry_at<=? OR o.deadline<=? AND o.phase NOT IN ('aborting','committed')) |
| + AND (o.phase NOT IN ('freezing','copying') OR o.phase='copying' AND p.snapshot_sha!='' OR p.work=X'' OR o.phase='freezing' AND p.hold_ready=0 OR p.hold_ack=1 AND o.phase='freezing' OR p.phase_until<=? OR o.deadline<=?) ORDER BY o.id LIMIT ?`, restart, now.UnixNano(), now.Unix(), now.UnixNano(), now.Unix(), demobuild.QueueLimit) |
| + if err != nil { |
| + return err |
| + } |
| + var ids []string |
| + for rows.Next() { |
| + var id string |
| + if err = rows.Scan(&id); err != nil { |
| + break |
| + } |
| + ids = append(ids, id) |
| + } |
| + err = errors.Join(err, rows.Err(), rows.Close()) |
| + if err != nil { |
| + return err |
| + } |
| + var errs []error |
| + for _, id := range ids { |
| + if err = s.advanceDemoClaim(ctx, id); err != nil { |
| + errs = append(errs, err) |
| + } |
| + if _, e := s.store.db.ExecContext(ctx, `UPDATE demo_claim_progress SET retry_at=? WHERE operation_id=?`, time.Now().Add(2*time.Second).UnixNano(), id); e != nil { |
| + errs = append(errs, e) |
| + } |
| + } |
| + return errors.Join(errs...) |
| +} |
| +func (s *Server) pruneDemoClaims(ctx context.Context, now time.Time) error { |
| + tx, err := s.store.demoTx(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + for _, q := range []struct { |
| + sql string |
| + arg any |
| + }{ |
| + {`DELETE FROM demo_claim_flows WHERE expires_at<=? AND NOT EXISTS(SELECT 1 FROM demo_claim_ops o WHERE o.flow_hash=demo_claim_flows.hash)`, now.Unix()}, |
| + {`DELETE FROM demo_claim_flows WHERE hash IN (SELECT flow_hash FROM demo_claim_ops WHERE source_expires_at<=?)`, now.Add(-24 * time.Hour).Unix()}, |
| + {`UPDATE demo_claim_ops SET flow_hash='' WHERE source_expires_at<=? AND flow_hash!=''`, now.Add(-24 * time.Hour).Unix()}, |
| + {`DELETE FROM demo_claim_flows WHERE hash NOT IN (SELECT flow_hash FROM demo_claim_ops WHERE flow_hash!='') AND expires_at<=?`, now.Unix()}, |
| + {`DELETE FROM demo_claim_progress WHERE operation_id IN (SELECT o.id FROM demo_claim_ops o JOIN demo_apps d ON d.demo_id=o.demo_id WHERE o.phase IN ('done','aborted') AND d.purged_at>0 AND d.purged_at<=?)`, now.Add(-7 * 24 * time.Hour).Unix()}, |
| + {`DELETE FROM demo_claim_commits WHERE operation_id IN (SELECT o.id FROM demo_claim_ops o JOIN demo_apps d ON d.demo_id=o.demo_id WHERE o.phase IN ('done','aborted') AND d.purged_at>0 AND d.purged_at<=?)`, now.Add(-7 * 24 * time.Hour).Unix()}, |
| + {`DELETE FROM demo_claim_ops WHERE phase IN ('done','aborted') AND demo_id IN (SELECT demo_id FROM demo_apps WHERE purged_at>0 AND purged_at<=?)`, now.Add(-7 * 24 * time.Hour).Unix()}, |
| + } { |
| + if _, err = tx.ExecContext(ctx, q.sql, q.arg); err != nil { |
| + return err |
| + } |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +func demoClaimSourceGuard(ctx context.Context, q interface { |
| + QueryRowContext(context.Context, string, ...any) *sql.Row |
| +}, id string) error { |
| + var n int |
| + if err := q.QueryRowContext(ctx, `SELECT count(*) FROM demo_claim_ops WHERE demo_id=? AND phase!='aborted'`, id).Scan(&n); err != nil { |
| + return err |
| + } |
| + if n != 0 { |
| + return ErrDemoBusy |
| + } |
| + return nil |
| +} |
diff --git a/internal/console/demo_claim_transfer_test.go b/internal/console/demo_claim_transfer_test.go| new file mode 100644 |
| index 000000000..33b44ca91 |
| --- /dev/null |
| +++ b/internal/console/demo_claim_transfer_test.go |
| @@ -0,0 +1,597 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/sha256" |
| + "database/sql" |
| + "encoding/hex" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + lsfile "github.com/benbjohnson/litestream/file" |
| + "github.com/carlosframework/platform/internal/democlaim" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/seeds" |
| +) |
| + |
| +func claimTransferFixture(t *testing.T, flowOut ...*string) (*Server, claimOp, []byte) { |
| + t.Helper() |
| + s, d, j, out := demoPublishFixture(t) |
| + s.demoClaimTestEnabled = true |
| + s.cfg.Releases = s.cfg.Releases.(*demoCountingStore).Store |
| + s.cfg.AppsDomain = "apps.example.com" |
| + if err := s.publishDemo(t.Context(), d, j, out); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.store.db.Exec(`UPDATE demo_jobs SET state='published',publish_stage='live' 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) |
| + } |
| + raw, _ := randomToken() |
| + if len(flowOut) > 0 { |
| + *flowOut[0] = raw |
| + } |
| + life, _ := s.store.AppLife(d.AccountID, d.App) |
| + f, err := s.store.createDemoClaimFlow(t.Context(), raw, "shop@example.com", d, *life, time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f, err = s.proveDemoClaim(t.Context(), f, MethodEmail, "shop@example.com", "192.0.2.1", time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + acct := claimAccount(t, s, 501, f.Person, RoleOwner) |
| + op, err := s.reserveDemoClaim(t.Context(), f, acct, regionReq{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + claimSeedReadyFixture(t, s, 2, true, "v1.0.0") |
| + s.demoJobs.peers["box"].ready.ClaimCapability = democlaim.Capability |
| + dataRoot := t.TempDir() |
| + s.cfg.SeedData = release.NewDirStore(dataRoot) |
| + s.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) { |
| + return lsfile.NewReplicaClient(filepath.Join(dataRoot, prefix)), nil |
| + } |
| + s.cfg.HibernateBucket = "test-data" |
| + s.cfg.HibernatePrefix = "instances" |
| + s.seedScratch = newSeedScratch(t.TempDir(), func(string) (int64, error) { return 4 << 30, nil }) |
| + s.demoTransport = roundTripFunc(func(r *http.Request) (*http.Response, error) { |
| + if r.URL.Scheme != "https" || r.URL.Host != op.Target.Host { |
| + t.Fatalf("unexpected destination %s", r.URL) |
| + } |
| + if r.Header.Get("Carlos-Import-Verify") != "" { |
| + if _, err := provision.SetRecordSeed(r.Context(), s.cfg.Releases, op.Target.Sqid, op.Target.App, op.Target.Host, provision.SeedPlace(op.Target.SeedID)); err != nil { |
| + return nil, err |
| + } |
| + } |
| + return &http.Response{StatusCode: 200, Header: http.Header{"X-Carlos-Version": []string{op.Version}}, Body: io.NopCloser(bytes.NewReader(nil))}, nil |
| + }) |
| + path := filepath.Join(t.TempDir(), "source.db") |
| + db, err := sql.Open("sqlite", path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = db.Exec(`CREATE TABLE messages(body TEXT); INSERT INTO messages VALUES ('latest committed source data')`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = db.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + data, err := os.ReadFile(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return s, op, data |
| +} |
| + |
| +func claimAdvance(t *testing.T, s *Server, op claimOp) { |
| + t.Helper() |
| + if err := s.advanceDemoClaim(t.Context(), op.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| +func claimSnapshot(t *testing.T, s *Server, op claimOp, data []byte) error { |
| + t.Helper() |
| + h := sha256.Sum256(data) |
| + return s.acceptDemoClaimSnapshot(t.Context(), op.ID, bytes.NewReader(data), hex.EncodeToString(h[:]), int64(len(data))) |
| +} |
| +func claimToVerify(t *testing.T, s *Server, op claimOp, data []byte) { |
| + t.Helper() |
| + claimAdvance(t, s, op) |
| + if err := s.ackDemoClaim(t.Context(), op.ID, "freeze", uint64(op.Generation)); err != nil { |
| + t.Fatal(err) |
| + } |
| + claimAdvance(t, s, op) |
| + if err := claimSnapshot(t, s, op, data); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| +func claimPlace(t *testing.T, s *Server, op claimOp) { |
| + t.Helper() |
| + if _, err := provision.SetRecordSeed(t.Context(), s.cfg.Releases, op.Target.Sqid, op.Target.App, op.Target.Host, provision.SeedPlace(op.Target.SeedID)); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestDemoClaimTransfer(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + claimToVerify(t, s, op, data) |
| + got, _, err := s.cfg.SeedData.Get(t.Context(), seeds.SnapshotKey(op.Target.Host, op.Target.SeedID)) |
| + if err != nil || !bytes.Equal(got, data) { |
| + t.Fatalf("snapshot: %v", err) |
| + } |
| + m, err := release.GetManifest(t.Context(), s.cfg.Releases, op.Target.Sqid, op.Target.App, op.Version) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if m.Artifacts["linux-arm64"].SHA256 != op.ArtifactSHA256 { |
| + t.Fatal("artifact changed") |
| + } |
| + rec, err := provision.GetRecord(t.Context(), s.cfg.Releases, op.Target.Sqid, op.Target.App, op.Target.Host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if rec.Demo != nil || rec.DemoClaim != nil || rec.FleetBox != "" { |
| + t.Fatal("source fields copied") |
| + } |
| + life, _ := s.store.AppLife(op.Target.AccountID, op.Target.App) |
| + if life.ExpiresAt != 0 { |
| + t.Fatal("permanent expiry") |
| + } |
| + claimAdvance(t, s, op) |
| + current, err := s.store.demoClaimOp(t.Context(), op.ID) |
| + if err != nil || current.Phase != "done" { |
| + t.Fatalf("completion %s: %v", current.Phase, err) |
| + } |
| +} |
| + |
| +func TestDemoClaimExpiryRace(t *testing.T) { |
| + t.Run("updateGuard", func(t *testing.T) { |
| + s, op, _ := claimTransferFixture(t) |
| + if err := s.store.SpendDemoUpdate(t.Context(), op.DemoID, time.Now()); !errors.Is(err, ErrDemoBusy) { |
| + t.Fatalf("update admitted: %v", err) |
| + } |
| + }) |
| + t.Run("deadlineBeforeCommit", func(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + claimToVerify(t, s, op, data) |
| + claimPlace(t, s, op) |
| + if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET deadline=1 WHERE id=?`, op.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + _ = s.advanceDemoClaim(t.Context(), op.ID) |
| + got, _ := s.store.demoClaimOp(t.Context(), op.ID) |
| + if got.Phase != "aborting" { |
| + t.Fatalf("deadline committed: %s", got.Phase) |
| + } |
| + }) |
| +} |
| + |
| +func TestDemoClaimRetirement(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + claimToVerify(t, s, op, data) |
| + claimPlace(t, s, op) |
| + claimAdvance(t, s, op) |
| + var token sql.NullString |
| + var expiry, purged int64 |
| + if err := s.store.db.QueryRow(`SELECT claim_token_hash,purged_at FROM demo_apps WHERE demo_id=?`, op.DemoID).Scan(&token, &purged); err != nil { |
| + t.Fatal(err) |
| + } |
| + if token.Valid || purged != 0 { |
| + t.Fatal("token or offline live slot") |
| + } |
| + if err := s.store.db.QueryRow(`SELECT expires_at FROM apps WHERE demo_id=?`, op.DemoID).Scan(&expiry); err != nil { |
| + t.Fatal(err) |
| + } |
| + if expiry != op.SourceExpiresAt { |
| + t.Fatal("original expiry changed") |
| + } |
| + r, err := s.demoRetirement(t.Context(), op.DemoID) |
| + if err != nil || len(r.Wire) == 0 { |
| + t.Fatalf("receipt %v", err) |
| + } |
| +} |
| + |
| +func TestDemoClaimRequestCost(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + claimAdvance(t, s, op) |
| + st := &demoCountingStore{Store: s.cfg.Releases} |
| + s.cfg.Releases = st |
| + for range 3 { |
| + if err := s.ReconcileDemoClaims(t.Context(), false); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if st.gets.Load() != 0 || st.puts.Load() != 0 { |
| + t.Fatal("waiting work polled object store") |
| + } |
| + if err := s.ackDemoClaim(t.Context(), op.ID, "freeze", uint64(op.Generation)); err != nil { |
| + t.Fatal(err) |
| + } |
| + claimAdvance(t, s, op) |
| + if err := claimSnapshot(t, s, op, data); err != nil { |
| + t.Fatal(err) |
| + } |
| + seed := &demoCountingStore{Store: s.cfg.SeedData} |
| + s.cfg.SeedData = seed |
| + if err := claimSnapshot(t, s, op, data); err != nil { |
| + t.Fatal(err) |
| + } |
| + if seed.puts.Load() != 0 { |
| + t.Fatal("duplicate snapshot PUT") |
| + } |
| + work, err := s.pendingDemoClaims(t.Context(), "box") |
| + if err != nil || len(work) != 0 { |
| + t.Fatalf("duplicate export on reconnect: %v", err) |
| + } |
| +} |
| + |
| +func TestDemoClaimTransferVerifyRefusals(t *testing.T) { |
| + for _, status := range []int{302, 500, 200} { |
| + t.Run(http.StatusText(status), func(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + claimToVerify(t, s, op, data) |
| + claimPlace(t, s, op) |
| + s.demoTransport = roundTripFunc(func(r *http.Request) (*http.Response, error) { |
| + return &http.Response{StatusCode: status, Header: http.Header{"Location": []string{"https://other.example.com"}, "X-Carlos-Version": []string{"wrong"}}, Body: io.NopCloser(bytes.NewReader(nil))}, nil |
| + }) |
| + _ = s.advanceDemoClaim(t.Context(), op.ID) |
| + got, _ := s.store.demoClaimOp(t.Context(), op.ID) |
| + if got.Phase == "done" || got.Phase == "committed" { |
| + t.Fatal("unverified commit") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimTransferBoxGate(t *testing.T) { |
| + s, op, _ := claimTransferFixture(t) |
| + s.demoClaimTestEnabled = false |
| + for _, verb := range []string{"pickup", "snapshot", "ack"} { |
| + r := httptest.NewRequest("POST", "/api/box/demo-claims/"+op.ID+"/"+verb, nil) |
| + w := httptest.NewRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 503 { |
| + t.Fatalf("%s: %d", verb, w.Code) |
| + } |
| + } |
| +} |
| + |
| +func TestDemoClaimTransferSQLGate(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + claimToVerify(t, s, op, data) |
| + claimPlace(t, s, op) |
| + s.demoClaimBoundary = func(at string) error { |
| + if at == "commit" { |
| + return errors.New("stop after commit") |
| + } |
| + return nil |
| + } |
| + _ = s.advanceDemoClaim(t.Context(), op.ID) |
| + gated, err := OpenGated(claimDatabasePath(t, s.store)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer gated.Close() |
| + seedGateApp(t, gated) |
| + tables := []string{"demo_claim_progress", "demo_claim_commits", "demo_claim_outbox", "demo_moved_notices"} |
| + if err = gated.withClaimSQL(t.Context(), []claimSQLScope{gateScope}, allowAllClaimSQL, func(v *Store) error { |
| + for _, table := range tables { |
| + for _, q := range []string{"INSERT INTO " + table + " SELECT * FROM " + table, "DELETE FROM " + table} { |
| + _, e := v.db.Exec(q) |
| + requireDenied(t, q, e) |
| + } |
| + key := "operation_id" |
| + if table == "demo_moved_notices" { |
| + key = "demo_id" |
| + } |
| + q := "UPDATE " + table + " SET " + key + "=" + key |
| + _, e := v.db.Exec(q) |
| + requireDenied(t, q, e) |
| + if claimSQLTables[table].Refuse == "" || claimWriterReasons["sql/"+table] == "" { |
| + t.Fatal("missing gate inventory", table) |
| + } |
| + } |
| + return nil |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestDemoClaimTransferSnapshotRefusals(t *testing.T) { |
| + for _, mode := range []string{"wrongDigest", "short", "extra", "notSQLite", "noScratch", "changedRetry"} { |
| + t.Run(mode, func(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + claimAdvance(t, s, op) |
| + if err := s.ackDemoClaim(t.Context(), op.ID, "freeze", uint64(op.Generation)); err != nil { |
| + t.Fatal(err) |
| + } |
| + claimAdvance(t, s, op) |
| + sum := sha256.Sum256(data) |
| + sha := hex.EncodeToString(sum[:]) |
| + size := int64(len(data)) |
| + switch mode { |
| + case "wrongDigest": |
| + sha = hex.EncodeToString(make([]byte, 32)) |
| + case "short": |
| + data = data[:len(data)-1] |
| + case "extra": |
| + data = append(data, 1) |
| + case "notSQLite": |
| + data = []byte("not a database") |
| + size = int64(len(data)) |
| + sum = sha256.Sum256(data) |
| + sha = hex.EncodeToString(sum[:]) |
| + case "noScratch": |
| + s.seedScratch = nil |
| + case "changedRetry": |
| + if err := claimSnapshot(t, s, op, data); err != nil { |
| + t.Fatal(err) |
| + } |
| + data = append([]byte(nil), data...) |
| + data[len(data)-1] ^= 1 |
| + sum = sha256.Sum256(data) |
| + sha = hex.EncodeToString(sum[:]) |
| + } |
| + if err := s.acceptDemoClaimSnapshot(t.Context(), op.ID, bytes.NewReader(data), sha, size); err == nil { |
| + t.Fatal("invalid upload acknowledged") |
| + } |
| + current, _ := s.store.demoClaimOp(t.Context(), op.ID) |
| + if mode != "changedRetry" && current.Phase != "copying" { |
| + t.Fatal("invalid upload advanced phase") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimTransferBoxBinding(t *testing.T) { |
| + s, op, _ := claimTransferFixture(t) |
| + claimAdvance(t, s, op) |
| + for _, mode := range []string{"valid", "wrongBox", "wrongToken", "wrongGeneration", "wrongAction", "expired"} { |
| + t.Run(mode, func(t *testing.T) { |
| + action := "freeze" |
| + gen := op.Generation |
| + if mode == "wrongGeneration" { |
| + gen++ |
| + } |
| + if mode == "wrongAction" { |
| + action = "export" |
| + } |
| + if mode == "expired" { |
| + if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET deadline=1 WHERE id=?`, op.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + body := fmt.Sprintf(`{"action":%q,"generation":%d}`, action, gen) |
| + r := httptest.NewRequest("POST", "/api/box/demo-claims/"+op.ID+"/pickup", strings.NewReader(body)) |
| + r.Header.Set("Authorization", "Bearer worker-token") |
| + r.Header.Set("Carlos-Tunnel-Name", "demo/box") |
| + if mode == "wrongBox" { |
| + r.Header.Set("Carlos-Tunnel-Name", "demo/other") |
| + } |
| + if mode == "wrongToken" { |
| + r.Header.Set("Authorization", "Bearer other") |
| + } |
| + w := httptest.NewRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if mode == "valid" { |
| + if w.Code != 200 { |
| + t.Fatalf("%d %s", w.Code, w.Body) |
| + } |
| + } else if w.Code == 200 { |
| + t.Fatal("foreign or stale work admitted") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimTransferBusyBeforeFreeze(t *testing.T) { |
| + for _, mode := range []string{"active", "settling", "unpublished", "worker", "seedFloor"} { |
| + t.Run(mode, func(t *testing.T) { |
| + s, op, _ := claimTransferFixture(t) |
| + var err error |
| + switch mode { |
| + case "active": |
| + _, err = s.store.db.Exec(`UPDATE demo_apps SET active_job_id='pending' WHERE demo_id=?`, op.DemoID) |
| + case "settling": |
| + _, err = s.store.db.Exec(`UPDATE demo_jobs SET publish_stage='rollback:pending' WHERE demo_id=?`, op.DemoID) |
| + case "unpublished": |
| + _, err = s.store.db.Exec(`UPDATE demo_jobs SET state='failed' WHERE demo_id=?`, op.DemoID) |
| + case "worker": |
| + s.demoJobs.peers["box"].ready.ClaimCapability = "" |
| + case "seedFloor": |
| + claimSeedReadyFixture(t, s, 1, false, "") |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _ = s.advanceDemoClaim(t.Context(), op.ID) |
| + d, _ := s.store.demoByID(t.Context(), op.DemoID) |
| + rec, err := provision.GetRecord(t.Context(), s.cfg.Releases, d.AccountSqid, d.App, d.Host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if rec.DemoClaim != nil { |
| + t.Fatal("refusal froze source") |
| + } |
| + current, _ := s.store.demoClaimOp(t.Context(), op.ID) |
| + if current.Phase != "aborted" && current.Phase != "aborting" { |
| + t.Fatal("unsafe phase", current.Phase) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimTransferSnapshotHTTP(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + claimAdvance(t, s, op) |
| + if err := s.ackDemoClaim(t.Context(), op.ID, "freeze", uint64(op.Generation)); err != nil { |
| + t.Fatal(err) |
| + } |
| + claimAdvance(t, s, op) |
| + server := httptest.NewServer(s.mux) |
| + defer server.Close() |
| + sum := sha256.Sum256(data) |
| + for _, wrong := range []bool{true, false, false} { |
| + req, err := http.NewRequest("POST", server.URL+"/api/box/demo-claims/"+op.ID+"/snapshot", bytes.NewReader(data)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Header.Set("Authorization", "Bearer worker-token") |
| + req.Header.Set("Carlos-Tunnel-Name", "demo/box") |
| + req.Header.Set("Content-Type", "application/vnd.sqlite3") |
| + req.Header.Set(democlaim.SnapshotBytesHeader, strconv.Itoa(len(data))) |
| + sha := hex.EncodeToString(sum[:]) |
| + if wrong { |
| + sha = strings.Repeat("0", 64) |
| + } |
| + req.Header.Set(democlaim.SnapshotSHA256Header, sha) |
| + resp, err := server.Client().Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + want := 204 |
| + if wrong { |
| + want = 409 |
| + } |
| + if resp.StatusCode != want { |
| + t.Fatalf("snapshot status %d, want %d", resp.StatusCode, want) |
| + } |
| + } |
| +} |
| + |
| +func TestDemoClaimTransferJobLoop(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + done := make(chan struct{}) |
| + go func() { defer close(done); s.RunDemoJobs(ctx, nil) }() |
| + defer func() { cancel(); <-done }() |
| + await := func(phase string) { |
| + t.Helper() |
| + until := time.Now().Add(10 * time.Second) |
| + for time.Now().Before(until) { |
| + got, err := s.store.demoClaimOp(t.Context(), op.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got.Phase == phase { |
| + return |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| + t.Fatal("job loop did not reach", phase) |
| + } |
| + await("freezing") |
| + // Phase precedes durable hold publication. Pickup is the readiness gate. |
| + until := time.Now().Add(10 * time.Second) |
| + for { |
| + _, err := s.demoClaimPickup(t.Context(), op.ID, "freeze", uint64(op.Generation)) |
| + if err == nil { |
| + break |
| + } |
| + if time.Now().After(until) { |
| + t.Fatal(err) |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| + if err := s.ackDemoClaim(t.Context(), op.ID, "freeze", uint64(op.Generation)); err != nil { |
| + t.Fatal(err) |
| + } |
| + await("copying") |
| + if err := claimSnapshot(t, s, op, data); err != nil { |
| + t.Fatal(err) |
| + } |
| + await("done") |
| +} |
| + |
| +func TestDemoClaimRetirementPurgeAndRetention(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + claimToVerify(t, s, op, data) |
| + claimAdvance(t, s, op) |
| + d, err := s.store.demoByID(t.Context(), op.DemoID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + receipt, err := s.demoRetirement(t.Context(), op.DemoID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = s.ackDemoRetirement(t.Context(), d.Fleet+"/"+d.AssignedBox, receipt.Wire); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = s.retireDemoLocked(t.Context(), d, time.Now(), "claimed"); err != nil { |
| + t.Fatal(err) |
| + } |
| + held, _ := s.store.demoByID(t.Context(), d.ID) |
| + if held.PurgedAt != 0 { |
| + t.Fatal("purged before initialization cleanup") |
| + } |
| + if err = s.completeDemoRetirement(t.Context(), d.Fleet+"/"+d.AssignedBox, receipt.Wire); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = s.retireDemoLocked(t.Context(), d, time.Now(), "claimed"); err != nil { |
| + t.Fatal(err) |
| + } |
| + purged, _ := s.store.demoByID(t.Context(), d.ID) |
| + if purged.PurgedAt == 0 { |
| + t.Fatal("cleanup did not release ceiling") |
| + } |
| + var id string |
| + if err = s.store.db.QueryRow(`SELECT demo_id FROM demo_host_tombstones WHERE host=?`, d.Host).Scan(&id); err != nil || id != d.ID { |
| + t.Fatal("host tombstone missing", err) |
| + } |
| + later := time.Unix(purged.PurgedAt, 0).Add(7 * 24 * time.Hour) |
| + if err = s.store.WipeDemoAbuse(t.Context(), later); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = s.store.demoByID(t.Context(), d.ID); err != nil { |
| + t.Fatal("abuse pruning erased claim retention clock", err) |
| + } |
| + if err = s.pruneDemoClaims(t.Context(), later); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = s.store.demoClaimOp(t.Context(), op.ID); !errors.Is(err, sql.ErrNoRows) { |
| + t.Fatal("terminal op retained", err) |
| + } |
| + if err = s.store.WipeDemoAbuse(t.Context(), later); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = s.store.db.QueryRow(`SELECT demo_id FROM demo_host_tombstones WHERE host=?`, d.Host).Scan(&id); err != nil { |
| + t.Fatal("permanent tombstone pruned", err) |
| + } |
| + life, err := s.store.AppLife(op.Target.AccountID, op.Target.App) |
| + if err != nil || life == nil || life.ExpiresAt != 0 || life.Trashed() { |
| + t.Fatal("source purge retired permanent app", err) |
| + } |
| +} |
| + |
| +func TestDemoClaimTransferRequiresStreamingStore(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + claimAdvance(t, s, op) |
| + if err := s.ackDemoClaim(t.Context(), op.ID, "freeze", uint64(op.Generation)); err != nil { |
| + t.Fatal(err) |
| + } |
| + claimAdvance(t, s, op) |
| + buffered := &demoCountingStore{Store: s.cfg.SeedData} |
| + s.cfg.SeedData = buffered |
| + if err := claimSnapshot(t, s, op, data); err == nil { |
| + t.Fatal("snapshot used buffered Put fallback") |
| + } |
| + if buffered.puts.Load() != 0 { |
| + t.Fatal("snapshot was buffered") |
| + } |
| +} |
diff --git a/internal/console/demo_expiry.go b/internal/console/demo_expiry.go| index 842bc00c5..769b11f5b 100644 |
| --- a/internal/console/demo_expiry.go |
| +++ b/internal/console/demo_expiry.go |
| @@ -59,6 +59,12 @@ func (s *Server) expireDemos(ctx context.Context, now time.Time, evidence bool) |
| jobFailed(ctx, err) |
| continue |
| } |
| + var pending string |
| + if e := s.store.db.QueryRowContext(ctx, `SELECT id FROM demo_claim_ops WHERE demo_id=? AND phase NOT IN ('done','committed','aborted') AND (source_expires_at<=? OR phase='aborting')`, d.ID, now.Unix()).Scan(&pending); e == nil { |
| + if e = s.abortDemoClaim(ctx, pending, "expired"); e != nil { |
| + jobFailed(ctx, e) |
| + } |
| + } |
| func() { |
| defer s.lockApp(d.AccountSqid, d.App)() |
| if d.State == "anonymous" && !evidence { |
| @@ -102,9 +108,43 @@ func (s *Server) expireDemoLocked(ctx context.Context, d DemoRow, now time.Time) |
| } |
| func (s *Server) retireDemoLocked(ctx context.Context, d DemoRow, now time.Time, reason string) error { |
| - if reason != "expired" && reason != "operator" { |
| + if reason != "expired" && reason != "operator" && reason != "claimed" { |
| + return demo.ErrPolicy |
| + } |
| + var committed int |
| + if err := s.store.db.QueryRowContext(ctx, `SELECT count(*) FROM demo_claim_commits WHERE demo_id=?`, d.ID).Scan(&committed); err != nil { |
| + return err |
| + } |
| + if reason == "claimed" && committed != 1 { |
| return demo.ErrPolicy |
| } |
| + var pending int |
| + if err := s.store.db.QueryRowContext(ctx, `SELECT count(*) FROM demo_claim_ops o LEFT JOIN demo_claim_progress p ON p.operation_id=o.id WHERE o.demo_id=? AND o.phase NOT IN ('done','committed','aborted') AND coalesce(p.cleanup,0)=0`, d.ID).Scan(&pending); err != nil { |
| + return err |
| + } |
| + if pending != 0 { |
| + if reason == "operator" { |
| + tx, err := s.store.demoTx(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + if _, err = tx.ExecContext(ctx, `INSERT OR IGNORE INTO demo_claim_progress(operation_id) SELECT id FROM demo_claim_ops WHERE demo_id=? AND phase NOT IN ('committed','done','aborted')`, d.ID); err != nil { |
| + return err |
| + } |
| + if _, err = tx.ExecContext(ctx, `UPDATE demo_claim_progress SET reason='operator',retry_at=0 WHERE operation_id IN (SELECT id FROM demo_claim_ops WHERE demo_id=? AND phase NOT IN ('committed','done','aborted'))`, d.ID); err != nil { |
| + return err |
| + } |
| + if _, err = tx.ExecContext(ctx, `UPDATE demo_claim_ops SET phase='aborting' WHERE demo_id=? AND phase NOT IN ('committed','done','aborted')`, d.ID); err != nil { |
| + return err |
| + } |
| + if err = tx.Commit(); err != nil { |
| + return err |
| + } |
| + s.signalDemoJobs() |
| + } |
| + return ErrDemoBusy |
| + } |
| var err error |
| d, err = s.store.demoByID(ctx, d.ID) |
| if err != nil { |
| @@ -133,8 +173,8 @@ func (s *Server) retireDemoLocked(ctx context.Context, d DemoRow, now time.Time, |
| r, err := s.demoRetirement(ctx, d.ID) |
| if errors.Is(err, sql.ErrNoRows) { |
| receipt := demobuild.Retirement{Demo: demo.Descriptor{ID: d.ID, Host: d.Host, Lifetime: life.Lifetime, ExpiresAt: life.ExpiresAt}, Account: d.AccountSqid, App: d.App, Fleet: d.Fleet, Box: d.AssignedBox, Tombstone: now.Unix()} |
| - if reason == "operator" { |
| - receipt.Reason = "operator" |
| + if reason == "operator" || reason == "claimed" { |
| + receipt.Reason = reason |
| } |
| jobs, err := s.store.db.QueryContext(ctx, `SELECT id FROM demo_jobs WHERE demo_id=? ORDER BY id`, d.ID) |
| if err != nil { |
diff --git a/internal/console/demo_jobs.go b/internal/console/demo_jobs.go| index a70f70301..4601f277c 100644 |
| --- a/internal/console/demo_jobs.go |
| +++ b/internal/console/demo_jobs.go |
| @@ -91,6 +91,9 @@ func demoSourceKey(j demobuild.Job) string { |
| // placement load and the global queue check. No store write happens here. |
| func (s *Server) insertDemoJob(ctx context.Context, tx *sql.Tx, d DemoRow, life AppLife, src demobuild.Source) (demobuild.Job, error) { |
| var j demobuild.Job |
| + if err := demoClaimSourceGuard(ctx, tx, d.ID); err != nil { |
| + return j, err |
| + } |
| if !s.cfg.Demo.EdgeProtections || !demoServingEnabled(ctx, tx) || !s.cfg.Demo.Enabled || s.cfg.HostClaim || len(s.cfg.Key) != ed25519.PrivateKeySize || !demoLifeValid(d, &life, time.Now()) || d.ActiveJobID != "" { |
| return j, errDemoJob |
| } |
| @@ -374,6 +377,9 @@ func (s *Server) pickupDemo(ctx context.Context, id string, attempt uint32, flee |
| // ReconcileDemoJobs uses SQL, including apps without routes. Restart fails |
| // picked work lacking a committed result; ready bytes remain for Task 7. |
| func (s *Server) ReconcileDemoJobs(ctx context.Context, restart bool) error { |
| + if err := s.ReconcileDemoClaims(ctx, restart); err != nil { |
| + log.Printf("console: %s: %v", demoClaimPending, err) |
| + } |
| if !s.cfg.Demo.Enabled { |
| return nil |
| } |
| @@ -466,8 +472,16 @@ func (s *Server) RunDemoJobs(ctx context.Context, watch *release.ChangeWatch) { |
| if err := s.publishReadyDemos(ctx); err != nil { |
| log.Printf("console: demo publication: %v", err) |
| } |
| + if err := s.ReconcileDemoClaims(ctx, false); err != nil { |
| + log.Printf("console: %s: %v", demoClaimPending, err) |
| + } |
| + var claimNext sql.NullInt64 |
| + _ = s.store.db.QueryRowContext(ctx, `SELECT min(CASE WHEN o.phase='freezing' AND p.hold_ready=1 AND p.hold_ack=0 OR o.phase='copying' AND p.snapshot_sha='' THEN min(p.phase_until,o.deadline*1000000000) ELSE max(coalesce(p.retry_at,0),?) END) FROM demo_claim_ops o LEFT JOIN demo_claim_progress p ON p.operation_id=o.id WHERE o.phase NOT IN ('done','aborted')`, time.Now().Add(time.Second).UnixNano()).Scan(&claimNext) |
| var next sql.NullInt64 |
| err := s.store.db.QueryRowContext(ctx, `SELECT min(CASE state WHEN 'queued' THEN deadline WHEN 'ready' THEN ? ELSE result_by END) FROM demo_jobs WHERE state IN ('queued','picked','ready')`, time.Now().Add(time.Second).UnixNano()).Scan(&next) |
| + if claimNext.Valid && (!next.Valid || claimNext.Int64 < next.Int64) { |
| + next = claimNext |
| + } |
| var timer *time.Timer |
| var due <-chan time.Time |
| if err == nil && next.Valid { |
diff --git a/internal/console/demo_store.go b/internal/console/demo_store.go| index 505ad8b92..664e0b7fe 100644 |
| --- a/internal/console/demo_store.go |
| +++ b/internal/console/demo_store.go |
| @@ -374,6 +374,9 @@ func (s *Store) SpendDemoUpdate(ctx context.Context, id string, now time.Time) e |
| if !demoLifeValid(row, &life, now) { |
| return ErrDemoToken |
| } |
| + if err = demoClaimSourceGuard(ctx, tx, id); err != nil { |
| + return err |
| + } |
| if row.ActiveJobID != "" { |
| return ErrDemoBusy |
| } |
| @@ -425,6 +428,9 @@ func (s *Server) withDemoLocked(ctx context.Context, id string, fn func(DemoRow, |
| if err := s.store.db.QueryRowContext(ctx, `SELECT 1 FROM demo_caps WHERE demo_id=? AND lifetime=?`, row.ID, life.Lifetime).Scan(&snapshot); err != nil { |
| return ErrDemoToken |
| } |
| + if err = demoClaimSourceGuard(ctx, s.store.db, id); err != nil { |
| + return err |
| + } |
| return fn(row, *life) |
| } |
| @@ -447,7 +453,7 @@ func (s *Store) WipeDemoAbuse(ctx context.Context, now time.Time) error { |
| if _, err = tx.ExecContext(ctx, `UPDATE demo_apps SET creating_ip='',source_sha256=X'',client='' WHERE purged_at>0 AND purged_at<=? AND (creating_ip!='' OR length(source_sha256)>0 OR client!='')`, cutoff); err != nil { |
| return err |
| } |
| - const expired = `SELECT d.demo_id FROM demo_apps d JOIN demo_host_tombstones t ON t.demo_id=d.demo_id AND t.host=d.host WHERE d.purged_at>0 AND d.purged_at<=? AND NOT EXISTS (SELECT 1 FROM demo_retirements r WHERE r.demo_id=d.demo_id)` |
| + const expired = `SELECT d.demo_id FROM demo_apps d JOIN demo_host_tombstones t ON t.demo_id=d.demo_id AND t.host=d.host WHERE d.purged_at>0 AND d.purged_at<=? AND NOT EXISTS (SELECT 1 FROM demo_retirements r WHERE r.demo_id=d.demo_id) AND NOT EXISTS (SELECT 1 FROM demo_claim_ops o WHERE o.demo_id=d.demo_id)` |
| if _, err = tx.ExecContext(ctx, `DELETE FROM demo_jobs WHERE demo_id IN (`+expired+`)`, cutoff); err != nil { |
| return err |
| } |
diff --git a/internal/console/server.go b/internal/console/server.go| index 7351af17d..8d79de426 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1252,7 +1252,8 @@ type Server struct { |
| limits emailLimits |
| // flowLocks serialise /auth/continue per sign-in flow (flowLock). |
| flowLocks [256]sync.Mutex |
| - demoClaimTestEnabled bool // Task 8 wires the deployment switch. |
| + demoClaimBoundary func(string) error // Test-only crash injection after durable boundaries. |
| + demoClaimTestEnabled bool // Task 8 wires the deployment switch. |
| // challengeSem bounds the sign-in and step-up sends in flight |
| // (sendChallengeAsync). challengeSent, when non-nil, is signalled after |
| // each one finishes or is dropped. Tests only, as cliNotified. |
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go| index 540afd897..fab603220 100644 |
| --- a/internal/console/store_gate.go |
| +++ b/internal/console/store_gate.go |
| @@ -188,6 +188,10 @@ var claimAppsTerminal = map[string][]string{ |
| // cannot silently ship ungated. There is deliberately no exemption class: |
| // audit and mail telemetry are app-scoped and are gated like the rest. |
| var claimSQLTables = map[string]claimSQLTable{ |
| + "demo_claim_progress": {App: "operation_id", Refuse: "anonymous demo claims require claims mode off"}, |
| + "demo_claim_commits": {App: "operation_id", Refuse: "anonymous demo claims require claims mode off"}, |
| + "demo_claim_outbox": {App: "operation_id", Refuse: "anonymous demo claims require claims mode off"}, |
| + "demo_moved_notices": {App: "demo_id", Refuse: "anonymous demo claims require claims mode off"}, |
| "demo_claim_ops": {Account: "account_id", App: "app", Refuse: "anonymous demo claims require claims mode off"}, |
| "demo_claim_flows": {App: "demo_id", Refuse: "anonymous demo claim flows require claims mode off"}, |
| "demo_reports": {App: "demo_id", Refuse: "anonymous demo reports require claims mode off"}, |
diff --git a/internal/demobuild/retirement.go b/internal/demobuild/retirement.go| index cb04f7e30..e2a5c2c17 100644 |
| --- a/internal/demobuild/retirement.go |
| +++ b/internal/demobuild/retirement.go |
| @@ -24,7 +24,7 @@ type Retirement struct { |
| const retirementDomain = "carlos-demo-retirement-v1\x00" |
| func (r Retirement) valid() bool { |
| - if demo.ValidateBinding(r.Demo, r.Account, r.App, r.Demo.Host, r.Demo.Lifetime, r.Fleet) != nil || r.Tombstone <= 0 || (r.Reason != "" && r.Reason != "expired" && r.Reason != "operator") || (r.Reason != "operator" && r.Tombstone < r.Demo.ExpiresAt) || len(r.Jobs) > 61 { |
| + if demo.ValidateBinding(r.Demo, r.Account, r.App, r.Demo.Host, r.Demo.Lifetime, r.Fleet) != nil || r.Tombstone <= 0 || (r.Reason != "" && r.Reason != "expired" && r.Reason != "operator" && r.Reason != "claimed") || (r.Reason != "operator" && r.Reason != "claimed" && r.Tombstone < r.Demo.ExpiresAt) || len(r.Jobs) > 61 { |
| return false |
| } |
| for _, id := range r.Jobs { |
diff --git a/internal/demobuild/retirement_test.go b/internal/demobuild/retirement_test.go| index b98997ea2..081f41d86 100644 |
| --- a/internal/demobuild/retirement_test.go |
| +++ b/internal/demobuild/retirement_test.go |
| @@ -178,3 +178,22 @@ func TestDemoOperatorRetirementWire(t *testing.T) { |
| t.Fatal(err) |
| } |
| } |
| + |
| +func TestDemoClaimRetirementWire(t *testing.T) { |
| + w, j, key, _ := workerFixture(t) |
| + r := Retirement{Reason: "claimed", Demo: demo.Descriptor{ID: j.DemoID, Host: j.Host, Lifetime: j.Lifetime, ExpiresAt: j.Deadline.Unix()}, Account: j.Account, App: j.App, Fleet: j.Fleet, Box: j.Box, Tombstone: j.Deadline.Unix() - 1} |
| + wire, err := SignRetirement(key, r) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := VerifyRetirement(w.pub, wire) |
| + if err != nil || got.Reason != "claimed" { |
| + t.Fatal("claim receipt refused", err) |
| + } |
| + for _, reason := range []string{"", "expired", "unknown"} { |
| + r.Reason = reason |
| + if _, err := SignRetirement(key, r); err == nil { |
| + t.Fatal("early unsigned reason accepted") |
| + } |
| + } |
| +} |
diff --git a/internal/provision/agent_start_demo_3_census_test.go b/internal/provision/agent_start_demo_3_census_test.go| index 57c5c6447..93178d3fb 100644 |
| --- a/internal/provision/agent_start_demo_3_census_test.go |
| +++ b/internal/provision/agent_start_demo_3_census_test.go |
| @@ -9,12 +9,30 @@ package provision |
| // __demo-snapshot accepts no arguments, runs the fixed non-root worker and |
| // returns before public dispatch. The instances/sidecars literals and their |
| // calls are unchanged; no new record write. Independent review is pending. |
| +// Tasks 4/5 self-review, independent approval remains with the controller. |
| +// The seed upload writes only SnapshotKey through PutObjectFrom; its record |
| +// transition uses SetRecordSeed. Other new record writers use the typed seed |
| +// API or WriteRecord. finishDemoClaimAbort excludes record keys from purge. |
| +// finishSeedOnce and journalPass retain their key-site classes: claim seeds |
| +// add refusal/cleanup checks, not a second record Put primitive. |
| +// Reconcile closes an orphan seed's gate and proves local cleanup before |
| +// deleting its registry row. WriteRecord keeps its sequencing/CAS rules; |
| +// its scoped hold writer can change only a bound demo's own claim hold. |
| func agentStartDemo3WriteCensusInventory() []censusEntry { |
| entries := append([]censusEntry(nil), agentStartDemo2WriteCensusInventory()...) |
| for _, next := range []censusEntry{ |
| {"main.go", "main", "key-site", "lit:instances,lit:sidecars", "10fd9b177a6bfbf46dac51134a3b1db2212c234ff9e35035c08de329bf505545"}, |
| - {"internal/provision/reconcile.go", "Reconcile", "key-site", "key:ParseRecordKey,key:RecordKey,lit:instances", "80ba9d52a062a71915bb49bfe0a1315bb0d3dfe6fc866abd957dcda8ba091250"}, |
| + {"internal/provision/reconcile.go", "Reconcile", "key-site", "key:ParseRecordKey,key:RecordKey,lit:instances", "e31dcb19a6022bbaf69e69736666a2f48991db5d5bfd1c8ed5b4680f0c738ed1"}, |
| {"internal/console/plancaps.go", "Server.runningThings", "key-site", "key:ParseRecordKey,key:RecordsPrefix", "5079fd758e620905ab39fdfe6b44ac1214ab155abb988b0edfa395a2a6d83aab"}, |
| + {"internal/console/seedfinish.go", "Server.finishSeedOnce", "key-site", "key:RecordKey", "a6b0b3fa6002e4266dda8d97338fd087b48bb405a437ce0b43f8f72a5b580772"}, |
| + {"internal/provision/record_sequence.go", "WriteRecord", "record-primitive", "key:IsRecordKey,key:WriteRecord,key:preparedRecordKey,sel:Put", "662234cef59a4fafa59dc0c2e46d3b081872e044da7e756573113bcf8fa6aa48"}, |
| + {"internal/provision/seedreconcile.go", "journalPass", "key-site", "key:RecordKey", "61c3ba65d7fbe5c1f9a129c2320033d11f2a07a24e8e97a93321ace338fb9dd3"}, |
| + {"internal/console/demo_claim_seed.go", "Server.publishDemoClaimSeed", "foreign-recordkey", "key:SetRecordSeed,sel:PutObjectFrom", "9f14bb92e70c1a19c84c04b716d01a07b28039f79d17924d5c95d181c467acda"}, |
| + {"internal/console/demo_claim_seed.go", "Server.requestDemoClaimSeedAbort", "record-writer", "key:SetRecordSeed", "94501d591a5a7ce4eda8b291530928967da3b5aec43d80608682c9d11a2137ad"}, |
| + {"internal/console/demo_claim_transfer.go", "Server.finishDemoClaim", "record-writer", "key:SetRecordSeed", "8fdcc5b7b9f0e94bd14c927d1edefc3ea461fda090173d11bd87d1994f9a6d0a"}, |
| + {"internal/console/demo_claim_transfer.go", "Server.finishDemoClaimAbort", "key-site", "key:IsRecordKey", "ad2e5ad2046445529c09ee4054ccb1587849c2f1c6a037a84cfc7f44a6981224"}, |
| + {"internal/provision/demo_claim_hold.go", "SetDemoClaimHold", "record-writer", "key:RecordKey,key:WriteRecord", "d9e48616f87d7c42a4e590ca069b7d53346600c86d353059785a61cd50d57f4b"}, |
| + {"internal/provision/demo_claim_seed.go", "abortDemoClaimSeed", "record-writer", "key:SetRecordSeed", "d12bbba6be4f28897d11d1d916229373ca4a4a69585c39fcb6e685ee66c7735d"}, |
| } { |
| found := false |
| for i, old := range entries { |
| @@ -25,7 +43,7 @@ func agentStartDemo3WriteCensusInventory() []censusEntry { |
| } |
| } |
| if !found { |
| - panic("missing prior demo claim record census entry") |
| + entries = append(entries, next) |
| } |
| } |
| return entries |
diff --git a/internal/provision/demo_claim_hold.go b/internal/provision/demo_claim_hold.go| new file mode 100644 |
| index 000000000..cb118f671 |
| --- /dev/null |
| +++ b/internal/provision/demo_claim_hold.go |
| @@ -0,0 +1,67 @@ |
| +package provision |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "reflect" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/democlaim" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +type demoClaimHoldWrite struct{ before, after *democlaim.Hold } |
| + |
| +// SetDemoClaimHold changes only the exact demo's claim hold. A caller must |
| +// already own the console operation and source lifecycle lock. |
| +func SetDemoClaimHold(ctx context.Context, store release.Store, account, app string, desc demo.Descriptor, box string, hold democlaim.Hold, clear bool) error { |
| + rec, raw, tag, err := GetRecordRaw(ctx, store, account, app, desc.Host) |
| + if err != nil { |
| + return err |
| + } |
| + if rec.Retired || rec.Demo == nil || *rec.Demo != desc || rec.FleetBox != box { |
| + return democlaim.ErrWork |
| + } |
| + before := rec.DemoClaim |
| + if before != nil && *before != hold { |
| + return democlaim.ErrWork |
| + } |
| + if clear { |
| + rec.DemoClaim = nil |
| + } else { |
| + rec.DemoClaim = &hold |
| + } |
| + if reflect.DeepEqual(before, rec.DemoClaim) { |
| + return nil |
| + } |
| + if err = ValidateShape(*rec); err != nil { |
| + return err |
| + } |
| + body, err := json.Marshal(rec) |
| + if err != nil { |
| + return err |
| + } |
| + ctx = context.WithValue(ctx, demoClaimHoldWrite{}, demoClaimHoldWrite{before, rec.DemoClaim}) |
| + _, _, err = WriteRecord(ctx, store, RecordKey(account, app, desc.Host), raw, body, tag) |
| + return err |
| +} |
| + |
| +func demoFixedForWrite(ctx context.Context, before, after []byte) error { |
| + permit, ok := ctx.Value(demoClaimHoldWrite{}).(demoClaimHoldWrite) |
| + if !ok { |
| + return demoFixed(before, after) |
| + } |
| + var a, b Record |
| + if json.Unmarshal(before, &a) != nil || json.Unmarshal(after, &b) != nil || a.Demo == nil || b.Demo == nil || |
| + !reflect.DeepEqual(a.DemoClaim, permit.before) || !reflect.DeepEqual(b.DemoClaim, permit.after) { |
| + return democlaim.ErrWork |
| + } |
| + b.DemoClaim = a.DemoClaim |
| + // WriteRecord owns this counter; all other bytes of the decoded record |
| + // must match. Neither a hold change nor its permit can edit identity. |
| + b.RecordSeq = a.RecordSeq |
| + if !reflect.DeepEqual(a, b) { |
| + return democlaim.ErrWork |
| + } |
| + return nil |
| +} |
diff --git a/internal/provision/demo_claim_seed.go b/internal/provision/demo_claim_seed.go| index a14a5f88b..510c81bb0 100644 |
| --- a/internal/provision/demo_claim_seed.go |
| +++ b/internal/provision/demo_claim_seed.go |
| @@ -186,3 +186,77 @@ func abortDemoClaimSeed(ctx context.Context, store release.Store, reg *registry. |
| } |
| } |
| } |
| + |
| +// removeDemoClaimOrphan is the removal path for an uncommitted seed whose |
| +// record disappeared. Keep the closed route until stop and local cleanup |
| +// finish, so a crash cannot turn its database into another app's warm data. |
| +func removeDemoClaimOrphan(ctx context.Context, store release.Store, reg *registry.Registry, cfg ReconcileConfig, row registry.Route) (bool, error) { |
| + src, err := seeds.ParseRowSeed(row.SeedSource) |
| + if err != nil { |
| + return false, err |
| + } |
| + if src == nil || src.Kind != seeds.KindDemoClaim || src.State == seeds.StateCommitted { |
| + return false, nil |
| + } |
| + if cfg.ClaimEnabled || row.HoldOp != "" || !rollbackArmed(cfg.Seeds) || !NestedPaths(cfg.DataDir, row) { |
| + return true, ErrSeedConflict |
| + } |
| + if err = reg.CompareSeedGate(row, row.SeedSource, registry.ImportGateClosed); err != nil { |
| + return true, err |
| + } |
| + row.ImportGate = registry.ImportGateClosed |
| + h := cfg.Seeds |
| + gen, err := h.NextFenceGen() |
| + if err != nil { |
| + return true, err |
| + } |
| + if gen == 0 { |
| + return true, ErrSeedConflict |
| + } |
| + ok, err := h.FenceForRollback(ctx, row.Host, gen) |
| + defer h.LiftFence(row.Host, gen) |
| + if err != nil { |
| + return true, err |
| + } |
| + if !ok { |
| + return true, ErrSeedConflict |
| + } |
| + current, err := reg.Get(row.Host) |
| + if err != nil { |
| + return true, err |
| + } |
| + if current == nil { |
| + return true, nil |
| + } |
| + if *current != row { |
| + return true, ErrSeedConflict |
| + } |
| + // The scan can predate a new record. Read fresh authority after the stop. |
| + rec, _, _, err := GetRecordRaw(ctx, freshStore(store), row.Account, row.App, row.Host) |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + return true, err |
| + } |
| + if err == nil && !rec.Retired { |
| + return true, ErrSeedConflict |
| + } |
| + if rec != nil && (rec.Incarnation != row.Incarnation || !rec.Seed.DemoClaim() || rec.Seed.ID != src.ID || rec.Seed.ClaimID != src.ClaimID) { |
| + return true, ErrSeedConflict |
| + } |
| + marker, err := h.LocalSeedID(row.DBPath) |
| + if err != nil { |
| + return true, err |
| + } |
| + if marker == src.ID { |
| + if err = h.RemoveLocal(row); err != nil { |
| + return true, err |
| + } |
| + } |
| + deleted, err := reg.DeleteSeedRoute(row) |
| + if err != nil { |
| + return true, err |
| + } |
| + if !deleted { |
| + return true, ErrSeedConflict |
| + } |
| + return true, nil |
| +} |
diff --git a/internal/provision/demo_claim_seed_test.go b/internal/provision/demo_claim_seed_test.go| index c2a34fad7..376fec3a8 100644 |
| --- a/internal/provision/demo_claim_seed_test.go |
| +++ b/internal/provision/demo_claim_seed_test.go |
| @@ -321,3 +321,79 @@ func TestDemoClaimSeedCommitNeverUsesImportJournal(t *testing.T) { |
| } |
| x.untouched(t) |
| } |
| + |
| +func TestDemoClaimOrphanCleanup(t *testing.T) { |
| + for _, mode := range []string{"matching", "foreignMarker", "stopUncertain", "removeFails", "replacement"} { |
| + t.Run(mode, func(t *testing.T) { |
| + st := dirStore(t) |
| + account := writeAccountManifest(t, st, acctID, "Shop") |
| + if err := PutManifest(ctx, st, account, "shop", Manifest{Schema: 1, App: "shop", Domain: "example.com", Channel: "stable"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + r := claimSeedRecord(t, account) |
| + r.Seed.State = seeds.StateReady |
| + r.Seed.SHA256 = strings.Repeat("a", 64) |
| + r.Seed.Bytes = 4096 |
| + r.Seed.VerifyHash = strings.Repeat("b", 64) |
| + row := RouteFor(r, "/data", "", true, nil) |
| + reg := regWith(t, row) |
| + cfg := nestedSeedCfg(dirStore(t)) |
| + cfg.Pools = nil |
| + cfg.Seeds.NextFenceGen = func() (uint64, error) { return 1, nil } |
| + stopped := false |
| + removed := false |
| + cfg.Seeds.FenceForRollback = func(context.Context, string, uint64) (bool, error) { |
| + stopped = true |
| + return mode != "stopUncertain", nil |
| + } |
| + cfg.Seeds.LiftFence = func(string, uint64) {} |
| + cfg.Seeds.LocalSeedID = func(string) (string, error) { |
| + if !stopped { |
| + t.Fatal("marker read before stop") |
| + } |
| + if mode == "foreignMarker" { |
| + return "foreign", nil |
| + } |
| + return r.Seed.ID, nil |
| + } |
| + cfg.Seeds.RemoveLocal = func(registry.Route) error { |
| + if !stopped { |
| + t.Fatal("removed before stop") |
| + } |
| + removed = true |
| + if mode == "removeFails" { |
| + return errors.New("injected removal failure") |
| + } |
| + return nil |
| + } |
| + cfg.Seeds.RetireKey = func(string, string, string) error { return nil } |
| + cfg.Seeds.DeleteReplica = func(context.Context, string) error { t.Fatal("orphan deleted replica"); return nil } |
| + if mode == "replacement" { |
| + cfg.Seeds.FenceForRollback = func(context.Context, string, uint64) (bool, error) { |
| + stopped = true |
| + if err := CreateRecord(ctx, st, r); err != nil { |
| + t.Fatal(err) |
| + } |
| + return true, nil |
| + } |
| + } |
| + if err := Reconcile(ctx, st, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, _ := reg.Get(r.Host) |
| + if mode == "stopUncertain" || mode == "removeFails" || mode == "replacement" { |
| + if got == nil { |
| + t.Fatal("uncertain orphan deleted") |
| + } |
| + } else if got != nil { |
| + t.Fatal("clean orphan retained") |
| + } |
| + if mode == "matching" && !removed { |
| + t.Fatal("orphan database was not removed") |
| + } |
| + if (mode == "foreignMarker" || mode == "replacement" || mode == "stopUncertain") && removed { |
| + t.Fatal("unproven removal") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/provision/demo_claim_test.go b/internal/provision/demo_claim_test.go| index eab7ca885..cf48d4b85 100644 |
| --- a/internal/provision/demo_claim_test.go |
| +++ b/internal/provision/demo_claim_test.go |
| @@ -106,3 +106,35 @@ func TestDemoClaimRecordHold(t *testing.T) { |
| } |
| }) |
| } |
| + |
| +func TestDemoClaimHoldWriter(t *testing.T) { |
| + s := dirStore(t) |
| + id, _ := demobuild.NewJobID() |
| + other, _ := demobuild.NewJobID() |
| + r := Record{Schema: 1, Account: "shop", App: "tmp-demo-bright-otter-42", Host: "bright-otter-42.example.com", Region: "fleet/demo", FleetBox: "box", Channel: "edge", RecordSeq: 1, Demo: &demo.Descriptor{ID: "AAAAAAAAAAAAAAAAAAAAAA", Host: "bright-otter-42.example.com", Lifetime: "life", ExpiresAt: time.Now().Add(time.Hour).Unix()}} |
| + raw, _ := json.Marshal(r) |
| + if _, err := s.Put(t.Context(), RecordKey(r.Account, r.App, r.Host), raw, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + hold := democlaim.Hold{ID: id, Generation: 1} |
| + if err := SetDemoClaimHold(t.Context(), s, r.Account, r.App, *r.Demo, "box", hold, false); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := GetRecord(t.Context(), s, r.Account, r.App, r.Host) |
| + if err != nil || got.DemoClaim == nil || got.RecordSeq != 2 { |
| + t.Fatal("hold did not sequence", err) |
| + } |
| + if err := SetDemoClaimHold(t.Context(), s, r.Account, r.App, *r.Demo, "box", democlaim.Hold{ID: other, Generation: 1}, true); err == nil { |
| + t.Fatal("foreign hold cleared") |
| + } |
| + if err := SetDemoClaimHold(t.Context(), s, r.Account, r.App, *r.Demo, "other", hold, true); err == nil { |
| + t.Fatal("wrong box cleared hold") |
| + } |
| + if err := SetDemoClaimHold(t.Context(), s, r.Account, r.App, *r.Demo, "box", hold, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err = GetRecord(t.Context(), s, r.Account, r.App, r.Host) |
| + if err != nil || got.DemoClaim != nil || got.RecordSeq != 3 { |
| + t.Fatal("hold release did not sequence", err) |
| + } |
| +} |
diff --git a/internal/provision/reconcile.go b/internal/provision/reconcile.go| index ae0d57da2..a3f953b41 100644 |
| --- a/internal/provision/reconcile.go |
| +++ b/internal/provision/reconcile.go |
| @@ -2549,6 +2549,14 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg |
| log.Printf("provision: dry-run: would remove retired %s route %s (%s)", rt.Kind, rt.Host, why) |
| continue |
| } |
| + if handled, err := removeDemoClaimOrphan(ctx, s, reg, cfg, rt); handled || err != nil { |
| + if err != nil { |
| + pr.fail(rt.Account, rt.App) |
| + } else { |
| + removed[rt.Host] = true |
| + } |
| + continue |
| + } |
| // A held row whose own record is gone is held by an op that |
| // record does not carry: it is deleted only while that op still |
| // holds it, with the move's timers, so a row a new hold took |
| @@ -2584,6 +2592,7 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg |
| log.Printf("provision: removed retired %s route %s (%s)", rt.Kind, rt.Host, why) |
| continue |
| } |
| + |
| if err := cfg.claimRetire(ctx, reg, rt); err != nil { |
| log.Printf("provision: remove retired %s route %s: %v", rt.Kind, rt.Host, err) |
| pr.fail(rt.Account, rt.App) |
diff --git a/internal/provision/record_sequence.go b/internal/provision/record_sequence.go| index 019e3630c..de5dabf37 100644 |
| --- a/internal/provision/record_sequence.go |
| +++ b/internal/provision/record_sequence.go |
| @@ -143,7 +143,7 @@ func WriteRecord(ctx context.Context, s release.Store, key string, before, body |
| if err := replicaFieldsFixed(ctx, before, body); err != nil { |
| return "", 0, err |
| } |
| - if err := demoFixed(before, body); err != nil { |
| + if err := demoFixedForWrite(ctx, before, body); err != nil { |
| return "", 0, err |
| } |
| if err := runtimeFixed(before, body); err != nil { |
| @@ -171,7 +171,7 @@ func WriteRecord(ctx context.Context, s release.Store, key string, before, body |
| } |
| p.body, p.seq, p.sequenced = append([]byte(nil), body...), base+1, true |
| } |
| - if err := demoFixed(before, body); err != nil { |
| + if err := demoFixedForWrite(ctx, before, body); err != nil { |
| return "", 0, err |
| } |
| if err := runtimeFixed(before, body); err != nil { |