carlos / platform Public

plan: platform accounts slice 1, Astra round 2 fixes

r2-1: customer creation and account deletion serialize on a dedicated
platform lifecycle lock instead of the account lock; the order is
lifecycle, then account/plan, then billing, and a deterministic test
covers deletion interleaved with a domain purchase.
r2-2: revoking a grant also marks its credential rows revoked in the
same transaction; the generation check stays the authorization rule.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev a63af377e49f811d7bf2a16732b4135e63114c7b parent f33cb87
1 file changed, +63 −21
  • docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md +63 −21

Intent

Attributed to this commit: 3.91 g CO₂e (458,003 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-platform-accounts, 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/docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md b/docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md
index b37294b5a..43312dfbe 100644
--- a/docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md
+++ b/docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md
@@ -16,12 +16,17 @@ Round 1 (Astra, findings `docs/superpowers/plans/ASTRA-FINDINGS-platform-account
- **r1-1 (P1), one live account per platform reference; pending creates use capacity.** Confirmed: `NextAccountID` (`mint.go:141-193`) counts a stranded manifest, so a retry after a failed row insert minted a second account, and Task 4's ref-drop on birth then kept both. Fix, one invariant in two halves: the console records a **pending mint** (its own random mint id, the ref, the name, the plan) in SQLite before the bucket write, and counts pending mints against `max_customers`; the bucket half is that `MintLinkedAccount` is **idempotent on the mint id**, which it writes into the manifest (`platform_mint`) and finds again in the scan it already does. Any later platform request finishes pending mints first, under the platform lock, so a retry, a ref-less create or a console restart all converge on the one account. Tasks 2, 4, 8.
- **r1-2 (P1), re-granting must not restore authority issued before a revoke.** Confirmed: the bearer resolves once before the handler (`authcli.go:503`), so a mint could insert after the revoke's row sweep. Fix: the grant carries a **generation** that every revoke increments. Every platform-role and per-customer credential row records the generation it was minted under; resolution accepts a row only while its generation is the grant's current active one, and the mint checks the same thing inside its insert transaction. The row sweep is dropped: the generation check is the one place this is enforced. Tasks 4, 7, 10.
-- **r1-3 (P1), a platform with customers cannot be retired.** Confirmed: `deleteAccountNow` (`ownership.go:183-223`) checks, tombstones, then deletes, and a tombstoned live account is reaped at start (`materialize.go:125-138`). Fix: deletion and customer creation serialize on the same `s.lockAccount(platform sqid)`; `deleteAccountNow` takes it before its re-check, and customer create re-reads the platform and its grant after taking it. Pending mints count as customers in the deletion check. Tasks 8, 9.
+- **r1-3 (P1), a platform with customers cannot be retired.** Confirmed: `deleteAccountNow` (`ownership.go:183-223`) checks, tombstones, then deletes, and a tombstoned live account is reaped at start (`materialize.go:125-138`). Fix: deletion and customer creation serialize on one lock, and customer create re-reads the platform and its grant after taking it. Pending mints count as customers in the deletion check. Round 1 used `s.lockAccount`; round 2 replaced it with the platform lifecycle lock (Astra r2-1). Tasks 8, 9.
- **r1-4 (P1), refused service requests must not write control-plane policy.** Confirmed: `writeEnableManifest` writes, audits and bumps the serial (`apiinstances.go:3841-3857`) and the service control-plane refusal comes later, in the create handler (`:1597`); the create also takes `beginCopiesMutation` itself (`:2626`). Fix: the platform-host door **writes no manifest at all**. Reconcile already serves a record whose app has no manifest (`provision/reconcile.go:1628-1636`: "the manifest only governs the API door"; absent is "no seed", "no policy"), so the door hands the create handler an in-memory default manifest through a request-context value that only `instanceManifest` reads. Every write is then the create handler's own, after its own refusals and under its own locks. Task 12.
- **r1-5 (P2), the witness must tell refusal from absence.** Confirmed: `apiAccountAppSaying` 404s a missing app (`apicli.go:95-101`), so probing `c2/site` when only `c1` has `site` proves nothing. Fix: both customers get `site`, each through its own credential, each shown working before the cross-account reads and writes are asserted. Tasks 10, 14.
Declined: none.
+Round 2 (Astra, findings `docs/superpowers/plans/ASTRA-FINDINGS-platform-accounts-1-r2.md`, reviewed at `9b4c07a2`): NOT READY, one P1 and one P2, both introduced by round 1's fixes. Citations re-read; both accepted.
+
+- **r2-1 (P1), account and billing locks have one acquisition order.** Confirmed: `startDomainPurchase` takes `planLock` (`domainbuy.go:131`), which with plans on is `lockAccount`, and then `holdBilling` (`:165`); the deletion path holds the billing hold across `deleteAccountNow` (`ownership.go:139-144`), so r1-3's account lock inside `deleteAccountNow` could deadlock with a purchase. Fix: r1-3's serialization moves off the account lock onto a **dedicated platform lifecycle lock** (`s.lockPlatformLifecycle(sqid)`), taken by customer creation (including finishing pending mints), by account deletion (platform and customer) and by nothing else. Deletion takes it in `handleDeleteAccount` before `retireForDeletion`'s billing hold, and `deleteAccountNow` takes no account lock. The global order, written into the lock comments: **platform lifecycle → account/plan → billing**. `startDomainPurchase` already takes account/plan before billing, and deletion takes lifecycle, then billing, and no account lock, so no two paths take any pair in opposite orders. The coordinator's steer gave the tail as "billing, then account/plan"; the code takes them the other way round (`domainbuy.go:131` then `:165`), so the plan records the order the code actually has. Tasks 8, 9.
+- **r2-2 (P2), credential management agrees with authentication.** Confirmed: `ServicePrincipals` filters on `revoked_at = 0` only (`svcprincipal.go:456-465`), rotation matches the same rows and keeps the generation (`:486-505`), and name reservation counts live rows (`:422`, backed by `authstore.go:326`). Fix: the generation check stays the authorization rule (it is what refuses an in-flight mint), and `RevokePlatformGrant` additionally marks every platform-role and per-customer row of the platform revoked **in the same transaction** that ends the generation. Listing, rotation and name reuse then see what authentication sees. Tasks 4, 7.
+
## Global Constraints
House rules (from the brief, verbatim where they are rules):
@@ -43,7 +48,8 @@ From the spec and AGENTS.md:
- Per-customer credentials: kind `platform`; role Publish (account-wide, no app) or Deploy (one app, rungs required); expiry default 1 h, at most 24 h, at least 1 minute; checked on every request against a live link and an active grant.
- Revoking a grant refuses the platform credential and every per-customer credential from the next request, read doors included. Links stay; sites keep serving. A credential is valid only under the grant generation it was minted in, and re-granting starts a new generation (Astra r1-2).
- The ops account (`OpsAccountID`, `domains.ReservedAccountID`) and any linked account can never hold a grant.
-- A platform account is never deleted while it has a live linked customer or a pending mint; deletion and customer creation take the same account lock (Astra r1-3).
+- A platform account is never deleted while it has a live linked customer or a pending mint; deletion and customer creation take the same platform lifecycle lock (Astra r1-3, r2-1).
+- Lock order (Astra r2-1): platform lifecycle → account/plan (`lockAccount`, `planLock`) → billing hold. Nothing takes a lock earlier in this list while holding a later one.
- One live account per (platform, ref), and a pending mint uses capacity until it is finished (Astra r1-1).
- A refused request writes nothing: no manifest, no audit row, no serial bump (Astra r1-4).
- Test seams are unexported `Server` func fields, nil in production, the `lapseBeforeConverge` precedent (`plangracepass.go:177`).
@@ -289,7 +295,7 @@ var (
func (s *Store) migratePlatformAccounts() error
func (s *Store) PlatformGrant(ctx context.Context, accountID int64) (*PlatformGrant, error) // nil, nil: none
func (s *Store) PutPlatformGrant(ctx context.Context, g PlatformGrant, now time.Time) error // upsert, state active, revoke fields cleared
-func (s *Store) RevokePlatformGrant(ctx context.Context, accountID int64, by, reason string, now time.Time) (credentials int, err error) // credentials: live rows of the ending generation, counted, not swept
+func (s *Store) RevokePlatformGrant(ctx context.Context, accountID int64, by, reason string, now time.Time) (credentials int, err error) // credentials: rows it marked revoked
func (s *Store) AccountPlatform(ctx context.Context, accountID int64) (platformSqid, ref string, err error) // "" when unlinked or unknown
func (s *Store) LinkedCustomers(ctx context.Context, platformSqid string) ([]LinkedCustomer, error) // live only, by id
func (s *Store) LinkedCustomer(ctx context.Context, platformSqid, customerSqid string) (*LinkedCustomer, error) // nil when not this platform's
@@ -348,9 +354,10 @@ The link column holds the platform's sqid, not its id, so materialization (Task
```go
func TestPlatformGrantRoundTrip(t *testing.T) // Put, read back every field; second Put re-grants (state active, revoke fields "", generation unchanged)
-func TestRevokePlatformGrantEndsItsGeneration(t *testing.T) { // (Astra r1-2)
- // grant gen 1; rows of gen 1: kind 'platform' platform_account_id=P (2), kind 'service' role 'platform' account_id=P (1);
- // RevokePlatformGrant(P) returns 3, generation 2, state "revoked", no cli_tokens row changed.
+func TestRevokePlatformGrantEndsItsGeneration(t *testing.T) { // (Astra r1-2, r2-2)
+ // grant gen 1; rows: kind 'platform' platform_account_id=P (2), kind 'service' role 'platform' account_id=P (1),
+ // kind 'service' role 'publish' account_id=P (1), kind 'platform' platform_account_id=Q (1).
+ // RevokePlatformGrant(P) returns 3, generation 2, state "revoked"; exactly those three rows have revoked_at != 0.
// PlatformGenerationLive(P, 1) false; PutPlatformGrant again: (P, 2) true, (P, 1) still false.
}
func TestPendingMintsCountAndHoldTheirRef(t *testing.T) { // (Astra r1-1)
@@ -388,7 +395,7 @@ func TestMigrateIsIdempotentWithPlatformTables(t *testing.T) // Open, Close, Ope
- `EnsureLinkedAccount`: `EnsureAccount`'s body (share an unexported helper) plus the two columns; inside its transaction, a ref already held by a live account of the same platform is dropped to `""` before the insert, so the unique index can never turn a birth into an ignored insert. No sponsorship either.
- `DeleteAccount` (`ownership.go:790`): inside its transaction, before the deletes, count live accounts whose `platform` is this account's sqid plus its pending mints; non-zero is `ErrPlatformHasCustomers` (Astra r1-3).
- `DeleteUnclaimedCustomer`: one transaction: the row must be live with `platform = platformSqid` (else `ErrAccountGone`); owner count 0 (else `ErrCustomerClaimed`); `apps` count 0, unfiltered like `AppCount` (else `ErrCustomerHasApps`); then the same statements as `DeleteAccount`. No token sweep: a deleted account fails the link check every credential resolution makes (Task 10).
- - `RevokePlatformGrant` (Astra r1-2): one transaction: count live rows minted under the current generation (`(kind = 'platform' AND platform_account_id = ?) OR (kind = 'service' AND role = 'platform' AND account_id = ?)`, `platform_generation = ?`, unrevoked, unexpired), then set state revoked and `generation = generation + 1`. It touches no `cli_tokens` row: the generation check is what ends them, in the one place every resolution and every mint asks. A missing grant is `ErrNotPlatform`. `PutPlatformGrant` never changes the generation, so a re-grant after a revoke runs under the new one.
+ - `RevokePlatformGrant` (Astra r1-2, r2-2): one transaction: set state revoked and `generation = generation + 1`, and `UPDATE cli_tokens SET revoked_at = ? WHERE revoked_at = 0 AND ((kind = 'platform' AND platform_account_id = ?) OR (kind = 'service' AND role = 'platform' AND account_id = ?))`, returning that count. Two rules, two jobs: the generation check is **authorization** (every resolution and every mint asks `PlatformGenerationLive`, so a mint in flight across the revoke is refused even though its row did not exist when the sweep ran); the sweep is **bookkeeping**, so listing, rotation and name reservation, which read `revoked_at`, agree with authentication. A missing grant is `ErrNotPlatform`. `PutPlatformGrant` never changes the generation, so a re-grant after a revoke runs under the new one.
- [ ] **Step 5: Run** the Step 2 command, then the existing migration and deletion tests: `go test ./internal/console/ -run 'TestOpen|TestMigrate|TestDeleteAccount|TestEnsureAccount' -count=1`. Expected: PASS.
@@ -517,10 +524,16 @@ func TestPlatformCredentialFromAnEndedGenerationIsRefused(t *testing.T) { // (As
// mint P under gen 1; RevokePlatformGrant; PutPlatformGrant (gen 2, active): P -> 401 at a platform door;
// a fresh mint now resolves with PlatformGeneration 2.
}
+func TestRevokedPlatformCredentialIsGoneFromManagement(t *testing.T) { // (Astra r2-2)
+ // owner mints "cms" (role platform); RevokePlatformGrant; PutPlatformGrant. Then, in order:
+ // GET /api/cli/services/<p> does not list "cms"; POST .../services/<p>/cms/rotate -> 404 (ErrNoServicePrincipal),
+ // no token issued; POST /api/cli/services/<p> {name:"cms", role:"platform"} -> 201; the new token resolves with
+ // PlatformGeneration 2 and reaches GET /api/cli/platform/<p>/customers -> 200; the old token still -> 401.
+}
func TestBrowserMintFormDoesNotOfferPlatform(t *testing.T) // servicePane's ServiceRoles has no "platform"
```
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestServicesDoorMintsAPlatform|TestPlatformCredentialTakesNoApp|TestPlatformRoleRowWithAnApp|TestRowWithAPlatformAccountID|TestPlatformCredentialFromAnEndedGeneration|TestBrowserMintFormDoesNotOfferPlatform' -count=1`. Expected: FAIL.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestServicesDoorMintsAPlatform|TestPlatformCredentialTakesNoApp|TestPlatformRoleRowWithAnApp|TestRowWithAPlatformAccountID|TestPlatformCredentialFromAnEndedGeneration|TestRevokedPlatformCredentialIsGoneFromManagement|TestBrowserMintFormDoesNotOfferPlatform' -count=1`. Expected: FAIL. (The management test needs Task 8's customer list door; until Task 8 lands, assert the new token's resolution instead of the GET, and Task 8's Step 4 re-runs it.)
- [ ] **Step 3: Implement.** In `claimRawNewServicePrincipalScoped` (`svcprincipal.go:355`), beside the Service rule: Platform with an app is `ErrAppScopedPlatform`; inside the existing transaction, read the grant: missing or not active is `ErrNotPlatform`; otherwise insert with that generation (Astra r1-2). The services door is person-only, so a mint paused across a revoke and re-grant takes the generation current at its insert, which is the authority its owner holds then. Map both in `handleAPIServiceCreate` (`apiservices.go:256-299`) to 400 and 409 with the copy rows. Add `platform_account_id` and `platform_generation` to the `CLIPrincipalContext` SELECT and the checks above. `servicePane` skips `svcrole.Platform` when building `ServiceRoles`.
- [ ] **Step 4: Run** the Step 2 command plus `-run 'TestServiceCreate|TestCLIPrincipal'`. Expected: PASS.
- [ ] **Step 5: Commit**
@@ -575,7 +588,12 @@ git commit -m "console: mint platform credentials on granted accounts only"
func validPlatformRef(ref string) bool // 1-64 of [A-Za-z0-9._:-]
// finishPendingMints finishes every pending mint of the platform, oldest first: MintLinkedAccount
// with the mint's id (idempotent, Task 2), startNewAccountAnalytics, CreateLinkedAccount. The caller
- // holds s.lockAccount(platform.Sqid). It stops at the first failure and returns it (Astra r1-1).
+ // holds s.lockPlatformLifecycle(platform.Sqid). It stops at the first failure and returns it (Astra r1-1).
+ // lockPlatformLifecycle is the platform lifecycle lock (Astra r2-1): a keyedLocks field platformLocks on
+ // Server, in applocks.go, emitting lockEvent("platform", sqid, ...) like lockHostname does. Its comment
+ // states the order: platform lifecycle -> account/plan -> billing hold. Taken by customer creation, pending-mint
+ // finishing and account deletion, and nothing else.
+ func (s *Server) lockPlatformLifecycle(sqid string) func()
func (s *Server) finishPendingMints(ctx context.Context, platform *Account) error
// Test seam, nil in production: called with "lock" just before create takes the platform lock,
// "mint" before MintLinkedAccount and "finish" before CreateLinkedAccount; a non-nil error is
@@ -584,12 +602,12 @@ git commit -m "console: mint platform credentials on granted accounts only"
```
- List reply `{"platform": sqid, "max_customers": n, "count": n, "customers": [...]}`; create reply 201 `{"created": true, "customer": view}` or 200 `{"created": false, "customer": view}` on a ref hit.
-`platformGate` order: `apiPrincipalAccount` (service binding or membership; the family's 404) → a person who is not an owner gets 403 `door.not_owner` → `PlatformGrant` missing is 403 `door.not_platform`, revoked is 403 `door.revoked` (a service principal of an ended generation never gets here: resolution refused it, Task 7) → when the platform has pending mints, take `s.lockAccount(platform.Sqid)`, run `finishPendingMints`, and release the lock before the handler runs (the lock is not re-entrant; create takes it again in its step 2); on a read door a failure is logged and the request goes on, on a write door it is 502 `create.failed` (Astra r1-1). One indexed query when there are none. `platformCustomer`: `LinkedCustomer(platform.Sqid, PathValue("customer"))` nil is the stdlib 404, whatever the reason.
+`platformGate` order: `apiPrincipalAccount` (service binding or membership; the family's 404) → a person who is not an owner gets 403 `door.not_owner` → `PlatformGrant` missing is 403 `door.not_platform`, revoked is 403 `door.revoked` (a service principal of an ended generation never gets here: resolution refused it, Task 7) → when the platform has pending mints, take `s.lockPlatformLifecycle(platform.Sqid)`, run `finishPendingMints`, and release the lock before the handler runs (the lock is not re-entrant; create takes it again in its step 2); on a read door a failure is logged and the request goes on, on a write door it is 502 `create.failed` (Astra r1-1). One indexed query when there are none. `platformCustomer`: `LinkedCustomer(platform.Sqid, PathValue("customer"))` nil is the stdlib 404, whatever the reason.
Create, in order. The invariant (Astra r1-1): **one live account per (platform, ref), and a promised account uses capacity from the moment it is promised until it exists.** It holds because the promise (`ReservePlatformMint`) is written before the bucket is touched, the bucket write is idempotent on the promise's id, and every path finishes promises before it reads capacity or refs.
1. Decode `{name, ref, plan}` → `ValidAccountName` (`create.name`) → `ref == "" || validPlatformRef` (`create.ref`) → plan: empty means `Grant.DefaultPlan`; non-empty must be in `Grant.Plans` (`create.plan`); with no catalog a named plan is `create.no_catalog_plan`.
-2. Take `s.lockAccount(platform.Sqid)`, the lock platform deletion also takes (Astra r1-3). Under it, re-read: `AccountByIDContext(platform.ID)` nil is the stdlib 404, and the grant must still be active with the generation the gate saw, else 403 `door.revoked`. Nothing below runs for a platform being deleted or revoked.
+2. Take `s.lockPlatformLifecycle(platform.Sqid)`, the lock platform deletion also takes (Astra r1-3, r2-1). Hold no account/plan lock or billing hold while taking it. Under it, re-read: `AccountByIDContext(platform.ID)` nil is the stdlib 404, and the grant must still be active with the generation the gate saw, else 403 `door.revoked`. Nothing below runs for a platform being deleted or revoked.
3. `finishPendingMints` (502 `create.failed` on error). This is what makes a retry after a failed finish, or the first request after a restart, land on the account the first attempt minted.
4. A ref held by a live customer: answer 200 with it, spending nothing.
5. `allowCreate(P)` (`create.rate`, 429) → `LinkedCustomerCount >= MaxCustomers` (pending mints included) is 409 `create.cap`.
@@ -636,7 +654,7 @@ func TestCustomerCreateConvergesAcrossARestart(t *testing.T) { // (Astra r1-1)
// plan_source "platform" (the gate finished the mint over the materialized row); pending mints empty.
}
func TestCustomerCreateRechecksThePlatformUnderTheLock(t *testing.T) { // (Astra r1-3)
- // the test holds s.lockAccount(p), starts a create and waits for platformMintStep("lock"), deletes the
+ // the test holds s.lockPlatformLifecycle(p), starts a create and waits for platformMintStep("lock"), deletes the
// platform with Store.DeleteAccount (it has no customers yet), and releases: the create answers the stdlib 404
// and writes no manifest and no pending mint. Same with a revoke in place of the delete: 403 door.revoked.
}
@@ -663,7 +681,7 @@ git commit -m "console: platform doors to create, list and show customer account
### Task 9: Customer update and delete; platform accounts keep their customers
**Files:**
-- Modify: `internal/console/apiplatformcustomers.go`, `internal/console/routedecls.go`, `internal/console/ownership.go`, `internal/console/platformlinked.go` (create)
+- Modify: `internal/console/apiplatformcustomers.go`, `internal/console/routedecls.go`, `internal/console/ownership.go`, `internal/console/applocks.go`, `internal/console/billinghold.go` (lock events only), `internal/console/platformlinked.go` (create)
- Test: `internal/console/apiplatformcustomers_test.go`, `internal/console/platformlinked_test.go` (create)
**Interfaces:**
@@ -677,11 +695,15 @@ git commit -m "console: platform doors to create, list and show customer account
Update: write budget; nothing to change is 400 `update.empty`; a name runs `ValidAccountName`, then `domains.RenameAccountManifest` (bucket first), then `RenameAccount`, audit `audit.customer_rename`; a plan must be in `Grant.Plans` (`create.plan`), then `applyPlatformPlan` (`update.operator_plan` on refusal), audit `audit.customer_plan`. Empty reason becomes `fmt.Sprintf("platform %s", platform.Sqid)`.
-Delete: write budget; take `s.lockAccount(customer.Sqid)` for the rest; `LinkedCustomer.Owners > 0` is 409 `delete.claimed`; `AppCount > 0` is 409 `delete.apps`; then `tombstoneAccount` (bucket first, `ownership.go:672`), `s.manifestSeen.Delete`, `DeleteUnclaimedCustomer`, `auditAccountDeleted`. A bucket failure is 502 `delete.failed` and nothing is deleted. If `DeleteUnclaimedCustomer` refuses after the tombstone (an owner added box-side by `console member` in that window), log one line naming the account and answer 409 `delete.claimed`: the same accepted hazard `deleteAccountNow` documents (`ownership.go:196-201`), and the lock is what slice 2's claim must take to close it for claims.
+Delete: write budget; take `s.lockPlatformLifecycle(customer.Sqid)` for the rest (Astra r2-1: deletion takes the lifecycle lock, never the account lock); `LinkedCustomer.Owners > 0` is 409 `delete.claimed`; `AppCount > 0` is 409 `delete.apps`; then `tombstoneAccount` (bucket first, `ownership.go:672`), `s.manifestSeen.Delete`, `DeleteUnclaimedCustomer`, `auditAccountDeleted`. A bucket failure is 502 `delete.failed` and nothing is deleted. If `DeleteUnclaimedCustomer` refuses after the tombstone (an owner added box-side by `console member` in that window), log one line naming the account and answer 409 `delete.claimed`: the same accepted hazard `deleteAccountNow` documents (`ownership.go:196-201`), and the lock is what slice 2's claim must take to close it for claims.
Platform account deletion: `deletionRefused` (`ownership.go:161`) adds, before the app count, a refusal when `LinkedCustomerCount(acct.Sqid) > 0` (live customers and pending mints; flash `delete.platform_has_customers`), and a refusal for a linked account deleted by a person in the browser (flash `delete.linked`): until slice 2's leave, a linked account's end is its platform's door (decision D11).
-Serializing deletion with creation (Astra r1-3). The invariant: **no customer, pending or live, can appear between the deletion's last check and its tombstone.** `deleteAccountNow` (`ownership.go:183`) takes `s.lockAccount(acct.Sqid)` as its first line and holds it to the end, so its existing re-run of `deletionRefused` and the tombstone and `DeleteAccount` all happen while customer create (which takes the same lock before reserving, Task 8 step 2) cannot run; a create that was waiting re-reads the platform afterwards and finds it gone. Lock order: on the billing path `retireForDeletion` holds the billing hold (`billingretire.go:228`) and then `deleteAccountNow` takes the account lock; nothing in this plan, and no existing `lockAccount` caller found (`grep -n 's.lockAccount(\|s.planLock(' internal/console/*.go`), takes the billing hold while holding the account lock. `deleteAccountNow`'s callees take no account lock. The test seam `deleteBeforeTombstone func()` (nil in production) is called after the re-check, before `tombstoneAccount`.
+Serializing deletion with creation (Astra r1-3, r2-1). The invariant: **no customer, pending or live, can appear between the deletion's last check and its tombstone.** `handleDeleteAccount` (`ownership.go:101`) takes `s.lockPlatformLifecycle(acct.Sqid)` right after the typed-name check (`:123-127`) and holds it to the end of the request, so on both paths (billing on: `deletionRefused`, `retireForDeletion`, `deleteAccountNow`, `ownership.go:136-147`; billing off: `requireFreshAuth`, `deleteAccountNow`) the re-run of `deletionRefused`, the tombstone and `DeleteAccount` all happen while customer create (same lock, Task 8 step 2) cannot run; a create that was waiting re-reads the platform afterwards and finds it gone. It is taken for every account, platform or not: the key is the account being deleted, so unrelated deletions never contend.
+
+Lock order (Astra r2-1), stated in `lockPlatformLifecycle`'s comment and beside the billing branch of `handleDeleteAccount`: **platform lifecycle → account/plan → billing hold.** Deletion takes lifecycle, then billing (`retireForDeletion`, `billingretire.go:228`), and no account/plan lock: `deleteAccountNow` and its callees take none. `startDomainPurchase` takes account/plan (`domainbuy.go:131`), then billing (`:165`), and never lifecycle. Customer creation takes lifecycle only. So no two paths take a pair of these locks in opposite orders. The test seam `deleteBeforeTombstone func()` (nil in production) is called after `deleteAccountNow`'s re-check, before `tombstoneAccount`; it runs while lifecycle and (billing on) the billing hold are held.
+
+To let the test observe the interleaving without sleeps, `holdBilling` (`billinghold.go:81`) and `lockAccount` (`applocks.go`) emit `lockEvent("billing"|"account", sqid, lockWaiting|lockHeld|lockReleased)` around their acquisition, the existing `lifetimeLockHook` seam (`lifetimes.go:171-179`); with no hook installed this is one atomic load.
- [ ] **Step 1: Write the failing tests**
@@ -705,15 +727,35 @@ func TestCreateWaitsForAnInFlightPlatformDeletion(t *testing.T) { // (Astra r1-3
// waits; release the delete -> platform deleted; the create answers the stdlib 404; no customer manifest and
// no pending mint exist.
}
+func TestDeletionAndDomainPurchaseDoNotDeadlock(t *testing.T) { // (Astra r2-1), the reviewer's interleaving
+ // Fixture with billing on (the domain-buy test fake billing and registrar), plans on (so planLock is lockAccount),
+ // an account with one app. lifetimeLockHook records events onto a channel.
+ // 1. Browser delete of the account runs in a goroutine; deleteBeforeTombstone blocks it. It now holds the
+ // lifecycle lock and the billing hold.
+ // 2. startDomainPurchase for the same account runs in a goroutine. Wait for ("account", sqid, held) and then
+ // ("billing", sqid, waiting) from it: it holds the account lock and is waiting on billing, the reviewer's state.
+ // 3. Release the delete. Its done channel closes: it never emitted ("account", sqid, waiting).
+ // (With the r1-3 placement it would have waited on the account lock here, forever.)
+ // 4. The purchase's done channel closes: it got the billing hold after the delete released it and answers a
+ // refusal (the account is gone), with no purchase row and no billing customer.
+ // Every wait is a select on the event or done channel against one 10 s guard timer, so a deadlock fails the
+ // test instead of hanging it; there is no sleep. Run it 20 times in a loop inside the test.
+}
+func TestLockOrderLifecycleAccountBilling(t *testing.T) { // (Astra r2-1)
+ // Drive one request at a time (sequentially, so every event on a sqid belongs to that request): a customer
+ // create, a platform delete with billing on and with billing off, a domain purchase, an app create on a
+ // plan-capped account. lifetimeLockHook tracks which of platform, account, billing are held for the sqid and
+ // fails on any "waiting" for a lock earlier in the order while a later one is held.
+}
```
-- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestCustomerRename|TestCustomerPlanChange|TestCustomerDelete|TestPlatformAccountDeletionRefused|TestLinkedAccountBrowserDeletionRefused|TestPlatformDeletionWaitsForAnInFlightCreate|TestCreateWaitsForAnInFlightPlatformDeletion' -count=1`. Expected: FAIL.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestCustomerRename|TestCustomerPlanChange|TestCustomerDelete|TestPlatformAccountDeletionRefused|TestLinkedAccountBrowserDeletionRefused|TestPlatformDeletionWaitsForAnInFlightCreate|TestCreateWaitsForAnInFlightPlatformDeletion|TestDeletionAndDomainPurchaseDoNotDeadlock|TestLockOrderLifecycleAccountBilling' -count=1`. Expected: FAIL.
- [ ] **Step 3: Implement.**
-- [ ] **Step 4: Run** the Step 2 command plus `-run 'TestDeleteAccount|TestHandleDeleteAccount|TestAccountPlan'`. Expected: PASS.
+- [ ] **Step 4: Run** the Step 2 command plus `-run 'TestDeleteAccount|TestHandleDeleteAccount|TestAccountPlan|TestDomainBuy|TestBillingRetire|TestBillingHold'`. Expected: PASS.
- [ ] **Step 5: Commit**
```bash
-git add internal/console/apiplatformcustomers*.go internal/console/routedecls.go internal/console/ownership.go internal/console/platformlinked*.go internal/console/platform_copy.go
+git add internal/console/apiplatformcustomers*.go internal/console/routedecls.go internal/console/ownership.go internal/console/applocks.go internal/console/billinghold.go internal/console/platformlinked*.go internal/console/platform_copy.go
git commit -m "console: platforms rename, re-plan and delete unclaimed customers"
```
@@ -1185,9 +1227,9 @@ Cap names in usage reuse the approved `cliPlanCopyLimit*` labels (apps and insta
- D3. §6.3: Publish on the instance list plus one narrow `platform-host` door that writes no manifest (Astra r1-4), not the domains route (blocked on reserve consoles) and not opening `instances-manifest` (pinned by `policyDoors`).
- D4. The manifest also carries `platform_ref`, so ref idempotency survives a console rebuild.
- D5. Ref grammar: 1-64 of `A-Z a-z 0-9 . _ : -`, case-sensitive, unique per platform among live accounts.
-- D6. Revoking a grant ends its generation; every platform-role and per-customer credential is bound to the generation it was minted in, so a re-grant restores no old credential (Astra r1-2). No token rows are swept.
+- D6. Revoking a grant ends its generation; every platform-role and per-customer credential is bound to the generation it was minted in, so a re-grant restores no old credential (Astra r1-2). The same transaction marks those rows revoked so credential management agrees (Astra r2-2).
- D14. Customer creation records a pending mint before touching the bucket; pending mints count against `max_customers` and hold their ref until finished (Astra r1-1).
-- D15. Platform deletion and customer creation serialize on `s.lockAccount(platform sqid)` (Astra r1-3).
+- D15. Platform deletion and customer creation serialize on a dedicated platform lifecycle lock; the order is lifecycle → account/plan → billing (Astra r1-3, r2-1).
- D7. Budgets: customer create spends `allowCreate` (service 100 a day, person 10) except a ref hit, which spends nothing; update, delete and credential mint spend `allowWrite`.
- D8. TTL bounds 1 minute to 24 hours; `max_customers` 1 to 10000. Without a plan catalog a grant has no plans and customers get no plan row.
- D9. Linked accounts never take the launch sponsorship.
@@ -1207,7 +1249,7 @@ Cap names in usage reuse the approved `cliPlanCopyLimit*` labels (apps and insta
## Slice 2/3 hand-offs
Slice 2 (claim and leave) needs from slice 1:
-- `AccountPlatform`, `LinkedCustomer.Owners` (claimed = owners > 0), `DeleteUnclaimedCustomer`'s owner check, and `ErrCustomerClaimed`. Accepting a claim must hold `s.lockAccount(customer.Sqid)`, the lock the platform's delete door holds across its owner check and tombstone, or a claim can land between them.
+- `AccountPlatform`, `LinkedCustomer.Owners` (claimed = owners > 0), `DeleteUnclaimedCustomer`'s owner check, and `ErrCustomerClaimed`. Accepting a claim must hold `s.lockPlatformLifecycle(customer.Sqid)`, the lock the platform's delete door holds across its owner check and tombstone, or a claim can land between them; and it must take it before any account/plan lock or billing hold (the r2-1 order).
- Leave/release: clear `accounts.platform` and `platform_ref`, rewrite the manifest without `platform`/`platform_ref`/`platform_mint` keeping `owner` (a `domains` CAS helper beside `RenameAccountManifest`), revoke kind-platform rows for the account, set the plan row to the catalog default, and lift D11's browser deletion refusal and Task 13's billing refusal for the account (both read `AccountPlatform`, so clearing the column is enough).
- Claim must write `owner` into the manifest and teach materialization to adopt a late owner for linked accounts only (spec §7.4); `materializeOwner`'s birth-only rule is untouched by slice 1.
- How per-customer credentials appear to a claimed customer (D10): `ServicePrincipals` would add `cliKindPlatform`.