fix: keep claim recovery open when switched off and stop polling
Apply R5a to existing claim recovery and status while refusing new freezes when admission is disabled. Checkpoint hold clearing, wait for abort acknowledgments, and back off committed recovery up to five minutes. Skip busy operations in background passes and preserve the first abort reason. Cover switch-off recovery, request costs, migrations and contention. Targeted claim and demo regressions, console vet and formatting checks pass.
internal/console/apidemobox.go+1 −1internal/console/demo_claim_auth.go+7 −1internal/console/demo_claim_auth_test.go+5 −1internal/console/demo_claim_store.go+13 −1internal/console/demo_claim_transfer.go+71 −21internal/console/demo_claim_transfer_test.go+281 −5internal/console/demo_expiry.go+8 −2internal/console/demo_jobs.go+5 −1
CI failed — run details
Intent
<task-notification> <task-id>bi7470bu0</task-id> <tool-use-id>toolu_01Dv8ihjaZJaMni8QwS3guvb</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/bi7470bu0.output</output-file> <status>completed</status> <summary>Background command "S=/home/paulca/.cache/tmp/claude-1001/agent-start-demo-3; until [ -f $S/t5.done ]; do sleep 30; done; tail -1 $S/t5.log" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a60ecd904ffa8316f</task-id> <tool-use-id>toolu_01TxAQsVEHzXxeBbUBNBCEMj</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/a60ecd904ffa8316f.output</output-file> <status>completed</status> <summary>Agent "Review Task 5 (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: ❌** Most of the brief is in place. The phase table, ordered-lock commit and abort ordering match it. So do the claimed-retirement extension and the operation guard. The guard sits on enqueue (`demo_jobs.go` `insertDemoJob`), update spending (`demo_store.go` `SpendDemoUpdate`) and every `withDemoLocked` publication and result boundary. Leaving `demo_publish.go` and `cmd/console/main.go` unmodified is justified: they reach the guard through `withDemoLocked` and the existing `ReconcileDemoJobs`. Two items fail the new ruling R5a: the box handlers and the status read are gated, and freeze dispatch is not (findings 1 and 2). The idle and waiting request-cost requirement is only partly met (finding 3). ⚠️ Not verifiable from this diff: - Whether the box accepts an early `claimed` receipt only while it holds the claim (that is Task 3 host code). - Whether the box dedupes `export` work, which the console resends on every wake while copying (`apidemobox.go` `pendingDemoClaims`; every ready message calls `wakeDemoBox`). - Real systemd/cgroup stop behaviour. 2) **Findings** **P1:** none. I found no path that leaves two writable apps or strands a committed claim: - Abort is refused once committed (`beginDemoClaimAbort`). - Commit requires `phase='verifying'`, so an aborting operation can never commit. - Abort pickup requires `cleanup=1`. - The hold is cleared only while aborting with cleanup proven. - The post-commit steps (open, moved, retire) do not depend on the gated box handlers. **P2-1. All box claim handlers refuse while the switch is off. This violates R5a.** - Evidence: `internal/console/apidemobox.go:404`. `authenticatedDemoClaim` returns 503 unless `demoClaimEnabled()`, and pickup, snapshot and ack all go through it. `TestDemoClaimTransferBoxGate` (`demo_claim_transfer_test.go:260`) asserts this behaviour. - Failure: the switch goes off while an operation is freezing, copying or aborting. The console still advances it to `aborting`, clears the record hold and signs abort work, and `pendingDemoClaims` still streams that work. The box's abort pickup gets 503, so `abort_ack` never arrives. The anonymous source stays frozen until its original expiry, up to 24 h, and is then retired as expired. That is a user-visible outage of every in-flight demo, though never two writers. - Fix: drop the `demoClaimEnabled` check from `authenticatedDemoClaim`. Keep `HostClaim`/`claimGated` and the existing auth, box, phase, generation and lifetime binding. If you want snapshot and export refused when switched off, gate only those actions for operations not yet frozen. Invert the box-gate test. - Family: termination/liveness (admission switch vs recovery). **P2-2. Freeze dispatch is not gated, and the status read is gated. Both are the wrong way round under R5a.** - Evidence (freeze): `demo_claim_transfer.go:67` checks only `HostClaim`/`claimGated`. The `case "reserved"` branch at `:100` pins the source, writes the hold and dispatches freeze. `demoClaimSeedReady` also lost its `demoClaimEnabled` check (`demo_claim_seed.go`). - Failure (freeze): a reserved operation is still frozen while the switch is off, after a restart or after a flip just past reservation. Combined with P2-1, that freeze can never be acknowledged or undone until expiry. - Evidence (status): `handleDemoClaimStatus` (`demo_claim_auth.go:365`, Task 2 code) starts with `demoClaimGate`. - Failure (status): when the switch is off, a committed or aborting claim cannot report its result through the flow token. - Fix: in `advanceDemoClaim`'s `reserved` branch, if `!s.demoClaimEnabled()` then `beginDemoClaimAbort(ctx, op, "disabled")`. The source is never frozen, because `Action==""` releases without needing a box ack. For status, skip the enabled check but keep the origin, `claimGated` and token checks. - Family: admission switch scope (R5a). **P2-3. An abort waiting for the box's acknowledgement polls the object store and forces a full box reconcile about every 2 s.** - Evidence: `ReconcileDemoClaims` selects `aborting` rows whenever `retry_at<=now` and resets `retry_at` to now+2 s after every pass (`demo_claim_transfer.go:887`). `RunDemoJobs` wakes on that clock: its `claimNext` query uses the ELSE branch for aborting rows (`demo_jobs.go`). Each pass, `continueDemoClaimAbort` calls `ensureDemoClaimHold(ctx, op, true)` (`:811`). That runs `SetDemoClaimHold` → `GetRecordRaw`, one store GET even when the hold is already cleared, and then `NotifyDemoBox` (`:303`). On the box, `NotifyDemoBox` sets `p.reconcile` → `msg.Reconcile` → `notify()` → `backstopFullDue.Store(true)` (`internal/host/demo_jobs.go:551`, `:108`). That is a full backstop pass. - Failure: a slow or offline box, or P2-1 with the switch off, means a store GET plus a full box reconcile every ~2 s for up to 24 h per operation. The same unbounded 2 s loop exists after commit when the `open` step's verify keeps failing (`:693`): a record GET plus an HTTPS GET with no backoff. This breaks the "unchanged tick → zero additional store requests" invariant. `TestDemoClaimRequestCost` covers only the freezing wait. - Fix: - Persist "hold cleared" (e.g. a `hold_cleared` column) so the clear runs once. - Exclude `aborting` rows waiting on `abort_ack` (`cleanup=1`, work present, `phase_until` in the future) from the select, as freezing already is. Wake them by ack or `phase_until`. - Notify the box only when the record actually changes. - Give `committed` retries exponential backoff. - Extend the request-cost test to aborting and committed waits. - Family: request cost (S3 polling). **P3 (follow-ups)** - `acceptDemoClaimSnapshot` holds the per-operation lock for the whole upload, up to `SnapshotWindow`. A due retry or expiry abort on that operation blocks the serial `RunDemoJobs`/`expireDemos` pass meanwhile. Either use a try-lock in the reconcile pass, or skip operations with an upload in flight. - `beginDemoClaimAbort` overwrites a stored reason (`deadline`/`capability`) with `expired` when the expiry pass re-enters. That is diagnostic loss only. - `demo_moved_notices` rows are never pruned. Task 6 should own this; note it in Task 6's brief. - Provision orphan path (risk 9): `removeDemoClaimOrphan` passes `row.DBPath` from the agent-written registry row to `LocalSeedID`/`RemoveLocal`. It is confined by `NestedPaths(cfg.DataDir, row)`, and `seedrollback.go:162` already passes a registry row the same way. It runs on the agent's reconcile path. I found no new path a tenant or agent could name, but the census overlay under R9 should still classify it. 3) **Strengths** - The commit is a single SQL transaction that rechecks identity, membership, the target reservation (`a.expires_at=0`), the hold acknowledgement, source lifetime, generation, deadline and `phase_until` under the account → apps → hostname lock order. It records the decision, nulls the token hash, deletes flows, stores the moved notice and enqueues the outbox together. `checkRunningThings(acct, 0)` is used correctly. - Status keeps working after flows are deleted because it is keyed off `demo_claim_ops.flow_hash`. - The snapshot path is careful: - It reserves scratch before reading any bytes. - It hashes while streaming, then runs an integrity check. - It pins the digest before the PUT and reads before any retry PUT. - It refuses changed bytes. - Verify uses the exact apex host, refuses redirects, requires 2xx plus a matching `X-Carlos-Version`, and checks `placed` after the wake. - On expiry, `retireDemoLocked` refuses while an uncommitted operation has cleanup pending, and the expiry pass aborts the destination first. Operator intent survives retries. - `SetDemoClaimHold` uses a permit that is exact on the decoded record and keeps `WriteRecord`'s sequencing and CAS. - Recovery coverage is broad: SQL and object boundaries, lost replies, and a trigger-forced commit rollback. 4) **Verdict: READY AFTER FIXES.** No P1; fix P2-1, P2-2 and P2-3.</result> <usage><subagent_tokens>172868</subagent_tokens><tool_uses>35</tool_uses><duration_ms>402535</duration_ms></usage> </task-notification>
Attributed to this commit: 16.7 g CO₂e (2,013,272 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/apidemobox.go b/internal/console/apidemobox.go| index 8fd8d629f..c34582608 100644 |
| --- a/internal/console/apidemobox.go |
| +++ b/internal/console/apidemobox.go |
| @@ -401,7 +401,7 @@ func (s *Server) handleDemoResult(w http.ResponseWriter, r *http.Request) { |
| // 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() { |
| + if s.cfg.HostClaim || s.store.claimGated() { |
| jsonError(w, 503, demoClaimUnavailable) |
| return claimOp{}, false |
| } |
diff --git a/internal/console/demo_claim_auth.go b/internal/console/demo_claim_auth.go| index b93a10a41..c83c5dd46 100644 |
| --- a/internal/console/demo_claim_auth.go |
| +++ b/internal/console/demo_claim_auth.go |
| @@ -362,7 +362,13 @@ func (s *Server) handleDemoClaimSelect(w http.ResponseWriter, r *http.Request) { |
| } |
| func (s *Server) handleDemoClaimStatus(w http.ResponseWriter, r *http.Request) { |
| - if !s.demoClaimGate(w, r) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + if s.cfg.HostClaim || s.store.claimGated() { |
| + jsonError(w, 503, demoClaimUnavailable) |
| + return |
| + } |
| + if !s.demoClaimOrigin(r) { |
| + jsonError(w, 403, demoClaimWrongSite) |
| return |
| } |
| auth := r.Header.Get("Authorization") |
diff --git a/internal/console/demo_claim_auth_test.go b/internal/console/demo_claim_auth_test.go| index 51bfe9eca..dfd0146d9 100644 |
| --- a/internal/console/demo_claim_auth_test.go |
| +++ b/internal/console/demo_claim_auth_test.go |
| @@ -499,7 +499,11 @@ func TestDemoClaimProofStatusAndSelection(t *testing.T) { |
| } else { |
| w = claimRaw(s, path, "{}") |
| } |
| - if w.Code != 503 || w.Header().Get("Cache-Control") != "no-store" { |
| + want := 503 |
| + if path == "/api/demo/claims/status" { |
| + want = 202 |
| + } |
| + if w.Code != want || w.Header().Get("Cache-Control") != "no-store" { |
| t.Fatalf("disabled %s: %d", path, w.Code) |
| } |
| } |
diff --git a/internal/console/demo_claim_store.go b/internal/console/demo_claim_store.go| index 96699042e..bd433589b 100644 |
| --- a/internal/console/demo_claim_store.go |
| +++ b/internal/console/demo_claim_store.go |
| @@ -5,6 +5,7 @@ import ( |
| "database/sql" |
| "encoding/base64" |
| "errors" |
| + "strings" |
| "time" |
| ) |
| @@ -40,7 +41,18 @@ func (s *Store) migrateDemoClaims() error { |
| 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 |
| + if err != nil { |
| + return err |
| + } |
| + for _, stmt := range []string{ |
| + `ALTER TABLE demo_claim_progress ADD COLUMN hold_cleared INTEGER NOT NULL DEFAULT 0`, |
| + `ALTER TABLE demo_claim_progress ADD COLUMN retry_delay INTEGER NOT NULL DEFAULT 0`, |
| + } { |
| + if _, err = s.db.Exec(stmt); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| + return err |
| + } |
| + } |
| + return nil |
| } |
| func (s *Store) demoClaimFlow(ctx context.Context, raw string, now time.Time) (claimFlow, error) { |
diff --git a/internal/console/demo_claim_transfer.go b/internal/console/demo_claim_transfer.go| index 3ba4c6fa5..d6ed6abe3 100644 |
| --- a/internal/console/demo_claim_transfer.go |
| +++ b/internal/console/demo_claim_transfer.go |
| @@ -22,10 +22,10 @@ import ( |
| ) |
| type demoClaimProgress struct { |
| - Wire []byte |
| - Action, SHA, Reason string |
| - HoldReady, HoldAck, Copied, Cleanup, AbortAck bool |
| - Bytes, RetryAt, Until int64 |
| + Wire []byte |
| + Action, SHA, Reason string |
| + HoldReady, HoldAck, Copied, Cleanup, AbortAck, HoldCleared bool |
| + Bytes, RetryAt, Until int64 |
| } |
| func (s *Store) demoClaimOp(ctx context.Context, id string) (claimOp, error) { |
| @@ -33,7 +33,7 @@ func (s *Store) demoClaimOp(ctx context.Context, id string) (claimOp, error) { |
| } |
| 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) |
| + 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,hold_cleared 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, &p.HoldCleared) |
| return p, err |
| } |
| func (s *Server) claimBoundary(at string) error { |
| @@ -64,10 +64,13 @@ func (s *Server) demoClaimCapabilitiesReady(ctx context.Context, op claimOp) err |
| // 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 { |
| + defer s.acctLocks.lock("demo-claim:" + id)() |
| + return s.advanceDemoClaimLocked(ctx, id) |
| +} |
| +func (s *Server) advanceDemoClaimLocked(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 { |
| @@ -98,6 +101,9 @@ func (s *Server) advanceDemoClaim(ctx context.Context, id string) error { |
| ctx = bounded |
| switch op.Phase { |
| case "reserved": |
| + if !s.demoClaimEnabled() { |
| + return s.beginDemoClaimAbort(ctx, op, "disabled") |
| + } |
| if err = s.demoClaimCapabilitiesReady(ctx, op); err != nil { |
| return s.beginDemoClaimAbort(ctx, op, "capability") |
| } |
| @@ -141,6 +147,9 @@ func (s *Server) advanceDemoClaim(ctx context.Context, id string) error { |
| } |
| return s.ensureDemoClaimHold(ctx, op, false) |
| case "freezing": |
| + if !p.HoldReady && !s.demoClaimEnabled() { |
| + return s.beginDemoClaimAbort(ctx, op, "disabled") |
| + } |
| if !p.HoldAck { |
| if len(p.Wire) == 0 { |
| if err = s.setDemoClaimWork(ctx, op, "freeze", 30*time.Second); err != nil { |
| @@ -289,18 +298,30 @@ func (s *Server) ensureDemoClaimHold(ctx context.Context, op claimOp, clear bool |
| if fresh.Phase != "aborting" || !p.Cleanup { |
| return ErrDemoToken |
| } |
| + if p.HoldCleared { |
| + return nil |
| + } |
| } else if fresh.Phase != "freezing" { |
| return ErrDemoToken |
| } |
| + before, err := provision.GetRecord(ctx, s.cfg.Releases, d.AccountSqid, d.App, d.Host) |
| + if err != nil { |
| + return err |
| + } |
| + changed := clear && before.DemoClaim != nil || !clear && before.DemoClaim == nil |
| 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 |
| - } |
| + if changed { |
| + s.NotifyDemoBox(op.SourceBox) |
| + } |
| + column := "hold_ready" |
| + if clear { |
| + column = "hold_cleared" |
| + } |
| + if _, err = s.store.db.ExecContext(ctx, "UPDATE demo_claim_progress SET "+column+"=1 WHERE operation_id=?", op.ID); err != nil { |
| + return err |
| } |
| - s.NotifyDemoBox(op.SourceBox) |
| if !clear { |
| return s.claimBoundary("hold") |
| } |
| @@ -738,6 +759,9 @@ func (s *Server) finishDemoClaim(ctx context.Context, op claimOp) error { |
| func (s *Server) abortDemoClaim(ctx context.Context, id, reason string) error { |
| defer s.acctLocks.lock("demo-claim:" + id)() |
| + return s.abortDemoClaimLocked(ctx, id, reason) |
| +} |
| +func (s *Server) abortDemoClaimLocked(ctx context.Context, id, reason string) error { |
| return s.lifetimesStep(withDemoClaimOperation(ctx, id), true, func(ctx context.Context) error { |
| op, err := s.store.demoClaimOp(ctx, id) |
| if err != nil { |
| @@ -764,7 +788,7 @@ func (s *Server) beginDemoClaimAbort(ctx context.Context, op claimOp, reason str |
| 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 { |
| + if _, err = tx.ExecContext(ctx, `UPDATE demo_claim_progress SET reason=CASE WHEN reason!='' THEN reason ELSE ? END,retry_at=0 WHERE operation_id=?`, reason, op.ID); err != nil { |
| return err |
| } |
| if err = tx.Commit(); err != nil { |
| @@ -808,8 +832,10 @@ func (s *Server) continueDemoClaimAbort(ctx context.Context, op claimOp) error { |
| } else if !p.AbortAck && p.Action == "" { |
| p.AbortAck = true |
| } else if !p.AbortAck { |
| - if err = s.ensureDemoClaimHold(ctx, op, true); err != nil { |
| - return err |
| + if !p.HoldCleared { |
| + 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" { |
| @@ -862,8 +888,9 @@ func (s *Server) ReconcileDemoClaims(ctx context.Context, restart bool) error { |
| 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) |
| + WHERE o.phase NOT IN ('done','aborted') AND (p.operation_id IS NULL OR (? AND o.phase!='committed') 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<=?) AND (o.phase!='aborting' OR p.cleanup=0 OR p.hold_cleared=0 OR p.abort_ack=1 OR p.action!='abort' OR p.reason='operator' OR p.phase_until<=? OR o.source_expires_at<=?) |
| + ORDER BY o.id LIMIT ?`, restart, now.UnixNano(), now.Unix(), now.UnixNano(), now.Unix(), now.UnixNano(), now.Unix(), demobuild.QueueLimit) |
| if err != nil { |
| return err |
| } |
| @@ -881,16 +908,39 @@ func (s *Server) ReconcileDemoClaims(ctx context.Context, restart bool) error { |
| } |
| 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) |
| + unlock, ok := s.acctLocks.tryLock("demo-claim:" + id) |
| + if !ok { |
| + continue |
| } |
| + func() { |
| + defer unlock() |
| + if err = s.advanceDemoClaimLocked(ctx, id); err != nil { |
| + errs = append(errs, err) |
| + } |
| + // Keep failed committed work bounded across ticks and console restarts. |
| + _, e := s.store.db.ExecContext(ctx, `UPDATE demo_claim_progress SET |
| + retry_at=? + CASE WHEN (SELECT phase FROM demo_claim_ops WHERE id=operation_id)='committed' THEN min(max(retry_delay*2,?),?) ELSE ? END, |
| + retry_delay=CASE WHEN (SELECT phase FROM demo_claim_ops WHERE id=operation_id)='committed' THEN min(max(retry_delay*2,?),?) ELSE 0 END |
| + WHERE operation_id=?`, time.Now().UnixNano(), int64(2*time.Second), int64(5*time.Minute), int64(2*time.Second), int64(2*time.Second), int64(5*time.Minute), id) |
| + if e != nil { |
| + errs = append(errs, e) |
| + } |
| + }() |
| } |
| return errors.Join(errs...) |
| } |
| func (s *Server) pruneDemoClaims(ctx context.Context, now time.Time) error { |
| + // demoTx acquires the writer lock with a settings-row update. Avoid that |
| + // write when neither capabilities nor terminal operations need pruning. |
| + var due bool |
| + err := s.store.db.QueryRowContext(ctx, `SELECT |
| + EXISTS(SELECT 1 FROM demo_claim_flows f WHERE f.expires_at<=? AND NOT EXISTS(SELECT 1 FROM demo_claim_ops o WHERE o.flow_hash=f.hash)) |
| + OR EXISTS(SELECT 1 FROM demo_claim_ops WHERE source_expires_at<=? AND flow_hash!='') |
| + OR EXISTS(SELECT 1 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.Unix(), now.Add(-24*time.Hour).Unix(), now.Add(-7*24*time.Hour).Unix()).Scan(&due) |
| + if err != nil || !due { |
| + return err |
| + } |
| tx, err := s.store.demoTx(ctx) |
| if err != nil { |
| return err |
diff --git a/internal/console/demo_claim_transfer_test.go b/internal/console/demo_claim_transfer_test.go| index 33b44ca91..f3074ec3d 100644 |
| --- a/internal/console/demo_claim_transfer_test.go |
| +++ b/internal/console/demo_claim_transfer_test.go |
| @@ -258,16 +258,28 @@ func TestDemoClaimTransferVerifyRefusals(t *testing.T) { |
| } |
| func TestDemoClaimTransferBoxGate(t *testing.T) { |
| - s, op, _ := claimTransferFixture(t) |
| + s, op, _ := claimAbortWaitFixture(t) |
| s.demoClaimTestEnabled = false |
| - for _, verb := range []string{"pickup", "snapshot", "ack"} { |
| - r := httptest.NewRequest("POST", "/api/box/demo-claims/"+op.ID+"/"+verb, nil) |
| + for _, verb := range []string{"pickup", "ack"} { |
| + body := fmt.Sprintf(`{"action":"abort","generation":%d}`, op.Generation) |
| + r := httptest.NewRequest("POST", "/api/box/demo-claims/"+op.ID+"/"+verb, strings.NewReader(body)) |
| + r.Header.Set("Authorization", "Bearer worker-token") |
| + r.Header.Set("Carlos-Tunnel-Name", "demo/box") |
| w := httptest.NewRecorder() |
| s.mux.ServeHTTP(w, r) |
| - if w.Code != 503 { |
| - t.Fatalf("%s: %d", verb, w.Code) |
| + want := 200 |
| + if verb == "ack" { |
| + want = 204 |
| + } |
| + if w.Code != want { |
| + t.Fatalf("%s: %d %s", verb, w.Code, w.Body) |
| } |
| } |
| + claimAdvance(t, s, op) |
| + current, _ := s.store.demoClaimOp(t.Context(), op.ID) |
| + if current.Phase != "aborted" { |
| + t.Fatal(current.Phase) |
| + } |
| } |
| func TestDemoClaimTransferSQLGate(t *testing.T) { |
| @@ -442,6 +454,7 @@ func TestDemoClaimTransferSnapshotHTTP(t *testing.T) { |
| t.Fatal(err) |
| } |
| claimAdvance(t, s, op) |
| + s.demoClaimTestEnabled = false |
| server := httptest.NewServer(s.mux) |
| defer server.Close() |
| sum := sha256.Sum256(data) |
| @@ -595,3 +608,266 @@ func TestDemoClaimTransferRequiresStreamingStore(t *testing.T) { |
| t.Fatal("snapshot was buffered") |
| } |
| } |
| + |
| +// claimAbortWaitFixture reaches the real cleanup path before waiting for the |
| +// assigned worker's abort acknowledgment. |
| +func claimAbortWaitFixture(t *testing.T) (*Server, claimOp, []byte) { |
| + t.Helper() |
| + s, op, data := claimTransferFixture(t) |
| + claimToVerify(t, s, op, data) |
| + claimLocalLeaseServer(t, s) |
| + if err := s.abortDemoClaim(t.Context(), op.ID, "test"); 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) |
| + } |
| + claimAdvance(t, s, op) |
| + return s, op, data |
| +} |
| + |
| +func TestDemoClaimTransferDisabledReserved(t *testing.T) { |
| + s, op, _ := claimTransferFixture(t) |
| + s.demoClaimTestEnabled = false |
| + claimAdvance(t, s, op) |
| + current, _ := s.store.demoClaimOp(t.Context(), op.ID) |
| + if current.Phase != "aborted" { |
| + t.Errorf("disabled reservation phase = %s", current.Phase) |
| + } |
| + 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 || rec.DemoClaim != nil { |
| + t.Errorf("source frozen: %v", err) |
| + } |
| + life, err := s.store.AppLife(op.Target.AccountID, op.Target.App) |
| + if err != nil || life != nil { |
| + t.Errorf("reservation retained: %v", err) |
| + } |
| +} |
| + |
| +func TestDemoClaimTransferDisabledStatus(t *testing.T) { |
| + for _, phase := range []string{"committed", "aborting"} { |
| + t.Run(phase, func(t *testing.T) { |
| + var flow string |
| + s, op, data := claimTransferFixture(t, &flow) |
| + claimToVerify(t, s, op, data) |
| + if phase == "committed" { |
| + s.demoClaimBoundary = func(at string) error { |
| + if at == "commit" { |
| + return errors.New("pause") |
| + } |
| + return nil |
| + } |
| + _ = s.advanceDemoClaim(t.Context(), op.ID) |
| + } else { |
| + claimLocalLeaseServer(t, s) |
| + if err := s.abortDemoClaim(t.Context(), op.ID, "test"); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + s.demoClaimTestEnabled = false |
| + r := httptest.NewRequest("GET", "/api/demo/claims/status", nil) |
| + r.Header.Set("Authorization", "Bearer "+flow) |
| + w := httptest.NewRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 202 || !strings.Contains(w.Body.String(), phase) { |
| + t.Fatalf("status %d %s", w.Code, w.Body) |
| + } |
| + for _, path := range []string{"/api/demo/claims", "/api/demo/claims/verify", "/api/demo/claims/select"} { |
| + if got := claimRaw(s, path, "{}"); got.Code != 503 { |
| + t.Fatalf("admission %s: %d", path, got.Code) |
| + } |
| + } |
| + r.Header.Set("Origin", "https://other.example.com") |
| + w = httptest.NewRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 403 { |
| + t.Fatalf("origin %d", w.Code) |
| + } |
| + r.Header.Del("Origin") |
| + r.Header.Set("Authorization", "Bearer invalid") |
| + w = httptest.NewRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 401 { |
| + t.Fatalf("token %d", w.Code) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimRequestCostAbortWait(t *testing.T) { |
| + s, op, _ := claimAbortWaitFixture(t) |
| + st := &demoCountingStore{Store: s.cfg.Releases} |
| + s.cfg.Releases = st |
| + s.demoJobs.peers["box"].reconcile = false |
| + for range 3 { |
| + if _, err := s.store.db.Exec(`UPDATE demo_claim_progress SET retry_at=0 WHERE operation_id=?`, op.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.ReconcileDemoClaims(t.Context(), false); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.expireDemos(t.Context(), time.Now(), true) |
| + } |
| + if st.gets.Load() != 0 || st.puts.Load() != 0 || s.demoJobs.peers["box"].reconcile { |
| + t.Fatalf("unchanged abort wait: gets=%d puts=%d notify=%v", st.gets.Load(), st.puts.Load(), s.demoJobs.peers["box"].reconcile) |
| + } |
| +} |
| + |
| +func TestDemoClaimRequestCostCommittedWait(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + claimToVerify(t, s, op, data) |
| + s.demoClaimBoundary = func(at string) error { |
| + if at == "commit" { |
| + return errors.New("pause") |
| + } |
| + return nil |
| + } |
| + _ = s.advanceDemoClaim(t.Context(), op.ID) |
| + s.demoClaimBoundary = nil |
| + s.demoTransport = roundTripFunc(func(*http.Request) (*http.Response, error) { return nil, errors.New("offline") }) |
| + for attempt := 0; attempt < 10; attempt++ { |
| + if _, err := s.store.db.Exec(`UPDATE demo_claim_progress SET retry_at=0 WHERE operation_id=?`, op.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + before := time.Now() |
| + _ = s.ReconcileDemoClaims(t.Context(), false) |
| + p, err := s.claimProgress(t.Context(), op.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := min(2*time.Second*time.Duration(1<<attempt), 5*time.Minute) |
| + delay := time.Unix(0, p.RetryAt).Sub(before) |
| + if delay < want || delay > want+time.Second { |
| + t.Fatalf("attempt %d retry delay %v, want %v", attempt, delay, want) |
| + } |
| + st := &demoCountingStore{Store: s.cfg.Releases} |
| + s.cfg.Releases = st |
| + s.demoJobs.peers["box"].reconcile = false |
| + for range 3 { |
| + if err := s.ReconcileDemoClaims(t.Context(), false); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if st.gets.Load() != 0 || st.puts.Load() != 0 || s.demoJobs.peers["box"].reconcile { |
| + t.Fatal("committed wait polled or notified") |
| + } |
| + s.cfg.Releases = st.Store |
| + } |
| +} |
| + |
| +func TestDemoClaimTransferBusyPass(t *testing.T) { |
| + for _, pass := range []string{"reconcile", "expiry"} { |
| + t.Run(pass, func(t *testing.T) { |
| + s, op, _ := claimTransferFixture(t) |
| + claimAdvance(t, s, op) |
| + if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET source_expires_at=1,deadline=1 WHERE id=?`, op.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + unlock := s.acctLocks.lock("demo-claim:" + op.ID) |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + if pass == "reconcile" { |
| + _ = s.ReconcileDemoClaims(t.Context(), false) |
| + } else { |
| + s.expireDemos(t.Context(), time.Now(), true) |
| + } |
| + }() |
| + select { |
| + case <-done: |
| + unlock() |
| + case <-time.After(time.Second): |
| + unlock() |
| + <-done |
| + t.Fatal("pass blocked on upload operation lock") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimTransferAbortReason(t *testing.T) { |
| + s, op, _ := claimAbortWaitFixture(t) |
| + if err := s.abortDemoClaim(t.Context(), op.ID, "expired"); err != nil { |
| + t.Fatal(err) |
| + } |
| + p, err := s.claimProgress(t.Context(), op.ID) |
| + if err != nil || p.Reason != "test" { |
| + t.Fatalf("reason %q: %v", p.Reason, err) |
| + } |
| +} |
| + |
| +func TestDemoClaimRequestCostHoldCheckpoint(t *testing.T) { |
| + s, op, _ := claimAbortWaitFixture(t) |
| + st := &demoCountingStore{Store: s.cfg.Releases} |
| + s.cfg.Releases = st |
| + s.demoJobs.peers["box"].reconcile = false |
| + // A delivery-window refresh must not read the cleared source record again. |
| + for range 3 { |
| + claimAdvance(t, s, op) |
| + } |
| + if st.gets.Load() != 0 || st.puts.Load() != 0 || s.demoJobs.peers["box"].reconcile { |
| + t.Fatal("cleared hold replayed") |
| + } |
| + // Simulate a crash after clearing the object but before the SQL checkpoint. |
| + if _, err := s.store.db.Exec(`UPDATE demo_claim_progress SET hold_cleared=0 WHERE operation_id=?`, op.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + claimAdvance(t, s, op) |
| + if st.puts.Load() != 0 || s.demoJobs.peers["box"].reconcile { |
| + t.Fatal("unchanged hold notified box") |
| + } |
| +} |
| + |
| +func TestDemoClaimTransferProgressMigration(t *testing.T) { |
| + s, op, _ := claimAbortWaitFixture(t) |
| + for _, column := range []string{"hold_cleared", "retry_delay"} { |
| + if _, err := s.store.db.Exec("ALTER TABLE demo_claim_progress DROP COLUMN " + column); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for range 2 { |
| + if err := s.store.migrateDemoClaims(); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + p, err := s.claimProgress(t.Context(), op.ID) |
| + if err != nil || !p.Cleanup || p.HoldCleared || p.Reason != "test" { |
| + t.Fatalf("migration lost progress: %+v %v", p, err) |
| + } |
| + claimAdvance(t, s, op) |
| + p, err = s.claimProgress(t.Context(), op.ID) |
| + if err != nil || !p.HoldCleared { |
| + t.Fatalf("legacy clear not checkpointed: %+v %v", p, err) |
| + } |
| +} |
| + |
| +func TestDemoClaimRequestCostAbortRefresh(t *testing.T) { |
| + s, op, _ := claimAbortWaitFixture(t) |
| + if _, err := s.store.db.Exec(`UPDATE demo_claim_progress SET phase_until=1,work=X'',retry_at=0 WHERE operation_id=?`, op.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + st := &demoCountingStore{Store: s.cfg.Releases} |
| + s.cfg.Releases = st |
| + s.demoJobs.peers["box"].reconcile = false |
| + if err := s.ReconcileDemoClaims(t.Context(), false); err != nil { |
| + t.Fatal(err) |
| + } |
| + p, err := s.claimProgress(t.Context(), op.ID) |
| + if err != nil || p.Until <= time.Now().UnixNano() { |
| + t.Fatal("abort delivery window not refreshed", err) |
| + } |
| + if st.gets.Load() != 0 || st.puts.Load() != 0 || s.demoJobs.peers["box"].reconcile { |
| + t.Fatal("refresh polled or notified") |
| + } |
| + if err := s.ackDemoClaim(t.Context(), op.ID, "abort", uint64(op.Generation)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.ReconcileDemoClaims(t.Context(), false); err != nil { |
| + t.Fatal(err) |
| + } |
| + current, err := s.store.demoClaimOp(t.Context(), op.ID) |
| + if err != nil || current.Phase != "aborted" { |
| + t.Fatal("ack did not wake abort", err) |
| + } |
| +} |
diff --git a/internal/console/demo_expiry.go b/internal/console/demo_expiry.go| index 769b11f5b..c02b82920 100644 |
| --- a/internal/console/demo_expiry.go |
| +++ b/internal/console/demo_expiry.go |
| @@ -60,8 +60,14 @@ func (s *Server) expireDemos(ctx context.Context, now time.Time, evidence bool) |
| 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 { |
| + 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<=?`, d.ID, now.Unix()).Scan(&pending); e == nil { |
| + unlock, ok := s.acctLocks.tryLock("demo-claim:" + pending) |
| + if !ok { |
| + continue |
| + } |
| + e = s.abortDemoClaimLocked(ctx, pending, "expired") |
| + unlock() |
| + if e != nil { |
| jobFailed(ctx, e) |
| } |
| } |
diff --git a/internal/console/demo_jobs.go b/internal/console/demo_jobs.go| index 4601f277c..78b02d780 100644 |
| --- a/internal/console/demo_jobs.go |
| +++ b/internal/console/demo_jobs.go |
| @@ -476,7 +476,11 @@ func (s *Server) RunDemoJobs(ctx context.Context, watch *release.ChangeWatch) { |
| 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) |
| + _ = 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) WHEN o.phase='aborting' AND p.cleanup=1 AND p.hold_cleared=1 AND p.abort_ack=0 AND p.action='abort' AND p.reason!='operator' THEN min(p.phase_until,o.source_expires_at*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) |
| + if claimNext.Valid { |
| + // A busy upload may leave an overdue operation for the next pass. |
| + claimNext.Int64 = max(claimNext.Int64, time.Now().Add(time.Second).UnixNano()) |
| + } |
| 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) { |