carlos / platform Public

agent: never spawn on a stale or unknown mail switch

P2-1 (Fable's final review of b0aba39b0, ruled 2026-11-14): a serial
move now marks every cached switch answer stale, synchronously, before
the move's pass set and restart leg, and State reads a stale answer
again, bounded. The restart that completes a flip used to respawn a
bounced instance on the answer from before it, because Refresh runs on
its own goroutine after the bounce. A read that a MarkStale overtook
stores a stale entry, and never replaces a later one.

P2-2: an unreadable switch is unknown, never off. The activator decides
an unknown switch from the instance's own environment: submit when it
holds a *_MAIL_FROM and no *_SMTP_HOST, otherwise the SMTP channel its
bundle carries. The verb forwards an unknown app; the mailer reads the
switch itself and refuses an unswitched one.

Tests: TestFastTickMarksMailSwitchStaleBeforeTheBounce,
TestMailSwitchMarkStale, TestMailSwitchCache (unknown), and
TestMailUnknownSwitchDecidedByTheBundle; each watched to fail with its
fix removed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 81f68b1c3ca4af969ac9893ec5b3441abb470440 parent f578a85
10 files changed, +430 −114
  • internal/activator/agentowned_moves_test.go +1 −1
  • internal/activator/backend_exec.go +34 −7
  • internal/activator/mailbuild.go +1 −1
  • internal/activator/mailbuild_test.go +5 −5
  • internal/activator/mailswitch.go +75 −0
  • internal/activator/mailswitch_test.go +94 −0
  • internal/activator/mailverb_test.go +5 −5
  • internal/host/agent.go +14 −3
  • internal/host/mailswitch.go +86 −39
  • internal/host/mailswitch_test.go +115 −53
diff --git a/internal/activator/agentowned_moves_test.go b/internal/activator/agentowned_moves_test.go
index b4e8c48e1..3880903d8 100644
--- a/internal/activator/agentowned_moves_test.go
+++ b/internal/activator/agentowned_moves_test.go
@@ -35,7 +35,7 @@ func TestAgentOwnedVarsAreMovesBoxOwned(t *testing.T) {
}
cache := edge.NewCache(16, 1<<20)
absent := "<absent>"
- switched := func(string, string) bool { return true }
+ switched := func(string, string) MailSwitchState { return MailSwitchOn }
mailRT := rt
mailRT.Provisioned = true
for _, c := range []struct {
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index dc30b2b62..13b266aba 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -229,9 +229,15 @@ type ExecBackend struct {
// to the box-local mailer through this. Nil mounts nothing.
Mail mailsubmit.Forwarder
// MailSwitch reports whether an app is switched to the submit transport
- // (the app sender's submission block, cached by the agent). It decides
- // CARLOS_MAIL with the bind (agentOwnedVars). Nil is off for every app.
- MailSwitch func(acct, app string) bool
+ // (the app sender's submission block, cached by the agent): on, off, or
+ // unknown when the agent cannot read it. It decides CARLOS_MAIL with the
+ // bind (agentOwnedVars); an unknown answer is decided by the instance's
+ // own environment, never read as off (mailUnknownSubmits). Nil is off
+ // for every app.
+ MailSwitch func(acct, app string) MailSwitchState
+ // mailUnknownLogged holds the hosts agentOwnedVars has logged as
+ // started with the switch unreadable, so each is logged once.
+ mailUnknownLogged sync.Map
// mailUnprovisionedLogged holds the hosts agentOwnedVars has logged as
// unable to submit for want of an instance record, so each is logged
// once.
@@ -2794,7 +2800,7 @@ func (b *ExecBackend) controlMount(rt registry.Route, tokenReader func() (string
instanceupdates.Mount(mux, rt.Host, tokenReader, b.UpdatesReader)
}
if b.Mail != nil {
- mailsubmit.Mount(mux, rt, tokenReader, b.Mail, b.MailSwitch)
+ mailsubmit.Mount(mux, rt, tokenReader, b.Mail, b.mailVerbSwitched)
}
}
}
@@ -2829,7 +2835,7 @@ func (b *ExecBackend) agentOwnedVars(rt registry.Route, control string, fileEnv
} else {
childVars = withoutVars(childVars, "CARLOS_REGION")
}
- if b.mailSubmits(rt, haveControl) {
+ if b.mailSubmits(rt, haveControl, fileEnv) {
childVars = withVar(childVars, "CARLOS_MAIL", "submit")
} else {
childVars = withoutVars(childVars, "CARLOS_MAIL")
@@ -2857,13 +2863,34 @@ func (b *ExecBackend) agentOwnedVars(rt registry.Route, control string, fileEnv
// failure, plan gap G10). That is logged here at error level, once per
// host, with the remedy.
//
+// A switch the agent cannot read (MailSwitchUnknown) is never read as off
+// (Fable's final review, P2-2, ruled 2026-11-14): fileEnv, the environment
+// the instance is about to start with, decides it (mailUnknownSubmits). A
+// bundle holding a <stem>_MAIL_FROM and no <P>_SMTP_HOST submits; any
+// other keeps the SMTP channel its bundle carries. That is logged once per
+// host.
+//
// Everything else strips the variable, including a tenant-supplied one.
-func (b *ExecBackend) mailSubmits(rt registry.Route, haveControl bool) bool {
+func (b *ExecBackend) mailSubmits(rt registry.Route, haveControl bool, fileEnv map[string]string) bool {
if !haveControl || b.Mail == nil || b.MailSwitch == nil {
return false
}
acct := release.RouteAccount(rt)
- if !b.MailSwitch(acct, rt.App) {
+ switch b.MailSwitch(acct, rt.App) {
+ case MailSwitchOn:
+ case MailSwitchUnknown:
+ submit := mailUnknownSubmits(fileEnv)
+ if _, seen := b.mailUnknownLogged.LoadOrStore(rt.Host, true); !seen {
+ channel := "its bundle's SMTP settings, if it has any"
+ if submit {
+ channel = "submission (its bundle holds a From and no SMTP host)"
+ }
+ log.Printf("activator: the email submission switch of %s/%s could not be read; %s starts with %s", acct, rt.App, rt.Host, channel)
+ }
+ if !submit {
+ return false
+ }
+ default:
return false
}
if !rt.Provisioned {
diff --git a/internal/activator/mailbuild.go b/internal/activator/mailbuild.go
index e011ad057..5257b4904 100644
--- a/internal/activator/mailbuild.go
+++ b/internal/activator/mailbuild.go
@@ -29,7 +29,7 @@ func (b *ExecBackend) warnUndeclaredMailBuild(rt registry.Route, version string)
return
}
acct := release.RouteAccount(rt)
- if !b.MailSwitch(acct, rt.App) {
+ if b.MailSwitch(acct, rt.App) != MailSwitchOn {
return
}
key := rt.Host + "\x00" + version
diff --git a/internal/activator/mailbuild_test.go b/internal/activator/mailbuild_test.go
index 9da43ddd1..96e1b4230 100644
--- a/internal/activator/mailbuild_test.go
+++ b/internal/activator/mailbuild_test.go
@@ -99,9 +99,9 @@ func spawnFlat(t *testing.T, b *ExecBackend, host string) {
// build logs nothing, and an unreadable manifest is logged once and refuses
// nothing.
func TestWakeNeverRefusedForUndeclaredBuild(t *testing.T) {
- on := func(acct, app string) bool { return acct == "abcxyz" && app == "docs" }
+ on := switchedIf(func(acct, app string) bool { return acct == "abcxyz" && app == "docs" })
// spawnFlat's route names no account, so it is the ops account's.
- docsOn := func(_, app string) bool { return app == "docs" }
+ docsOn := switchedIf(func(_, app string) bool { return app == "docs" })
t.Run("undeclared, flat spawn", func(t *testing.T) {
logs := captureLogLines(t)
@@ -166,9 +166,9 @@ func TestWakeNeverRefusedForUndeclaredBuild(t *testing.T) {
reads := &manifestReads{}
rt := registry.Route{Host: "s.sheets.example.com", Account: "abcxyz", App: "sheets"}
for _, b := range []*ExecBackend{
- {MailSwitch: on, ManifestOf: reads.of}, // another app is switched
- {ManifestOf: reads.of}, // no switch reader
- {MailSwitch: func(string, string) bool { return true }}, // no manifest reader
+ {MailSwitch: on, ManifestOf: reads.of}, // another app is switched
+ {ManifestOf: reads.of}, // no switch reader
+ {MailSwitch: func(string, string) MailSwitchState { return MailSwitchOn }}, // no manifest reader
} {
b.warnUndeclaredMailBuild(rt, "v1")
}
diff --git a/internal/activator/mailswitch.go b/internal/activator/mailswitch.go
new file mode 100644
index 000000000..b5e3c8f7c
--- /dev/null
+++ b/internal/activator/mailswitch.go
@@ -0,0 +1,75 @@
+package activator
+
+import "strings"
+
+// MailSwitchState is the agent's answer to "is this app switched to the
+// submit transport?" (platform mail submission, decision 10). It has three
+// values, not two, because the agent cannot always read the switch: after
+// every agent restart its cache is cold, and a store blip at that moment
+// used to read as off. Off for a switched app, whose bundles no longer hold
+// the five <P>_SMTP_*, left its instances with neither channel, the dead
+// state decision 11 rejected (Fable's final review, P2-2, ruled 2026-11-14).
+// An unknown answer is never read as off: the instance's own bundle decides
+// (mailUnknownSubmits).
+type MailSwitchState uint8
+
+const (
+ // MailSwitchOff: the record was read and the app is not switched (or
+ // has no sender record).
+ MailSwitchOff MailSwitchState = iota
+ // MailSwitchOn: the record was read and the app is switched.
+ MailSwitchOn
+ // MailSwitchUnknown: the record could not be read, and no answer read
+ // since the last serial move is cached.
+ MailSwitchUnknown
+)
+
+func (s MailSwitchState) String() string {
+ switch s {
+ case MailSwitchOff:
+ return "off"
+ case MailSwitchOn:
+ return "on"
+ case MailSwitchUnknown:
+ return "unknown"
+ }
+ return "invalid"
+}
+
+// mailUnknownSubmits is how an unreadable switch is decided for one
+// instance, from the environment it is about to start with: submit when it
+// holds a <stem>_MAIL_FROM and no <P>_SMTP_HOST, and otherwise the SMTP
+// channel its bundle carries, if any.
+//
+// It follows from the switch's write order (plan ruling 2, P2-3). The
+// console delivers the From before it writes On:true and takes the five
+// <P>_SMTP_* out only after; on the way off it delivers the five first,
+// writes On:false, and only then takes the From out. So a bundle with a
+// From and no SMTP host belongs to an app that is switched, and submit is
+// its only working channel; a bundle that still holds the SMTP host has a
+// delivered key, whichever side of a flip the app is on. Submitting for an
+// app that is not in fact switched is safe: the mailer reads the app's
+// switch itself and refuses it (403 SUBMISSION_OFF).
+func mailUnknownSubmits(env map[string]string) bool {
+ from, smtp := false, false
+ for k, v := range env {
+ if v == "" {
+ continue
+ }
+ switch {
+ case strings.HasSuffix(k, "_MAIL_FROM"):
+ from = true
+ case strings.HasSuffix(k, "_SMTP_HOST"):
+ smtp = true
+ }
+ }
+ return from && !smtp
+}
+
+// mailVerbSwitched is the verb's read of the switch (mailsubmit.Mount): an
+// app known to be off is answered 403 SUBMISSION_OFF before its body is
+// read; on and unknown are forwarded, and the mailer, which reads the
+// switch itself, refuses an app that is not switched.
+func (b *ExecBackend) mailVerbSwitched(acct, app string) bool {
+ return b.MailSwitch != nil && b.MailSwitch(acct, app) != MailSwitchOff
+}
diff --git a/internal/activator/mailswitch_test.go b/internal/activator/mailswitch_test.go
new file mode 100644
index 000000000..b1e4e92e5
--- /dev/null
+++ b/internal/activator/mailswitch_test.go
@@ -0,0 +1,94 @@
+package activator
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// switchedIf is a MailSwitch that reads every app it names as on and
+// every other as off: a switch that always reads.
+func switchedIf(on func(acct, app string) bool) func(string, string) MailSwitchState {
+ return func(acct, app string) MailSwitchState {
+ if on(acct, app) {
+ return MailSwitchOn
+ }
+ return MailSwitchOff
+ }
+}
+
+// An unreadable switch is never read as off (Fable's final review, P2-2,
+// ruled 2026-11-14). The instance's own environment decides: a From and no
+// SMTP host submits, anything else keeps what its bundle carries. Before
+// the fix an unknown answer was off, so a switched app's instance started
+// in a store blip after an agent restart had neither channel.
+func TestMailUnknownSwitchDecidedByTheBundle(t *testing.T) {
+ unknown := func(string, string) MailSwitchState { return MailSwitchUnknown }
+ rt := registry.Route{Host: "a.docs.example.com", Account: "abcxyz", App: "docs", Provisioned: true}
+ handMade := rt
+ handMade.Host, handMade.Provisioned = "handmade.docs.example.com", false
+ const from, host = "hello@docs.example.com", "email-smtp.eu-west-1.amazonaws.com"
+ for _, c := range []struct {
+ name string
+ rt registry.Route
+ env map[string]string
+ want bool
+ }{
+ {"a From and no SMTP host: switched, submit", rt, map[string]string{"TITO_MAIL_FROM": from, "APP": "1"}, true},
+ {"the default stem's From", rt, map[string]string{"CARLOS_MAIL_FROM": from}, true},
+ {"a tenant's CARLOS_MAIL changes nothing", rt, map[string]string{"TITO_MAIL_FROM": from, "CARLOS_MAIL": "off"}, true},
+ {"From and SMTP host: mid-flip, SMTP works", rt, map[string]string{"TITO_MAIL_FROM": from, "TITO_SMTP_HOST": host}, false},
+ {"SMTP only: an unswitched app", rt, map[string]string{"TITO_SMTP_HOST": host, "TITO_SMTP_FROM": from}, false},
+ {"no mail at all", rt, map[string]string{"APP": "1"}, false},
+ {"an empty From", rt, map[string]string{"TITO_MAIL_FROM": ""}, false},
+ {"a hand-made route still cannot submit", handMade, map[string]string{"TITO_MAIL_FROM": from}, false},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ b := &ExecBackend{ServedPools: eligibleSharedPools, Mail: &failingForwarder{}, MailSwitch: unknown}
+ got := b.agentOwnedVars(c.rt, "/run/carlos/x.sock.control", c.env, true)
+ v, ok := got["CARLOS_MAIL"]
+ if c.want && v != "submit" {
+ t.Fatalf("CARLOS_MAIL = %q (present %v), want submit", v, ok)
+ }
+ if !c.want && ok {
+ t.Fatalf("CARLOS_MAIL = %q, want it stripped", v)
+ }
+ })
+ }
+
+ // Each host is logged once, saying which channel it got.
+ buf := captureLog(t)
+ b := &ExecBackend{ServedPools: eligibleSharedPools, Mail: &failingForwarder{}, MailSwitch: unknown}
+ for range 3 {
+ b.agentOwnedVars(rt, "/run/carlos/x.sock.control", map[string]string{"TITO_MAIL_FROM": from}, true)
+ }
+ if n := strings.Count(buf.String(), "could not be read"); n != 1 || !strings.Contains(buf.String(), "starts with submission") {
+ t.Fatalf("logged %d times: %q", n, buf.String())
+ }
+
+ // The verb forwards an unknown app to the mailer, which reads the
+ // switch itself; only an app known to be off is refused at the socket.
+ for _, c := range []struct {
+ sw func(string, string) MailSwitchState
+ want bool
+ }{
+ {unknown, true},
+ {switchedIf(func(string, string) bool { return true }), true},
+ {switchedIf(func(string, string) bool { return false }), false},
+ {nil, false},
+ } {
+ if got := (&ExecBackend{MailSwitch: c.sw}).mailVerbSwitched("abcxyz", "docs"); got != c.want {
+ t.Errorf("verb switched = %v, want %v", got, c.want)
+ }
+ }
+
+ // The spawn-time warning is for a switch read as on, never an unknown
+ // one: it reads no manifest.
+ nb := &ExecBackend{MailSwitch: unknown, ManifestOf: func(registry.Route, string) (*release.Manifest, error) {
+ t.Fatal("an unknown switch read the manifest")
+ return nil, nil
+ }}
+ nb.warnUndeclaredMailBuild(rt, "v1")
+}
diff --git a/internal/activator/mailverb_test.go b/internal/activator/mailverb_test.go
index 9bae0e6de..9464c4e07 100644
--- a/internal/activator/mailverb_test.go
+++ b/internal/activator/mailverb_test.go
@@ -72,7 +72,7 @@ func TestMailVerbMountedAtBothBindSites(t *testing.T) {
t.Run("flat, mounted", func(t *testing.T) {
b := testExecBackend(t) // Timers and UpdatesReader nil
rec := &mailRecorder{}
- b.Mail, b.MailSwitch = rec, func(string, string) bool { return true }
+ b.Mail, b.MailSwitch = rec, func(string, string) MailSwitchState { return MailSwitchOn }
ctl, token, stop := startAndReachControlSocket(t, b, "flatmail.example.com")
defer stop()
if code := mailPost(t, ctl, token); code != http.StatusOK {
@@ -96,7 +96,7 @@ func TestMailVerbMountedAtBothBindSites(t *testing.T) {
nested := func(t *testing.T, mail mailsubmit.Forwarder) (string, string, func()) {
b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{})
b.GenContainment = true
- b.Mail, b.MailSwitch = mail, func(string, string) bool { return true }
+ b.Mail, b.MailSwitch = mail, func(string, string) MailSwitchState { return MailSwitchOn }
p0 := b.pathsFor(rt)
if err := os.MkdirAll(p0.runDir, 0o750); err != nil {
t.Fatal(err)
@@ -145,8 +145,8 @@ func TestMailVerbMountedAtBothBindSites(t *testing.T) {
// an instance record, and anything else strips it, a tenant's own value
// included.
func TestCarlosMailFollowsTheBind(t *testing.T) {
- on := func(acct, app string) bool { return acct == "abcxyz" && app == "docs" }
- off := func(string, string) bool { return false }
+ on := switchedIf(func(acct, app string) bool { return acct == "abcxyz" && app == "docs" })
+ off := func(string, string) MailSwitchState { return MailSwitchOff }
provisioned := registry.Route{Host: "a.docs.example.com", Account: "abcxyz", App: "docs", Provisioned: true}
handMade := provisioned
handMade.Provisioned = false
@@ -157,7 +157,7 @@ func TestCarlosMailFollowsTheBind(t *testing.T) {
for _, c := range []struct {
name string
mail mailsubmit.Forwarder
- sw func(string, string) bool
+ sw func(string, string) MailSwitchState
rt registry.Route
control bool
want bool
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 8323a9eb6..517f7541a 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -565,14 +565,15 @@ func runAgent(args []string, buildClaims ClaimFactory) {
// design, decision 1), forwarded to the box-local mailer, and the
// per-app switch that decides CARLOS_MAIL (decision 11), read from
// the app sender record and refreshed on every serial move. While
- // there is no deploy store the switch reads off for every app: the
- // verb is still there, and the mailer refuses an unswitched app.
+ // there is no deploy store the switch is unknown for every app: each
+ // instance's bundle decides its channel, the verb forwards, and the
+ // mailer refuses an unswitched app.
// A store that does not open now is retried, at most once a
// minute, with an error line each time, rather than leaving every
// app unswitched for the agent's life.
eb.Mail = mailsubmit.SocketForwarder{}
mailSwitch := newMailSwitchCacheOpening(openDeployStore)
- eb.MailSwitch = mailSwitch.On
+ eb.MailSwitch = mailSwitch.State
armedMailSwitch.Store(mailSwitch)
// Region HA P1a: the lifetime index the reconcile passes fill, the
// registry and files store an HA restore reads, the startup sweep's
@@ -3332,6 +3333,16 @@ func fastTick(ctx context.Context, d *fastDeps, now time.Time) {
default:
d.serialBroken = false
if doc.Serial != d.lastSerial && now.Sub(d.lastFull) >= fastFullClamp {
+ // Every cached mail switch answer goes stale first, at once,
+ // before anything this move runs can start an instance: the
+ // pass set cycles adopted instances, and the restart leg below
+ // bounces every instance of an app whose switch just flipped
+ // (Fable's final review, P2-1). Refresh, further down, runs on
+ // its own goroutine and has not reached the app by then, so a
+ // spawn reads the switch itself, bounded.
+ if c := armedMailSwitch.Load(); c != nil {
+ c.MarkStale()
+ }
d.runFull(ctx)
fullRan = true
if d.restartLeg != nil {
diff --git a/internal/host/mailswitch.go b/internal/host/mailswitch.go
index 763f933c0..a5682131d 100644
--- a/internal/host/mailswitch.go
+++ b/internal/host/mailswitch.go
@@ -10,6 +10,7 @@ import (
"sync/atomic"
"time"
+ "github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/mailwire"
"github.com/carlosframework/platform/internal/release"
)
@@ -18,7 +19,7 @@ import (
const mailSwitchReadTimeout = 2 * time.Second
// mailSwitchRetryErr is how long an answer the agent could not read is
-// kept before the next On asks the store again.
+// kept before the next State asks the store again.
const mailSwitchRetryErr = 30 * time.Second
// mailSwitchLogEvery is the least time between two logged read failures
@@ -30,8 +31,18 @@ const mailSwitchLogEvery = time.Minute
// reads the switch"): the app sender record's submission block,
// apps/<acct>/<app>/email/senders/app.json, read on first use and re-read
// on every serial bump. The console's switch door bumps the serial, so a
-// flip reaches the next spawn within seconds. The activator asks On when it
-// composes CARLOS_MAIL (agentOwnedVars).
+// flip reaches the next spawn within seconds. The activator asks State when
+// it composes CARLOS_MAIL (agentOwnedVars).
+//
+// A serial move marks every answer stale (MarkStale) before the move's
+// passes and its restart leg run, and State reads a stale answer again,
+// bounded, rather than return it (Fable's final review, P2-1, ruled
+// 2026-11-14). The restart that completes a flip bounces instances at once,
+// before Refresh has reached their app, and a request that woke one of them
+// used to spawn it on the answer from before the flip.
+//
+// An answer the agent cannot read is unknown, never off (P2-2): the
+// activator decides it from the instance's own bundle.
type mailSwitchCache struct {
// open opens the deploy store; a cache built with one keeps trying it,
// at most once a mailSwitchReopenEvery, until it succeeds (review
@@ -45,6 +56,7 @@ type mailSwitchCache struct {
logf func(string, ...any)
mu sync.Mutex
+ gen uint64 // bumped by MarkStale; an entry read in an older one is stale
entries map[mailSwitchKey]mailSwitchEntry
logged map[mailSwitchKey]time.Time
@@ -54,10 +66,22 @@ type mailSwitchCache struct {
type mailSwitchKey struct{ acct, app string }
type mailSwitchEntry struct {
- on bool
- etag string
- at time.Time
- err bool // the last read failed; on is the last good answer, or false
+ on bool
+ known bool // the read succeeded; false: it failed, and the answer is unknown
+ etag string
+ at time.Time
+ gen uint64 // the cache's gen when the read began
+}
+
+// state is the entry's answer.
+func (e mailSwitchEntry) state() activator.MailSwitchState {
+ switch {
+ case !e.known:
+ return activator.MailSwitchUnknown
+ case e.on:
+ return activator.MailSwitchOn
+ }
+ return activator.MailSwitchOff
}
func newMailSwitchCache(s release.Store) *mailSwitchCache {
@@ -70,8 +94,8 @@ func newMailSwitchCache(s release.Store) *mailSwitchCache {
const mailSwitchReopenEvery = time.Minute
// newMailSwitchCacheOpening is a cache that opens its store itself, now and
-// again on later use until it succeeds. Until then every app reads as not
-// switched, and each failed attempt is logged at error level.
+// again on later use until it succeeds. Until then every app reads as
+// unknown, and each failed attempt is logged at error level.
func newMailSwitchCacheOpening(open func(context.Context) (release.Store, error)) *mailSwitchCache {
c := newMailSwitchCache(nil)
c.open = open
@@ -96,7 +120,7 @@ func (c *mailSwitchCache) storeNow() release.Store {
defer cancel()
s, err := c.open(ctx)
if err != nil {
- c.logf("agent: ERROR: mail switch: no deploy store (%v); every app reads as not switched until it opens, retried every %v", err, mailSwitchReopenEvery)
+ c.logf("agent: ERROR: mail switch: no deploy store (%v); every app's switch is unknown until it opens (each instance's bundle decides its channel), retried every %v", err, mailSwitchReopenEvery)
return nil
}
c.store = s
@@ -107,27 +131,45 @@ func (c *mailSwitchCache) storeNow() release.Store {
// fastTick. Nil until runAgent arms one.
var armedMailSwitch atomic.Pointer[mailSwitchCache]
-// On reports whether the app is switched. A cached answer is used; on a
-// miss, or on an answer whose read failed more than mailSwitchRetryErr ago,
-// the record is read once, bounded. A read that fails with no good answer
-// cached is false, and logged at most once a minute per app: a wake with
-// the switch unreadable gets its SMTP variables if the bundle has them, or
-// neither channel, and the app refuses at boot (decision 11's loud
-// failure).
-func (c *mailSwitchCache) On(acct, app string) bool {
+// State reports whether the app is switched: on, off, or unknown. A cached
+// answer read since the last serial move is used; on a miss, on a stale
+// answer (one read before the last MarkStale), or on an answer whose read
+// failed more than mailSwitchRetryErr ago, the record is read once,
+// bounded. A read that fails is unknown, whatever was cached before it, and
+// logged at most once a minute per app: an answer from before a serial move
+// may be the very one the move changed. The activator decides an unknown
+// switch from the instance's own bundle, so a store blip neither leaves a
+// switched app with no channel nor gives an unswitched one a dead one.
+func (c *mailSwitchCache) State(acct, app string) activator.MailSwitchState {
if c == nil || c.storeNow() == nil {
- return false
+ return activator.MailSwitchUnknown
}
k := mailSwitchKey{acct, app}
c.mu.Lock()
e, ok := c.entries[k]
+ fresh := ok && e.gen == c.gen
c.mu.Unlock()
- if ok && (!e.err || c.now().Sub(e.at) < mailSwitchRetryErr) {
- return e.on
+ if fresh && (e.known || c.now().Sub(e.at) < mailSwitchRetryErr) {
+ return e.state()
}
ctx, cancel := context.WithTimeout(context.Background(), mailSwitchReadTimeout)
defer cancel()
- return c.read(ctx, k).on
+ return c.read(ctx, k).state()
+}
+
+// MarkStale makes every cached answer stale at once: the next State of
+// each app reads its record again. fastTick calls it on a serial move,
+// synchronously, before the move's pass set and restart leg, so no
+// instance the move restarts (or a request wakes) spawns on an answer from
+// before the move. A read already in flight when it is called stores a
+// stale answer too.
+func (c *mailSwitchCache) MarkStale() {
+ if c == nil {
+ return
+ }
+ c.mu.Lock()
+ c.gen++
+ c.mu.Unlock()
}
// Refresh re-reads every cached app. fastTick runs it on each serial move,
@@ -151,43 +193,48 @@ func (c *mailSwitchCache) Refresh(ctx context.Context) {
}
}
-// read fetches and stores one app's switch, and returns what it stored. An
-// absent record is off. A failed read or an undecodable body keeps the last
-// good answer (or false), marked as an error so On asks again later.
+// read fetches and stores one app's switch, and returns what it read. An
+// absent record is off. A failed read or an undecodable body is unknown,
+// so State asks again after mailSwitchRetryErr. The entry carries the
+// cache's gen from before the Get, so a read that a MarkStale overtook
+// stores a stale answer; and it never replaces an entry read in a later
+// gen.
func (c *mailSwitchCache) read(ctx context.Context, k mailSwitchKey) mailSwitchEntry {
+ c.mu.Lock()
+ gen := c.gen
+ prev, had := c.entries[k]
+ c.mu.Unlock()
body, etag, err := c.storeNow().Get(ctx, mailwire.SenderKey(k.acct, k.app, mailwire.SenderAppID))
now := c.now()
var e mailSwitchEntry
switch {
case errors.Is(err, os.ErrNotExist):
- e = mailSwitchEntry{on: false, at: now}
+ e = mailSwitchEntry{on: false, known: true, at: now}
case err != nil:
e = c.failed(k, now, err)
+ case had && prev.known && etag != "" && prev.etag == etag:
+ e = mailSwitchEntry{on: prev.on, known: true, etag: etag, at: now}
default:
- c.mu.Lock()
- prev, had := c.entries[k]
- c.mu.Unlock()
- if had && !prev.err && etag != "" && prev.etag == etag {
- e = mailSwitchEntry{on: prev.on, etag: etag, at: now}
- break
- }
var v mailwire.SenderView
if derr := json.Unmarshal(body, &v); derr != nil {
e = c.failed(k, now, derr)
break
}
- e = mailSwitchEntry{on: v.Submission != nil && v.Submission.On, etag: etag, at: now}
+ e = mailSwitchEntry{on: v.Submission != nil && v.Submission.On, known: true, etag: etag, at: now}
}
+ e.gen = gen
c.mu.Lock()
- c.entries[k] = e
+ if cur, ok := c.entries[k]; !ok || cur.gen <= gen {
+ c.entries[k] = e
+ }
c.mu.Unlock()
return e
}
-// failed is a failed read's entry: the last good answer, or false.
+// failed is a failed read's entry: unknown, logged at most once a
+// mailSwitchLogEvery per app.
func (c *mailSwitchCache) failed(k mailSwitchKey, now time.Time, err error) mailSwitchEntry {
c.mu.Lock()
- prev, had := c.entries[k]
last := c.logged[k]
report := last.IsZero() || now.Sub(last) >= mailSwitchLogEvery
if report {
@@ -195,7 +242,7 @@ func (c *mailSwitchCache) failed(k mailSwitchKey, now time.Time, err error) mail
}
c.mu.Unlock()
if report {
- c.logf("agent: mail switch for %s/%s unreadable: %v (answering %v until a read succeeds)", k.acct, k.app, err, had && prev.on)
+ c.logf("agent: mail switch for %s/%s unreadable: %v (unknown until a read succeeds: each instance's bundle decides its channel)", k.acct, k.app, err)
}
- return mailSwitchEntry{on: had && prev.on, etag: prev.etag, at: now, err: true}
+ return mailSwitchEntry{at: now}
}
diff --git a/internal/host/mailswitch_test.go b/internal/host/mailswitch_test.go
index 9db058f59..4df301a10 100644
--- a/internal/host/mailswitch_test.go
+++ b/internal/host/mailswitch_test.go
@@ -11,6 +11,7 @@ import (
"testing"
"time"
+ "github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/mailwire"
"github.com/carlosframework/platform/internal/release"
)
@@ -24,20 +25,30 @@ type switchStore struct {
etags map[string]string
fail error
reads int
+ // gate, when set, holds every Get after its read until it is closed,
+ // and entered is told once the read is done.
+ gate chan struct{}
+ entered chan struct{}
}
func (s *switchStore) Get(_ context.Context, key string) ([]byte, string, error) {
s.mu.Lock()
- defer s.mu.Unlock()
s.reads++
if s.fail != nil {
+ s.mu.Unlock()
return nil, "", s.fail
}
b, ok := s.objs[key]
+ etag, gate, entered := s.etags[key], s.gate, s.entered
+ s.mu.Unlock()
+ if gate != nil {
+ entered <- struct{}{}
+ <-gate
+ }
if !ok {
return nil, "", fmt.Errorf("%s: %w", key, os.ErrNotExist)
}
- return []byte(b), s.etags[key], nil
+ return []byte(b), etag, nil
}
func (s *switchStore) set(acct, app string, on bool, etag string) {
@@ -51,6 +62,7 @@ func (s *switchStore) set(acct, app string, on bool, etag string) {
func (s *switchStore) n() int { s.mu.Lock(); defer s.mu.Unlock(); return s.reads }
func TestMailSwitchCache(t *testing.T) {
+ const on, off, unknown = activator.MailSwitchOn, activator.MailSwitchOff, activator.MailSwitchUnknown
st := &switchStore{objs: map[string]string{}, etags: map[string]string{}}
st.set("abcxyz", "docs", true, `"e1"`)
clock := time.Unix(1_700_000_000, 0)
@@ -60,113 +72,163 @@ func TestMailSwitchCache(t *testing.T) {
c.logf = func(f string, a ...any) { logs = append(logs, fmt.Sprintf(f, a...)) }
// A miss reads once; a hit does not read again.
- if !c.On("abcxyz", "docs") {
+ if c.State("abcxyz", "docs") != on {
t.Fatal("a switched app reads off")
}
- if !c.On("abcxyz", "docs") || st.n() != 1 {
+ if c.State("abcxyz", "docs") != on || st.n() != 1 {
t.Fatalf("a hit read the store again (%d reads)", st.n())
}
// An app with no sender record is off, and cached.
- if c.On("abcxyz", "sheets") || c.On("abcxyz", "sheets") || st.n() != 2 {
+ if c.State("abcxyz", "sheets") != off || c.State("abcxyz", "sheets") != off || st.n() != 2 {
t.Fatalf("absent record: %d reads", st.n())
}
// A record with no submission block, or one switched off, is off.
k := mailwire.SenderKey("abcxyz", "slides", "app")
st.objs[k] = `{"id":"app","provisioned":{"active":true}}`
- if c.On("abcxyz", "slides") {
+ if c.State("abcxyz", "slides") != off {
t.Fatal("no submission block reads on")
}
// Refresh flips a cached value once the record changes.
st.set("abcxyz", "docs", false, `"e2"`)
- if !c.On("abcxyz", "docs") {
+ if c.State("abcxyz", "docs") != on {
t.Fatal("the cache moved without a refresh")
}
c.Refresh(context.Background())
- if c.On("abcxyz", "docs") {
+ if c.State("abcxyz", "docs") != off {
t.Fatal("a refresh did not flip the switch off")
}
st.set("abcxyz", "sheets", true, `"e3"`)
c.Refresh(context.Background())
- if !c.On("abcxyz", "sheets") {
+ if c.State("abcxyz", "sheets") != on {
t.Fatal("a refresh did not see a new switch-on")
}
- // A read error with nothing cached is off, logged once a minute, and
- // retried only after mailSwitchRetryErr.
+ // A read error with nothing cached is unknown, never off (P2-2),
+ // logged once a minute, and retried only after mailSwitchRetryErr.
st.fail = errors.New("store down")
- if c.On("abcxyz", "calendar") || c.On("abcxyz", "calendar") {
- t.Fatal("an unreadable switch reads on")
+ if c.State("abcxyz", "calendar") != unknown || c.State("abcxyz", "calendar") != unknown {
+ t.Fatal("an unreadable switch is not unknown")
}
if len(logs) != 1 || !strings.Contains(logs[0], "abcxyz/calendar") {
t.Fatalf("logs %q", logs)
}
before := st.n()
- c.On("abcxyz", "calendar")
+ c.State("abcxyz", "calendar")
if st.n() != before {
t.Fatal("a failed read was retried inside the retry window")
}
clock = clock.Add(mailSwitchRetryErr + time.Second)
- c.On("abcxyz", "calendar")
+ c.State("abcxyz", "calendar")
if st.n() != before+1 {
t.Fatal("a failed read was not retried after the window")
}
- // A failed refresh keeps the last good answer.
+ // A refresh that fails leaves no answer from before the move standing:
+ // it is unknown.
+ c.MarkStale()
c.Refresh(context.Background())
- if !c.On("abcxyz", "sheets") {
- t.Fatal("a failed refresh dropped a good answer")
+ if got := c.State("abcxyz", "sheets"); got != unknown {
+ t.Fatalf("a failed refresh after a serial move answered %v, want unknown", got)
}
// The store comes back: the next read after the window is believed.
st.fail = nil
st.set("abcxyz", "calendar", true, `"e4"`)
clock = clock.Add(mailSwitchRetryErr + time.Second)
- if !c.On("abcxyz", "calendar") {
+ if c.State("abcxyz", "calendar") != on {
t.Fatal("a recovered read was not believed")
}
- // A nil cache, or one with no store, is off.
+ // A nil cache, or one with no store, is unknown.
var nilCache *mailSwitchCache
- if nilCache.On("abcxyz", "docs") || newMailSwitchCache(nil).On("abcxyz", "docs") {
- t.Fatal("no store reads on")
+ if nilCache.State("abcxyz", "docs") != unknown || newMailSwitchCache(nil).State("abcxyz", "docs") != unknown {
+ t.Fatal("no store is not unknown")
}
}
-// A deploy store that does not open at agent start is retried, at most
-// once a minute, with an error line per attempt, and the switch is read
-// once it opens (review round 1, Task 4 P3).
-func TestMailSwitchCacheRetriesTheStore(t *testing.T) {
+// A serial move makes every answer stale at once, and State reads a stale
+// answer again rather than return it (Fable's final review, P2-1). A read
+// that began before the move and lands after it does not count as fresh,
+// and never replaces an answer read after the move.
+func TestMailSwitchMarkStale(t *testing.T) {
+ const on, off = activator.MailSwitchOn, activator.MailSwitchOff
st := &switchStore{objs: map[string]string{}, etags: map[string]string{}}
- st.set("abcxyz", "docs", true, `"e1"`)
- clock := time.Unix(1_700_000_000, 0)
- var logs []string
- opens := 0
- fail := true
- open := func(context.Context) (release.Store, error) {
- opens++
- if fail {
- return nil, errors.New("no credentials yet")
- }
- return st, nil
+ st.set("abcxyz", "docs", false, `"e1"`)
+ c := newMailSwitchCache(st)
+ c.logf = func(string, ...any) {}
+ if c.State("abcxyz", "docs") != off {
+ t.Fatal("first read")
}
- c := &mailSwitchCache{open: open, now: func() time.Time { return clock },
- logf: func(f string, a ...any) { logs = append(logs, fmt.Sprintf(f, a...)) },
- entries: map[mailSwitchKey]mailSwitchEntry{}, logged: map[mailSwitchKey]time.Time{}}
- if c.On("abcxyz", "docs") || opens != 1 || len(logs) != 1 || !strings.Contains(logs[0], "ERROR") {
- t.Fatalf("first attempt: opens %d logs %q", opens, logs)
+ // The door switches the app on and bumps the serial; the tick marks
+ // every answer stale before it bounces anything.
+ st.set("abcxyz", "docs", true, `"e2"`)
+ c.MarkStale()
+ if got := c.State("abcxyz", "docs"); got != on || st.n() != 2 {
+ t.Fatalf("after MarkStale: %v with %d reads, want on, read again", got, st.n())
}
- c.On("abcxyz", "docs")
- c.Refresh(context.Background())
- if opens != 1 {
- t.Fatalf("retried inside the minute: %d opens", opens)
+ if c.State("abcxyz", "docs") != on || st.n() != 2 {
+ t.Fatal("a fresh answer was read again")
+ }
+
+ // A refresh whose Get began before a MarkStale (and returned the old
+ // body) stores a stale entry: the next State reads again.
+ st.set("abcxyz", "docs", false, `"e3"`)
+ st.mu.Lock()
+ st.gate = make(chan struct{})
+ st.entered = make(chan struct{}, 1)
+ st.mu.Unlock()
+ done := make(chan struct{})
+ go func() { defer close(done); c.Refresh(context.Background()) }()
+ <-st.entered // the refresh's Get has read "off"
+ st.set("abcxyz", "docs", true, `"e4"`)
+ c.MarkStale()
+ st.mu.Lock()
+ close(st.gate)
+ st.gate = nil
+ st.mu.Unlock()
+ <-done
+ if got := c.State("abcxyz", "docs"); got != on {
+ t.Fatalf("a read overtaken by MarkStale answered %v, want on", got)
+ }
+}
+
+// The restart that completes a flip bounces instances on the serial move
+// at once, and a spawn reads the switch before Refresh has run (Fable's
+// final review, P2-1). fastTick marks the cache stale before its pass set
+// and restart leg, so the spawn reads the switch again and gets the new
+// answer. Without that, the bounced instance respawned on the answer from
+// before the flip.
+func TestFastTickMarksMailSwitchStaleBeforeTheBounce(t *testing.T) {
+ st := &switchStore{objs: map[string]string{}, etags: map[string]string{}}
+ st.set("abcxyz", "docs", false, `"e1"`)
+ c := newMailSwitchCache(st)
+ c.logf = func(string, ...any) {}
+ prev := armedMailSwitch.Swap(c)
+ t.Cleanup(func() { armedMailSwitch.Store(prev) })
+ if c.State("abcxyz", "docs") != activator.MailSwitchOff {
+ t.Fatal("first read")
+ }
+
+ env := newFastFixture(t)
+ var inPass, inRestart []activator.MailSwitchState
+ d := env.deps(func() { inPass = append(inPass, c.State("abcxyz", "docs")) })
+ d.restartLeg = func(context.Context) { inRestart = append(inRestart, c.State("abcxyz", "docs")) }
+ now := time.Unix(1754640000, 0)
+ ctx := context.Background()
+ if err := release.BumpSerial(ctx, env.store, now); err != nil {
+ t.Fatal(err)
+ }
+ fastTick(ctx, d, now) // the seed
+ // The switch door: the record first, then the serial.
+ st.set("abcxyz", "docs", true, `"e2"`)
+ if err := release.BumpSerial(ctx, env.store, now); err != nil {
+ t.Fatal(err)
}
- fail = false
- clock = clock.Add(mailSwitchReopenEvery)
- if !c.On("abcxyz", "docs") || opens != 2 {
- t.Fatalf("after the store opens: opens %d", opens)
+ fastTick(ctx, d, now.Add(10*time.Second))
+ if len(inRestart) != 1 || inRestart[0] != activator.MailSwitchOn {
+ t.Fatalf("a spawn in the restart leg read %v, want on", inRestart)
}
- c.On("abcxyz", "docs")
- if opens != 2 {
- t.Fatal("an open store was opened again")
+ if len(inPass) != 1 || inPass[0] != activator.MailSwitchOn {
+ t.Fatalf("a spawn in the pass set read %v, want on", inPass)
}
}