console: first sign-in survives a re-tap; fields don't zoom on iOS
A new person's first email sign-in spent the link, then minted their account inside the same POST: about 100 serial S3 reads, ~3 s with no feedback. A new user re-tapped on a phone twice (17:20Z, 17:34Z on 2026-11-07), the first request was cancelled mid-mint, and the retry found a spent link: "Link expired". - finishSignin now redirects to / (with next) as soon as the session exists; the front page's GET resolves the account and mints, so a reload is safe. - currentAccount mints under a per-person lock with a membership re-check (one account for concurrent landings) and detached from the request's cancellation (no half-minted manifest when a browser quits). - NextAccountID reads manifests 16 at a time; same answer, same fail-closed rule for an unreadable manifest. - Sign-in buttons use data-busy (no double submit, spinner). - Touch screens get 16px fields so iOS Safari stops zooming the front page on focus; the sign-in field and button go full width on phones. Census: internal/domains envelope re-pinned (overlay plan14-root-reads-signin-first-run-mobile), needs cross-family approval.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
14 files changed,
+268
−42
docs/superpowers/notes/census-proposal-signin-first-run-mobile.md+11 −0internal/console/emailsignin.go+24 −17internal/console/emailsignin_test.go+21 −4internal/console/landing_test.go+55 −0internal/console/server.go+38 −2internal/console/server_test.go+17 −0internal/console/templates/check.html+2 −2internal/console/templates/console_chrome.html+14 −0internal/console/templates/email_link.html+1 −1internal/console/templates/home.html+1 −1internal/domains/mint.go+45 −15internal/domains/mint_test.go+35 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-signin-first-run-mobile.tsv+3 −0
CI cancelled — superseded by a newer push — run details
diff --git a/docs/superpowers/notes/census-proposal-signin-first-run-mobile.md b/docs/superpowers/notes/census-proposal-signin-first-run-mobile.md| new file mode 100644 |
| index 000000000..7f3462301 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-signin-first-run-mobile.md |
| @@ -0,0 +1,11 @@ |
| +# Census approval: signin-first-run-mobile |
| + |
| +Ruling `census-ruling-signin-first-run-mobile`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +Envelopes re-pinned: `internal/domains`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Seal: `61027a32e31cb7ce017304f526f668c26980999e2699a3013a82e2630164143e` → `61027a32e31cb7ce017304f526f668c26980999e2699a3013a82e2630164143e`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-signin-first-run-mobile.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go| index 28450fe32..d663c65ce 100644 |
| --- a/internal/console/emailsignin.go |
| +++ b/internal/console/emailsignin.go |
| @@ -188,6 +188,14 @@ func (s *Server) flowLock(flow string) *sync.Mutex { |
| return &s.flowLocks[sum[0]] |
| } |
| +// landingLock serialises currentAccount's mint for one person. Striped by the |
| +// address's hash, like flowLock: bounded memory, and two people rarely share |
| +// a stripe (when they do, one waits for the other's mint). |
| +func (s *Server) landingLock(addr string) *sync.Mutex { |
| + sum := sha256.Sum256([]byte(addr)) |
| + return &s.landingLocks[sum[0]] |
| +} |
| + |
| // homeForm is what the front page's one form starts with. flow, when set, is |
| // the flow the caller already holds for this request. |
| type homeForm struct { |
| @@ -254,9 +262,14 @@ func safeNext(raw string) string { |
| // the person, store the Keymail grant (Keymail only), open a session that |
| // remembers its method row, set the cookies, then land. An email sign-in also |
| // records a step-up at the moment of use, the same proof a step-up would ask |
| -// for minutes later. The current account is resolved (minted for a new user) |
| -// before ordinary redirects. The exact claim return skips account landing; |
| -// its explicit confirmation uses the claim person lock and account cap. |
| +// for minutes later. Landing is NOT resolved here: the answer is a redirect to |
| +// the front page (with next), whose GET resolves the current account, minting |
| +// one for a new person. Minting can take seconds, and a sign-in POST has |
| +// already spent its link or code: a person who taps again, or whose browser |
| +// gives up, must find a signed-in session on the retry, not a spent link |
| +// (2026-11-07, a first sign-in on a phone). The exact claim return skips |
| +// account landing; its explicit confirmation uses the claim person lock and |
| +// account cap. |
| // freshAuthTime carries the claim callback's validated Keymail gesture, if any. |
| // Like an email sign-in's, the presence it records is not scoped to the claim: |
| // for StepUpWindow it satisfies every step-up gated action of this new session, |
| @@ -267,24 +280,18 @@ func (s *Server) finishSignin(w http.ResponseWriter, r *http.Request, proved, ke |
| if len(freshAuthTime) > 0 { |
| authTime = freshAuthTime[0] |
| } |
| - person, ok := s.completeSigninSession(w, r, proved, keymailToken, method, authTime) |
| - if !ok { |
| + if _, ok := s.completeSigninSession(w, r, proved, keymailToken, method, authTime); !ok { |
| return |
| } |
| - if n := safeNext(next); n != "" { |
| - if n == "/demo/claim" { |
| - http.Redirect(w, r, n, http.StatusSeeOther) |
| - return |
| - } |
| - if _, err := s.currentAccount(r.Context(), person); err != nil { |
| - log.Printf("console: landing for %s: %v", person, err) |
| - s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not open your account. Please try again.") |
| - return |
| - } |
| + n := safeNext(next) |
| + switch n { |
| + case "/demo/claim": |
| http.Redirect(w, r, n, http.StatusSeeOther) |
| - return |
| + case "": |
| + http.Redirect(w, r, "/", http.StatusSeeOther) |
| + default: |
| + http.Redirect(w, r, "/?next="+url.QueryEscape(n), http.StatusSeeOther) |
| } |
| - s.redirectToCurrentAccount(w, r, person, http.StatusSeeOther) |
| } |
| // completeSigninSession records identity and opens the browser session without |
diff --git a/internal/console/emailsignin_test.go b/internal/console/emailsignin_test.go| index 4448ebd70..71271e268 100644 |
| --- a/internal/console/emailsignin_test.go |
| +++ b/internal/console/emailsignin_test.go |
| @@ -50,7 +50,7 @@ func keymailWalk(t *testing.T, fx *consoleFixture, c *http.Client, signinQuery, |
| fx.fk.expectCode = code |
| fx.fk.mu.Unlock() |
| status, loc, _ = get(t, c, fx.ts.URL+"/auth/callback?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(q.Get("state"))) |
| - return status, loc |
| + return followLanding(t, fx, c, status, loc) |
| } |
| func browserCookie(t *testing.T, fx *consoleFixture, c *http.Client, name string) string { |
| @@ -122,7 +122,8 @@ func TestFinishSigninEmailRecordsStepUp(t *testing.T) { |
| r := httptest.NewRequest(http.MethodGet, "/", nil) |
| fx.srv.finishSignin(w, r, "bob@example.com", "", MethodEmail, "/invite/abc") |
| res := w.Result() |
| - if res.StatusCode != http.StatusSeeOther || res.Header.Get("Location") != "/invite/abc" { |
| + // Landing (and a first sign-in's mint) waits for the front page's GET. |
| + if res.StatusCode != http.StatusSeeOther || res.Header.Get("Location") != "/?next=%2Finvite%2Fabc" { |
| t.Fatalf("finishSignin = %d -> %q", res.StatusCode, res.Header.Get("Location")) |
| } |
| var raw string |
| @@ -148,6 +149,18 @@ func TestFinishSigninEmailRecordsStepUp(t *testing.T) { |
| if g, _ := fx.st.GrantToken("bob@example.com"); g != "" { |
| t.Fatalf("an email sign-in stored a grant token %q", g) |
| } |
| + // The sign-in POST mints nothing; the front page's GET does, then follows |
| + // next. |
| + if accts, err := fx.st.AccountsFor("bob@example.com"); err != nil || len(accts) != 0 { |
| + t.Fatalf("the sign-in itself minted: %v, %v", accts, err) |
| + } |
| + hw := httptest.NewRecorder() |
| + hr := httptest.NewRequest(http.MethodGet, res.Header.Get("Location"), nil) |
| + hr.AddCookie(&http.Cookie{Name: sessionCookie, Value: raw}) |
| + fx.srv.handleHome(hw, hr) |
| + if hw.Code != http.StatusFound || hw.Header().Get("Location") != "/invite/abc" { |
| + t.Fatalf("landing = %d -> %q, want 302 -> /invite/abc", hw.Code, hw.Header().Get("Location")) |
| + } |
| if accts, err := fx.st.AccountsFor("bob@example.com"); err != nil || len(accts) == 0 { |
| t.Fatalf("no personal account minted: %v, %v", accts, err) |
| } |
| @@ -715,13 +728,17 @@ func openLink(t *testing.T, fx *consoleFixture, c *http.Client, link string) (in |
| // postLink submits the confirm page's form from the console's own origin. |
| func postLink(t *testing.T, fx *consoleFixture, c *http.Client, link, nonce string) (int, string, string) { |
| t.Helper() |
| - return postFrom(t, fx, c, "/auth/email/link", fx.ts.URL, url.Values{"t": {link}, "nonce": {nonce}}) |
| + status, loc, body := postFrom(t, fx, c, "/auth/email/link", fx.ts.URL, url.Values{"t": {link}, "nonce": {nonce}}) |
| + status, loc = followLanding(t, fx, c, status, loc) |
| + return status, loc, body |
| } |
| // postCode submits the check page's code form from the console's own origin. |
| func postCode(t *testing.T, fx *consoleFixture, c *http.Client, code string) (int, string, string) { |
| t.Helper() |
| - return postFrom(t, fx, c, "/auth/email/code", fx.ts.URL, url.Values{"code": {code}}) |
| + status, loc, body := postFrom(t, fx, c, "/auth/email/code", fx.ts.URL, url.Values{"code": {code}}) |
| + status, loc = followLanding(t, fx, c, status, loc) |
| + return status, loc, body |
| } |
| // emailSession asserts browser c holds a live email-method session for addr |
diff --git a/internal/console/landing_test.go b/internal/console/landing_test.go| new file mode 100644 |
| index 000000000..bc763d65d |
| --- /dev/null |
| +++ b/internal/console/landing_test.go |
| @@ -0,0 +1,55 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "sync" |
| + "testing" |
| +) |
| + |
| +// A first sign-in's landing can arrive twice at once (a double tap, a reload |
| +// while the first is still minting): one personal account, not two. |
| +func TestCurrentAccountConcurrentLandingsMintOnce(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + const addr = "twice@example.com" |
| + var wg sync.WaitGroup |
| + got := make([]string, 8) |
| + errs := make([]error, 8) |
| + for i := range got { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + got[i], errs[i] = fx.srv.currentAccount(context.Background(), addr) |
| + }() |
| + } |
| + wg.Wait() |
| + for i := range got { |
| + if errs[i] != nil { |
| + t.Fatalf("landing %d: %v", i, errs[i]) |
| + } |
| + if got[i] != got[0] { |
| + t.Fatalf("landings disagree: %q vs %q", got[i], got[0]) |
| + } |
| + } |
| + accts, err := fx.st.AccountsFor(addr) |
| + if err != nil || len(accts) != 1 { |
| + t.Fatalf("accounts = %v, %v; want exactly one", accts, err) |
| + } |
| +} |
| + |
| +// A browser that gives up mid-landing must not strand a half-minted account: |
| +// the mint runs to the end even when the request's context is already gone. |
| +func TestCurrentAccountMintSurvivesCancelledRequest(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.Releases = ctxStore{fx.srv.cfg.Releases} // metricsview_test.go |
| + const addr = "gaveup@example.com" |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + cancel() |
| + sqid, err := fx.srv.currentAccount(ctx, addr) |
| + if err != nil { |
| + t.Fatalf("landing with a cancelled request: %v", err) |
| + } |
| + accts, err := fx.st.AccountsFor(addr) |
| + if err != nil || len(accts) != 1 || accts[0].Sqid != sqid { |
| + t.Fatalf("accounts = %v, %v; want the one minted (%s)", accts, err, sqid) |
| + } |
| +} |
diff --git a/internal/console/server.go b/internal/console/server.go| index b4c3fdb82..77ff98605 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1258,7 +1258,9 @@ type Server struct { |
| // memory, one console process per deployment. |
| limits emailLimits |
| // flowLocks serialise /auth/continue per sign-in flow (flowLock). |
| - flowLocks [256]sync.Mutex |
| + flowLocks [256]sync.Mutex |
| + // landingLocks serialise a first landing's mint per person (landingLock). |
| + landingLocks [256]sync.Mutex |
| demoClaimSelections demoClaimSelectionReceipts |
| demoClaimBoundary func(string) error // Test-only crash injection after durable boundaries. |
| demoClaimTestEnabled bool // Test-only readiness bypass. |
| @@ -3079,8 +3081,22 @@ func (s *Server) takeFlash(w http.ResponseWriter, r *http.Request) (flash, flash |
| // ---- auth handlers ---------------------------------------------------------- |
| +// handleHome lands a signed-in person: on next when it is a safe local path, |
| +// else on their current account. Either way the current account is resolved |
| +// first, minting a personal account on a first sign-in, so every sign-in door |
| +// can redirect here the moment the session exists and leave the slow part to |
| +// a GET a reload can safely repeat. |
| func (s *Server) handleHome(w http.ResponseWriter, r *http.Request) { |
| if addr, _, ok := s.session(r); ok { |
| + if n := safeNext(r.URL.Query().Get("next")); n != "" { |
| + if _, err := s.currentAccount(r.Context(), addr); err != nil { |
| + log.Printf("console: landing for %s: %v", addr, err) |
| + s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not open your account. Please try again.") |
| + return |
| + } |
| + http.Redirect(w, r, n, http.StatusFound) |
| + return |
| + } |
| s.redirectToCurrentAccount(w, r, addr, http.StatusFound) |
| return |
| } |
| @@ -3112,6 +3128,12 @@ func (s *Server) redirectToCurrentAccount(w http.ResponseWriter, r *http.Request |
| // currentAccount resolves the three landing cases in order: MRU history (only |
| // if still a member — an account you were removed from must not strand you), |
| // first membership, or mint. |
| +// |
| +// The mint is serialised per person and re-checks membership under the lock, |
| +// so two landings at once (a double tap, a reload while the first is still |
| +// minting) give one personal account, not two. It runs detached from the |
| +// request's cancellation, bounded by landingMintTimeout: a browser that gives |
| +// up mid-mint must not leave a manifest in the bucket with no console row. |
| func (s *Server) currentAccount(ctx context.Context, addr string) (string, error) { |
| a, err := s.memberAccount(addr) |
| if err != nil { |
| @@ -3120,13 +3142,27 @@ func (s *Server) currentAccount(ctx context.Context, addr string) (string, error |
| if a != nil { |
| return a.Sqid, nil |
| } |
| - m, err := s.mintAccount(ctx, addr, addr) |
| + mu := s.landingLock(addr) |
| + mu.Lock() |
| + defer mu.Unlock() |
| + if a, err := s.memberAccount(addr); err != nil { |
| + return "", err |
| + } else if a != nil { |
| + return a.Sqid, nil |
| + } |
| + mctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), landingMintTimeout) |
| + defer cancel() |
| + m, err := s.mintAccount(mctx, addr, addr) |
| if err != nil { |
| return "", err |
| } |
| return m.Sqid, nil |
| } |
| +// landingMintTimeout bounds a landing's mint once it no longer follows the |
| +// request's cancellation. |
| +const landingMintTimeout = 30 * time.Second |
| + |
| // memberAccount is currentAccount's first two cases WITHOUT the mint: the MRU |
| // account if the viewer is still a member of it, else their first membership |
| // by creation order, else nil. Split out because pages that merely want the |
diff --git a/internal/console/server_test.go b/internal/console/server_test.go| index 53a58ee41..dac6be4bd 100644 |
| --- a/internal/console/server_test.go |
| +++ b/internal/console/server_test.go |
| @@ -292,6 +292,7 @@ func signUp(t *testing.T, fx *consoleFixture, c *http.Client, code string) { |
| fx.fk.expectCode = code |
| fx.fk.mu.Unlock() |
| status, loc, _ = get(t, c, fx.ts.URL+"/auth/callback?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(q.Get("state"))) |
| + status, loc = followLanding(t, fx, c, status, loc) |
| // Signing in lands you in an account — the MRU one, your first membership, |
| // or one minted on the spot. |
| if status != http.StatusSeeOther || !strings.HasPrefix(loc, "/a/") { |
| @@ -299,6 +300,22 @@ func signUp(t *testing.T, fx *consoleFixture, c *http.Client, code string) { |
| } |
| } |
| +// followLanding follows a sign-in's redirect to the front page, where the |
| +// landing (and a first sign-in's mint) now happens, and returns the sign-in's |
| +// own status with the Location the front page then gave. Any other answer is |
| +// returned as it came. |
| +func followLanding(t *testing.T, fx *consoleFixture, c *http.Client, status int, loc string) (int, string) { |
| + t.Helper() |
| + if status != http.StatusSeeOther || (loc != "/" && !strings.HasPrefix(loc, "/?next=")) { |
| + return status, loc |
| + } |
| + hs, hloc, _ := get(t, c, fx.ts.URL+loc) |
| + if hs != http.StatusFound { |
| + t.Fatalf("landing %s = %d -> %q, want 302", loc, hs, hloc) |
| + } |
| + return status, hloc |
| +} |
| + |
| func sessionToken(t *testing.T, fx *consoleFixture, c *http.Client) string { |
| t.Helper() |
| u, _ := url.Parse(fx.ts.URL) |
diff --git a/internal/console/templates/check.html b/internal/console/templates/check.html| index adafdcccb..30f5403b2 100644 |
| --- a/internal/console/templates/check.html |
| +++ b/internal/console/templates/check.html |
| @@ -6,13 +6,13 @@ |
| {{if .Next}}<input type="hidden" name="next" value="{{.Next}}">{{end}} |
| <label for="code">{{.SigninCopy.CodeLabel}}</label> |
| <input id="code" type="text" name="code" inputmode="numeric" autocomplete="one-time-code" required autofocus> |
| - <button type="submit">{{.SigninCopy.CodeButton}}</button> |
| + <button type="submit" data-busy>{{.SigninCopy.CodeButton}}</button> |
| </form> |
| {{if .CodeError}}<p class="error">{{.CodeError}}</p>{{end}} |
| <p class="small">{{.SigninCopy.Nothing}}</p> |
| <form class="signin" method="post" action="/auth/continue"> |
| <input type="hidden" name="address" value="{{.Prefill}}"> |
| {{if .Next}}<input type="hidden" name="next" value="{{.Next}}">{{end}} |
| - <button type="submit">{{.SigninCopy.AgainButton}}</button> |
| + <button type="submit" data-busy>{{.SigninCopy.AgainButton}}</button> |
| </form> |
| {{template "bottom" .}}{{end}} |
diff --git a/internal/console/templates/console_chrome.html b/internal/console/templates/console_chrome.html| index 6c762daa3..dcfe696db 100644 |
| --- a/internal/console/templates/console_chrome.html |
| +++ b/internal/console/templates/console_chrome.html |
| @@ -71,6 +71,13 @@ |
| border: 1px solid var(--rst-line-strong); border-radius: var(--rst-radius-sm); padding: 0.3rem 0.5rem; |
| box-shadow: var(--shadow-inset); |
| } |
| + /* iOS Safari zooms the page in when it focuses a field whose text is under |
| + 16px, and never zooms back out: the page is left cut off at the right. |
| + Touch screens get 16px fields so focusing one leaves the page alone. */ |
| + @media (pointer: coarse) { |
| + select, textarea, input[type=text], input[type=search], input[type=email], input[type=number], |
| + input[type=password], input[type=url], input[type=tel] { font-size: max(16px, 1rem); } |
| + } |
| select:disabled, input:disabled { |
| background: var(--rst-surface-2); color: var(--muted); box-shadow: none; cursor: not-allowed; |
| } |
| @@ -538,6 +545,13 @@ |
| form.signin { display: flex; gap: 0.6rem; flex-wrap: wrap; margin: 0 0 1rem; } |
| form.signin input[type=text], form.signin input[type=email] { padding: 0.55rem 0.8rem; min-width: 16rem; } |
| form.signin label { flex-basis: 100%; font-weight: 600; } |
| + /* On a phone the sign-in field and its button share the column's full |
| + width, so the form reads as one block instead of a short box over a |
| + shorter button. */ |
| + @media (max-width: 40rem) { |
| + form.signin input[type=text], form.signin input[type=email] { flex: 1 1 100%; min-width: 0; } |
| + form.signin button { flex: 1 1 100%; } |
| + } |
| /* A button is a small raised module: a fill, a hairline edge in its own |
| darker tone, a short lip under it that it sinks into when pressed. The |
| variants below only swap the --btn-* tones, so hover, press and busy |
diff --git a/internal/console/templates/email_link.html b/internal/console/templates/email_link.html| index e21ab2a0d..1e2b7611f 100644 |
| --- a/internal/console/templates/email_link.html |
| +++ b/internal/console/templates/email_link.html |
| @@ -3,6 +3,6 @@ |
| <form class="signin" method="post" action="/auth/email/link"> |
| <input type="hidden" name="t" value="{{.LinkToken}}"> |
| <input type="hidden" name="nonce" value="{{.LinkNonce}}"> |
| - <button type="submit">{{if .StepUpLink}}{{.SigninCopy.StepUpLinkButton}}{{else}}{{.SigninCopy.LinkButton}}{{end}}</button> |
| + <button type="submit" data-busy>{{if .StepUpLink}}{{.SigninCopy.StepUpLinkButton}}{{else}}{{.SigninCopy.LinkButton}}{{end}}</button> |
| </form> |
| {{template "bottom" .}}{{end}} |
diff --git a/internal/console/templates/home.html b/internal/console/templates/home.html| index cd9944420..66ad11d2f 100644 |
| --- a/internal/console/templates/home.html |
| +++ b/internal/console/templates/home.html |
| @@ -12,7 +12,7 @@ |
| <label for="address">{{.SigninCopy.EmailLabel}}</label> |
| <input id="address" type="email" name="address" value="{{.Prefill}}" placeholder="{{.SigninCopy.EmailPlaceholder}}" autocomplete="email" required autofocus> |
| {{if .Next}}<input type="hidden" name="next" value="{{.Next}}">{{end}} |
| - <button type="submit">{{.SigninCopy.EmailButton}}</button> |
| + <button type="submit" data-busy>{{.SigninCopy.EmailButton}}</button> |
| </form> |
| <p class="small">{{.SigninCopy.Small}}</p> |
| {{template "bottom" .}}{{end}} |
diff --git a/internal/domains/mint.go b/internal/domains/mint.go| index 1fa33bfe1..c478398ec 100644 |
| --- a/internal/domains/mint.go |
| +++ b/internal/domains/mint.go |
| @@ -12,6 +12,7 @@ import ( |
| "errors" |
| "fmt" |
| "strings" |
| + "sync" |
| "time" |
| "github.com/carlosframework/platform/internal/release" |
| @@ -142,29 +143,58 @@ func NextAccountID(ctx context.Context, s release.Store) (int64, error) { |
| if err != nil { |
| return 0, fmt.Errorf("domains: list accounts: %w", err) |
| } |
| - max := int64(ReservedAccountID) |
| + var manifests []string |
| for _, key := range keys { |
| - if _, ok := AccountManifestSqid(key); !ok { |
| - continue |
| - } |
| - body, _, err := s.Get(ctx, key) |
| - if err != nil { |
| - // Unreadable is not "free": an id we cannot see is an id we must |
| - // not reuse, so a read failure fails the mint rather than risking |
| - // a collision. |
| - return 0, fmt.Errorf("domains: read %s: %w", key, err) |
| + if _, ok := AccountManifestSqid(key); ok { |
| + manifests = append(manifests, key) |
| } |
| - var m AccountManifest |
| - if err := json.Unmarshal(body, &m); err != nil { |
| - continue // unparseable: claims no id we can honour |
| + } |
| + // Every manifest is read, because a manifest's body (not its key) says |
| + // which id it claims. The reads run nextIDReaders at a time: one after |
| + // another they took about 25 ms each, so a deployment with a hundred |
| + // accounts made every new person's first sign-in wait nearly three |
| + // seconds (2026-11-07). |
| + ids := make([]int64, len(manifests)) |
| + errs := make([]error, len(manifests)) |
| + sem := make(chan struct{}, nextIDReaders) |
| + var wg sync.WaitGroup |
| + for i, key := range manifests { |
| + wg.Add(1) |
| + sem <- struct{}{} |
| + go func() { |
| + defer wg.Done() |
| + defer func() { <-sem }() |
| + body, _, err := s.Get(ctx, key) |
| + if err != nil { |
| + // Unreadable is not "free": an id we cannot see is an id we |
| + // must not reuse, so a read failure fails the mint rather |
| + // than risking a collision. |
| + errs[i] = fmt.Errorf("domains: read %s: %w", key, err) |
| + return |
| + } |
| + var m AccountManifest |
| + if err := json.Unmarshal(body, &m); err != nil { |
| + return // unparseable: claims no id we can honour |
| + } |
| + ids[i] = m.ID |
| + }() |
| + } |
| + wg.Wait() |
| + max := int64(ReservedAccountID) |
| + for i := range manifests { |
| + if errs[i] != nil { |
| + return 0, errs[i] |
| } |
| - if m.ID > max { |
| - max = m.ID |
| + if ids[i] > max { |
| + max = ids[i] |
| } |
| } |
| return skipReservedIDs(max + 1), nil |
| } |
| +// nextIDReaders is how many account manifests NextAccountID reads at once. |
| +const nextIDReaders = 16 |
| + |
| // MintAccount allocates the next free account id and publishes its manifest, |
| // returning the id and its frozen sqid. |
| // |
diff --git a/internal/domains/mint_test.go b/internal/domains/mint_test.go| index 5114b31f2..ba9781089 100644 |
| --- a/internal/domains/mint_test.go |
| +++ b/internal/domains/mint_test.go |
| @@ -3,6 +3,7 @@ package domains_test |
| import ( |
| "context" |
| "encoding/json" |
| + "errors" |
| "strings" |
| "testing" |
| "time" |
| @@ -248,3 +249,37 @@ func (r *racingStore) Put(ctx context.Context, key string, body []byte, ifMatch |
| r.beforePut(key) |
| return r.Store.Put(ctx, key, body, ifMatch) |
| } |
| + |
| +// failingGetStore refuses to read one key. |
| +type failingGetStore struct { |
| + release.Store |
| + bad string |
| +} |
| + |
| +func (f failingGetStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if key == f.bad { |
| + return nil, "", errors.New("synthetic read failure") |
| + } |
| + return f.Store.Get(ctx, key) |
| +} |
| + |
| +// The manifests are read several at a time; the answer is still the highest |
| +// claim over all of them, and one unreadable manifest still fails the mint |
| +// (an id nobody can see must not be handed out). |
| +func TestNextAccountIDReadsEveryManifest(t *testing.T) { |
| + ctx := t.Context() |
| + s := release.NewDirStore(t.TempDir()) |
| + for id := int64(2); id <= 60; id++ { |
| + writeManifest(t, s, id, domains.Sqid(id)) |
| + } |
| + // A manifest whose body claims more than its key says still counts. |
| + writeManifest(t, s, 90, domains.Sqid(30)+"x") |
| + got, err := domains.NextAccountID(ctx, s) |
| + if err != nil || got != 91 { |
| + t.Fatalf("NextAccountID = %d (%v), want 91", got, err) |
| + } |
| + bad := failingGetStore{Store: s, bad: domains.AccountManifestKey(domains.Sqid(41))} |
| + if got, err := domains.NextAccountID(ctx, bad); err == nil { |
| + t.Fatalf("NextAccountID with an unreadable manifest = %d, want an error", got) |
| + } |
| +} |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index feebf54e9..95d483abc 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -113,3 +113,4 @@ plan14-root-reads-region-ha-g2-fixes.tsv 3c1d54d297da31d147cdb4e1ad4627f759c8cb8 |
| plan14-root-reads-fix-asset-e2e-unsized-flake.tsv 3c1d54d297da31d147cdb4e1ad4627f759c8cb8eae2db53cc92218db35e59c7b |
| plan14-root-reads-region-ha-g2r-fixes.tsv 5c6f157c56e24dc835edc534c5dc0e043e6527e8116e5bb470e68e4fd271796c |
| plan14-root-reads-fix-incomplete-domains-pass.tsv 61027a32e31cb7ce017304f526f668c26980999e2699a3013a82e2630164143e |
| +plan14-root-reads-signin-first-run-mobile.tsv 61027a32e31cb7ce017304f526f668c26980999e2699a3013a82e2630164143e |
diff --git a/internal/provision/testdata/plan14-root-reads-signin-first-run-mobile.tsv b/internal/provision/testdata/plan14-root-reads-signin-first-run-mobile.tsv| new file mode 100644 |
| index 000000000..878078d6e |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-signin-first-run-mobile.tsv |
| @@ -0,0 +1,3 @@ |
| +# Census overlay signin-first-run-mobile, written by census-propose (#369). census-ruling-signin-first-run-mobile, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-signin-first-run-mobile.md. |
| +# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@coverage internal/domains b5925d633145236d4cdff2213805dd0fba262bc67cbf9001fe12f32e43941b37 |