carlos / platform Public

email: whole-branch review R1 fixes (2 P1s, 2 P2s)

P1-1: instance delete holds the app lock from its "no sender" check to
the end, and sender create re-checks the instance under the same lock
(CreateInstanceSenderIf), so neither ordering leaves a sender for a
retired instance (both orderings tested over HTTP with parked stores).
P1-2: in per-instance mode the app-wide operator pause writes the hold
over every instance (InstancesPause) and resume lifts it, so a reported
pause is an enforced one. P2-3: removal reconciles every domain pin of
the app at its end, so an unpin failure is recovered on retry. P2-4:
the new verbs validate --account-id without exiting (checkAccountIDE).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev bb78b3eb5c91a95fcbaab5bcd65a15365fa1dbd5 parent d2c1dd6
13 files changed, +409 −30
  • accounts.go +13 −4
  • docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-WB-R1.md +61 −0
  • internal/console/apiinstances.go +4 −0
  • internal/console/apiinstancesender.go +46 −8
  • internal/console/apiinstancesender_test.go +173 −0
  • internal/console/apimail.go +9 −0
  • internal/mail/addresses.go +15 −0
  • internal/mail/applock.go +16 −0
  • internal/mail/instancesender.go +39 −16
  • internal/mail/instancesender_test.go +8 −0
  • internal/provision/testdata/plan14-root-reads-instance-senders-1.tsv +1 −1
  • mail_instance_cli.go +8 −1
  • mail_instance_cli_test.go +16 −0

CI cancelled — superseded by a newer push — run details

CI log
=== gate ===
go: downloading go1.26.10 (linux/arm64)
go version go1.26.10 linux/arm64
opentofu: arm64, tofu 1.13.9, aws 6.73.0, archive 2.8.1
  tofu: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/tofu_1.13.9_linux_arm64.tar.gz
  tofu: downloaded, digest verified
  aws: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-aws_6.73.0_linux_arm64.zip
  aws: downloaded, digest verified
  archive: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-archive_2.8.1_linux_arm64.zip
  archive: downloaded, digest verified
  installed in /tmp/carlos-opentofu-Uvhims
.amadan/test-gate.sh
go: downloading github.com/aws/aws-sdk-go-v2 v1.44.0
go: downloading github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.68.0
go: downloading github.com/aws/aws-sdk-go-v2/service/s3 v1.105.0
go: downloading github.com/aws/aws-sdk-go-v2/service/costexplorer v1.67.5
go: downloading github.com/aws/smithy-go v1.28.1
go: downloading golang.org/x/crypto/x509roots/fallback v0.0.0-20260209214922-2f26647a795e
go: downloading golang.org/x/net v0.62.0
go: downloading modernc.org/sqlite v1.55.0
go: downloading golang.org/x/crypto v0.58.0
go: downloading github.com/aws/aws-sdk-go-v2/config v1.32.6
go: downloading github.com/aws/aws-sdk-go-v2/service/ec2 v1.324.0
go: downloading github.com/aws/aws-sdk-go-v2/service/acm v1.45.0
go: downloading github.com/aws/aws-sdk-go-v2/service/iam v1.58.2
go: downloading github.com/aws/aws-sdk-go-v2/service/route53 v1.64.1
go: downloading golang.org/x/sys v0.49.0
go: downloading golang.org/x/mod v0.41.0
go: downloading github.com/pion/logging v0.2.4
go: downloading github.com/pion/stun/v3 v3.1.5
go: downloading github.com/pion/turn/v4 v4.1.4
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading github.com/prometheus/client_golang v1.17.0
go: downloading github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.20.18
go: downloading github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4
go: downloading github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.38
go: downloading github.com/klauspost/compress v1.20.2
go: downloading github.com/cespare/xxhash/v2 v2.3.0
go: downloading github.com/prometheus/client_model v0.5.0
go: downloading github.com/beorn7/perks v1.0.1
go: downloading github.com/prometheus/common v0.45.0
go: downloading github.com/prometheus/procfs v0.12.0
go: downloading google.golang.org/protobuf v1.36.10
go: downloading github.com/pion/randutil v0.1.0
go: downloading github.com/pion/transport/v4 v4.0.2
go: downloading github.com/pion/dtls/v3 v3.1.4
go: downloading github.com/wlynxg/anet v0.0.5
go: downloading github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0
go: downloading golang.org/x/text v0.43.0
go: downloading modernc.org/sqlite v1.55.0
go: downloading github.com/klauspost/compress v1.20.2
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0
go: downloading modernc.org/libc v1.74.1
go: downloading modernc.org/libc v1.74.1
go: downloading github.com/dustin/go-humanize v1.0.1
go: downloading github.com/google/uuid v1.6.0
go: downloading modernc.org/mathutil v1.7.1
go: downloading modernc.org/mathutil v1.7.1
go: downloading github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec

amadan: job cancelled — a newer push superseded it
diff --git a/accounts.go b/accounts.go
index 1cd44306d..e5c3a0fb0 100644
--- a/accounts.go
+++ b/accounts.go
@@ -870,20 +870,29 @@ func pickAccount(accts []registry.Account, want string) (string, error) {
// real ops account is "bab". A name in --account-id is a mistake with no
// honest reading, so it is refused by shape before anything else happens.
func checkAccountID(wantID string) string {
+ id, err := checkAccountIDE(wantID)
+ if err != nil {
+ log.Fatal(err)
+ }
+ return id
+}
+
+// checkAccountIDE is checkAccountID returning its refusal, for a command
+// that returns errors (AGENTS.md "Writing Go here").
+func checkAccountIDE(wantID string) (string, error) {
wantID = strings.TrimSpace(wantID)
if wantID == "" || domains.ValidSqid(wantID) {
- return wantID
+ return wantID, nil
}
// "ops" is THE trap: it is the default --account value, the one account
// name every operator types, and it is name-shaped in a way that reads
// exactly like a short sqid. Name its actual sqid rather than making
// someone go look it up.
if wantID == "ops" {
- log.Fatalf(`--account-id takes a sqid; "ops" is a name — use --account ops, or --account-id %s`, release.OpsAccount)
+ return "", fmt.Errorf(`--account-id takes a sqid; "ops" is a name — use --account ops, or --account-id %s`, release.OpsAccount)
}
- log.Fatalf("--account-id %q is not a sqid (sqids use only the letters %s — no i, l, o) — "+
+ return "", fmt.Errorf("--account-id %q is not a sqid (sqids use only the letters %s — no i, l, o) — "+
"it looks like a NAME; names go in --account", wantID, domains.SqidAlphabet)
- return ""
}
// resolveAccount turns a --account/--account-id pair into an account sqid.
diff --git a/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-WB-R1.md b/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-WB-R1.md
new file mode 100644
index 000000000..3bb00e3df
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-FINDINGS-instance-senders-1-WB-R1.md
@@ -0,0 +1,61 @@
+# Whole-branch review, round 1 (Astra, gpt-6-astra, on d2c1dd61a)
+
+Reviewed `e4bd27f37..d2c1dd61a`. **Two P1 findings and two P2 findings.**
+
+1. **P1 — Instance deletion races sender creation.**
+
+ **Evidence:** [apiinstances.go:3486](internal/console/apiinstances.go:3486) checks for a sender before retirement, without sharing creation’s lock. [apiinstancesender.go:214](internal/console/apiinstancesender.go:214) checks the instance record before calling `CreateInstanceSender`.
+
+ **Failure scenario:** Delete observes no sender and pauses. Sender creation observes the still-existing instance and grants its addresses. Delete resumes and retires the instance successfully, leaving its sender behind. Recreating that hostname inherits the surviving sending authority.
+
+ **Invariant / fault family:** Sender lifecycle admission must serialize creation with retirement; decision 13 requires removal of the sender before instance deletion.
+
+ **Fix:** Put both existence checks and their mutations under shared serialization, with checks repeated inside that boundary. Add signal-controlled HTTP tests for both orderings. Locking only the sender write is insufficient.
+
+2. **P1 — An app-wide operator pause succeeds without stopping instance sends.**
+
+ **Evidence:** Without `host`, [apimail.go:1687](internal/console/apimail.go:1687) still calls `SetPaused`, which writes the app sender’s `Pause`. The new selection at [policy.go:172](internal/mailer/policy.go:172) reads only the instance’s pause and `appSender.InstancesPause`.
+
+ **Failure scenario:** Enable per-instance mode with an unpaused instance. Run `carlos email pause --app …`. The request succeeds and records a manual app pause, but the instance continues sending even after cache expiry.
+
+ **Invariant / fault family:** A successful operator pause must enforce the stop it reports. Ignoring the compatibility sentinel must not silently ignore a real operator hold.
+
+ **Fix:** Either refuse the unsupported app-wide pause before writing, directing the operator to instance pauses, or implement an effective app-wide hold while preserving the sentinel. Test through the operator door and mailer admission.
+
+3. **P2 — Interrupted removal can permanently strand the domain pin.**
+
+ **Evidence:** [instancesender.go:193](internal/mail/instancesender.go:193) derives domains exclusively from the grants remaining after recovery. It revokes those grants before attempting unpinning at line 211. [addresses.go:598](internal/mail/addresses.go:598) finishes release recovery without unpinning.
+
+ **Failure scenario:** Remove the last sender using a domain. Address cleanup succeeds, but the domain-unpin write fails. On retry, the sender has no grants or pending addresses, so the domain list is empty; removal deletes the sender and succeeds. `AddressApp` remains set, and another app’s domain-add is refused with zero dependencies.
+
+ **Invariant / fault family:** Domain sharing must recover once all address dependencies disappear, including across interrupted cleanup. This is the earlier domain-pin recovery family.
+
+ **Fix:** Centrally reconcile unused pins under the existing locks, or retain durable cleanup information until unpinning succeeds. Extend the failure-injection test to assert the pin clears and another app can join; its current assertions check only sender and address-key removal.
+
+4. **P2 — New CLI verbs still have a process-exit path during account resolution.**
+
+ **Evidence:** [mail_instance_cli.go:122](mail_instance_cli.go:122) calls `apiAccount`, which calls `checkAccountID`; [accounts.go:882](accounts.go:882) invokes `log.Fatalf`.
+
+ **Failure scenario:** With a valid console session, a new instance/address/per-instance command using `--account-id ops` terminates the process instead of returning an error.
+
+ **Invariant / fault family:** New CLI commands return errors; the dispatcher owns termination. The earlier Task 7 finding is only partly resolved.
+
+ **Fix:** Use error-returning account validation throughout `mailSessionE`, and test invalid account IDs through a new command.
+
+The requested SwitchOn/SwitchOff locks are present. The serialization witness now signals lock entry, and the plan-pause tests exercise replacement after the initial read and across a CAS conflict. Normal last-address unpinning works; finding 3 concerns its interrupted path.
+
+Census verdicts:
+
+| Envelope | Verdict | Evidence |
+|---|---|---|
+| `.` | **APPROVE** | `mail_instance_cli.go:113–313`, `mail_cli.go:215–246,1649–1658,2101–2136`, `services.go:173–179`: console requests and rendering; no new root-local authority. Finding 4 remains a correctness issue. |
+| `internal/mailer` | **REJECT** | `policy.go:156–175`: sender identity checks are sound, but the pause selection bypasses an accepted operator hold (finding 2). `ses.go:80–90` preserves app-derived tenant and encoded attribution. |
+| `internal/mailsubmit` | **APPROVE** | `proto.go:54–61`: additive refusal code only. |
+| `internal/mailwire` | **APPROVE** | `instance.go:50–158`, `mailwire.go:83–120`: additive projections and pure validation; exact-address authorization retains domain verification and exclusive-app checks. |
+| `internal/svcrole` | **APPROVE** | `svcrole.go:90–107`: catalogue addition retains explicit admission and Admin’s union. Console registrations admit `mail` to exactly five doors. |
+
+The record-write census classifications at `instance_senders_1_census_test.go:23–24` are appropriate: `claimUnserializedSwitchOff` remains a reference writer, and `claimAddressKey` writes an email-address key, not an instance record.
+
+Validation was static. The targeted `mailwire` test could not start because the sandbox refused Go’s work-directory creation. No files were edited, reviewers spawned, or full suites run.
+
+**NOT READY**
\ No newline at end of file
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index e7c77270e..6bd8c8f7f 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -43,6 +43,7 @@ import (
"github.com/carlosframework/platform/internal/edge"
"github.com/carlosframework/platform/internal/gate"
"github.com/carlosframework/platform/internal/hostops"
+ "github.com/carlosframework/platform/internal/mail"
"github.com/carlosframework/platform/internal/metrics"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/ratelimit"
@@ -3483,6 +3484,9 @@ func (s *Server) handleAPIInstanceDelete(w http.ResponseWriter, r *http.Request)
jsonError(w, http.StatusBadRequest, "invalid host")
return
}
+ // Held to the end of the delete: creating a sender takes the same lock
+ // and re-checks the instance under it (instance senders decision 13).
+ defer mail.LockApp(acct.Sqid, app)()
if s.refuseInstanceDeleteWithSender(ctx, w, acct.Sqid, app, host) {
return
}
diff --git a/internal/console/apiinstancesender.go b/internal/console/apiinstancesender.go
index b15f32997..9c65d97ec 100644
--- a/internal/console/apiinstancesender.go
+++ b/internal/console/apiinstancesender.go
@@ -14,6 +14,7 @@ import (
"fmt"
"log"
"net/http"
+ "os"
"slices"
"time"
@@ -211,18 +212,21 @@ func (s *Server) handleAPIInstanceSenderCreate(w http.ResponseWriter, r *http.Re
}
ctx, cancel := context.WithTimeout(r.Context(), instanceSenderTimeout)
defer cancel()
- rec, err := provision.GetRecord(ctx, s.cfg.Releases, acct.Sqid, app, host)
- if err != nil {
- log.Printf("console: instance sender create %s/%s: record: %v", app, host, err)
- jsonError(w, http.StatusBadGateway, mailInstanceCopy.WriteFailed)
- return
+ // The record check runs under the app lock that instance delete also
+ // holds, so a sender is never created for an instance being retired.
+ exists := func(ctx context.Context) (bool, error) {
+ rec, err := provision.GetRecord(ctx, s.cfg.Releases, acct.Sqid, app, host)
+ if errors.Is(err, os.ErrNotExist) {
+ return false, nil
+ }
+ return rec != nil, err
}
- if rec == nil {
+ p, _ := principalFrom(r.Context())
+ sn, err := mail.CreateInstanceSenderIf(ctx, s.claimMailStore(), acct.Sqid, app, host, req.Addresses, principalKey(p), time.Now(), exists)
+ if errors.Is(err, mail.ErrNoInstance) {
jsonError(w, http.StatusNotFound, fmt.Sprintf(mailInstanceCopy.NoInstance, host))
return
}
- p, _ := principalFrom(r.Context())
- sn, err := mail.CreateInstanceSender(ctx, s.claimMailStore(), acct.Sqid, app, host, req.Addresses, principalKey(p), time.Now())
if err != nil {
s.writeInstanceSenderError(w, app, host, err)
return
@@ -457,3 +461,37 @@ func joinSemi(parts []string) string {
}
return out
}
+
+// pausePerInstanceApp is the operator pause door's app-wide form for a
+// per-instance app: pause writes a manual hold over every instance; resume
+// lifts whatever hold is there. It reports false, writing nothing, for an
+// app not in per-instance mode.
+func (s *Server) pausePerInstanceApp(ctx context.Context, w http.ResponseWriter, acct *Account, app, addr string, paused bool) bool {
+ sn, _, err := mail.GetSender(ctx, s.cfg.Releases, acct.Sqid, app, mail.SenderAppID)
+ if err != nil {
+ log.Printf("console: api email pause %s/%s: %v", acct.Sqid, app, err)
+ jsonError(w, http.StatusBadGateway, "could not read the email record — try again")
+ return true
+ }
+ if sn == nil || !sn.PerInstance {
+ return false
+ }
+ var hold *mailwire.Pause
+ if paused {
+ hold = &mailwire.Pause{At: time.Now()} // manual: never lifts on its own
+ }
+ if _, err := mail.SetInstancesPause(ctx, s.claimMailStore(), acct.Sqid, app, hold); err != nil {
+ log.Printf("console: api email pause %s/%s: instances hold: %v", acct.Sqid, app, err)
+ jsonError(w, http.StatusBadGateway, "could not change the pause state — try again")
+ return true
+ }
+ s.audit(acct, app, addr, "email-pause", fmt.Sprintf("every instance: %s (cli)",
+ map[bool]string{true: "email paused", false: "email resumed"}[paused]))
+ rec, _, err := mail.Get(ctx, s.cfg.Releases, acct.Sqid, app)
+ if err != nil || rec == nil {
+ writeJSON(w, http.StatusOK, map[string]any{"app": app, "instances_paused": paused})
+ return true
+ }
+ s.mailWalkReply(ctx, w, acct, app, rec)
+ return true
+}
diff --git a/internal/console/apiinstancesender_test.go b/internal/console/apiinstancesender_test.go
index cc41cf1c2..b3b7844b1 100644
--- a/internal/console/apiinstancesender_test.go
+++ b/internal/console/apiinstancesender_test.go
@@ -15,6 +15,7 @@ import (
"github.com/carlosframework/platform/internal/hostops"
"github.com/carlosframework/platform/internal/mail"
"github.com/carlosframework/platform/internal/mailwire"
+ "github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/svcrole"
)
@@ -353,3 +354,175 @@ func TestInstanceSenderWritesClassifyToApp(t *testing.T) {
}
}
}
+
+// parkGetStore parks the first Get of key until released.
+type parkGetStore struct {
+ release.Store
+ key string
+ once sync.Once
+ arrived chan struct{}
+ release chan struct{}
+}
+
+func (p *parkGetStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if key == p.key {
+ p.once.Do(func() {
+ close(p.arrived)
+ <-p.release
+ })
+ }
+ return p.Store.Get(ctx, key)
+}
+
+// Whole-branch review R1 P1-1: instance delete and sender create share the
+// app lock. With the delete parked inside it (at its "no sender" read), a
+// create reaches the lock and waits; when the delete finishes, the create
+// re-checks the instance under the lock and is refused 404. Nothing is left
+// sending for a retired instance.
+func TestInstanceDeleteAndSenderCreateSerialize(t *testing.T) {
+ fx, tok, u, owner := instanceSenderFixtureOwner(t)
+ base := fx.srv.cfg.Releases
+ park := &parkGetStore{Store: base, key: mail.SenderKey("bab", "titogo", isHost),
+ arrived: make(chan struct{}), release: make(chan struct{})}
+ fx.srv.cfg.Releases = park
+ deleted := make(chan int, 1)
+ go func() {
+ status, _, _ := rawReq(t, http.MethodDelete, u+"/"+isHost, owner, "")
+ deleted <- status
+ }()
+ select {
+ case <-park.arrived:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the delete never reached its sender check")
+ }
+ // The rest of the delete (and the create) run on the real store: the
+ // wrapper exists only to park the delete at that one read.
+ fx.srv.cfg.Releases = base
+ reached := make(chan struct{})
+ var once sync.Once
+ restore := mail.SetLockAttemptHook(func(key string) {
+ if key == "bab/titogo" {
+ once.Do(func() { close(reached) })
+ }
+ })
+ defer restore()
+ created := make(chan int, 1)
+ go func() {
+ status, _, out := rawReq(t, http.MethodPost, u+"/"+isHost+"/email", tok, `{"addresses":["p@`+isDomain+`"]}`)
+ if status != http.StatusNotFound {
+ t.Logf("create answered %d %s", status, out)
+ }
+ created <- status
+ }()
+ select {
+ case <-reached:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the create never reached the app lock")
+ }
+ select {
+ case st := <-created:
+ t.Fatalf("create finished (%d) while the delete held the lock", st)
+ default:
+ }
+ close(park.release)
+ if st := <-deleted; st != http.StatusOK {
+ t.Fatalf("delete = %d, want 200", st)
+ }
+ if st := <-created; st != http.StatusNotFound {
+ t.Fatalf("create after the delete = %d, want 404", st)
+ }
+ if has, _ := mail.HasInstanceSender(context.Background(), base, "bab", "titogo", isHost); has {
+ t.Fatal("a sender exists for a retired instance")
+ }
+}
+
+// Whole-branch review R1 P1-2: in per-instance mode an app-wide operator
+// pause holds every instance (InstancesPause, which the mailer reads), and
+// resume lifts it.
+func TestAppWidePausePerInstanceHoldsInstances(t *testing.T) {
+ fx, _, u := instanceSenderFixture(t)
+ ctx := context.Background()
+ fx.srv.cfg.MailOperators = []string{"ops@keymail.dev"}
+ op := emailOperatorToken(t, fx, "code-inst-apppause-op")
+ sn, etag, _ := mail.GetSender(ctx, fx.rel, "bab", "titogo", mail.SenderAppID)
+ now := time.Now()
+ sn.Submission.AppUserReapedAt = &now
+ if _, err := mail.PutSender(ctx, fx.rel, "bab", "titogo", sn, etag); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := mail.SetPerInstance(ctx, fx.rel, "bab", "titogo", true, "op", now); err != nil {
+ t.Fatal(err)
+ }
+ pauseURL := strings.TrimSuffix(u, "/instances") + "/email/pause"
+ hold := func() *mailwire.Pause {
+ sn, _, err := mail.GetSender(ctx, fx.rel, "bab", "titogo", mail.SenderAppID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return sn.InstancesPause
+ }
+ if status, _, out := rawReq(t, http.MethodPost, pauseURL, op, `{"paused":true}`); status != http.StatusOK {
+ t.Fatalf("pause = %d %s", status, out)
+ }
+ if h := hold(); h == nil || h.Kind != "" {
+ t.Fatalf("app-wide pause left instances unheld: %+v", h)
+ }
+ if status, _, out := rawReq(t, http.MethodPost, pauseURL, op, `{"paused":false}`); status != http.StatusOK {
+ t.Fatalf("resume = %d %s", status, out)
+ }
+ if h := hold(); h != nil {
+ t.Fatalf("resume left the hold: %+v", h)
+ }
+}
+
+// The other ordering: a create parked inside the app lock (at its instance
+// check) makes the delete wait at the lock; the create then succeeds and
+// the delete, re-checking under the lock, is refused 409.
+func TestSenderCreateThenInstanceDeleteSerialize(t *testing.T) {
+ fx, tok, u, owner := instanceSenderFixtureOwner(t)
+ base := fx.srv.cfg.Releases
+ park := &parkGetStore{Store: base, key: provision.RecordKey("bab", "titogo", isHost),
+ arrived: make(chan struct{}), release: make(chan struct{})}
+ fx.srv.cfg.Releases = park
+ created := make(chan int, 1)
+ go func() {
+ status, _, _ := rawReq(t, http.MethodPost, u+"/"+isHost+"/email", tok, `{"addresses":["p@`+isDomain+`"]}`)
+ created <- status
+ }()
+ select {
+ case <-park.arrived:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the create never reached its instance check")
+ }
+ fx.srv.cfg.Releases = base
+ reached := make(chan struct{})
+ var once sync.Once
+ restore := mail.SetLockAttemptHook(func(key string) {
+ if key == "bab/titogo" {
+ once.Do(func() { close(reached) })
+ }
+ })
+ defer restore()
+ deleted := make(chan int, 1)
+ go func() {
+ status, _, _ := rawReq(t, http.MethodDelete, u+"/"+isHost, owner, "")
+ deleted <- status
+ }()
+ select {
+ case <-reached:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the delete never reached the app lock")
+ }
+ select {
+ case st := <-deleted:
+ t.Fatalf("delete finished (%d) while the create held the lock", st)
+ default:
+ }
+ close(park.release)
+ if st := <-created; st != http.StatusOK {
+ t.Fatalf("create = %d, want 200", st)
+ }
+ if st := <-deleted; st != http.StatusConflict {
+ t.Fatalf("delete after the create = %d, want 409", st)
+ }
+}
diff --git a/internal/console/apimail.go b/internal/console/apimail.go
index 2bb40abbc..88824d149 100644
--- a/internal/console/apimail.go
+++ b/internal/console/apimail.go
@@ -1650,6 +1650,15 @@ func (s *Server) handleAPIEmailPause(w http.ResponseWriter, r *http.Request) {
s.pauseInstanceSender(ctx, w, acct, app, addr, req.Host, req.Paused, req.DailyCap)
return
}
+ // In per-instance mode no instance sends as the app sender, so an
+ // app-wide pause or resume is the hold over every instance
+ // (InstancesPause), which the mailer reads for each of them
+ // (whole-branch review R1 P1-2).
+ if req.Paused != nil {
+ if handled := s.pausePerInstanceApp(ctx, w, acct, app, addr, *req.Paused); handled {
+ return
+ }
+ }
if req.DailyCap > 0 {
domains, err := s.mailAppDomains(ctx, acct, app)
diff --git a/internal/mail/addresses.go b/internal/mail/addresses.go
index fae9aa7da..88bbe38ec 100644
--- a/internal/mail/addresses.go
+++ b/internal/mail/addresses.go
@@ -268,6 +268,21 @@ func unpinDomainIfUnused(ctx context.Context, s release.Store, acct, app, domain
return fmt.Errorf("mail: %s: domain record kept changing: %w", domain, release.ErrCASConflict)
}
+// unpinUnusedDomains reconciles every domain the app sender is granted:
+// a pin to this app that no address uses any more is released.
+func unpinUnusedDomains(ctx context.Context, s release.Store, acct, app string) error {
+ appSender, _, err := GetSender(ctx, s, acct, app, SenderAppID)
+ if err != nil || appSender == nil || appSender.Grant == nil {
+ return err
+ }
+ for _, d := range appSender.Grant.Domains {
+ if err := unpinDomainIfUnused(ctx, s, acct, app, d); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
// pinDomainForAddresses sets the domain record's AddressApp to app by CAS,
// refusing a domain any other app holds or is pinned to (decision 6).
func pinDomainForAddresses(ctx context.Context, s release.Store, acct, app, domain string) error {
diff --git a/internal/mail/applock.go b/internal/mail/applock.go
index 93ba31143..f0bbc2010 100644
--- a/internal/mail/applock.go
+++ b/internal/mail/applock.go
@@ -43,3 +43,19 @@ func lockMailApp(acct, app string) func() { return lockFrom(&mailAppLocks, acct+
// lockMailDomain serializes a domain's address pin with any app joining it.
func lockMailDomain(acct, domain string) func() { return lockFrom(&mailDomainLocks, acct+"/"+domain) }
+
+// LockApp takes the app's lock for a caller outside this package that must
+// serialize with instance sender work: the console's instance delete holds
+// it from its "no sender" check through the retirement, so a sender cannot
+// be created for an instance being retired (whole-branch review R1 P1-1).
+// The caller must not call this package's exported functions for the same
+// app while holding it.
+func LockApp(acct, app string) func() { return lockMailApp(acct, app) }
+
+// SetLockAttemptHook installs lockAttemptHook and returns the restore, for
+// tests in other packages. Never called by production code.
+func SetLockAttemptHook(h func(key string)) func() {
+ prev := lockAttemptHook
+ lockAttemptHook = h
+ return func() { lockAttemptHook = prev }
+}
diff --git a/internal/mail/instancesender.go b/internal/mail/instancesender.go
index b7570a800..7e8d71844 100644
--- a/internal/mail/instancesender.go
+++ b/internal/mail/instancesender.go
@@ -87,6 +87,19 @@ func claimUnserializedCreateInstanceSender(ctx context.Context, s release.Store,
// instance's sender before it turns the mode on.
func CreateInstanceSender(ctx context.Context, s release.Store, acct, app, host string, addresses []string,
actor string, now time.Time) (*Sender, error) {
+ return CreateInstanceSenderIf(ctx, s, acct, app, host, addresses, actor, now, nil)
+}
+
+// ErrNoInstance is CreateInstanceSenderIf's refusal when its precondition
+// finds no instance at the host.
+var ErrNoInstance = errors.New("mail: no instance at that host")
+
+// CreateInstanceSenderIf is CreateInstanceSender with a precondition asked
+// under the app lock, before any write: the console passes "the instance
+// record exists", so a create cannot interleave with the instance's delete,
+// which holds the same lock (whole-branch review R1 P1-1).
+func CreateInstanceSenderIf(ctx context.Context, s release.Store, acct, app, host string, addresses []string,
+ actor string, now time.Time, exists func(context.Context) (bool, error)) (*Sender, error) {
canonical, err := canonicalAll(addresses)
if err != nil {
return nil, err
@@ -96,6 +109,15 @@ func CreateInstanceSender(ctx context.Context, s release.Store, acct, app, host
return nil, err
}
defer lockMailApp(acct, app)()
+ if exists != nil {
+ ok, err := exists(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if !ok {
+ return nil, ErrNoInstance
+ }
+ }
if _, err := recoverAddressesAdmitted(ctx, s, acct, app, id); err != nil {
return nil, err
}
@@ -175,9 +197,12 @@ func HasInstanceSender(ctx context.Context, s release.Store, acct, app, host str
// delete the record by its etag.
func claimUnserializedRemoveInstanceSender(ctx context.Context, s release.Store, acct, app, id string, now time.Time) error {
sn, _, err := getInstanceSender(ctx, s, acct, app, id)
- if err != nil || sn == nil {
+ if err != nil {
return err
}
+ if sn == nil {
+ return unpinUnusedDomains(ctx, s, acct, app) // a retry after the record went
+ }
if _, err := mutateSender(ctx, s, acct, app, id, func(sn *Sender) bool {
if sn.Removing != nil {
return false
@@ -199,27 +224,25 @@ func claimUnserializedRemoveInstanceSender(ctx context.Context, s release.Store,
return err
}
}
- // The record still exists (Removing), but it lists nothing now, so a
- // domain this sender alone kept pinned is released.
- var domains []string
- for _, c := range grants {
- if d := addressDomain(c); !slices.Contains(domains, d) {
- domains = append(domains, d)
- }
- }
- for _, d := range domains {
- if err := unpinDomainIfUnused(ctx, s, acct, app, d); err != nil {
- return err
- }
- }
+
sn, etag, err := getInstanceSender(ctx, s, acct, app, id)
- if err != nil || sn == nil {
+ if err != nil {
return err
}
+ if sn == nil {
+ return unpinUnusedDomains(ctx, s, acct, app)
+ }
if len(sn.Reserving) != 0 || len(sn.Releasing) != 0 || (sn.Grant != nil && len(sn.Grant.Addresses) != 0) {
return fmt.Errorf("mail: %s/%s/%s: addresses still pending after release: %w", acct, app, id, release.ErrCASConflict)
}
- return release.DeleteIfMatch(ctx, s, SenderKey(acct, app, id), etag)
+ if err := release.DeleteIfMatch(ctx, s, SenderKey(acct, app, id), etag); err != nil {
+ return err
+ }
+ // Release every pin no address uses any more, reconciled across all
+ // the app's domains rather than from this sender's grants: a retry
+ // after an unpin failure has no grants left to name the domain
+ // (whole-branch review R1 P2-3).
+ return unpinUnusedDomains(ctx, s, acct, app)
}
// RemoveInstanceSender removes the host's sender (decision 13). An absent
diff --git a/internal/mail/instancesender_test.go b/internal/mail/instancesender_test.go
index 8ae2ce8f3..eec9dfdef 100644
--- a/internal/mail/instancesender_test.go
+++ b/internal/mail/instancesender_test.go
@@ -233,6 +233,14 @@ func TestRemoveFromEveryInterruptedState(t *testing.T) {
t.Fatalf("re-run after a failure at write %d: %v", n, err)
}
gone(t, base, "failure at write "+itoa(n))
+ // The domain pin is released even when the failure hit the unpin
+ // itself and the re-run had no grants left to name the domain.
+ if rec, _, err := GetDomain(ctx, base, tAcct, tDom); err != nil || rec.AddressApp != "" {
+ t.Fatalf("failure at write %d: domain still pinned to %q (%v)", n, rec.AddressApp, err)
+ }
+ if err := refuseDomainShareWhileAddressesUse(ctx, base, tAcct, "other", tDom); err != nil {
+ t.Fatalf("failure at write %d: another app still refused: %v", n, err)
+ }
}
}
diff --git a/internal/provision/testdata/plan14-root-reads-instance-senders-1.tsv b/internal/provision/testdata/plan14-root-reads-instance-senders-1.tsv
index 3194f4427..29518ec8e 100644
--- a/internal/provision/testdata/plan14-root-reads-instance-senders-1.tsv
+++ b/internal/provision/testdata/plan14-root-reads-instance-senders-1.tsv
@@ -1,6 +1,6 @@
# Census overlay instance-senders-1, written by census-propose (#369). census-ruling-instance-senders-1, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-instance-senders-1.md.
# 0 body, 0 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
-@coverage . 8fc50b771fdab063318e8fd13562f88cddbf35082f818eba9f07c27ecac777bb
+@coverage . 76a4deb60063c5e27109aa0c93191dfeb6778ec75da59fc9a705793da3e0040f
@coverage internal/mailer 7faad983d368293409cd67c257a99faf7814075cc0bf9dad034955ce849dce26
@coverage internal/mailsubmit 293b1864d19aa444237d4976d8e4d5bcffbed8b268c9c4fd7fade244d0b0f604
@coverage internal/mailwire a080b525495cc7762aa536a015ce961f6263c3e89d69bb115adb5a64978d84d6
diff --git a/mail_instance_cli.go b/mail_instance_cli.go
index bd9e7bccd..6159b5bef 100644
--- a/mail_instance_cli.go
+++ b/mail_instance_cli.go
@@ -118,8 +118,15 @@ func mailSessionE(consoleFlag string, acctRaw, acctID *string) (*apiSession, api
if sess == nil {
return nil, apiAcct{}, errors.New(mailDirectModeRefusal)
}
+ id, err := checkAccountIDE(*acctID)
+ if err != nil {
+ return nil, apiAcct{}, err
+ }
printUsing(stdout, sess)
- acct := apiAccount(acctRaw, acctID)
+ acct := apiAcct{Seg: strings.TrimSpace(*acctRaw)}
+ if id != "" {
+ acct = apiAcct{Seg: id, Exact: true}
+ }
if acct.Seg == "" {
if acct, err = sess.defaultAccount(context.Background()); err != nil {
return nil, apiAcct{}, err
diff --git a/mail_instance_cli_test.go b/mail_instance_cli_test.go
index d043e291a..232aa5d09 100644
--- a/mail_instance_cli_test.go
+++ b/mail_instance_cli_test.go
@@ -69,3 +69,19 @@ func TestParseInstanceArgs(t *testing.T) {
t.Errorf("address missing: %v", err)
}
}
+
+// Whole-branch review R1 P2-4: a bad --account-id is a returned error from
+// a new verb, never a process exit.
+func TestInstanceVerbBadAccountIDReturnsError(t *testing.T) {
+ ops := "ops"
+ empty := ""
+ if _, _, err := mailSessionE("", &empty, &ops); err == nil {
+ t.Skip("no console session in this environment; covered by checkAccountIDE below")
+ }
+ if _, err := checkAccountIDE("ops"); err == nil || !strings.Contains(err.Error(), "--account ops") {
+ t.Fatalf("checkAccountIDE(ops) = %v", err)
+ }
+ if id, err := checkAccountIDE(""); err != nil || id != "" {
+ t.Fatalf("empty: %q %v", id, err)
+ }
+}