carlos / platform Public

platform accounts: back off held creates; sweep expired customer creds

Two follow-ups from #1295 that had to land before a platform runs in
production. A pending customer create the console refuses to finish
(bucket and console disagree) is now retried at most once every 5
minutes, so it no longer costs a bucket scan and a log line on every
platform request; a create for its own ref still refuses at once and
it still counts against the cap. Pruning re-reads pending mints under
the lifecycle lock. Expired app-bound per-customer credentials are
swept in their own statement when the claim gate is not armed. Runbook
timing copy approved by Luna. Reviewed by Astra (two rounds).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from platform-accounts-followups into main.
claude agent, operated by paul@keymail.dev 40d86b44c2412c76348b106c680ed1e8fc5a6897 parent e468866
8 files changed, +613 −23
  • approved_platform_accounts_copy_test.go +3 −3
  • docs/site/cli.md +3 −3
  • docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md +3 −3
  • internal/console/apiplatformcustomers.go +49 −7
  • internal/console/apiplatformcustomers_backoff_test.go +376 −0
  • internal/console/authstore.go +17 −4
  • internal/console/platform_credentials_test.go +45 −1
  • internal/console/platform_seams.go +117 −2

CI passed — run details

diff --git a/approved_platform_accounts_copy_test.go b/approved_platform_accounts_copy_test.go
index ef247b7b5..3156fe2b9 100644
--- a/approved_platform_accounts_copy_test.go
+++ b/approved_platform_accounts_copy_test.go
@@ -161,17 +161,17 @@ func TestApprovedPlatformAccountsCopy(t *testing.T) {
{"docs.platform_credentials.ttl", "docs/site/cli.md", "It lasts an hour unless you pass `--ttl`, up to 24 hours. It works only in that one account. It stops working when the platform’s access is turned off, or when the platform credential that minted it is revoked or rotated. Use it as `CARLOS_SERVICE_TOKEN`."},
{"docs.held_promise.heading", "docs/site/cli.md", "#### A customer create that stays pending"},
{"docs.held_promise", "docs/site/cli.md", "When a platform creates a customer account, the console first records a promise for the account. The promise holds the customer’s ref and a place in `--max-customers`. The console then writes the account to the deployment bucket and records it in the database. If the bucket and database disagree, the console stops the create and keeps the promise. Nothing else is written until an operator repairs the mismatch."},
- {"docs.held_promise.log_intro", "docs/site/cli.md", "While a promise is held, the console logs this line for every request from the platform:"},
+ {"docs.held_promise.log_intro", "docs/site/cli.md", "While a promise is held, the console logs this line at most once every 5 minutes, when the platform makes a request:"},
{"docs.held_promise.scope", "docs/site/cli.md", "Only that platform’s create requests are affected. It can still list customers, update them and use its credentials. A create for the held ref fails. If the reason is `is in this console with no manifest in the bucket`, every create on that platform fails because the bucket gives each new create the same id. The promise counts towards `--max-customers` until it is repaired."},
{"docs.held_promise.read", "docs/site/cli.md", "Read the promise and account from the console’s database first:"},
{"docs.held_promise.manifest_key", "docs/site/cli.md", "The account’s manifest is `accounts/<sqid>/account.json` in the deployment bucket."},
{"docs.held_promise.no_manifest", "docs/site/cli.md", "**The account has no manifest, or the create’s manifest is at its id.** The reason is `is in this console with no manifest in the bucket` or `is another account in this console`. Check that the manifest is missing, or that its `platform_mint` is the mint id and the account row’s `platform_mint` is not the mint id. Then restore the account’s manifest. Write `accounts/<sqid>/account.json` from the row: `id`, `sqid`, `name` and `created_at` as an RFC 3339 UTC time. Add `platform`, `platform_ref` and `platform_mint` when the row has them. Add `deleted_at` as an RFC 3339 UTC time when the row’s value is not 0."},
{"docs.held_promise.owner", "docs/site/cli.md", "If the row has no `platform`, also add `owner`, using the account’s first owner from the console’s memberships table. Find it with this query:"},
{"docs.held_promise.owner_stop", "docs/site/cli.md", "If the query returns no address, stop and escalate. Do not write the manifest. A rebuilt console would give the account no owner. For an account with a `platform`, leave `owner` out. It has no owner until someone claims it."},
- {"docs.held_promise.no_manifest_end", "docs/site/cli.md", "This replaces the create’s manifest if one is present. The platform’s next request creates the customer with a new id."},
+ {"docs.held_promise.no_manifest_end", "docs/site/cli.md", "This replaces the create’s manifest if one is present. After the repair, the console retries the create when the platform next requests it, with a delay of up to 5 minutes, and creates the customer with a new id."},
{"docs.held_promise.ref", "docs/site/cli.md", "**Another live customer holds the ref.** The reason starts with `holds ref` or `would take ref`. Check which account holds it:"},
{"docs.held_promise.ref_repair", "docs/site/cli.md", "If it is the customer the platform intended, the promise is stale. Search the bucket’s account manifests for `\"platform_mint\":\"<mint id>\"`. If one has that value, add `deleted_at` with the current UTC time. Do not delete the manifest: an account id is never given out twice. Then remove the promise:"},
- {"docs.held_promise.done", "docs/site/cli.md", "After the repair, the log line stops, and `carlos platform customers list --platform <platform>` shows the expected count."},
+ {"docs.held_promise.done", "docs/site/cli.md", "After the repair, the console retries the create on a platform request, with a delay of up to 5 minutes; once it succeeds, the log line stops and `carlos platform customers list --platform <platform>` shows the expected count."},
{"docs.held_promise.log_line", "docs/site/cli.md", "console: platform <platform>: pending customer create <mint id> held for account <id>: <reason>; repair the bucket or console"},
{"log.held_promise", "internal/console/apiplatformcustomers.go", "console: platform %s: pending customer create %s held for account %d: %s; repair the bucket or console"},
}
diff --git a/docs/site/cli.md b/docs/site/cli.md
index ef4213f98..dfae3413f 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -2697,7 +2697,7 @@ Turning platform access off stops the platform’s credentials at once. Its cust
When a platform creates a customer account, the console first records a promise for the account. The promise holds the customer’s ref and a place in `--max-customers`. The console then writes the account to the deployment bucket and records it in the database. If the bucket and database disagree, the console stops the create and keeps the promise. Nothing else is written until an operator repairs the mismatch.
-While a promise is held, the console logs this line for every request from the platform:
+While a promise is held, the console logs this line at most once every 5 minutes, when the platform makes a request:
```text
console: platform <platform>: pending customer create <mint id> held for account <id>: <reason>; repair the bucket or console
@@ -2724,7 +2724,7 @@ SELECT address FROM memberships WHERE account_id = <id> AND role = 'owner' ORDER
If the query returns no address, stop and escalate. Do not write the manifest. A rebuilt console would give the account no owner. For an account with a `platform`, leave `owner` out. It has no owner until someone claims it.
-This replaces the create’s manifest if one is present. The platform’s next request creates the customer with a new id.
+This replaces the create’s manifest if one is present. After the repair, the console retries the create when the platform next requests it, with a delay of up to 5 minutes, and creates the customer with a new id.
**Another live customer holds the ref.** The reason starts with `holds ref` or `would take ref`. Check which account holds it:
@@ -2738,7 +2738,7 @@ If it is the customer the platform intended, the promise is stale. Search the bu
DELETE FROM platform_pending_mints WHERE mint_id = '<mint id>';
```
-After the repair, the log line stops, and `carlos platform customers list --platform <platform>` shows the expected count.
+After the repair, the console retries the create on a platform request, with a delay of up to 5 minutes; once it succeeds, the log line stops and `carlos platform customers list --platform <platform>` shows the expected count.
### carlos accounts subdomain
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 4d822b1ba..ddfb723ca 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
@@ -1394,17 +1394,17 @@ Cap names in usage reuse the approved `cliPlanCopyLimit*` labels (apps and insta
| docs.platform_customers_retry | Appended to docs.platform_customers by Task 11: "Without `--ref`, a create retried after a timeout can make a second account, so pass `--ref` when your server retries." | approved |
| docs.held_promise.heading | `#### A customer create that stays pending`, under `### carlos accounts platform` (final fix wave, held-promise runbook) | approved (Luna pass 2026-11-19) |
| docs.held_promise | When a platform creates a customer account, the console first records a promise for the account. The promise holds the customer’s ref and a place in `--max-customers`. The console then writes the account to the deployment bucket and records it in the database. If the bucket and database disagree, the console stops the create and keeps the promise. Nothing else is written until an operator repairs the mismatch. | approved (Luna pass 2026-11-19) |
-| docs.held_promise.log_intro | While a promise is held, the console logs this line for every request from the platform: | approved (Luna pass 2026-11-19) |
+| docs.held_promise.log_intro | While a promise is held, the console logs this line at most once every 5 minutes, when the platform makes a request: | approved (Luna pass 2026-11-20; platform-accounts-followups, held-promise backoff #1295; was "While a promise is held, the console logs this line for every request from the platform:") |
| docs.held_promise.scope | Only that platform’s create requests are affected. It can still list customers, update them and use its credentials. A create for the held ref fails. If the reason is `is in this console with no manifest in the bucket`, every create on that platform fails because the bucket gives each new create the same id. The promise counts towards `--max-customers` until it is repaired. | approved (Luna pass 2026-11-19) |
| docs.held_promise.read | Read the promise and account from the console’s database first: | approved (Luna pass 2026-11-19) |
| docs.held_promise.manifest_key | The account’s manifest is `accounts/<sqid>/account.json` in the deployment bucket. | approved (Luna pass 2026-11-19) |
| docs.held_promise.no_manifest | **The account has no manifest, or the create’s manifest is at its id.** The reason is `is in this console with no manifest in the bucket` or `is another account in this console`. Check that the manifest is missing, or that its `platform_mint` is the mint id and the account row’s `platform_mint` is not the mint id. Then restore the account’s manifest. Write `accounts/<sqid>/account.json` from the row: `id`, `sqid`, `name` and `created_at` as an RFC 3339 UTC time. Add `platform`, `platform_ref` and `platform_mint` when the row has them. Add `deleted_at` as an RFC 3339 UTC time when the row’s value is not 0. | approved (Luna pass 2026-11-19) |
| docs.held_promise.owner | If the row has no `platform`, also add `owner`, using the account’s first owner from the console’s memberships table. Find it with this query: | approved (Luna pass 2026-11-19 (owner step)) |
| docs.held_promise.owner_stop | If the query returns no address, stop and escalate. Do not write the manifest. A rebuilt console would give the account no owner. For an account with a `platform`, leave `owner` out. It has no owner until someone claims it. | approved (Luna pass 2026-11-19 (owner step)) |
-| docs.held_promise.no_manifest_end | This replaces the create’s manifest if one is present. The platform’s next request creates the customer with a new id. | approved (Luna pass 2026-11-19) |
+| docs.held_promise.no_manifest_end | This replaces the create’s manifest if one is present. After the repair, the console retries the create when the platform next requests it, with a delay of up to 5 minutes, and creates the customer with a new id. | approved (Luna pass 2026-11-20; platform-accounts-followups, held-promise backoff #1295) |
| docs.held_promise.ref | **Another live customer holds the ref.** The reason starts with `holds ref` or `would take ref`. Check which account holds it: | approved (Luna pass 2026-11-19) |
| docs.held_promise.ref_repair | If it is the customer the platform intended, the promise is stale. Search the bucket’s account manifests for `"platform_mint":"<mint id>"`. If one has that value, add `deleted_at` with the current UTC time. Do not delete the manifest: an account id is never given out twice. Then remove the promise: | approved (Luna pass 2026-11-19) |
-| docs.held_promise.done | After the repair, the log line stops, and `carlos platform customers list --platform <platform>` shows the expected count. | approved (Luna pass 2026-11-19) |
+| docs.held_promise.done | After the repair, the console retries the create on a platform request, with a delay of up to 5 minutes; once it succeeds, the log line stops and `carlos platform customers list --platform <platform>` shows the expected count. | approved (Luna pass 2026-11-20; platform-accounts-followups, held-promise backoff #1295) |
| log.held_promise | Operator log line, `internal/console/apiplatformcustomers.go` (`held`), quoted by the runbook: `console: platform %s: pending customer create %s held for account %d: %s; repair the bucket or console` | approved (Luna pass 2026-11-19) |
**Task 15 (copy review, Luna pass + Paul 2026-11-19).** Paul approved Luna's rows as written except four, which carry his text: `delete.platform_has_customers` (no count), `audit.revoke`, `Minted` (split into `MintedPublish` and `MintedDeploy`, with `audit.credential` split the same way into `audit.credential_publish` and `audit.credential_deploy`: publish names the customer, deploy names the app in the customer), and `email.lapse_grace` for a platform's owners (new `email.platform.lapse_grace`: the approved `email.lapse_grace` without "unless you choose what stays", which only the customer's own owners can act on; the ordinary owner email keeps `email.lapse_grace`). Task 15 also added `list.failed` and `show.failed`, the read doors' own failure rows for a store error (500), in Paul's wording.
diff --git a/internal/console/apiplatformcustomers.go b/internal/console/apiplatformcustomers.go
index b6a92a766..8ba8e4338 100644
--- a/internal/console/apiplatformcustomers.go
+++ b/internal/console/apiplatformcustomers.go
@@ -214,7 +214,12 @@ func (s *Server) platformFinishPending(w http.ResponseWriter, r *http.Request, c
ctx := r.Context()
acct := c.Platform
pending, err := s.store.PendingPlatformMints(ctx, acct.Sqid)
- if err == nil && len(pending) > 0 {
+ // With nothing pending but a held promise still backed off (an operator
+ // removed it), finishPendingMints drops its entry: it re-reads the
+ // pending mints under the lock, as every backoff is set under it. This
+ // snapshot, read outside the lock, may be stale and must never prune
+ // (Astra, follow-ups review): it could erase a backoff set since.
+ if err == nil && (len(pending) > 0 || s.mintBackoffFor(acct.Sqid)) {
unlock := s.lockPlatformLifecycle(acct.Sqid)
err = s.finishPendingMints(ctx, acct)
unlock()
@@ -479,9 +484,13 @@ func (s *Server) handlePlatformCustomerCreate(w http.ResponseWriter, r *http.Req
if m.Ref != req.Ref {
continue
}
- if _, err := s.finishPlatformMint(ctx, platform, m); err != nil && !errors.Is(err, errPlatformMintEnded) {
- log.Printf("console: platform %s: create customer for ref %q refused: its pending create %s "+
- "did not finish: %v", platform.Sqid, req.Ref, m.MintID, err)
+ if _, err := s.finishPlatformMintPaced(ctx, platform, m); err != nil && !errors.Is(err, errPlatformMintEnded) {
+ // Inside a held promise's backoff window the refusal is not
+ // logged again: it was logged with the try that held it.
+ if !errors.Is(err, errMintBackedOff) {
+ log.Printf("console: platform %s: create customer for ref %q refused: its pending create %s "+
+ "did not finish: %v", platform.Sqid, req.Ref, m.MintID, err)
+ }
s.platformDoorFailed(w, c)
return
}
@@ -544,7 +553,7 @@ func (s *Server) handlePlatformCustomerCreate(w http.ResponseWriter, r *http.Req
}
// Step 7.
- cust, err := s.finishPlatformMint(ctx, platform, m)
+ cust, err := s.finishPlatformMintPaced(ctx, platform, m)
if err != nil {
if errors.Is(err, errMintNotWritten) {
// Refused before anything named it in the bucket: this
@@ -552,6 +561,8 @@ func (s *Server) handlePlatformCustomerCreate(w http.ResponseWriter, r *http.Req
// leaves nothing behind and holds no slot.
if uerr := s.store.unreservePlatformMint(ctx, platform.Sqid, m.MintID); uerr != nil {
log.Printf("console: platform %s: create customer: withdraw pending create %s: %v", platform.Sqid, m.MintID, uerr)
+ } else {
+ s.forgetMint(m.MintID)
}
}
s.platformDoorFailed(w, c)
@@ -630,14 +641,17 @@ const platformMintHeldOtherID = "is another account in this console, and the man
// that ended without an account (errPlatformMintEnded) is past, and a held
// one (errPlatformMintHeld, its operator line already logged) is passed
// over: one bad record must not stop the platform's other writes (Task 8
-// fix round 2). Any other failure stops it, and is returned (Astra r1-1).
+// fix round 2). A held one is tried at most once per platformMintHeldRetry
+// (finishPlatformMintPaced). Any other failure stops it, and is returned
+// (Astra r1-1).
func (s *Server) finishPendingMints(ctx context.Context, platform *Account) error {
pending, err := s.store.PendingPlatformMints(ctx, platform.Sqid)
if err != nil {
return err
}
+ s.pruneMintBackoff(platform.Sqid, pending)
for _, m := range pending {
- if _, err := s.finishPlatformMint(ctx, platform, m); err != nil &&
+ if _, err := s.finishPlatformMintPaced(ctx, platform, m); err != nil &&
!errors.Is(err, errPlatformMintEnded) && !errors.Is(err, errPlatformMintHeld) {
return err
}
@@ -645,6 +659,34 @@ func (s *Server) finishPendingMints(ctx context.Context, platform *Account) erro
return nil
}
+// errMintBackedOff marks an errPlatformMintHeld answered from the backoff,
+// without a try: nothing was read or logged, and its caller logs nothing
+// either.
+var errMintBackedOff = errors.New("console: the held pending customer create was not tried again yet")
+
+// finishPlatformMintPaced is finishPlatformMint for the platform's
+// requests, paced for a held promise. Trying one again scans every account
+// manifest in the bucket and logs the operator's line, and nothing changes
+// until an operator repairs it, so once a mint is found held it is not tried
+// again for platformMintHeldRetry: within that window it answers
+// errPlatformMintHeld (and errMintBackedOff) at once, touching neither the
+// bucket nor the log. The
+// promise is untouched, so it still counts against capacity and holds its
+// ref, and a create for that ref is still refused. The first request after
+// the window tries it again, finishing it if it was repaired. The caller
+// holds the platform lifecycle lock.
+func (s *Server) finishPlatformMintPaced(ctx context.Context, platform *Account, m PendingMint) (*Account, error) {
+ if s.mintBackedOff(m.MintID) {
+ return nil, fmt.Errorf("%w (%w): mint %s: found held less than %s ago", errPlatformMintHeld, errMintBackedOff,
+ m.MintID, platformMintHeldRetry)
+ }
+ cust, err := s.finishPlatformMint(ctx, platform, m)
+ if errors.Is(err, errPlatformMintHeld) {
+ s.backOffMint(platform.Sqid, m.MintID)
+ }
+ return cust, err
+}
+
// finishPlatformMint finishes one pending mint, or refuses to and leaves it
// pending. The caller holds the platform lifecycle lock.
//
diff --git a/internal/console/apiplatformcustomers_backoff_test.go b/internal/console/apiplatformcustomers_backoff_test.go
new file mode 100644
index 000000000..a809907a2
--- /dev/null
+++ b/internal/console/apiplatformcustomers_backoff_test.go
@@ -0,0 +1,376 @@
+package console
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "net/http"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// manifestScanCounter counts the bucket calls a pending mint's finish makes
+// to find a free id: lists of accounts/ and reads of account manifests.
+type manifestScanCounter struct {
+ release.Store
+ mu sync.Mutex
+ lists, gets int
+}
+
+func (s *manifestScanCounter) List(ctx context.Context, prefix string) ([]string, error) {
+ if strings.HasPrefix(prefix, "accounts/") {
+ s.mu.Lock()
+ s.lists++
+ s.mu.Unlock()
+ }
+ return s.Store.List(ctx, prefix)
+}
+
+func (s *manifestScanCounter) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if _, ok := domains.AccountManifestSqid(key); ok {
+ s.mu.Lock()
+ s.gets++
+ s.mu.Unlock()
+ }
+ return s.Store.Get(ctx, key)
+}
+
+// take answers the calls counted since the last take, and starts again.
+func (s *manifestScanCounter) take() (lists, gets int) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ lists, gets = s.lists, s.gets
+ s.lists, s.gets = 0, 0
+ return lists, gets
+}
+
+// heldBackoffWorld is a platform with one accepted promise (ref 4812) that
+// is held because this console holds the id the bucket gives it with no
+// manifest for it, a counting bucket under the console, a fake clock on
+// the backoff and a captured log.
+type heldBackoffWorld struct {
+ fx *consoleFixture
+ acct *Account
+ tok string
+ next int64
+ scans *manifestScanCounter
+ clock atomic.Int64
+ logs *lockedLog
+}
+
+func newHeldBackoffWorld(t *testing.T) *heldBackoffWorld {
+ t.Helper()
+ w := &heldBackoffWorld{scans: &manifestScanCounter{}, logs: &lockedLog{}}
+ w.fx = newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: true, WrapReleases: func(r release.Store) release.Store {
+ w.scans.Store = r
+ return w.scans
+ }})
+ w.clock.Store(time.Unix(1_800_000_000, 0).UnixNano())
+ w.fx.srv.platformClock = func() time.Time { return time.Unix(0, w.clock.Load()) }
+ w.acct = planAccount(t, w.fx, 501)
+ grantPlatformAccount(t, w.fx, w.acct.Sqid, 5)
+ w.tok = platformToken(t, w.fx, w.acct.ID, "cms")
+ next, err := domains.NextAccountID(context.Background(), w.fx.rel)
+ if err != nil {
+ t.Fatal(err)
+ }
+ w.next = next
+ // The promise is accepted, and its first finish fails before writing.
+ w.fx.srv.platformMintStep = failStep("mint", true)
+ status, out, _ := createCustomer(t, w.fx.ts.URL, w.acct.Sqid, w.tok, map[string]any{"name": "shop", "ref": "4812"})
+ wantPlatformError(t, "create with a failed mint", status, out, http.StatusBadGateway, "create.failed")
+ // Then this console gives its id to another account with no manifest.
+ if err := w.fx.st.CreateAccount(next, domains.Sqid(next), "other", "other@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ w.scans.take()
+ prev := log.Writer()
+ log.SetOutput(w.logs)
+ t.Cleanup(func() { log.SetOutput(prev) })
+ return w
+}
+
+func (w *heldBackoffWorld) advance(d time.Duration) { w.clock.Add(int64(d)) }
+
+// heldLines counts the operator's held line in the log so far.
+func (w *heldBackoffWorld) heldLines() int {
+ return strings.Count(w.logs.String(), " held for account ")
+}
+
+// listAsync makes one platform read request on its own goroutine, and
+// answers its status (or its transport error) on the channel.
+func (w *heldBackoffWorld) listAsync() <-chan error {
+ done := make(chan error, 1)
+ go func() {
+ status, _, raw, err := callJSON(http.MethodGet, platformCustomersURL(w.fx.ts.URL, w.acct.Sqid), w.tok, nil)
+ if err == nil && status != http.StatusOK {
+ err = fmt.Errorf("list = %d %s", status, raw)
+ }
+ done <- err
+ }()
+ return done
+}
+
+// wantListed fails unless an async list answered 200.
+func wantListed(t *testing.T, what string, err error) {
+ t.Helper()
+ if err != nil {
+ t.Fatalf("%s: %v", what, err)
+ }
+}
+
+// logLines counts every line logged so far.
+func (w *heldBackoffWorld) logLines() int {
+ return strings.Count(w.logs.String(), "\n")
+}
+
+// ownRefCreates makes n creates for the held ref, each refused.
+func (w *heldBackoffWorld) ownRefCreates(t *testing.T, n int) {
+ t.Helper()
+ for i := 0; i < n; i++ {
+ status, out, _ := createCustomer(t, w.fx.ts.URL, w.acct.Sqid, w.tok, map[string]any{"name": "shop", "ref": "4812"})
+ wantPlatformError(t, "create for the held ref", status, out, http.StatusBadGateway, "create.failed")
+ }
+}
+
+// backoffEntries is how many held promises the server is backing off.
+func (w *heldBackoffWorld) backoffEntries() int {
+ w.fx.srv.mintBackoffMu.Lock()
+ defer w.fx.srv.mintBackoffMu.Unlock()
+ return len(w.fx.srv.mintBackoff)
+}
+
+// list is one platform read request, which runs the gate.
+func (w *heldBackoffWorld) list(t *testing.T) map[string]any {
+ t.Helper()
+ status, out, raw := getPlatform(t, platformCustomersURL(w.fx.ts.URL, w.acct.Sqid), w.tok)
+ if status != http.StatusOK {
+ t.Fatalf("list = %d %s, want the read door to go on past the held promise", status, raw)
+ }
+ return out
+}
+
+// wantScans fails unless the bucket calls since the last take are a scan
+// (scanned) or none at all.
+func (w *heldBackoffWorld) wantScans(t *testing.T, what string, scanned bool) {
+ t.Helper()
+ lists, gets := w.scans.take()
+ if scanned && lists == 0 {
+ t.Fatalf("%s: no manifest list, want the held promise tried again", what)
+ }
+ if !scanned && (lists != 0 || gets != 0) {
+ t.Fatalf("%s: %d manifest lists and %d reads, want none inside the backoff window", what, lists, gets)
+ }
+}
+
+// TestHeldPromiseBacksOffItsScanAndLogLine: a promise found held is not
+// tried again for platformMintHeldRetry. Within that window the platform's
+// requests make no manifest list or read and log nothing more, the promise
+// still counts against capacity, and a create for its own ref is still
+// refused. After the window one request tries it again, logs again and
+// backs off again.
+func TestHeldPromiseBacksOffItsScanAndLogLine(t *testing.T) {
+ w := newHeldBackoffWorld(t)
+ out := w.list(t)
+ w.wantScans(t, "the first request", true)
+ if n := w.heldLines(); n != 1 {
+ t.Fatalf("held lines after the first request = %d, want 1:\n%s", n, w.logs)
+ }
+ if out["count"] != float64(1) {
+ t.Fatalf("list count = %v, want the held promise counted", out["count"])
+ }
+
+ for i := 0; i < 5; i++ {
+ w.advance(time.Minute - time.Second)
+ if out := w.list(t); out["count"] != float64(1) {
+ t.Fatalf("list count = %v inside the window, want the held promise counted", out["count"])
+ }
+ }
+ w.wantScans(t, "five requests inside the window", false)
+ if n := w.heldLines(); n != 1 {
+ t.Fatalf("held lines inside the window = %d, want still 1:\n%s", n, w.logs)
+ }
+ if n := linkedCount(t, w.fx.st, w.acct.Sqid); n != 1 {
+ t.Fatalf("LinkedCustomerCount = %d, want 1: the held promise keeps its slot", n)
+ }
+
+ // A create for the held ref is refused at once, without a rescan, and
+ // adds no log line at all, however often it is retried.
+ before := w.logLines()
+ w.ownRefCreates(t, 3)
+ w.wantScans(t, "the own-ref creates", false)
+ if n := w.logLines() - before; n != 0 {
+ t.Fatalf("own-ref creates inside the window logged %d lines, want none:\n%s", n, w.logs)
+ }
+ wantHeldPromise(t, w.fx, w.acct.Sqid, "4812", 1)
+
+ // After the window one request tries again, logs and backs off again.
+ w.advance(time.Minute)
+ w.list(t)
+ w.wantScans(t, "the first request after the window", true)
+ if n := w.heldLines(); n != 2 {
+ t.Fatalf("held lines after the window = %d, want 2:\n%s", n, w.logs)
+ }
+ w.list(t)
+ w.list(t)
+ w.wantScans(t, "requests after the retry", false)
+ if n := w.heldLines(); n != 2 {
+ t.Fatalf("held lines after the retry = %d, want still 2:\n%s", n, w.logs)
+ }
+ wantHeldPromise(t, w.fx, w.acct.Sqid, "4812", 1)
+
+ // A window later, the first create for the held ref tries it: the held
+ // line and the create's refusal, once each. Its retries log nothing.
+ w.advance(platformMintHeldRetry)
+ before = w.logLines()
+ w.ownRefCreates(t, 1)
+ w.wantScans(t, "the first own-ref create after the window", true)
+ if n := w.logLines() - before; n != 2 || w.heldLines() != 3 ||
+ !strings.Contains(w.logs.String(), `create customer for ref "4812" refused`) {
+ t.Fatalf("the first own-ref create after the window logged %d lines, want the held line and the refusal:\n%s", n, w.logs)
+ }
+ before = w.logLines()
+ w.ownRefCreates(t, 3)
+ w.wantScans(t, "own-ref creates after the retry", false)
+ if n := w.logLines() - before; n != 0 {
+ t.Fatalf("own-ref creates after the retry logged %d lines, want none:\n%s", n, w.logs)
+ }
+ wantHeldPromise(t, w.fx, w.acct.Sqid, "4812", 1)
+}
+
+// TestHeldPromiseBackoffSurvivesAStalePrune is Astra's finding on the
+// follow-ups: a request that read no pending mints must not prune with
+// that list after a concurrent request has held a new promise. The first
+// request is paused just as it prunes, and a second promise is reserved and
+// held by another request. Prunes run under the platform lifecycle lock, so
+// with the first request paused there the second waits for it; were the
+// prune outside the lock, the second would hold its promise first and the
+// stale prune would erase that backoff. Either way the entry must survive,
+// and the next request must neither scan nor log.
+func TestHeldPromiseBackoffSurvivesAStalePrune(t *testing.T) {
+ w := newHeldBackoffWorld(t)
+ ctx := context.Background()
+ w.list(t)
+ // The operator removes the first promise: nothing is pending, and its
+ // entry is left for the next request's prune.
+ if _, err := w.fx.st.db.ExecContext(ctx, `DELETE FROM platform_pending_mints WHERE platform = ?`, w.acct.Sqid); err != nil {
+ t.Fatal(err)
+ }
+ w.scans.take()
+
+ paused, resume := make(chan struct{}), make(chan struct{})
+ // Only the first prune pauses; a later one (the second request's) goes
+ // straight through.
+ var pausedOnce atomic.Bool
+ w.fx.srv.mintPruneEnter = func() {
+ if pausedOnce.CompareAndSwap(false, true) {
+ close(paused)
+ <-resume
+ }
+ }
+ first := w.listAsync()
+ <-paused
+
+ // A second promise, held for the same reason as the first.
+ mintID := strings.Repeat("ef", 16)
+ if err := w.fx.st.ReservePlatformMint(ctx, PendingMint{MintID: mintID, Platform: w.acct.Sqid, Ref: "4900", Name: "cafe",
+ By: "service:" + w.acct.Sqid + "/cms", CreatedAt: time.Now()}); err != nil {
+ t.Fatal(err)
+ }
+ if w.fx.srv.platformLocks.held(w.acct.Sqid) {
+ // The paused prune holds the lock: the request holding the new
+ // promise waits for it, so resume first.
+ second := w.listAsync()
+ close(resume)
+ wantListed(t, "the paused request", <-first)
+ wantListed(t, "the request holding the new promise", <-second)
+ } else {
+ w.list(t)
+ close(resume)
+ wantListed(t, "the paused request", <-first)
+ }
+
+ w.fx.srv.mintBackoffMu.Lock()
+ _, ok := w.fx.srv.mintBackoff[mintID]
+ w.fx.srv.mintBackoffMu.Unlock()
+ if !ok {
+ t.Fatalf("the new held promise's backoff entry is gone, want it kept")
+ }
+ w.scans.take()
+ before := w.logLines()
+ w.list(t)
+ w.wantScans(t, "the request after the prune", false)
+ if n := w.logLines() - before; n != 0 {
+ t.Fatalf("the request after the prune logged %d lines, want none:\n%s", n, w.logs)
+ }
+}
+
+// TestHeldPromiseFinishesAfterRepairOnceTheWindowEnds: an operator restores
+// the missing manifest. A request inside the window still leaves the
+// promise alone; the first one after it finishes the create, and clears
+// its backoff.
+func TestHeldPromiseFinishesAfterRepairOnceTheWindowEnds(t *testing.T) {
+ w := newHeldBackoffWorld(t)
+ w.list(t)
+ w.wantScans(t, "the first request", true)
+
+ other, err := w.fx.st.AccountBySqid(domains.Sqid(w.next))
+ if err != nil || other == nil {
+ t.Fatalf("the other account %+v %v", other, err)
+ }
+ if err := WriteAccountManifest(context.Background(), w.fx.rel, other.ID, other.Sqid, other.Name, other.CreatedAt); err != nil {
+ t.Fatal(err)
+ }
+
+ w.advance(time.Minute)
+ w.list(t)
+ w.wantScans(t, "a request inside the window after the repair", false)
+ if p := pendingMints(t, w.fx.st, w.acct.Sqid); len(p) != 1 {
+ t.Fatalf("pending mints %+v inside the window, want the promise left alone", p)
+ }
+
+ w.advance(platformMintHeldRetry)
+ if out := w.list(t); len(customersIn(t, out)) != 1 || out["count"] != float64(1) {
+ t.Fatalf("list after the window = %v, want the repaired create finished", out)
+ }
+ w.wantScans(t, "the first request after the window", true)
+ if p := pendingMints(t, w.fx.st, w.acct.Sqid); len(p) != 0 {
+ t.Fatalf("pending mints %+v, want the repaired promise finished", p)
+ }
+ if n := w.heldLines(); n != 1 {
+ t.Fatalf("held lines = %d, want only the first:\n%s", n, w.logs)
+ }
+ if n := w.backoffEntries(); n != 0 {
+ t.Fatalf("backoff entries after the finish = %d, want none", n)
+ }
+ status, out, raw := createCustomer(t, w.fx.ts.URL, w.acct.Sqid, w.tok, map[string]any{"name": "shop", "ref": "4812"})
+ if status != http.StatusOK || out["created"] != false {
+ t.Fatalf("create 4812 after the repair = %d %s, want the finished customer", status, raw)
+ }
+}
+
+// TestHeldPromiseRemovedByAnOperatorDropsItsBackoff: the backoff holds an
+// entry only while its promise is pending. Once an operator removes the
+// promise, the platform's next request drops the entry, inside the window.
+func TestHeldPromiseRemovedByAnOperatorDropsItsBackoff(t *testing.T) {
+ w := newHeldBackoffWorld(t)
+ w.list(t)
+ if n := w.backoffEntries(); n != 1 {
+ t.Fatalf("backoff entries after the held finish = %d, want 1", n)
+ }
+ if _, err := w.fx.st.db.ExecContext(context.Background(), `DELETE FROM platform_pending_mints WHERE platform = ?`, w.acct.Sqid); err != nil {
+ t.Fatal(err)
+ }
+ if out := w.list(t); out["count"] != float64(0) {
+ t.Fatalf("list count = %v, want the removed promise gone", out["count"])
+ }
+ if n := w.backoffEntries(); n != 0 {
+ t.Fatalf("backoff entries after the promise was removed = %d, want none", n)
+ }
+}
diff --git a/internal/console/authstore.go b/internal/console/authstore.go
index 009bc67a8..a38121aca 100644
--- a/internal/console/authstore.go
+++ b/internal/console/authstore.go
@@ -527,14 +527,27 @@ func (s *Store) PurgeCLIAuth(now time.Time) {
// also end its channel.
//
// An app-bound per-customer credential (kind platform, an app) is left
- // out too. This DELETE holds no permit, and under the armed claim gate
- // one such row would abort the whole statement, so nothing expired
- // would be purged again. An expired one already resolves to nothing,
- // and app purge deletes it with its app.
+ // out of this statement and swept by the next one. This DELETE holds no
+ // permit, and under the armed claim gate one such row would abort the
+ // whole statement, so nothing expired would be purged again.
if _, err := s.db.ExecContext(ctx, `DELETE FROM cli_tokens WHERE expires_at != 0 AND expires_at < ? AND kind != ?
AND NOT (kind = ? AND app != '')`, now.Unix(), cliKindLink, cliKindPlatform); err != nil {
log.Printf("console: purge expired tokens: %v", err)
}
+ // Expired app-bound per-customer credentials, in a statement of their
+ // own so a failure here never stops the ordinary purge above. Under the
+ // armed claim gate they stay: a DELETE of an app-bound row needs that
+ // app's host-claim permit (withAutoAppSQL, a bucket admission per app),
+ // which housekeeping on the login path does not take. There an expired
+ // one already resolves to nothing, and app purge deletes it with its
+ // app. Everywhere else they are swept with the rest.
+ if s.claimGated() {
+ return
+ }
+ if _, err := s.db.ExecContext(ctx, `DELETE FROM cli_tokens WHERE expires_at != 0 AND expires_at < ? AND kind = ? AND app != ''`,
+ now.Unix(), cliKindPlatform); err != nil {
+ log.Printf("console: purge expired app-bound platform credentials: %v", err)
+ }
}
// CLIAuthByUserCode resolves a typed code to the request it names, for the
diff --git a/internal/console/platform_credentials_test.go b/internal/console/platform_credentials_test.go
index 17483dfa0..0b8c581cc 100644
--- a/internal/console/platform_credentials_test.go
+++ b/internal/console/platform_credentials_test.go
@@ -1025,7 +1025,7 @@ func TestCustomerCredentialUnderTheGateIsSweptByARevoke(t *testing.T) {
// review, Fable I1): the expired-token sweep holds no permit. Under the
// armed claim gate an expired app-bound per-customer credential is left to
// app purge, and the sweep still purges an ordinary expired token instead
-// of aborting on that row.
+// of aborting on that row. Neither of the sweep's statements fails.
func TestExpiredTokenSweepUnderTheGateGoesOnPastACustomerCredential(t *testing.T) {
s, _, _ := sqlIngestFixture(t)
ctx := context.Background()
@@ -1054,7 +1054,11 @@ func TestExpiredTokenSweepUnderTheGateGoesOnPastACustomerCredential(t *testing.T
lastCLIPurge.Store(0)
defer lastCLIPurge.Store(0)
+ logs := captureLog(t)
s.PurgeCLIAuth(later)
+ if strings.Contains(logs.String(), "console: purge") {
+ t.Fatalf("the sweep logged a failure under the gate:\n%s", logs)
+ }
rows := func(raw string) int {
var n int
@@ -1074,6 +1078,46 @@ func TestExpiredTokenSweepUnderTheGateGoesOnPastACustomerCredential(t *testing.T
}
}
+// TestExpiredTokenSweepTakesAppBoundCustomerCredentials: on a console
+// without the claim gate the sweep deletes an expired app-bound
+// per-customer credential with the rest, and keeps one still in date.
+func TestExpiredTokenSweepTakesAppBoundCustomerCredentials(t *testing.T) {
+ s := openTestStore(t)
+ ctx := context.Background()
+ p := mustAccount(t, s, "bcd")
+ gen := grantPlatformGen(t, s, p.ID)
+ reserveMint(t, s, "bcd", "aa11", "4812")
+ c := customerOf("bcd", "bdf", "4812", "aa11")
+ if err := s.CreateLinkedAccount(ctx, c, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ later := now.Add(CLITokenTTL + time.Hour)
+ expired, live := now.Add(time.Hour).Unix(), later.Add(time.Hour).Unix()
+ insertTokenRow(t, s, "deploy-expired", cliKindPlatform, c.ID, "blog", string(svcrole.Deploy), expired, p.ID, gen)
+ insertTokenRow(t, s, "deploy-live", cliKindPlatform, c.ID, "blog", string(svcrole.Deploy), live, p.ID, gen)
+ insertTokenRow(t, s, "publish-expired", cliKindPlatform, c.ID, "", string(svcrole.Publish), expired, p.ID, gen)
+ user := mintUserToken(t, s, "paul@keymail.dev", now)
+
+ lastCLIPurge.Store(0)
+ defer lastCLIPurge.Store(0)
+ logs := captureLog(t)
+ s.PurgeCLIAuth(later)
+ if strings.Contains(logs.String(), "console: purge") {
+ t.Fatalf("the sweep logged a failure:\n%s", logs)
+ }
+
+ for raw, want := range map[string]int{"deploy-expired": 0, "deploy-live": 1, "publish-expired": 0, user: 0} {
+ var n int
+ if err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM cli_tokens WHERE token_hash = ?`, hashToken(raw)).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ if n != want {
+ t.Errorf("rows for %s after the sweep = %d, want %d", raw, n, want)
+ }
+ }
+}
+
// TestRevokingAPlatformCredentialUnderTheGateEndsItsDeployMints: under the
// armed claim gate, the revoke of a platform credential ends the app-bound
// Deploy credential it minted with no permit (RevokeFree), and succeeds.
diff --git a/internal/console/platform_seams.go b/internal/console/platform_seams.go
index 9ff96c787..5953fc470 100644
--- a/internal/console/platform_seams.go
+++ b/internal/console/platform_seams.go
@@ -1,8 +1,14 @@
package console
+import (
+ "slices"
+ "sync"
+ "time"
+)
+
// platformSeams is the platform accounts plan's one addition to Server
-// (pre-flight C1): the platform lifecycle lock's table and the plan's test
-// seams, embedded in Server with a single line. Later tasks of the plan add
+// (pre-flight C1): the platform lifecycle lock's table, the held-promise
+// backoff and the plan's test seams, embedded in Server with a single line. Later tasks of the plan add
// their seams here; nothing else of the plan becomes a Server field. Every
// field's zero value is ready, so &Server{} literals in tests stay safe.
//
@@ -42,6 +48,115 @@ type platformSeams struct {
// manifest and the HA row), just before it hands the request to the
// create handler, with no lock held: a test may recreate the app there.
platformHostBeforeCreate func()
+ // platformClock, when set (tests only), is the clock the held-promise
+ // backoff reads (platformNow); nil is time.Now.
+ platformClock func() time.Time
+ // mintBackoff is the held-promise backoff (finishPlatformMintPaced):
+ // a pending mint found held is not tried again, and its operator line
+ // not logged again, until its entry's time. Keyed by mint id, guarded
+ // by mintBackoffMu; nil until the first held promise.
+ mintBackoffMu sync.Mutex
+ mintBackoff map[string]mintBackoffEntry
+ // mintPruneEnter, when set (tests only), is the first statement of
+ // pruneMintBackoff, after its caller read the pending mints: a test may
+ // pause the prune there.
+ mintPruneEnter func()
+}
+
+// platformMintHeldRetry is how long a held pending mint is left alone
+// before the next platform request tries it again. Each try scans every
+// account manifest in the bucket and logs the operator's line.
+const platformMintHeldRetry = 5 * time.Minute
+
+// mintBackoffEntry is one held pending mint: its platform, and when it is
+// tried again.
+type mintBackoffEntry struct {
+ platform string
+ until time.Time
+}
+
+// platformNow is the held-promise backoff's clock.
+func (s *platformSeams) platformNow() time.Time {
+ if s.platformClock != nil {
+ return s.platformClock()
+ }
+ return time.Now()
+}
+
+// mintBackedOff reports whether the pending mint was found held less than
+// platformMintHeldRetry ago. An entry whose time has come is dropped: it
+// would mean the same as no entry.
+func (s *platformSeams) mintBackedOff(mintID string) bool {
+ s.mintBackoffMu.Lock()
+ defer s.mintBackoffMu.Unlock()
+ e, ok := s.mintBackoff[mintID]
+ if !ok {
+ return false
+ }
+ if s.platformNow().Before(e.until) {
+ return true
+ }
+ delete(s.mintBackoff, mintID)
+ return false
+}
+
+// backOffMint records the pending mint as held, to be tried again after
+// platformMintHeldRetry. It also drops every entry whose time has come, so
+// the map holds only promises found held in the last window.
+func (s *platformSeams) backOffMint(platform, mintID string) {
+ s.mintBackoffMu.Lock()
+ defer s.mintBackoffMu.Unlock()
+ now := s.platformNow()
+ for id, e := range s.mintBackoff {
+ if !now.Before(e.until) {
+ delete(s.mintBackoff, id)
+ }
+ }
+ if s.mintBackoff == nil {
+ s.mintBackoff = map[string]mintBackoffEntry{}
+ }
+ s.mintBackoff[mintID] = mintBackoffEntry{platform: platform, until: now.Add(platformMintHeldRetry)}
+}
+
+// forgetMint drops the pending mint's backoff entry, if it has one.
+func (s *platformSeams) forgetMint(mintID string) {
+ s.mintBackoffMu.Lock()
+ defer s.mintBackoffMu.Unlock()
+ delete(s.mintBackoff, mintID)
+}
+
+// mintBackoffFor reports whether any of the platform's held promises has a
+// backoff entry.
+func (s *platformSeams) mintBackoffFor(platform string) bool {
+ s.mintBackoffMu.Lock()
+ defer s.mintBackoffMu.Unlock()
+ for _, e := range s.mintBackoff {
+ if e.platform == platform {
+ return true
+ }
+ }
+ return false
+}
+
+// pruneMintBackoff drops the platform's entries for promises no longer
+// pending (finished, or removed by an operator). pending is every pending
+// mint of the platform, read under the platform lifecycle lock, which the
+// caller still holds: every backoff is set under that lock, so a list read
+// outside it could be older than an entry and erase it.
+func (s *platformSeams) pruneMintBackoff(platform string, pending []PendingMint) {
+ if s.mintPruneEnter != nil {
+ s.mintPruneEnter()
+ }
+ s.mintBackoffMu.Lock()
+ defer s.mintBackoffMu.Unlock()
+ for id, e := range s.mintBackoff {
+ if e.platform != platform {
+ continue
+ }
+ if !slices.ContainsFunc(pending, func(m PendingMint) bool { return m.MintID == id }) {
+ delete(s.mintBackoff, id)
+ }
+ }
}
// platformStep runs the platformMintStep seam, if one is set.