fix: tighten demo claim proof test and refusals
Require exact stale-proof refusals and prove the recheck catches a mutation. Keep durable reservations successful after pipeline write failures, return clear token and pending-claim refusals, and skip pending targets in settle. Verify targeted demo claim, email, settle and materialize tests, plus vet.
internal/console/demo_claim_auth_test.go+4 −4internal/console/demo_claim_store_test.go+13 −2internal/console/demo_claim_target.go+12 −3internal/console/demo_claim_target_test.go+62 −2internal/console/settle.go+3 −0
CI failed — run details
Intent
<task-notification> <task-id>b7qrpxab4</task-id> <tool-use-id>toolu_01WMXMPmC9e7BiFDTQBzL5iZ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/b7qrpxab4.output</output-file> <status>completed</status> <summary>Background command "S=/home/paulca/.cache/tmp/claude-1001/agent-start-demo-3; until [ -f $S/t2.done ]; do sleep 30; done; tail -1 $S/t2.log" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a64f11241eab083f6</task-id> <tool-use-id>toolu_019nUDkhTrQKsrsbRKA9Uohe</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/a64f11241eab083f6.output</output-file> <status>completed</status> <summary>Agent "Review Task 2 (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 one test regression listed under P2. - **Interfaces.** `chooseDemoClaimAccount`, `reserveDemoClaim`, `claimTarget`/`claimOp` and `demoClaimMutationRefusal` match the brief. `claimOp` also carries `SourceExpiresAt`, which is harmless. - **Rulings.** R1 is honoured: `demo_claim_auth.go:303-344` wires verify and select. R2 is honoured: the `demoClaimCapabilitiesReady` seam is at `demo_claim_target.go:73`. - **Task 1 follow-ups.** All three are folded in: the explicit `explicit` parameter, the first-sign-in audit with no session, and the 429 `errDemoClaimSignupBusy`. - **No source effects.** Reservation does not freeze, call a box or publish. - **Status after reservation.** It returns 202 `claiming`/`reserved`. - **Files outside the Modify list.** `apicli.go:228` and `apiinstances.go:1806` were not edited. They are covered through the shared gates instead. I checked that `handleAPIShip`, `handleAPIPromote`, `handleAPITrashApp`, `handleAPIRunCreate` and `handleAPIPipelinePut` all go through `apiAccountApp`. `handleAPIInstanceCreate` goes through `instanceGate`, which calls `apiAccountAppSaying` (`apicli.go:94`). Browser writes go through `accountApp` (`server.go:4318`). - **Placement check.** `region != s.cfg.Region` (`demo_claim_target.go:134`) is correct. Both values use the record vocabulary, where "" is the home region (`server.go:661-665`). The same comparison is used at `apiinstanceimport.go:133`. - ⚠️ **Cannot verify from the diff:** - Whether the over-cap grace pass or account deletion would hit a pending target through a door that skips the shared gates. - That Task 4/5 will create the destination record with exactly `op.Target.Host`. The counting key `app+"/"+host` depends on it. 2) **Findings** **P2-1. A Task 1 proof-binding test now passes no matter what the code does.** - **Where:** `internal/console/demo_claim_store_test.go:208` (`TestDemoClaimProofIdentity/staleLifetimeAndGeneration`). - **Problem:** The test asserts `claimVerify(...).Code == 200 → Fatal`. After this task, a successful verify returns 202 (claiming) or 200 only for `account_required`. The test has no `claimNoProof` backstop, unlike lines 77 and 139 and `auth_test:340`. - **Failure scenario:** `proveDemoClaim` stops rechecking lifetime or generation. Verify then answers 202, or 503 when the reservation's own recheck refuses. The test still passes, so the stale-binding witness for Review Focus 1 is gone. - **Fix:** Assert `w.Code == 401` and call `claimNoProof(t, s, flow)` inside the loop. - **Fault family:** proof binding (a code for another lifetime or generation grants nothing). **P3 (follow-ups)** 1. **A failed pipeline write fails the request even though the reservation stands.** - **Where:** `finishDemoClaimReservation` (`demo_claim_target.go:224-232`). - **Problem:** A pipeline write failure becomes a 503 "Try again". The reservation is already durable, and status already reports `claiming/reserved`. - **Why it matters:** On the verify path the code is already used up, so a retry gets 401. A freshly minted personal account's sqid was never sent to the client, so it cannot retry through select either. - **Fix:** The ordinary create (`server.go` after `ensureAccountManifest`) treats `SetPipeline` failure as log-only. Do the same here: log it, return 202, and let Task 5 recovery re-ensure the pipeline. - **Fault family:** retry semantics. 2. **Misleading 503s for permanent conditions.** - **Where:** `demoClaimAccountError` maps `ErrDemoToken` (expired or retired demo, stale flow) to 503 `demoClaimReserveFailed`. Separately, `claimReserved`/`claimInvalid` outcomes return 503 instead of a clear refusal (`demo_claim_target.go:~176`). - **Why it matters:** These invite pointless retry loops. - **Fix:** Use `demoError(w, ErrDemoToken)` for the first case. 3. **Materialisation logs a failure for every pending claim.** - **Where:** The `settleApp` guard (`settle.go:78`) returns an error for a pending target. - **Why it matters:** `materializeAppsJudged` (`lifetimes_purge.go:323`) then logs and calls `jobFailed` for each pending claim. For a live, unmarked row, settle would do nothing anyway. - **Fix:** Return nil for pending targets, like the existing `DemoID` early return. 4. **The guard hides a programming-error signal in claims mode.** - **Where:** The `withAutoAppSQL` guard (`claim_sql_auto.go:15`) runs before the `outerInsideView` check. - **Why it matters:** An outer-store call made inside a view now reports "unavailable" instead of `errOuterStoreInView`. Demo claims refuse claims mode anyway. - **Fix:** Move the guard after that check. 5. **The record-lock guard can never pass the operation's own context.** - **Where:** `withRecordLock` checks the guard with `context.Background()`. - **Why it matters:** Task 4/5's operation-owned destination record write must use a create path that passes its context (`createRecordMarked`/the lifetime create). This should be recorded in the Task 5 brief. 6. **The isolation test checks labels, not doors.** - **Where:** `TestDemoClaimTargetIsolation`'s action loop only calls `appMutation` with label strings. - **Mitigation:** The real door coverage is the shared `apiAccountApp` HTTP witness plus the service-mint witness. That is acceptable, but the loop proves less than its names suggest. 7. **Bucket reads under the source demo app lock.** - **Problem:** The source demo app lock is held across up to 17 rounds of name checks (`apexHolder`, prefix list, policy read) plus a channel and manifest read. - **Why it matters:** The demo's own lifecycle paths wait meanwhile. It's not a protocol breach, since this is bucket I/O and not a transfer wait. 3) **Strengths** - **Atomic reservation.** One SQLite transaction (`reserveDemoClaimRows`) under the demo writer lock writes the app row, the `demo_claim_op` marker and the op row. It rechecks membership/role, account liveness, flow expiry, lifetime, generation, token, serving switch and active job, with partial unique indexes as backstops. - **Counting.** It reuses the ordinary `runningThings` and subtracts only the app/record already counted. Trashed or missing destinations keep both slots. Retry reuses the op without rechecking caps. - **Account choice.** It is exact-sqid only, ignores MRU, and returns an identical `http.NotFound` (with no-store from the gate) for foreign, deleted, name, missing and empty IDs. The person lock is held for minting with `checkNewFreeAccount`. - **Ordinary create unchanged.** Extracting `validateClaimAppName` is behaviour-preserving for ordinary creates. The claim passes `ownerClaim=false`, uses no client destination, and skips names with a stale policy rather than clearing it. - **Lock order.** It follows the protocol: person lock for mint only, then the account, then sorted app locks, then hostname, then the SQLite writer. 4) **Verdict: READY AFTER FIXES** (P2-1).</result> <usage><subagent_tokens>171356</subagent_tokens><tool_uses>47</tool_uses><duration_ms>495548</duration_ms></usage> </task-notification>
Attributed to this commit: 5.61 g CO₂e (641,119 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/demo_claim_auth_test.go b/internal/console/demo_claim_auth_test.go| index 1975e085a..51bfe9eca 100644 |
| --- a/internal/console/demo_claim_auth_test.go |
| +++ b/internal/console/demo_claim_auth_test.go |
| @@ -85,12 +85,12 @@ func claimVerify(s *Server, flow, code string) *httptest.ResponseRecorder { |
| } |
| func claimNoProof(t *testing.T, s *Server, raw string) { |
| t.Helper() |
| - f, err := s.store.demoClaimFlow(t.Context(), raw, time.Now()) |
| - if err != nil { |
| + var person, method string |
| + if err := s.store.db.QueryRowContext(t.Context(), `SELECT person,method FROM demo_claim_flows WHERE hash=?`, hashToken(raw)).Scan(&person, &method); err != nil { |
| t.Fatal(err) |
| } |
| - if f.Person != "" || f.Method != "" { |
| - t.Fatalf("unexpected proof: %+v", f) |
| + if person != "" || method != "" { |
| + t.Fatalf("unexpected proof: person=%q method=%q", person, method) |
| } |
| } |
diff --git a/internal/console/demo_claim_store_test.go b/internal/console/demo_claim_store_test.go| index 0f2e7da82..61d612995 100644 |
| --- a/internal/console/demo_claim_store_test.go |
| +++ b/internal/console/demo_claim_store_test.go |
| @@ -202,12 +202,23 @@ func TestDemoClaimProofIdentity(t *testing.T) { |
| s, m, token := claimTestServer(t) |
| flow, _ := claimStart(t, s, token, "shop@example.com", "") |
| code, _ := claimMail(t, s, m) |
| + bound, err := s.store.demoClaimFlow(t.Context(), flow, time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| if _, err := s.store.db.Exec(query); err != nil { |
| t.Fatal(err) |
| } |
| - if claimVerify(s, flow, code).Code == 200 { |
| - t.Fatalf("accepted stale binding: %s", query) |
| + if w := claimVerify(s, flow, code); w.Code != 401 { |
| + t.Fatalf("stale binding: %s: got %d %s, want 401", query, w.Code, w.Body) |
| + } |
| + claimNoProof(t, s, flow) |
| + // Also exercise a binding read before the source changed, as can |
| + // happen between the handler's first read and proof consumption. |
| + if _, err := s.proveDemoClaim(t.Context(), bound, MethodEmail, bound.Address, "192.0.2.10", time.Now()); !errors.Is(err, ErrDemoToken) { |
| + t.Fatalf("stale proof recheck: %s: got %v, want ErrDemoToken", query, err) |
| } |
| + claimNoProof(t, s, flow) |
| } |
| }) |
| } |
diff --git a/internal/console/demo_claim_target.go b/internal/console/demo_claim_target.go| index 3e7436a24..8feb3b81d 100644 |
| --- a/internal/console/demo_claim_target.go |
| +++ b/internal/console/demo_claim_target.go |
| @@ -6,6 +6,7 @@ import ( |
| "database/sql" |
| "errors" |
| "fmt" |
| + "log" |
| "net/http" |
| "os" |
| "sort" |
| @@ -172,6 +173,10 @@ func (s *Server) reserveDemoClaim(ctx context.Context, f claimFlow, acct *Accoun |
| case claimOK: |
| case claimTaken, claimApexHeld: |
| return claimOp{}, ErrDemoNameTaken |
| + case claimReserved: |
| + return claimOp{}, ErrDemoBusy |
| + case claimInvalid: |
| + return claimOp{}, ErrDemoToken |
| default: |
| return claimOp{}, errors.New(demoClaimReserveFailed) |
| } |
| @@ -226,12 +231,14 @@ func (s *Server) reserveDemoClaim(ctx context.Context, f claimFlow, acct *Accoun |
| func (s *Server) finishDemoClaimReservation(ctx context.Context, op claimOp) error { |
| // The durable reservation and marker already exist. A failed external write |
| - // retains both slots. Retrying writes the same default pipeline and target. |
| + // retains both slots. Task 5 recovery re-ensures the default pipeline. |
| if op.Phase != "reserved" { |
| return nil |
| } |
| - _, err := release.SetPipeline(withDemoClaimOperation(ctx, op.ID), s.cfg.Releases, s.cfg.Key, op.Target.Sqid, op.Target.App, release.DefaultPipelineChannels(), op.Person) |
| - return 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) |
| + } |
| + return nil |
| } |
| type demoClaimOperationKey struct{} |
| @@ -260,6 +267,8 @@ func (s *Server) demoClaimMutationRefusal(ctx context.Context, accountID int64, |
| func (s *Server) demoClaimAccountError(w http.ResponseWriter, r *http.Request, err error) { |
| switch { |
| + case errors.Is(err, ErrDemoToken): |
| + demoError(w, ErrDemoToken) |
| case errors.Is(err, errDemoClaimAccount): |
| http.NotFound(w, r) |
| case isPlanCap(err): |
diff --git a/internal/console/demo_claim_target_test.go b/internal/console/demo_claim_target_test.go| index e8f951454..c805ed5c6 100644 |
| --- a/internal/console/demo_claim_target_test.go |
| +++ b/internal/console/demo_claim_target_test.go |
| @@ -315,8 +315,9 @@ func TestDemoClaimTargetIsolationPartialReservation(t *testing.T) { |
| a := claimAccount(t, s, 501, f.Person, RoleOwner) |
| bucket := &claimPipelineFailure{Store: s.cfg.Releases, fail: true} |
| s.cfg.Releases = bucket |
| - if _, err := s.reserveDemoClaim(t.Context(), f, a, regionReq{}); err == nil { |
| - t.Fatal("expected external write failure") |
| + w := claimPost(s, "/api/demo/claims/select", map[string]string{"flowToken": raw, "accountId": a.Sqid}) |
| + if w.Code != 202 || !strings.Contains(w.Body.String(), `"state":"claiming"`) || !strings.Contains(w.Body.String(), `"phase":"reserved"`) { |
| + t.Fatalf("pipeline failure response: %d %s", w.Code, w.Body) |
| } |
| op, err := s.store.demoClaimOpForFlow(t.Context(), f.Hash) |
| if err != nil { |
| @@ -339,6 +340,9 @@ func TestDemoClaimTargetIsolationPartialReservation(t *testing.T) { |
| if err != nil || got.ID != op.ID || got.Target != op.Target { |
| t.Fatalf("retry changed identity: %+v %v", got, err) |
| } |
| + if p, err := release.GetPipeline(t.Context(), s.cfg.Releases, s.cfg.ReleasePub, op.Target.Sqid, op.Target.App); err != nil || p == nil || p.Entry() != "edge" { |
| + t.Fatalf("retry did not ensure default pipeline: %+v %v", p, err) |
| + } |
| if _, err := s.store.db.Exec(`UPDATE demo_claim_flows SET expires_at=1 WHERE hash=?`, f.Hash); err != nil { |
| t.Fatal(err) |
| } |
| @@ -353,6 +357,62 @@ func TestDemoClaimTargetIsolationPartialReservation(t *testing.T) { |
| } |
| } |
| +func TestDemoClaimReservationRefusals(t *testing.T) { |
| + for _, tc := range []struct { |
| + name, query, message string |
| + status int |
| + }{ |
| + {"reservedName", `UPDATE demo_apps SET name='new'`, demoClaimPending, 409}, |
| + {"invalidName", `UPDATE demo_apps SET name='invalid/name'`, demoCopy["DEMO-TOKEN"], 401}, |
| + {"expired", `UPDATE apps SET expires_at=1 WHERE demo_id<>''`, demoCopy["DEMO-TOKEN"], 401}, |
| + {"retired", `UPDATE demo_apps SET state='retiring'`, demoCopy["DEMO-TOKEN"], 401}, |
| + {"staleFlow", `UPDATE demo_apps SET generation=generation+1`, demoCopy["DEMO-TOKEN"], 401}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + f, _ := claimProved(t, s, token, "shop@example.com") |
| + a := claimAccount(t, s, 501, f.Person, RoleOwner) |
| + if _, err := s.store.db.Exec(tc.query); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, err := s.reserveDemoClaim(t.Context(), f, a, regionReq{}) |
| + if err == nil { |
| + t.Fatal("reservation accepted") |
| + } |
| + w := httptest.NewRecorder() |
| + s.demoClaimAccountError(w, httptest.NewRequest("POST", "/api/demo/claims/select", nil), err) |
| + if w.Code != tc.status || !strings.Contains(w.Body.String(), tc.message) { |
| + t.Fatalf("refusal: %d %s, want %d %q", w.Code, w.Body, tc.status, tc.message) |
| + } |
| + if n, err := s.runningThings(t.Context(), a); err != nil || n != 0 { |
| + t.Fatalf("refusal reserved capacity: %d %v", n, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimSettlePendingTarget(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + f, _ := claimProved(t, s, token, "shop@example.com") |
| + a := claimAccount(t, s, 501, f.Person, RoleOwner) |
| + op, err := s.reserveDemoClaim(t.Context(), f, a, regionReq{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := release.TrashApp(t.Context(), s.cfg.Releases, a.Sqid, op.Target.App, f.Person, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + unlock := s.lockApp(a.Sqid, op.Target.App) |
| + defer unlock() |
| + if err := s.settleApp(t.Context(), a.ID, a.Sqid, op.Target.App, time.Now(), always(true)); err != nil { |
| + t.Fatalf("pending claim must be skipped: %v", err) |
| + } |
| + life, err := s.store.AppLife(a.ID, op.Target.App) |
| + if err != nil || life == nil || life.Trashed() || life.Lifetime != op.Target.Lifetime { |
| + t.Fatalf("settle changed pending target: %+v %v", life, err) |
| + } |
| +} |
| + |
| func TestDemoClaimTargetIsolationHTTP(t *testing.T) { |
| s, _, token := claimTestServer(t) |
| s.cli = newCLILimits() |
diff --git a/internal/console/settle.go b/internal/console/settle.go| index 6f261d103..7daa8f396 100644 |
| --- a/internal/console/settle.go |
| +++ b/internal/console/settle.go |
| @@ -77,6 +77,9 @@ func (s *Server) doorEvidence(ctx context.Context) bool { |
| // An unreadable marker is an error and changes nothing. |
| func (s *Server) settleApp(ctx context.Context, accountID int64, sqid, app string, now time.Time, evidence evidenceFunc) error { |
| if ref := s.demoClaimMutationRefusal(ctx, accountID, app); ref != nil { |
| + if ref.Status == 409 { |
| + return nil // Claim recovery owns pending destinations. |
| + } |
| return fmt.Errorf("%s", ref.Msg) |
| } |
| if s.cfg.Releases == nil { |