carlos / platform Public

mail: serialize address work per app in the console (Task 3, ruling)

Paul's ruling on #1558 (2026-11-30, option (a)): a per-(account, app)
process mutex around every address transition, instance sender create
and removal, per-instance switch, teardown and RemoveDomain, and a
per-(account, domain) mutex around the address pin and EnsureDomain's
app-add, following the relay writer's relayAppLocks. The console is the
only caller and one process per deployment; HostClaim is off in
production, so the claim gate serializes nothing there. Interleaving
tests now drive the rules below the lock, and a new test proves the
exported operations cannot interleave.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev cf32b998bd9c38cba55f8863768b824b05170253 parent 86a793c
6 files changed, +138 −42
  • internal/mail/addresses.go +19 −2
  • internal/mail/addresses_interleave_test.go +71 −39
  • internal/mail/applock.go +38 −0
  • internal/mail/instancesender.go +4 −1
  • internal/mail/perinstance.go +1 −0
  • internal/mail/walk.go +5 −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-GnRrux
.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/costexplorer v1.67.5
go: downloading github.com/aws/aws-sdk-go-v2/service/s3 v1.105.0
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 modernc.org/sqlite v1.55.0
go: downloading golang.org/x/net v0.62.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/ec2 v1.324.0
go: downloading github.com/aws/aws-sdk-go-v2/service/sns v1.43.0
go: downloading golang.org/x/sys v0.49.0
go: downloading github.com/aws/aws-sdk-go-v2/service/iam v1.58.2
go: downloading golang.org/x/crypto v0.58.0
go: downloading github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi v1.37.0
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading github.com/pion/dtls/v3 v3.1.4
go: downloading github.com/pion/transport/v4 v4.0.2
go: downloading github.com/pion/randutil v0.1.0
go: downloading github.com/beorn7/perks v1.0.1
go: downloading github.com/prometheus/client_model v0.5.0
go: downloading github.com/cespare/xxhash/v2 v2.3.0
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/klauspost/compress v1.20.2
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/aws/aws-sdk-go-v2/service/ecs v1.91.0
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading modernc.org/libc v1.74.1
go: downloading modernc.org/libc v1.74.1
go: downloading github.com/google/uuid v1.6.0
go: downloading modernc.org/mathutil v1.7.1
go: downloading github.com/dustin/go-humanize v1.0.1

amadan: job cancelled — a newer push superseded it
diff --git a/internal/mail/addresses.go b/internal/mail/addresses.go
index 64b146c7c..1f3259bbb 100644
--- a/internal/mail/addresses.go
+++ b/internal/mail/addresses.go
@@ -33,6 +33,13 @@ package mail
// write retains the gate (claim_gate.go:425-427). Recovery runs as its own
// admitted call, before the call that may refuse.
//
+// SERIALIZATION (Paul's ruling on #1558, option (a)): every exported
+// function here holds the app's process lock (applock.go) for its whole
+// run, and the domain pin holds the domain's. The rules above make each
+// step safe on its own; the lock is what makes the sequence of steps safe
+// on a console without the mail claim gate, where three review rounds
+// showed the rules alone are not enough.
+//
// Domain sharing (decision 6) is pinned on the domain record itself:
// AddressApp is set by CAS before an address is reserved, and EnsureDomain
// refuses another app in the same CAS'd write that would add it. The
@@ -236,6 +243,7 @@ func keyCarries(ctx context.Context, s release.Store, acct, app, id, c, nonce st
// 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 {
+ defer lockMailDomain(acct, domain)()
for attempt := 0; attempt < 8; attempt++ {
rec, etag, err := GetDomain(ctx, s, acct, domain)
if err != nil {
@@ -687,6 +695,13 @@ func refuseDomainRemoveWhileAddressesUse(ctx context.Context, s release.Store, a
// RecoverAddresses finishes any pending grant or release of one instance
// sender, as its own admitted call.
func RecoverAddresses(ctx context.Context, s release.Store, acct, app, id string) (*Sender, error) {
+ defer lockMailApp(acct, app)()
+ return recoverAddressesAdmitted(ctx, s, acct, app, id)
+}
+
+// recoverAddressesAdmitted is RecoverAddresses for a caller already holding
+// the app lock.
+func recoverAddressesAdmitted(ctx context.Context, s release.Store, acct, app, id string) (*Sender, error) {
if _, enabled := s.(ClaimMailStore); !enabled {
return claimUnserializedRecoverAddresses(ctx, s, acct, app, id)
}
@@ -709,7 +724,8 @@ func GrantAddress(ctx context.Context, s release.Store, acct, app, id, address s
if err != nil {
return nil, err
}
- if _, err := RecoverAddresses(ctx, s, acct, app, id); err != nil {
+ defer lockMailApp(acct, app)()
+ if _, err := recoverAddressesAdmitted(ctx, s, acct, app, id); err != nil {
return nil, err
}
if _, enabled := s.(ClaimMailStore); !enabled {
@@ -733,7 +749,8 @@ func RevokeAddress(ctx context.Context, s release.Store, acct, app, id, address
if err != nil {
return nil, err
}
- if _, err := RecoverAddresses(ctx, s, acct, app, id); err != nil {
+ defer lockMailApp(acct, app)()
+ if _, err := recoverAddressesAdmitted(ctx, s, acct, app, id); err != nil {
return nil, err
}
if _, enabled := s.(ClaimMailStore); !enabled {
diff --git a/internal/mail/addresses_interleave_test.go b/internal/mail/addresses_interleave_test.go
index 6f0122a29..c85b9a9f2 100644
--- a/internal/mail/addresses_interleave_test.go
+++ b/internal/mail/addresses_interleave_test.go
@@ -11,6 +11,13 @@ import (
"github.com/carlosframework/platform/internal/release"
)
+// These schedules run the RULES of addresses.go step against step, below
+// the app lock (applock.go): the concurrent second operation calls the
+// claimUnserialized step directly, as two handlers would without the lock.
+// The exported functions take the app lock and cannot interleave at all
+// (TestExportedAddressOpsSerialize); the round-3 review showed a schedule
+// the rules alone do not survive, which is why the lock exists.
+
// pausingStore parks the first write whose op and key match, before or
// after it reaches the store, until the test releases it. Everything else
// passes straight through. This is the unserialized (HostClaim off)
@@ -98,6 +105,14 @@ func grantOn(id string) func(release.Store) error {
}
}
+// grantStepOn is the grant step below the app lock.
+func grantStepOn(id string) func(release.Store) error {
+ return func(s release.Store) error {
+ _, err := claimUnserializedGrantAddresses(context.Background(), s, tAcct, tApp, id, []string{"p@x.example"})
+ return err
+ }
+}
+
// A grant paused between its reservation and its key, while recovery runs:
// recovery rolls the reservation forward, the grant's key write finds its
// own key, and nothing is orphaned (round 1 P1).
@@ -105,8 +120,8 @@ func TestInterleaveGrantPausedBeforeKeyWhileRecover(t *testing.T) {
base := release.NewDirStore(t.TempDir())
addrFixture(t, base)
p := newPausing(base, "Put", "/email/addresses/", false)
- done := runParked(t, p, grantOn("a.shop.example"))
- if _, err := RecoverAddresses(context.Background(), base, tAcct, tApp, "a.shop.example"); err != nil {
+ done := runParked(t, p, grantStepOn("a.shop.example"))
+ if _, err := claimUnserializedRecoverAddresses(context.Background(), base, tAcct, tApp, "a.shop.example"); err != nil {
t.Fatal(err)
}
if err := finish(t, p, done); err != nil {
@@ -124,8 +139,8 @@ func TestInterleaveGrantPausedAfterKeyWhileRecover(t *testing.T) {
base := release.NewDirStore(t.TempDir())
addrFixture(t, base)
p := newPausing(base, "Put", "/email/addresses/", true)
- done := runParked(t, p, grantOn("a.shop.example"))
- if _, err := RecoverAddresses(context.Background(), base, tAcct, tApp, "a.shop.example"); err != nil {
+ done := runParked(t, p, grantStepOn("a.shop.example"))
+ if _, err := claimUnserializedRecoverAddresses(context.Background(), base, tAcct, tApp, "a.shop.example"); err != nil {
t.Fatal(err)
}
if err := finish(t, p, done); err != nil {
@@ -168,7 +183,7 @@ func TestInterleaveTwoSendersRace(t *testing.T) {
base := release.NewDirStore(t.TempDir())
addrFixture(t, base)
p := newPausing(base, "Put", "/email/addresses/", false)
- done := runParked(t, p, grantOn("a.shop.example"))
+ done := runParked(t, p, grantStepOn("a.shop.example"))
// b's direct step (its preflight read happens now, a's key not yet written).
if _, err := claimUnserializedGrantAddresses(context.Background(), base, tAcct, tApp, "b.shop.example", []string{"p@x.example"}); err != nil {
t.Fatalf("b: %v", err)
@@ -177,7 +192,7 @@ func TestInterleaveTwoSendersRace(t *testing.T) {
if aErr == nil {
t.Fatal("both senders' grants succeeded")
}
- if _, err := RecoverAddresses(context.Background(), base, tAcct, tApp, "a.shop.example"); err != nil {
+ if _, err := claimUnserializedRecoverAddresses(context.Background(), base, tAcct, tApp, "a.shop.example"); err != nil {
t.Fatal(err)
}
checkAddressInvariant(t, base, ilIDs, ilAddrs, "race")
@@ -189,56 +204,73 @@ func TestInterleaveTwoSendersRace(t *testing.T) {
}
}
-// Round 2's P1 schedule: a grant paused before its key write; recovery
-// grants the address; a revoke completes; the old grant resumes and writes
-// a key naming a sender that lists nothing. That key is stale: it must not
-// block another sender, and nothing is granted twice.
+// Round 2's P1 schedule, at the rule level: a grant step paused before its
+// key write; recovery grants the address; a revoke completes; the old step
+// resumes. Whatever it leaves does not block another sender, and nothing
+// is granted twice.
func TestInterleaveOldGrantAfterRecoverAndRevoke(t *testing.T) {
ctx := context.Background()
base := release.NewDirStore(t.TempDir())
addrFixture(t, base)
p := newPausing(base, "Put", "/email/addresses/", false)
- done := runParked(t, p, grantOn("a.shop.example"))
- if _, err := RecoverAddresses(ctx, base, tAcct, tApp, "a.shop.example"); err != nil {
+ done := runParked(t, p, grantStepOn("a.shop.example"))
+ if _, err := claimUnserializedRecoverAddresses(ctx, base, tAcct, tApp, "a.shop.example"); err != nil {
t.Fatal(err)
}
checkAddressInvariant(t, base, ilIDs, ilAddrs, "after recover")
- if _, err := RevokeAddress(ctx, base, tAcct, tApp, "a.shop.example", "p@x.example", time.Now()); err != nil {
+ if _, err := claimUnserializedRevokeAddress(ctx, base, tAcct, tApp, "a.shop.example", "p@x.example"); err != nil {
t.Fatal(err)
}
checkAddressInvariant(t, base, ilIDs, ilAddrs, "after revoke")
- _ = finish(t, p, done) // its outcome is not the point; the state is
- checkAddressInvariant(t, base, ilIDs, ilAddrs, "after the old grant resumed")
- if sn := senderOf(t, base, "a.shop.example"); sn.Grant != nil && len(sn.Grant.Addresses) != 0 {
- t.Fatalf("the revoked address came back: %+v", sn.Grant)
- }
- // Whatever key the old grant left, it does not block b.
- if _, err := GrantAddress(ctx, base, tAcct, tApp, "b.shop.example", "p@x.example", time.Now()); err != nil {
+ _ = finish(t, p, done)
+ checkAddressInvariant(t, base, ilIDs, ilAddrs, "after the old step resumed")
+ if _, err := claimUnserializedGrantAddresses(ctx, base, tAcct, tApp, "b.shop.example", []string{"p@x.example"}); err != nil {
t.Fatalf("b blocked by a stale key: %v", err)
}
checkAddressInvariant(t, base, ilIDs, ilAddrs, "b granted")
}
-// The public GrantAddress during a paused revoke: its recovery finishes the
-// release first, then it grants; the revoke's late delete cannot remove the
-// new key (its etag changed), and the invariant holds at every boundary.
-func TestInterleavePublicGrantDuringPausedRevoke(t *testing.T) {
+// TestExportedAddressOpsSerialize: with one exported address operation
+// parked mid-write, every other exported operation on the same app waits
+// for it (the app lock, Paul's ruling on #1558), and both finish with the
+// invariant intact. This is what rules out round 3's schedule, in which a
+// grant paused after its nonce check consumed a later reservation.
+func TestExportedAddressOpsSerialize(t *testing.T) {
ctx := context.Background()
- base := release.NewDirStore(t.TempDir())
- addrFixture(t, base)
- if _, err := GrantAddress(ctx, base, tAcct, tApp, "a.shop.example", "p@x.example", time.Now()); err != nil {
- t.Fatal(err)
+ others := map[string]func(release.Store) error{
+ "recover": func(s release.Store) error {
+ _, err := RecoverAddresses(ctx, s, tAcct, tApp, "a.shop.example")
+ return err
+ },
+ "revoke": func(s release.Store) error {
+ _, err := RevokeAddress(ctx, s, tAcct, tApp, "a.shop.example", "p@x.example", time.Now())
+ return err
+ },
+ "other sender's grant": grantOn("b.shop.example"),
+ "remove": func(s release.Store) error {
+ return RemoveInstanceSender(ctx, s, tAcct, tApp, "a.shop.example", time.Now())
+ },
}
- p := newPausing(base, "DeleteIfMatch", "/email/addresses/", false)
- done := runParked(t, p, func(s release.Store) error {
- _, err := RevokeAddress(ctx, s, tAcct, tApp, "a.shop.example", "p@x.example", time.Now())
- return err
- })
- checkAddressInvariant(t, base, ilIDs, ilAddrs, "revoke parked")
- if _, err := GrantAddress(ctx, base, tAcct, tApp, "a.shop.example", "p@x.example", time.Now()); err != nil {
- t.Fatalf("grant during a paused revoke: %v", err)
+ for name, other := range others {
+ base := release.NewDirStore(t.TempDir())
+ addrFixture(t, base)
+ p := newPausing(base, "Put", "/email/addresses/", false)
+ done := runParked(t, p, grantOn("a.shop.example"))
+ second := make(chan error, 1)
+ go func() { second <- other(base) }()
+ select {
+ case err := <-second:
+ t.Fatalf("%s finished while a grant of the same app was parked: %v", name, err)
+ case <-time.After(300 * time.Millisecond):
+ }
+ if err := finish(t, p, done); err != nil {
+ t.Fatalf("%s: the parked grant: %v", name, err)
+ }
+ select {
+ case <-second:
+ case <-time.After(10 * time.Second):
+ t.Fatalf("%s never finished after the grant released the lock", name)
+ }
+ checkAddressInvariant(t, base, ilIDs, ilAddrs, name)
}
- checkAddressInvariant(t, base, ilIDs, ilAddrs, "re-granted")
- _ = finish(t, p, done)
- checkAddressInvariant(t, base, ilIDs, ilAddrs, "revoke resumed")
}
diff --git a/internal/mail/applock.go b/internal/mail/applock.go
new file mode 100644
index 000000000..5e6fb73cf
--- /dev/null
+++ b/internal/mail/applock.go
@@ -0,0 +1,38 @@
+package mail
+
+// Per-(account, app) and per-(account, domain) serialization of instance
+// sender address work, Paul's ruling on #1558 (2026-11-30, option (a)).
+//
+// The production console runs with CARLOS_HOST_CLAIM off, so the mail
+// claim gate does not serialize anything there (claimMailStore returns the
+// bare store), and three review rounds showed that address ownership
+// cannot be made safe lock-free with the store's single-object CAS. This
+// package is linked into the console, the one process per deployment
+// (server.go, "one console process per deployment") and the only caller
+// of these functions, so a process mutex here is the serialization the
+// relay writer's relayAppLocks gives its operations (server.go:1641-1650).
+//
+// Lock order: an app lock, then a domain lock. Nothing takes an app lock
+// while holding a domain lock, so the two cannot deadlock. The locks are
+// never held across a call that takes them again.
+
+import "sync"
+
+var (
+ mailAppLocks sync.Map // "<acct>/<app>" -> *sync.Mutex
+ mailDomainLocks sync.Map // "<acct>/<domain>" -> *sync.Mutex
+)
+
+func lockFrom(m *sync.Map, key string) func() {
+ v, _ := m.LoadOrStore(key, &sync.Mutex{})
+ mu := v.(*sync.Mutex)
+ mu.Lock()
+ return mu.Unlock
+}
+
+// lockMailApp serializes every address transition, instance sender create
+// and removal, per-instance switch and teardown of one app.
+func lockMailApp(acct, app string) func() { return lockFrom(&mailAppLocks, acct+"/"+app) }
+
+// lockMailDomain serializes a domain's address pin with any app joining it.
+func lockMailDomain(acct, domain string) func() { return lockFrom(&mailDomainLocks, acct+"/"+domain) }
diff --git a/internal/mail/instancesender.go b/internal/mail/instancesender.go
index bbe1197e8..49cf52795 100644
--- a/internal/mail/instancesender.go
+++ b/internal/mail/instancesender.go
@@ -95,7 +95,8 @@ func CreateInstanceSender(ctx context.Context, s release.Store, acct, app, host
if err != nil {
return nil, err
}
- if _, err := RecoverAddresses(ctx, s, acct, app, id); err != nil {
+ defer lockMailApp(acct, app)()
+ if _, err := recoverAddressesAdmitted(ctx, s, acct, app, id); err != nil {
return nil, err
}
if _, enabled := s.(ClaimMailStore); !enabled {
@@ -141,6 +142,7 @@ func claimUnserializedSetInstanceSenderCap(ctx context.Context, s release.Store,
// the door.
func SetInstanceSenderCap(ctx context.Context, s release.Store, acct, app, host string, dailyCap int,
actor string, now time.Time) (*Sender, error) {
+ defer lockMailApp(acct, app)()
if _, enabled := s.(ClaimMailStore); !enabled {
return claimUnserializedSetInstanceSenderCap(ctx, s, acct, app, host, dailyCap, actor, now)
}
@@ -214,6 +216,7 @@ func RemoveInstanceSender(ctx context.Context, s release.Store, acct, app, host
if err != nil {
return err
}
+ defer lockMailApp(acct, app)()
if _, enabled := s.(ClaimMailStore); !enabled {
return claimUnserializedRemoveInstanceSender(ctx, s, acct, app, id, now)
}
diff --git a/internal/mail/perinstance.go b/internal/mail/perinstance.go
index 70a516798..af8d21414 100644
--- a/internal/mail/perinstance.go
+++ b/internal/mail/perinstance.go
@@ -113,6 +113,7 @@ func claimUnserializedSetPerInstance(ctx context.Context, s release.Store, acct,
// SetPerInstance turns per-instance mode on or off (decision 2). Every
// refusal is decided before the one write.
func SetPerInstance(ctx context.Context, s release.Store, acct, app string, on bool, _ string, now time.Time) (*Sender, error) {
+ defer lockMailApp(acct, app)()
if _, enabled := s.(ClaimMailStore); !enabled {
return claimUnserializedSetPerInstance(ctx, s, acct, app, on, now)
}
diff --git a/internal/mail/walk.go b/internal/mail/walk.go
index dacaa49a2..c63c47cf6 100644
--- a/internal/mail/walk.go
+++ b/internal/mail/walk.go
@@ -187,6 +187,9 @@ func claimUnserializedEnsureDomain(ctx context.Context, s release.Store, p Provi
}
// Read-only, before the claim's write: joining a domain another app's
// instance addresses depend on would share it under them (addresses.go).
+ // The domain's lock (applock.go) serializes this app-add with the
+ // domain's address pin for the rest of the walk.
+ defer lockMailDomain(acct, domain)()
if err := refuseDomainShareWhileAddressesUse(ctx, s, acct, app, domain); err != nil {
return nil, nil, err
}
@@ -2362,6 +2365,7 @@ func RevokeStandalone(ctx context.Context, s release.Store, p Provisioner, acct,
func Teardown(ctx context.Context, s release.Store, p Provisioner, w dnsrec.Writer,
d Deployment, acct, app string) error {
+ defer lockMailApp(acct, app)() // instance senders go first (applock.go)
if _, enabled := s.(ClaimMailStore); !enabled {
return claimUnserializedTeardown(ctx, s, p, w, d, acct, app)
}
@@ -2381,6 +2385,7 @@ func Teardown(ctx context.Context, s release.Store, p Provisioner, w dnsrec.Writ
func RemoveDomain(ctx context.Context, s release.Store, p Provisioner, w dnsrec.Writer,
d Deployment, acct, app, domain string) (*DomainRemoval, error) {
+ defer lockMailApp(acct, app)() // against this app's instance address grants (applock.go)
if _, enabled := s.(ClaimMailStore); !enabled {
return claimUnserializedRemoveDomain(ctx, s, p, w, d, acct, app, domain)
}